diff --git "a/1784.jsonl" "b/1784.jsonl" new file mode 100644--- /dev/null +++ "b/1784.jsonl" @@ -0,0 +1,60 @@ +{"seq_id":"598720674","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef hinton(matrix, max_weight=None, ax=None, patch_color=None):\n \"\"\" Draw Hinton Diagram for visualizing a weight matrix \"\"\"\n ax = ax if ax is not None else plt.gca()\n\n if not max_weight:\n max_weight = 2 ** np.ceil(np.log(np.abs(matrix).max()) / np.log(2))\n\n ax.patch.set_facecolor('white')\n ax.set_aspect('equal', 'box')\n ax.xaxis.set_major_locator(plt.NullLocator())\n ax.yaxis.set_major_locator(plt.NullLocator())\n\n for (x, y), w in np.ndenumerate(matrix):\n #color = 'red' if w > 0 else 'blue'\n color = patch_color\n size = np.sqrt(np.abs(w + 1e-10) / max_weight)\n rect = plt.Rectangle([x - size / 2, y - size / 2], size, size, facecolor=color, edgecolor=color, alpha=0.3)\n ax.add_patch(rect)\n\n ax.autoscale_view()\n ax.invert_yaxis()\n\n\ndef main():\n true_weight = np.genfromtxt(fname='../data/true_weight.txt' , delimiter=',')\n lr_weight = np.genfromtxt(fname='../data/lr_weight.txt' , delimiter=',')\n lasso_weight = np.genfromtxt(fname='../data/lasso_weight.txt', delimiter=',')\n\n hinton(true_weight, patch_color='red')\n hinton(lr_weight , patch_color='green')\n plt.show()\n\n hinton(true_weight , patch_color='red')\n hinton(lasso_weight, patch_color='blue')\n plt.show()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"regression/lassos/code/hinton_diagram.py","file_name":"hinton_diagram.py","file_ext":"py","file_size_in_byte":1371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"360894438","text":"\n\nfrom xai.brain.wordbase.verbs._perjure import _PERJURE\n\n#calss header\nclass _PERJURING(_PERJURE, ):\n\tdef __init__(self,): \n\t\t_PERJURE.__init__(self)\n\t\tself.name = \"PERJURING\"\n\t\tself.specie = 'verbs'\n\t\tself.basic = \"perjure\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/verbs/_perjuring.py","file_name":"_perjuring.py","file_ext":"py","file_size_in_byte":247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"480635600","text":"## multioutput_face_completion\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt \nplt.rc(\"font\", size=12)\n\nfrom sklearn import preprocessing\nfrom sklearn.datasets import fetch_olivetti_faces\nfrom sklearn.utils.validation import check_random_state\n\nfrom sklearn.ensemble import ExtraTreesRegressor\nfrom sklearn.neighbors import KNeighborsRegressor\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.linear_model import RidgeCV\n#自己加入\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.tree import DecisionTreeRegressor\n\nfrom sklearn.model_selection import train_test_split\n\n\n#loading face dataset\ndata, targets= fetch_olivetti_faces(return_X_y=True)\n\ntrain =data[targets < 30]\ntest = data[targets >= 30]\n\n# Test on a subset of people\nn_faces=5\nrng= check_random_state(4)\nface_ids = rng.randint(test.shape[0], size=(n_faces, ))\ntest = test[face_ids, :]\n\nn_pixels = data.shape[1]\n#上半部臉\nX_train = train[:, :(n_pixels+1)//2]\n#下半部臉\ny_train =train[:, n_pixels//2:]\nX_test = test[:, :(n_pixels+1)//2]\ny_test= test[:, n_pixels//2:]\n\n#fit estimators\nESTIMATORS={\n \"Extra trees\":ExtraTreesRegressor(n_estimators=10, max_features=32,\n random_state=0 ),\n \"Knn\":KNeighborsRegressor(),\n \"Linear regression\": LinearRegression(),\n \"Ridge\": RidgeCV(),\n #額外regression\n \"Decision tree\" : DecisionTreeRegressor(max_depth=10, random_state=0),\n}\ny_test_predict = dict()\nfor name, estimator in ESTIMATORS.items():\n estimator.fit(X_train, y_train)\n y_test_predict[name] =estimator.predict(X_test)\n\n#繪製完整臉譜\n\nimage_shape=(64,64)\n\nn_cols = 1 + len(ESTIMATORS)\nplt.figure(figsize=(2. * n_cols, 2.26 * n_faces))\nplt.suptitle('Face completion with multi-output estimators', size=12)\n\nfor i in range(n_faces):\n true_face= np.hstack((X_test[i], y_test[i]))\n if i:\n sub= plt.subplot(n_faces, n_cols, i * n_cols +1)\n else:\n sub= plt.subplot(n_faces, n_cols, i * n_cols +1, title='True face')\n \n sub.axis('off')\n sub.imshow(true_face.reshape(image_shape), cmap=plt.cm.gray, interpolation='nearest')\n \n for j, esti in enumerate(sorted(ESTIMATORS)):\n completed_face= np.hstack((X_test[i], y_test_predict[esti][i]))\n if i:\n sub= plt.subplot(n_faces, n_cols, i* n_cols+2+j)\n else:\n sub = plt.subplot(n_faces, n_cols, i * n_cols + 2 + j, title=esti)\n \n sub.axis('off')\n sub.imshow(completed_face.reshape(image_shape),cmap=plt.cm.gray, interpolation='nearest')\n\nplt.show()\n\n","sub_path":"_build/jupyter_execute/multioutput_face_completion.py","file_name":"multioutput_face_completion.py","file_ext":"py","file_size_in_byte":2586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"226887480","text":"# String Lists\n# Alexander Fraser\n# 28 Febuary 2020\n\n\"\"\"\nAsk the user for a string and print out whether this string\nis a palindrome or not. (A palindrome is a string that reads\nthe same forwards and backwards.)\n\"\"\"\n\n\ndef collect_input():\n # Get the input from the user.\n input_string = input(\"Input a string (possibly a palindrome): \")\n return input_string\n\n\ndef test_for_palindrome(input_string):\n # Check whether the string is a palindrome by going through\n # every character in the string.\n palindrome_test = True\n\n for counter in range(0, len(input_string)):\n if input_string[counter] != input_string[len(input_string) - 1 - counter]:\n palindrome_test = False\n\n if palindrome_test == True:\n print(\"That's a palindrome!\")\n else:\n print(\"That's nothing.\")\n\n\ndef main():\n input_string = collect_input()\n test_for_palindrome(input_string)\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"Python_009_String_Lists.py","file_name":"Python_009_String_Lists.py","file_ext":"py","file_size_in_byte":944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"154758705","text":"import logging\nfrom functools import wraps\nfrom threading import local\n\nfrom pyes import exceptions\nfrom pyes.es import thrift_enable\n\nimport elasticutils\nfrom elasticutils import F, InvalidFieldActionError\n\ntry:\n from django.conf import settings\nexcept ImportError:\n pass\n\ntry:\n from statsd import statsd\nexcept ImportError:\n statsd = None\n\n\nlog = logging.getLogger('elasticutils')\n\n\n_local = local()\n_local.disabled = {}\n\n\ndef get_es(**overrides):\n \"\"\"Return an ES object using settings from settings.py\n\n :arg overrides: Allows you to override defaults to create the ES.\n\n Things you can override:\n\n * default_indexes\n * timeout\n * dump_curl\n\n Values for these correspond with the arguments to pyes.es.ES.\n\n For example, if you wanted to create an ES for indexing with a timeout\n of 30 seconds, you'd do:\n\n >>> from elasticutils.contrib.django import get_es\n >>> es = get_es(timeout=30)\n\n If you wanted to create an ES for debugging that dumps curl\n commands to stdout, you could do:\n\n >>> class CurlDumper(object):\n ... def write(self, s):\n ... print s\n ...\n >>> from elasticutils.contrib.django import get_es\n >>> es = get_es(dump_curl=CurlDumper())\n \"\"\"\n if overrides or not hasattr(_local, 'es'):\n defaults = {\n 'default_indexes': [settings.ES_INDEXES['default']],\n 'timeout': getattr(settings, 'ES_TIMEOUT', 5),\n 'dump_curl': getattr(settings, 'ES_DUMP_CURL', False)\n }\n\n defaults.update(overrides)\n if (not thrift_enable and\n not settings.ES_HOSTS[0].split(':')[1].startswith('92')):\n raise ValueError('ES_HOSTS is not set to a valid port starting '\n 'with 9200-9299 range. Other ports are valid '\n 'if using pythrift.')\n es = elasticutils.get_es(settings.ES_HOSTS, **defaults)\n\n # Cache the es if there weren't any overrides.\n if not overrides:\n _local.es = es\n else:\n es = _local.es\n\n return es\n\n\ndef es_required(f):\n @wraps(f)\n def wrapper(*args, **kw):\n if settings.ES_DISABLED:\n # Log once.\n if f.__name__ not in _local.disabled:\n log.debug('Search disabled for %s.' % f)\n _local.disabled[f.__name__] = 1\n return\n\n return f(*args, es=get_es(), **kw)\n return wrapper\n\n\ndef es_required_or_50x(disabled_msg, error_msg):\n \"\"\"\n This takes a Django view that requires ElasticSearch.\n\n If `ES_DISABLED` is `True` then we raise a 501 Not Implemented and display\n the disabled_msg. If we try the view and an ElasticSearch exception is\n raised we raise a 503 error with the error_msg.\n\n We use user-supplied templates in elasticutils/501.html and\n elasticutils/503.html.\n \"\"\"\n def wrap(f):\n @wraps(f)\n def wrapper(request, *args, **kw):\n from django.shortcuts import render\n if settings.ES_DISABLED:\n response = render(request, 'elasticutils/501.html',\n {'msg': disabled_msg})\n response.status_code = 501\n return response\n else:\n try:\n return f(request, *args, **kw)\n except exceptions.ElasticSearchException as error:\n response = render(request, 'elasticutils/503.html',\n {'msg': error_msg, 'error': error})\n response.status_code = 503\n return response\n\n return wrapper\n\n return wrap\n\n\nclass S(elasticutils.S):\n \"\"\"S that's more Django-focused\n\n * uses an ES that's based on settings\n * if statsd is installed, calls statsd.timing with how long\n it took to do the query\n\n \"\"\"\n def __init__(self, mapping_type):\n \"\"\"Create and return an S.\n\n :arg mapping_type: class; the mapping type that this S is based on\n\n .. Note::\n\n The :class: `elasticutils.S` doesn't require the\n `mapping_type` argument, but the\n :class:`elasticutils.contrib.django.S` does.\n\n \"\"\"\n return super(S, self).__init__(mapping_type)\n\n def raw(self):\n hits = super(S, self).raw()\n if statsd:\n statsd.timing('search', hits['took'])\n return hits\n\n def get_es(self, default_builder=None):\n # Override the default_builder with the Django one\n return super(S, self).get_es(default_builder=get_es)\n\n def get_indexes(self, default_indexes=None):\n doctype = self.type.get_mapping_type_name()\n indexes = (settings.ES_INDEXES.get(doctype) or\n settings.ES_INDEXES['default'])\n return super(S, self).get_indexes(default_indexes=indexes)\n\n def get_doctypes(self, default_doctypes=None):\n doctype = self.type.get_mapping_type_name()\n return super(S, self).get_doctypes(default_doctypes=doctype)\n","sub_path":"elasticutils/contrib/django/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":5008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"78078859","text":"import pandas as pd\r\nimport numpy as np\r\n\r\nfrom sklearn.linear_model import LogisticRegression\r\n\r\ndef reg(features, Y_train, t_size):\r\n x_train, x_val, y_train, y_val = train_test_split(features, Y_train, test_size=t_size, random_state=0)\r\n logreg = LogisticRegression()\r\n logreg.fit(x_train,y_train)\r\n print(logreg.score(x_val,y_val))\r\n#%%\r\nfrom sklearn.neural_network import MLPClassifier\r\ndef mlp(features, Y_train, t_size):\r\n x_train, x_val, y_train, y_val = train_test_split(features, Y_train, test_size=t_size, random_state=0)\r\n mlp = MLPClassifier()\r\n mlp.fit(x_train,y_train)\r\n print(mlp.score(x_val,y_val))\r\n\r\n#%%\r\nfrom sklearn.naive_bayes import MultinomialNB\r\ndef nb(features, Y_train, t_size):\r\n x_train, x_val, y_train, y_val = train_test_split(features, Y_train, test_size=t_size, random_state=0)\r\n nb = MultinomialNB\r\n nb.fit(x_train,y_train)\r\n print(nb.score(x_val,y_val))\r\n\t\r\ntrain = pd.read_csv('dataset_portion.csv', sep=',')\r\nX_train = train.Text\r\ny_train = train.Score\r\n","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1027,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"423982606","text":"from flask import Flask, Blueprint, jsonify\nimport mysql.connector as mydb\n\nbp_wheather = Blueprint(\"wheather\", __name__, url_prefix=\"\")\n\ncredentials = {\n \"host\": \"localhost\",\n \"user\": \"root\",\n \"database\": \"REACT_REDUX_FLASK_NOTES\",\n \"password\": \"Wagvl1chorchana123\"\n}\n\n@bp_wheather.route(\"/wheather\")\ndef wheather():\n \n send_data = []\n conn = mydb.connect(**credentials)\n cursor = conn.cursor()\n\n cursor.execute(\"SELECT * from wheather\")\n\n data = cursor.fetchall()\n for i in data:\n\n obj_data = {\n \"city\": i[0],\n \"temp\": i[1],\n \"time\": i[2],\n \"sky\": i[3],\n \"id\": i[4]\n }\n send_data.append(obj_data)\n conn.close()\n\n \n return jsonify(send_data)\n\n","sub_path":"wheather_rout/w_rout.py","file_name":"w_rout.py","file_ext":"py","file_size_in_byte":761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"603187673","text":"\"\"\"给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。\n\n给定 nums = [2, 7, 11, 15], target = 9\n\n因为 nums[0] + nums[1] = 2 + 7 = 9\n所以返回 [0, 1]\"\"\"\n\ndef main():\n\tnums = [2, 7, 11, 15]\n\ttarget = 9\n\tresultList = []\n\temptyList = []\n\tlength = len(nums)\n\tfor num_out in nums:\n\t\tfor num_in in nums:\n\t\t\tif target == num_out + num_in:\n\t\t\t\tfirstNum = nums.index(num_out)\n\t\t\t\tsecondNum = nums.index(num_in)\n\t\temptyList.append(firstNum)\t\t\n\t\temptyList.append(secondNum)\t\n\t\t\n\n\tfor items in emptyList:\n\t\tif items not in resultList:\n\t\t\tresultList.append(items)\n\n\tprint(resultList)\n\n\nif __name__ == '__main__':\n\tmain()\n","sub_path":"第一题/firstQuestion.py","file_name":"firstQuestion.py","file_ext":"py","file_size_in_byte":718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"150556615","text":"from .pausa import MenuPausa\r\nfrom .equipo import MenuEquipo\r\nfrom .opciones import MenuOpciones\r\nfrom .cargar import MenuCargar\r\nfrom .principal import MenuPrincipal\r\nfrom .menu import Menu\r\nfrom .model import MenuModel\r\nfrom .name import MenuName\r\nfrom .ability import MenuAbility\r\n\r\ndefault_menus = {'MenuPausa': MenuPausa,\r\n 'MenuEquipo': MenuEquipo,\r\n 'MenuCargar': MenuCargar,\r\n 'MenuPrincipal': MenuPrincipal,\r\n 'MenuOpciones': MenuOpciones,\r\n 'MenuNuevo': MenuModel, # en realidad sería MenuModel,\r\n 'MenuName': MenuName, # pero está así para que diga \"nuevo\" en Principal.\r\n 'MenuAbility': MenuAbility # No es el verdadero (y viejo) \"MenuNuevo\".\r\n }\r\n\r\n# estructuras para los menues raiz Principal y Pausa.\r\n# No son lo más \"automático\" que se puede hacer,\r\n# pero son lo más aproximado y menos explicito que se me ocurre.\r\n\r\n# Botones del Menú Pausa\r\npause_menus = [\r\n 'MenuEquipo',\r\n 'MenuOpciones',\r\n 'MenuCargar'\r\n]\r\n\r\n# Botones del Menú Principal\r\ninital_menus = [\r\n 'MenuNuevo',\r\n 'MenuCargar',\r\n 'MenuOpciones',\r\n]\r\n\r\n__all__ = [\r\n 'Menu',\r\n \"default_menus\",\r\n 'pause_menus',\r\n 'inital_menus'\r\n]\r\n","sub_path":"engine/UI/menues/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"447722223","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport sys\nimport unittest\n\nsys.path.append('../../')\nfrom csj.prepare_path import Prepare\nfrom csj.labels.character import read_sdb\nfrom utils.measure_time_func import measure_time\n\nprep = Prepare(data_path='/n/sd8/inaguma/corpus/csj/data',\n run_root_path=os.path.abspath('../'))\n\nlabel_paths = {\n 'train_fullset': prep.trans(data_type='train_fullset'),\n 'train_subset': prep.trans(data_type='train_subset'),\n 'dev': prep.trans(data_type='dev'),\n 'eval1': prep.trans(data_type='eval1'),\n 'eval2': prep.trans(data_type='eval2'),\n 'eval3': prep.trans(data_type='eval3')\n}\n\n\nclass TestEnd2EndLabel(unittest.TestCase):\n\n def test(self):\n\n # CTC\n self.check_reading(model='ctc', divide_by_space=True)\n self.check_reading(model='ctc', divide_by_space=False)\n\n # Attention\n self.check_reading(model='attention', divide_by_space=True)\n self.check_reading(model='attention', divide_by_space=False)\n\n @measure_time\n def check_reading(self, model, divide_by_space):\n\n print('==================================================')\n print(' model: %s' % model)\n print(' divide_by_space: %s' % str(divide_by_space))\n print('==================================================')\n\n print('---------- train_fullset ----------')\n read_sdb(label_paths=label_paths['train_fullset'],\n run_root_path=prep.run_root_path,\n model=model,\n save_map_file=True,\n divide_by_space=divide_by_space,\n stdout_transcript=False)\n\n for data_type in ['train_subset', 'dev', 'eval1', 'eval2', 'eval3']:\n print('---------- %s ----------' % data_type)\n read_sdb(label_paths=label_paths[data_type],\n run_root_path=prep.run_root_path,\n model=model,\n divide_by_space=divide_by_space)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"csj/test/test_label_end2end.py","file_name":"test_label_end2end.py","file_ext":"py","file_size_in_byte":2151,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"605365561","text":"import functools\nfrom PyQt4 import QtGui, QtCore\n\nfrom cell_compare.core.gui.ui.cell_control import Ui_cell_control\nfrom cell_compare.core.gui.workbook_control import WorkbookControl\n\n\nclass CellControl(QtGui.QWidget, Ui_cell_control):\n\n remove_cell_control_signal = QtCore.pyqtSignal(object)\n\n def __init__(self, n_workbooks=2):\n super(CellControl, self).__init__()\n self.setupUi(self)\n\n self._n_workbooks = n_workbooks\n self._workbook_controls = []\n self._add_starting_workbook_controls()\n\n self._create_conext_menu()\n\n def _create_conext_menu(self):\n self.custom_name_frame.customContextMenuRequested.connect(self._on_context_menu)\n self.popMenu = QtGui.QMenu(self)\n self.popMenu.addAction('delete compare block', self.remove_cell_control_pressed)\n\n def _on_context_menu(self, point):\n self.popMenu.exec_(self.custom_name_frame.mapToGlobal(point))\n\n def _add_starting_workbook_controls(self):\n for i in range(0, self._n_workbooks):\n self.add_workbook_control(WorkbookControl)\n\n def _add_ordered_workbook_controls(self):\n for wbc in self._workbook_controls or []:\n self.contols_verticalLayout.addWidget(wbc)\n\n def remove_cell_control_pressed(self):\n self.remove_cell_control_signal.emit(self)\n\n def _get_wbc_index(self, wbc):\n \"\"\"\n gets index our workbook control object is at in the vertical layout\n\n :param wbc: pass a workbook control object\n :type wbc: WorkbookControl\n :return: index\n :rtype: int\n \"\"\"\n index = 0\n for i, control in enumerate(self._workbook_controls):\n if control == wbc:\n index = i\n return index\n\n def add_workbook_control(self, workbook_control):\n \"\"\"\n :param workbook_control: pass a workbook control object\n :type workbook_control: WorkbookControl\n :return:\n :rtype: None\n \"\"\"\n wbc = WorkbookControl()\n wbc.add_workbook_signal.connect(self.add_workbook_control)\n wbc.remove_workbook_signal.connect(self.remove_workbook_control)\n wbc.compare_cell_values_signal.connect(self.compare_cell_values)\n wbc_index = self._get_wbc_index(workbook_control)\n self._workbook_controls.insert(wbc_index + 1, wbc) # +1 to insert after index\n self._add_ordered_workbook_controls()\n self.disable_remove_workbook_button()\n\n def remove_workbook_control(self, workbook_control):\n \"\"\"\n :param workbook_control: pass a workbook control object\n :type workbook_control: WorkbookControl\n :return:\n :rtype: None\n \"\"\"\n self._workbook_controls.remove(workbook_control)\n workbook_control.setParent(None)\n self.disable_remove_workbook_button()\n\n def get_workbook_controls(self):\n return [self.contols_verticalLayout.itemAt(i) for i in range(self.contols_verticalLayout.count())]\n\n def disable_remove_workbook_button(self):\n disable = False\n if len(self._workbook_controls) > 2:\n disable = True\n\n for control in self._workbook_controls:\n control.remove_workbook_control.setEnabled(disable)\n\n def compare_cell_values(self):\n \"\"\"\n Compare cell values from our QLabel and sets icons accordingly for our cell control\n :rtype: None\n \"\"\"\n comparable_values = []\n for workbook in self._workbook_controls:\n if workbook.workbook: # check if workbook control has workbook loaded\n comparable_values.append(str(workbook.cell_value.text()))\n\n if len(comparable_values) >= 2:\n self.cell_match_icon.setPixmap(QtGui.QPixmap(\"../icons/cancel.png\"))\n if comparable_values[1:] == comparable_values[:-1]: # compare items in list\n self.cell_match_icon.setPixmap(QtGui.QPixmap(\"../icons/accept_button.png\"))\n else:\n self.cell_match_icon.setPixmap(QtGui.QPixmap(\"../icons/ask_and_answer.png\"))","sub_path":"python/cell_compare/core/gui/cell_control.py","file_name":"cell_control.py","file_ext":"py","file_size_in_byte":4056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"393293594","text":"from enum import Enum, unique\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.core.exceptions import ValidationError\n\n\n@unique\nclass CategoryType(Enum):\n FOR_FACE = 0\n FOR_LIPS = 1\n FOR_HANDS = 2\n FOR_HAIR = 3\n FOR_BODY = 4\n FOR_MEN = 5\n WELLNESS = 6\n\n\n# Convert enum to django choises with translation\nCATEGORY_TYPE_CHOISES = (\n (CategoryType.FOR_FACE.value, _('Для обличча')),\n (CategoryType.FOR_LIPS.value, _('Для губ')),\n (CategoryType.FOR_HANDS.value, _('Для рук')),\n (CategoryType.FOR_HAIR.value, _('Для волосся')),\n (CategoryType.FOR_BODY.value, _('Для тіла')),\n (CategoryType.FOR_MEN.value, _('Чоловікам')),\n (CategoryType.WELLNESS.value, _('Здоров\\'я')),\n )\n\n\ndef validate_category_type(value):\n if value not in [item.value for item in CategoryType]:\n raise ValidationError(\n _('Invalid CategoryType'),\n params={'value': value},\n )\n","sub_path":"common/consts/category_type.py","file_name":"category_type.py","file_ext":"py","file_size_in_byte":1028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"488791057","text":"'''\n네이버 웹툰 크롤러/데이터 스터디/조유신\n\n루트 URL : https://comic.naver.com\n웹툰 페이지 : /webtoon/detail.nhn?titleId={웹툰 ID}&no={페이지 넘버}\n덧글 페이지 : /comment/comment.nhn?titleId={웹툰 ID}&no={페이지 넘버}\n'''\nimport time\n\nfrom selenium import webdriver\n\nfrom lib import MySqlDB\nfrom lib import NWebtoonCrawler\n\nDB = MySqlDB.MySqlDB()\nCrawler = NWebtoonCrawler.NWebtoonCrawler()\n\nwebtoons = DB.getWebtoonData()\n\nfor webtoon in webtoons:\n\n WEBTOON_ID = webtoon[0]\n\n for page in range(1, webtoon[1]+1, 1) :\n page_data = Crawler.getPageData( WEBTOON_ID, page )\n\n page_id = DB.insertToPages(\n webtoon_id=WEBTOON_ID,\n page_num=int(page),\n page_title=page_data['title'],\n page_score=page_data['rank_point']\n )\n\n page_id = page_id[0]\n\n commnets_data = Crawler.getCommentsData( WEBTOON_ID, page )\n\n for comment in commnets_data:\n DB.insertToComments(\n webtoon_id=WEBTOON_ID,\n page_id=page_id,\n nick=comment['nick'],\n id=comment['nid'],\n content=comment['content'],\n created=comment['created'],\n like=comment['like'],\n unlike=comment['unlike']\n )\n","sub_path":"src/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":1328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"546781354","text":"#!/usr/bin/env python3\n\"\"\"\n setup the rss_miner sqlite3 database for first use. \n \n depends on schema.sql\n\n\"\"\"\nimport sqlite3\nimport sys\n\n\ndef main():\n setup_database('test_rss_database.sqlite', 'schema.sql')\n\n\ndef setup_database(database='my_news_data.sqlite', schemafile='schema.sql'):\n \"\"\" \n setup the sqlite database file for the first time. Use a predefined\n schema file, and init the database using this schema.\n \n \"\"\"\n try:\n conn = sqlite3.connect(database)\n sql = open(schemafile,'r').read()\n conn.executescript(sql)\n conn.commit()\n conn.close\n except Exception as oops:\n print ('config_database.py: database: %s, schema: %s\\nerror: %s' % (database, schemafile, oops))\n sys.exit(1)\n return True\n\n\nif __name__ == '__main__':\n main()","sub_path":"lib/config_database.py","file_name":"config_database.py","file_ext":"py","file_size_in_byte":834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"223854603","text":"#!/usr/bin/env python\n\n# Copyright (c) 2012, Marco Elver\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met:\n#\n# * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n#\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\n# distribution.\n#\n# * Neither the name of the software nor the names of its contributors\n# may be used to endorse or promote products derived from this\n# software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (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\n##\n# @file remind-repetitive.py\n# Script to remind myself of repetitive daily tasks. Unlike remind reminders,\n# this one is on-demand.\n#\n# This script is compatible with Python 2.6 or later (initially written for Python 3).\n# This introduced some limitations:\n# - argparse functionality only available with Python 2.7 or later\n# - String formatting with format(..) requires use of explicit field names, as\n# \"{}\" is only available since Python 2.7.\n#\n# @author Marco Elver \n# @date Sat Dec 3 15:02:14 GMT 2011\n#\n\nimport sys\nimport time\nimport datetime\nimport subprocess\nimport math\nimport os\nimport json\nimport pickle\n\nWEEK_DAYS = { \"Mon\" : 0, \"Tue\" : 1, \"Wed\" : 2, \"Thu\" : 3, \"Fri\" : 4,\n \"Sat\" : 5, \"Sun\" : 6 }\n\n# Argparse is only available from Python >= 2.7\ntry:\n import argparse\nexcept:\n argparse = None\n\n# For android message backend\ntry:\n import android\nexcept:\n android = None\n\ndef first_weekday_on_or_after(weekday, dt):\n days_to_go = weekday - dt.weekday()\n if days_to_go > 0:\n dt += datetime.timedelta(days=days_to_go)\n elif days_to_go < 0:\n dt += datetime.timedelta(days=days_to_go+7)\n return dt\n\ndef get_start_time(time_str):\n if time_str is None: return time.time()\n\n try:\n if time_str.startswith(\"+\"):\n # Start-time is relative, in minutes\n # Allowed formats: \"+MM\"\n time_offset = int(time_str[1:].strip()) * 60 # minutes -> seconds\n start_time = time.time() + time_offset\n elif \"%\" in time_str:\n # Time with interval\n # Allowed formats: \"seconds_since_epoch%seconds\", \"YYYY-MM-DDTHH:MM%MM\"\n time_str_args = time_str.strip().split(\"%\")\n if \"T\" in time_str_args[0]:\n time_base = time.mktime(datetime.datetime.strptime(time_str_args[0],\n \"%Y-%m-%dT%H:%M\").timetuple())\n time_interval = int(time_str_args[1]) * 60 # minutes -> seconds\n else:\n time_base = int(time_str_args[0]) # time in seconds since Epoch\n time_interval = int(time_str_args[1]) # seconds\n\n if time.time() < time_base:\n start_time = time_base\n else:\n start_time = time_base + math.ceil((time.time() - time_base) / time_interval) * time_interval\n else:\n # Time today/weekday\n # Allowed formats: \"HH:MM\", \"Day,HH:MM\"\n time_str_args = time_str.strip().split(\",\")\n\n dt_start_time_components = datetime.datetime.strptime(time_str_args[-1], \"%H:%M\") # provide localtime\n dt_start_time = datetime.datetime.now().replace( # localtime\n minute=dt_start_time_components.minute,\n hour=dt_start_time_components.hour,\n second=00\n )\n\n if len(time_str_args) > 1 and time_str_args[0] in WEEK_DAYS:\n dt_start_time = first_weekday_on_or_after(\n WEEK_DAYS[time_str_args[0]], dt_start_time)\n\n start_time = time.mktime(dt_start_time.timetuple()) # Takes localtime, not UTC\n except ValueError as e:\n print(\"[WARNING] '{0}' is not a valid time! [{1}]\".format(time_str, e))\n start_time = time.time()\n\n return start_time\n\nclass MessageBackend:\n TIMEOUT_NORMAL = 20\n TIMEOUT_CRITICAL = 60\n\n class MessageBackendImpl:\n @classmethod\n def stdout(cls, title, message, timeout_sec, args=None):\n print(\"[{0}] {1}\".format(title, message))\n return None\n\n @classmethod\n def gxmessage(cls, title, message, timeout_sec, args=None):\n cls.stdout(title, message, timeout_sec)\n _args = [\"gxmessage\", \"-center\"]\n if args: _args += args\n _args += [\"-title\", title, message]\n return subprocess.Popen(_args)\n\n @classmethod\n def libnotify(cls, title, message, timeout_sec, args=None):\n cls.stdout(title, message, timeout_sec)\n\n if timeout_sec == 0:\n timeout_sec = MessageBackend.TIMEOUT_NORMAL # my default\n\n if timeout_sec >= MessageBackend.TIMEOUT_CRITICAL:\n urgency = \"critical\"\n else:\n urgency = \"normal\"\n\n return subprocess.Popen([\"notify-send\",\n \"--expire-time={0}\".format(timeout_sec*1000),\n \"--urgency={0}\".format(urgency),\n title, message])\n\n @classmethod\n def android(cls, title, message, timeout_sec, args=None):\n try:\n getattr(cls, \"droid\")\n except AttributeError:\n cls.droid = android.Android()\n\n cls.droid.notify(title, message)\n cls.droid.makeToast(message)\n cls.droid.vibrate(1000)\n\n if cls.droid.getRingerVolume().result != 0 and \\\n not cls.droid.checkRingerSilentMode().result:\n for ext in [\"m4a\", \"mp3\", \"wav\", \"ogg\"]:\n if cls.droid.mediaPlay(\n \"/sdcard/remind-repetitive.{0}\".format(ext)).result:\n break\n\n return None\n\n @classmethod\n def command(cls, title, message, timeout_sec, args=None):\n if not args:\n raise Exception(\"The 'command' MessageBackend requires arguments: \")\n\n subprocess.call(\n args[0].format(title=title, message=message, timeout_sec=timeout_sec),\n shell=True)\n\n return None\n\n BACKENDS = {\n 'stdout' : MessageBackendImpl.stdout,\n 'gxmessage' : MessageBackendImpl.gxmessage,\n 'libnotify' : MessageBackendImpl.libnotify,\n 'android' : MessageBackendImpl.android,\n 'command' : MessageBackendImpl.command\n }\n\n def __init__(self, backend='stdout', args=[]):\n self.set_backend(backend, args)\n\n def set_backend(self, backend, args=[]):\n if backend in MessageBackend.BACKENDS:\n self.backend = backend\n self.args = args\n else:\n print(\"[WARNING] '{0}' not a valid choice!\".format(backend))\n\n def display_message(self, title, message, timeout_sec=0):\n return MessageBackend.BACKENDS[self.backend](title, message,\n timeout_sec, self.args)\n\n @classmethod\n def get_backends(cls):\n return cls.BACKENDS.keys()\n\nmessage_backend = MessageBackend()\n\nclass RepetitiveTask:\n def __init__(self, name, message, message_missed, frequency_mins=0,\n start_time=time.time(), message_timeout_sec=0):\n self.name = name\n self.message = message\n self.message_missed = message_missed\n self.set_frequency(frequency_mins)\n self.set_start_time(start_time)\n self.message_timeout_sec = message_timeout_sec\n\n self.last_proc = None\n self.missed = 0\n\n def __str__(self):\n result = []\n # Show only if enabled\n if self.frequency_mins != 0:\n result.append(\"[{0}] Next event scheduled for: {1}\".format(self.name,\n time.strftime(\"%a %b %d %H:%M:%S %Z %Y\", time.localtime(self.next_event))))\n\n if self.frequency_mins != 0:\n result.append(\"[{0}] Message frequency is {1} minutes.\".format(self.name, self.frequency_mins))\n\n return \"\\n\".join(result)\n\n def set_frequency(self, frequency_mins):\n self.frequency_mins = frequency_mins\n\n def get_frequency_sec(self):\n return self.frequency_mins * 60\n\n def set_start_time(self, epoch_sec):\n self.next_event = epoch_sec\n\n def display_message(self, display_time, missed):\n return message_backend.display_message(\n \"{0} -- {1}\".format(\n time.strftime(\"%a %b %d %H:%M:%S %Z %Y\", time.localtime(display_time)),\n self.name),\n missed > 0 and self.message_missed.format(missed) or self.message,\n timeout_sec=self.message_timeout_sec)\n\n def poll_check(self):\n if self.frequency_mins == 0: return\n\n if self.next_event < time.time():\n if self.next_event == 0:\n last_event = time.time()\n self.next_event = last_event + self.get_frequency_sec()\n else:\n last_event = self.next_event\n missed_count = int(math.floor(\n (time.time() - self.next_event)/ \\\n self.get_frequency_sec()\n ))\n self.next_event += self.get_frequency_sec() * (missed_count + 1)\n\n # This is to display number of missed events right after\n # startup.\n if self.last_proc is None and missed_count > 0:\n self.missed = missed_count\n\n # last_proc should only be None after startup\n if self.last_proc is None or self.last_proc.poll() is not None:\n # last process completed\n self.last_proc = self.display_message(last_event, self.missed)\n\n if self.missed > 0:\n print(\"[{0}] Resetting missed count.\".format(self.name))\n self.missed = 0\n else:\n # Message process still open, increment missed\n self.missed += 1\n print(\"[{0}] Skipped one, due to unclosed message [missed: {1}]\".format(self.name, self.missed))\n\n # clean up\n if self.last_proc is not None:\n self.last_proc.poll() # result still available if queried again\n\ndef get_args_cmdline(argv):\n parser = argparse.ArgumentParser(\n description=\"Repetitive Task Reminder: Helps you keep track of repetitive tasks throughout the day\")\n parser.add_argument(\"-b\", \"--backend\", metavar=\"BE\", type=str,\n dest=\"backend\", default=\"libnotify\",\n help=\"Method to display messages. [Default: libnotify | Available: {0}]\".format(\n \", \".join(MessageBackend.get_backends())))\n parser.add_argument(\"--backend-args\", metavar=\"ARG\", type=str,\n dest=\"backend_args\", default=[], nargs=\"+\",\n help=\"Arguments passed to backend.\")\n parser.add_argument(\"-t\", \"--start-time\", metavar=\"TIME\", type=str,\n dest=\"start_time\", default=None,\n help=\"Common starting time, in format HH:MM or relative +MM. [Default: None]\")\n parser.add_argument(\"-s\", \"--snapshot-file\", metavar=\"FILE\", type=str,\n dest=\"snapshot_file\", default=None,\n help=\"Snapshot file to periodically save the reminder states.\")\n parser.add_argument(\"--snapshot-freq\", metavar=\"MINS\", type=int,\n dest=\"snapshot_freq\", default=30,\n help=\"Snapshot frequency. [Default: 30]\")\n\n parser.add_argument(\"-T\", \"--tasks\", metavar=\"TASK\", type=str,\n dest=\"tasks\", default=[], nargs=\"+\",\n help=\"Custom task reminders, in format: ;[;[;]]\")\n\n # Alternative way to specify task reminders\n parser.add_argument(\"--tasks-comment\", metavar=\"COMMENT\", type=str,\n dest=\"tasks_comment\", default=[], nargs=\"+\",\n help=\"Comment for task reminders. (Alternative way to specify tasks.)\")\n parser.add_argument(\"--tasks-freq\", metavar=\"MINS\", type=int,\n dest=\"tasks_freq\", default=[], nargs=\"+\",\n help=\"Frequency of messages in mins, specified in same order as comments.\")\n parser.add_argument(\"--tasks-start-time\", metavar=\"TIME\", type=str,\n dest=\"tasks_start_time\", default=[], nargs=\"+\",\n help=\"Starting time for task reminders in format HH:MM or relative +MM, specified in same order as comments.\")\n parser.add_argument(\"--tasks-timeout\", metavar=\"TIME\", type=int,\n dest=\"tasks_timeout\", default=[], nargs=\"+\",\n help=\"Timeout for task reminders in seconds, specified in same order as comments.\")\n\n args = parser.parse_args()\n\n return args\n\ndef get_args_json(argv):\n class DefaultArgs:\n def __init__(self, entries={}):\n if android is not None:\n self.backend = \"android\"\n else:\n self.backend = \"libnotify\"\n\n self.backend_args = []\n self.start_time = None\n self.snapshot_file = None\n self.snapshot_freq = 30\n self.tasks = []\n self.tasks_comment = []\n self.tasks_freq = []\n self.tasks_start_time = []\n self.tasks_timeout = []\n\n self.__dict__.update(entries)\n\n # Perform type conversions after updating entries\n\n for i in range(len(self.tasks_freq)):\n self.tasks_freq[i] = int(self.tasks_freq[i])\n\n for i in range(len(self.tasks_timeout)):\n self.tasks_timeout[i] = int(self.tasks_timeout[i])\n\n try:\n if android is not None:\n jsonfile = open(\"/sdcard/remind-repetitive.json\")\n else:\n jsonfile = sys.stdin if argv[1] == \"-\" else open(argv[1])\n except Exception as e:\n print(e)\n return DefaultArgs()\n\n try:\n # Fast flexible string concatenation => make generator of strings and join.\n # Read lines and discard comments (// and # works).\n line_gen = (line for line in jsonfile if not (\n line.startswith(\"//\") or line.startswith(\"#\")))\n\n jsonargs = json.loads(''.join(line_gen))\n finally:\n jsonfile.close()\n\n return DefaultArgs(jsonargs)\n\ndef main(argv):\n if argparse is not None and android is None and \\\n (len(argv) <= 1 or (len(argv[1]) > 1 and argv[1][0] == \"-\")):\n args = get_args_cmdline(argv)\n else:\n args = get_args_json(argv)\n\n message_backend.set_backend(args.backend, args.backend_args)\n\n # Check if snapshot path is valid\n if args.snapshot_file is not None:\n snapshot_file_dirname = os.path.dirname(args.snapshot_file)\n if len(snapshot_file_dirname) != 0 and not os.path.isdir(snapshot_file_dirname):\n print(\"[WARNING] Not a valid path: {0}\".format(args.snapshot_file))\n args.snapshot_file = None\n\n if args.snapshot_file is not None and os.path.exists(args.snapshot_file):\n print(\"[INFO] Loading snapshot from: {0}\".format(args.snapshot_file))\n with open(args.snapshot_file, 'rb') as sf:\n all_tasks = pickle.load(sf)\n\n # Fix stale data\n for task in all_tasks:\n task.last_proc = None\n else:\n print(\"[INFO] Loading from config\")\n common_start_time = get_start_time(args.start_time)\n all_tasks = []\n\n def append_task(task_comment, **task_kwargs):\n task_comment = task_comment.split(\":\")\n task_name = task_comment[0]\n task_message = task_comment[1] if len(task_comment) > 1 else task_comment[0]\n all_tasks.append(\n RepetitiveTask(\n task_name,\n task_message,\n \"{0} You also missed {{0}} times.\".format(task_message),\n **task_kwargs\n )\n )\n\n for i in range(len(args.tasks)):\n task_kwargs = {}\n task = args.tasks[i].split(\";\")\n\n task_comment = task[0].strip()\n task_kwargs['frequency_mins'] = int(task[1].strip())\n\n if len(task) > 2:\n task_kwargs['start_time'] = get_start_time(task[2].strip())\n else:\n task_kwargs['start_time'] = common_start_time\n\n if len(task) > 3:\n task_kwargs['message_timeout_sec'] = int(task[3].strip())\n else:\n task_kwargs['message_timeout_sec'] = MessageBackend.TIMEOUT_NORMAL\n\n append_task(task_comment, **task_kwargs)\n\n\n for i in range(len(args.tasks_comment)):\n task_kwargs = {}\n\n task_comment = args.tasks_comment[i]\n task_kwargs['frequency_mins'] = args.tasks_freq[i]\n\n if i < len(args.tasks_start_time):\n task_kwargs['start_time'] = get_start_time(args.tasks_start_time[i])\n else:\n task_kwargs['start_time'] = common_start_time\n\n if i < len(args.tasks_timeout):\n task_kwargs['message_timeout_sec'] = args.tasks_timeout[i]\n else:\n task_kwargs['message_timeout_sec'] = MessageBackend.TIMEOUT_NORMAL\n\n append_task(task_comment, **task_kwargs)\n\n # Print info about all tasks\n have_active_tasks = False\n for task in all_tasks:\n if task.get_frequency_sec() > 0:\n print(task)\n have_active_tasks = True\n\n if not have_active_tasks:\n print(\"No active tasks, exiting.\")\n return 42\n\n try:\n last_snapshot = 0\n\n while True:\n for task in all_tasks:\n task.poll_check()\n\n if args.snapshot_file is not None and args.snapshot_freq > 0 \\\n and last_snapshot < time.time() - (args.snapshot_freq * 60):\n # Save snapshot of current state\n last_snapshot = time.time()\n with open(args.snapshot_file, 'wb') as sf:\n pickle.dump(all_tasks, sf)\n print(\"[INFO] Snapshot saved to: {0}\".format(args.snapshot_file))\n\n time.sleep(9)\n\n except KeyboardInterrupt:\n print(\"User interrupt, bye for now.\")\n return 0\n\n except Exception as e:\n print(\"An error occurred: {0}\".format(e))\n return 1\n\nif __name__ == \"__main__\":\n sys.exit(main(sys.argv))\n\n","sub_path":"python/lib/remind-repetitive.py","file_name":"remind-repetitive.py","file_ext":"py","file_size_in_byte":19426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"442139863","text":"# coding: utf-8\n\n\"\"\"\nContain solution for the python/numpy training\n\"\"\"\n\n__authors__ = [\"Pierre Knobel\", \"Jerome Kieffer\", \"Henri Payno\",\n \"Armando Sole\", \"Valentin Valls\", \"Thomas Vincent\"]\n__date__ = \"18/09/2018\"\n__license__ = \"MIT\"\n\n\nimport inspect\n\nimport numpy\n\n\ndef show(exercice_name):\n function = globals()[exercice_name]\n print(inspect.getsource(function))\n return function()\n\n\ndef ex3_1():\n \"\"\" Simple example of an element wise comparaison\"\"\"\n x = numpy.arange(10)\n y = numpy.arange(1, 11)\n\n difference = x - y\n return difference\n\n\ndef ex3_2():\n \"\"\" Simple way to compute the difference x[i+1]-x[i] for all the elements\n of the 1D array\"\"\"\n x = numpy.arange(10)\n\n difference = x[1:] - x[:-1]\n return difference\n\n\ndef ex4_1():\n \"\"\"Generate a 1D array of [1..99] then operate a binning 1 2 3 4 -> 1+2 3+4\n \"\"\"\n data = numpy.arange(100) + 1\n binned = data[::2] + data[1::2]\n return data, binned\n\n\ndef ex4_2():\n \"\"\"Generate a 2D array of [1..9999] then operate a 2x2 binning\n \"\"\"\n data = numpy.arange(10000).reshape(100, 100)\n data = data + 1\n binned = data[::2, ::2] + data[::2, 1::2] + data[1::2, ::2] + data[1::2, 1::2]\n return data, binned\n\n\ndef ex4_2_alt():\n \"\"\"Generate a 2D array of [1..9999] then operate a 2x2 binning using numpy\n sum and moving the array to 4D\n \"\"\"\n height = 100\n width = 100\n data = numpy.arange(10000).reshape(height, width)\n data = data + 1\n reshaped_data = data.reshape(height // 2, 2, width // 2, 2)\n binned = reshaped_data.sum(axis=3).sum(axis=1)\n return data, binned\n\n\ndef ex5_inefficient_fill(height=1000, width=1000):\n \"\"\"Inefficient fill using 2 for loops\"\"\"\n data = numpy.zeros((height, width), dtype=float)\n for row in range(int(height)):\n for col in range(int(width)):\n data[row, col] = numpy.cos(row) * numpy.sin(col)\n return data\n\n\ndef ex5_naive_fill(height=1000, width=1000):\n \"\"\"Fill using 2 for loops but pre-computing sin and cos\"\"\"\n width_sin = numpy.sin(numpy.arange(width))\n height_cos = numpy.cos(numpy.arange(height))\n data = numpy.zeros((height, width), dtype=numpy.float64)\n for row in range(int(height)):\n for col in range(int(width)):\n data[row, col] = height_cos[row] * width_sin[col]\n return data\n\n\ndef ex5_clever_fill(height=1000, width=1000):\n \"\"\"Fill using 2 outer products\"\"\"\n width_sin = numpy.sin(numpy.arange(width))\n height_cos = numpy.cos(numpy.arange(height))\n cos_loop = numpy.outer(height_cos, numpy.ones(width))\n sin_loop = numpy.outer(numpy.ones(height), width_sin)\n return cos_loop * sin_loop\n\n\ndef ex5_practical_fill(height=1000, width=1000):\n \"\"\"Fill using meshgrid\"\"\"\n width_sin = numpy.sin(numpy.arange(width))\n height_cos = numpy.cos(numpy.arange(height))\n sin_loop, cos_loop = numpy.meshgrid(width_sin, height_cos)\n return sin_loop * cos_loop\n\n\ndef ex5_optimized_fill(height=1000, width=1000):\n \"\"\"Fill using outer product\"\"\"\n width_sin = numpy.sin(numpy.arange(width))\n height_cos = numpy.cos(numpy.arange(height))\n return numpy.outer(height_cos, width_sin)\n\n\ndef ex5_atleast_2d_fill(height=1000, width=1000):\n \"\"\"Fill using atleast_2d and transpose\"\"\"\n sine = numpy.sin(numpy.arange(width))\n cosine = numpy.cos(numpy.arange(height))\n return numpy.atleast_2d(sine) * numpy.atleast_2d(cosine).T\n","sub_path":"python/numpy/exercicesolution.py","file_name":"exercicesolution.py","file_ext":"py","file_size_in_byte":3419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"563398761","text":"from tensorflow.examples.tutorials.mnist import input_data\nimport tensorflow as tf\n\n# 读取数据集\nmnist = input_data.read_data_sets(\"MNIST_data\", one_hot=True)\nsess = tf.InteractiveSession()\n\n# 创建初始化权重函数, 为权重制造一些噪声\n# 噪声为正态分布噪声,标准差为0.1\ndef weight_variable(shape):\n initial = tf.truncated_normal(shape, stddev=0.1)\n return tf.Variable(initial)\n# 初始化偏置函数,增加0.1,避免死亡节点\ndef bias_variable(shape):\n initial = tf.constant(0.1, shape=shape)\n return tf.Variable(initial)\n\n# 创建2维卷积核函数\ndef conv2d(x, W):\n return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')\n\n# 创建最大池化函数\ndef max_pool_2x2(x):\n return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')\n\n# 定义输入、输出、x输入的结构\nx = tf.placeholder(tf.float32, [None, 784])\ny = tf.placeholder(tf.float32, [None, 10])\nx_image = tf.reshape(x, [-1, 28, 28, 1])\n\n# 定义第一个卷积层\nw_conv1 = weight_variable([5, 5, 1, 32])\nb_conv1 = bias_variable([32])\n# 卷积操作后使用激活函数relu进行非线性处理\nh_conv1 = tf.nn.relu(conv2d(x_image, w_conv1) + b_conv1)\n# 池化处理\nh_pool1 = max_pool_2x2(h_conv1)\n\n# 定义第二个卷积层\nw_conv2 = weight_variable([5, 5, 32, 64])\nb_conv2 = bias_variable([64])\nh_conv2 = tf.nn.relu(conv2d(h_pool1, w_conv2) + b_conv2)\nh_pool2 = max_pool_2x2(h_conv2)\n\n# 对第二个卷积层输出进行relu处理\nw_fc1 = weight_variable([7 * 7 * 64, 1024])\nb_fc1 = bias_variable([1024])\nh_pool2_flat = tf.reshape(h_pool2, [-1, 7 * 7 * 64])\nh_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, w_fc1) + b_fc1)\n\n# dropout处理\nkeep_prob = tf.placeholder(tf.float32)\nh_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)\n\n# softmax处理\nw_fc2 = weight_variable([1024, 10])\nb_fc2 = bias_variable([10])\ny_conv = tf.nn.softmax(tf.matmul(h_fc1_drop, w_fc2) + b_fc2)\n\n# 损失函数\ny_ = tf.placeholder(tf.float32)\ncross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y_conv), reduction_indices=[1]))\ntrain_step = tf.train.AdagradOptimizer(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\ntf.global_variables_initializer().run()\nfor i in range(10000):\n batch = mnist.train.next_batch(64)\n if i % 100 == 0:\n train_accuracy = accuracy.eval(feed_dict={x: batch[0], y_: batch[1], keep_prob: 1.0})\n print(\"step %d, training accuracy %f\" % (i, train_accuracy))\n train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})\n\nprint(\"test accuracy %f\" % accuracy.eval(feed_dict={x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0}))","sub_path":"4_Simple-CNN.py","file_name":"4_Simple-CNN.py","file_ext":"py","file_size_in_byte":2755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"499406440","text":"#!/usr/bin/env python3\n\nimport io\nimport os\nfrom setuptools import find_packages, setup\n\n# Where are we?\nif 'sandbox' in os.getenv('JUPYTER_IMAGE', default=''):\n IS_DEAFRICA_SANDBOX = True\n\n# What packages are required for this module to be executed?\n# These are all on the Sandbox so shouldn't need installing on those platforms.\nREQUIRED = [\n # load_era5\n 'fsspec'\n 'warnings'\n # classification\n 'numpy',\n 'copy',\n 'time',\n 'multiprocessing',\n 'abc',\n 'xarray',\n 'geopandas',\n 'datacube',\n 'tqdm',\n 'dask',\n 'rasterio',\n 'scikit-learn',\n # coastal\n 'matplotlib',\n 'pandas',\n 'scipy',\n # 'otps', # Hard to install, but available on Sandbox\n # datahandling\n 'GDAL',\n 'odc-ui',\n 'numexpr',\n # plotting\n 'folium',\n 'pyproj',\n 'branca',\n 'shapely',\n 'scikit-image',\n # temporal\n 'hdstats',\n 'packaging'\n # spatial\n 'OWSLib',\n 'osgeo',\n 'fiona',\n 'shapely'\n]\n\n# What packages are optional?\nEXTRAS = {\n 'jupyter': ['IPython', 'ipywidgets', 'ipyleaflet'],\n 'boto': ['boto3'],\n}\n\n# Package meta-data.\nNAME = 'deafrica-tools'\nDESCRIPTION = 'Functions and algorithms for analysing Digital Earth Africa data.'\nURL = 'https://github.com/digitalearthafrica/deafrica-sandbox-notebooks'\nEMAIL = 'https://github.com/digitalearthafrica/deafrica-sandbox-notebooks/issues'\nAUTHOR = 'Digital Earth Africa'\nREQUIRES_PYTHON = '>=3.6.0' \n\n# Import the README and use it as the long-description.\nhere = os.path.abspath(os.path.dirname(__file__))\n\ntry:\n with io.open(os.path.join(here, 'README.md'), encoding='utf-8') as f:\n long_description = '\\n' + f.read()\nexcept FileNotFoundError:\n long_description = DESCRIPTION\n \nsetup_kwargs = {\n 'name': NAME,\n 'version': '0.1.0',\n 'description': DESCRIPTION,\n 'long_description': long_description,\n 'author': AUTHOR,\n 'author_email': EMAIL,\n 'python_requires': REQUIRES_PYTHON,\n 'url': URL,\n 'install_requires': REQUIRED if not IS_DEAFRICA_SANDBOX else [],\n 'packages': find_packages(),\n 'include_package_data':True,\n 'license':'Apache License 2.0'\n}\n\nsetup(**setup_kwargs)","sub_path":"Tools/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2174,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"546020251","text":"# # data supplied by the user\r\n# base_annual_salary = float(input('Enter your annual salary: '))\r\n#\r\n# # data that is fixed\r\n# portion_down_payment = 0.25\r\n# rate_of_return = 0.04\r\n# monthly_rate_of_return = rate_of_return / 12\r\n# total_cost = 1000000\r\n# down_payment = total_cost * portion_down_payment\r\n# semi_annual_raise = 0.07\r\n# months = 36\r\n#\r\n# # initially savings are zero. This variable is the core part of the decrementing\r\n# # function used to stop the algorithm\r\n# current_savings = 0.0\r\n#\r\n# # there is an acceptable margin of error for this algorithm\r\n# epsilon = 100\r\n#\r\n# # define high and low bounds for the bisection search\r\n# initial_high = 10000\r\n# high = initial_high\r\n# low = 0\r\n# portion_saved = (high + low) // 2\r\n# steps = 0\r\n#\r\n# # use bisection search to find the solution\r\n# while abs(current_savings - down_payment) > epsilon:\r\n# steps += 1\r\n# current_savings = 0.0\r\n# annual_salary = base_annual_salary\r\n# monthly_salary = annual_salary / 12\r\n# monthly_deposit = monthly_salary * (portion_saved / 10000)\r\n# for month in range(1, months + 1):\r\n# current_savings *= 1 + monthly_rate_of_return\r\n# current_savings += monthly_deposit\r\n# # problem states that semi-annual raises take effect the next month, so\r\n# # mutate monthly_salary after mutating current_savings\r\n# if month % 6 == 0:\r\n# annual_salary *= 1 + semi_annual_raise\r\n# monthly_salary = annual_salary / 12\r\n# monthly_deposit = monthly_salary * (portion_saved / 10000)\r\n# prev_portion_saved = portion_saved\r\n# if current_savings > down_payment:\r\n# high = portion_saved\r\n# else:\r\n# low = portion_saved\r\n# # if the solution is outside of the search space on the high bound, low\r\n# # will eventually equal the inital high value. However, if we use integer\r\n# # division, low will be one less than high. As such, we round the average\r\n# # of high and low and cast to an int so that low and high will converge\r\n# # completely if the solution is outside of the search space on the high\r\n# # bound\r\n# portion_saved = int(round((high + low) / 2))\r\n# # if portion_saved is no longer changing, our search space is no longer\r\n# # changing (because the search value is outside the search space), so we\r\n# # break to stop an infinite loop\r\n# if prev_portion_saved == portion_saved:\r\n# break\r\n#\r\n# if prev_portion_saved == portion_saved and portion_saved == initial_high:\r\n# print('It is not possible to pay the down payment in three years.')\r\n# else:\r\n# print('Best savings rate:', portion_saved / 10000)\r\n# print('Steps in bisection search:', steps)\r\n\r\n\r\n\r\n\r\n\r\n################################################################\r\n################################################################\r\n\r\nannual_salary = float(input('Enter your starting salary: '))\r\ntotal_cost = 1000000\r\nsemi_annual_raise = 0.07\r\ncurrent_savings = 0\r\nportion_down_payment = 0.25 * total_cost\r\nmonths = 0\r\nepsilon = 100\r\nlow = 0\r\nhigh = 10000\r\nsteps = 0\r\nportion_saved = (low + high) / 2\r\ncurrent_savings = 0\r\n\r\nwhile abs(current_savings - portion_down_payment) > epsilon:\r\n for mo in range(0, 36):\r\n monthly_salary = annual_salary / 12\r\n current_savings = current_savings + float((monthly_salary * portion_saved) / 10000) + (current_savings * 0.04) / 12\r\n if mo % 6 == 0:\r\n annual_salary = annual_salary + (annual_salary * semi_annual_raise)\r\n if current_savings > portion_down_payment:\r\n high = portion_saved\r\n else:\r\n low = portion_saved\r\n\r\n portion_saved = int(round((high + low) / 2))\r\n steps += 1\r\n\r\nprint('Best savings rate:', portion_saved / 10000)\r\nprint('Steps in bisection search:', steps)","sub_path":"ps1/ps1c.py","file_name":"ps1c.py","file_ext":"py","file_size_in_byte":3804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"497117712","text":"from glob import glob\r\nimport os\r\nimport numpy as np\r\nimport tsaug\r\nfrom tsaug.visualization import plot\r\nfrom tsaug import TimeWarp, Drift, Reverse\r\n\r\ndef dataAug():\r\n # Find the data\r\n dir = \"C:\\\\Users\\josha\\Desktop\\BMEG\\BMEG Year 3\\MINT\\data\\\\\"\r\n path_list = glob(dir)\r\n\r\n for path in path_list:\r\n data_path = glob(path + \"raw*.txt\")\r\n label_path = glob(path + \"log*.txt\")\r\n\r\n for data, label in zip(data_path, label_path):\r\n data_name = data.split(\"\\\\\")\r\n log_name = label.split(\"\\\\\")\r\n augmentation(data, dir, data_name[8], log_name[8])\r\n\r\n\r\ndef augmentation(data, dir, data_name, log_name):\r\n data_name = data_name.split(\".\")[0]\r\n log_name = log_name.split(\".\")[0]\r\n\r\n # Define augmenter\r\n my_augmenter = (\r\n TimeWarp()\r\n + Drift(max_drift=(0.1, 0.3)) @ 0.8\r\n + Reverse() @ 0.5\r\n + tsaug.AddNoise(scale=0.008)\r\n )\r\n\r\n # Read data, and split channels into time series plots\r\n num_lines = sum(1 for line in open(data)) - 7\r\n X = np.empty([num_lines])\r\n Y = np.empty([8, num_lines])\r\n timestamp = []\r\n ind = 0\r\n header = \"\"\r\n\r\n with open(data) as file:\r\n lines_read = 0\r\n for line in file:\r\n if lines_read < 7:\r\n if lines_read < 6:\r\n header = header + line\r\n lines_read += 1\r\n continue\r\n data = line.split(\", \")\r\n X[ind] = data[0]\r\n timestamp.append(data[12])\r\n for i in range(7):\r\n Y[i, ind] = data[i + 1]\r\n ind += 1\r\n\r\n file.close()\r\n\r\n # Augment data\r\n Y_aug1 = np.empty([8, num_lines])\r\n Y_aug2 = np.empty([8, num_lines])\r\n Y_aug3 = np.empty([8, num_lines])\r\n\r\n for i in range(8):\r\n Y_aug1[i,] = my_augmenter.augment(Y[i,])\r\n Y_aug2[i,] = my_augmenter.augment(Y[i,])\r\n Y_aug3[i,] = my_augmenter.augment(Y[i,])\r\n\r\n\r\n # write to new file\r\n newFile = open(dir + data_name + \"Aug1.txt\", 'w+')\r\n\r\n newFile.write(header)\r\n\r\n for i in range(num_lines):\r\n newFile.write(str(X[i]))\r\n for j in range(8):\r\n y = \"{:.2f}\".format(Y_aug1[j, i])\r\n newFile.write(\", \" + y)\r\n for k in range(3):\r\n newFile.write(\", 0.00\")\r\n newFile.write(timestamp[i])\r\n newFile.write(\"\\n\")\r\n newFile.close()\r\n\r\n newFile = open(dir + data_name + \"Aug2.txt\", 'w+')\r\n\r\n newFile.write(header)\r\n\r\n for i in range(num_lines):\r\n newFile.write(str(X[i]))\r\n for j in range(8):\r\n y = \"{:.2f}\".format(Y_aug1[j, i])\r\n newFile.write(\", \" + y)\r\n for k in range(3):\r\n newFile.write(\", 0.00\")\r\n newFile.write(timestamp[i])\r\n newFile.write(\"\\n\")\r\n newFile.close()\r\n\r\n newFile = open(dir + data_name + \"Aug3.txt\", 'w+')\r\n\r\n newFile.write(header)\r\n\r\n for i in range(num_lines):\r\n newFile.write(str(X[i]))\r\n for j in range(8):\r\n y = \"{:.2f}\".format(Y_aug1[j, i])\r\n newFile.write(\", \" + y)\r\n for k in range(3):\r\n newFile.write(\", 0.00\")\r\n newFile.write(timestamp[i])\r\n newFile.write(\"\\n\")\r\n newFile.close()\r\n\r\n # Copy all the log files\r\n suffix = [\"Aug1.txt\", \"Aug2.txt\", \"Aug3.txt\"]\r\n\r\n for suf in suffix:\r\n open(dir + log_name + suf, \"w\").writelines([l for l in open(dir + log_name + \".txt\").readlines()])\r\n\r\n\r\nif __name__ == \"__main__\":\r\n dataAug()","sub_path":"ML/utils/dataAug.py","file_name":"dataAug.py","file_ext":"py","file_size_in_byte":3511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"560099107","text":"# -*- coding: utf-8 -*-\n\"\"\"\n pylatex.command\n ~~~~~~~~~~~~~~~\n\n This module implements a class that implements a latex command. This can be\n used directly or it can be inherrited to make an easier interface to it.\n\n :copyright: (c) 2014 by Jelte Fennema.\n :license: MIT, see License for more details.\n\"\"\"\nfrom .parameters import Arguments, Options\nfrom .base_classes import BaseLaTeXClass\n\n\nclass Command(BaseLaTeXClass):\n \"\"\"\n A class that represents a command\n ::\n >>> Command('documentclass',\n >>> options=Options('12pt', 'a4paper', 'twoside'),\n >>> arguments='article').dumps()\n '\\\\documentclass[12pt,a4paper,twoside]{article}'\n\n \"\"\"\n\n def __init__(self, command, arguments=None, options=None, packages=None):\n \"\"\"\n :param command:\n :param arguments:\n :param options:\n :param packages:\n\n :type command: str\n :type arguments: str or list or :class:`parameters.Arguments` \\\n instance\n :type options: str or list or :class:`parameters.Options` instance\n :type packages: list\n \"\"\"\n\n self.command = command\n\n if isinstance(arguments, Arguments):\n self.arguments = arguments\n elif arguments is not None:\n self.arguments = Arguments(arguments)\n else:\n self.arguments = Arguments()\n\n if isinstance(options, Options):\n self.options = options\n elif options is not None:\n self.options = Options(options)\n else:\n self.options = Options()\n\n super().__init__(packages)\n\n def __key(self):\n \"\"\"\n :return:\n :rtype: tuple\n \"\"\"\n\n return self.command, self.arguments, self.options\n\n def __eq__(self, other):\n \"\"\"\n :param other: A command\n\n :type other: :class:`command.Command` instance\n\n :return:\n :rtype: bool\n \"\"\"\n\n return self.__key() == other.__key()\n\n def __hash__(self):\n \"\"\"\n :return:\n :rtype: int\n \"\"\"\n\n return hash(self.__key())\n\n def dumps(self):\n \"\"\"Represents the command as a string in LaTeX syntax.\n\n :return:\n :rtype: str\n \"\"\"\n\n return '\\\\{command}{options}{arguments}'.\\\n format(command=self.command, options=self.options.dumps(),\n arguments=self.arguments.dumps())\n","sub_path":"pylatex/command.py","file_name":"command.py","file_ext":"py","file_size_in_byte":2518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"333330280","text":"# coding: utf-8\nimport requests\nfrom bs4 import BeautifulSoup\nfrom datetime import datetime as dt\n\n\"\"\"\nNotes as I'm going about this.\n\nChallenge Description:\n Retrieve the number of people who visited a U.S. government website using Internet Explorer 6.0\n in the last 90 days.\n\nSupplied Link:\n https://analytics.usa.gov/data/live/ie.json\n\n- Looks like a good point to start using api's when possible\n\nAttempt to Reconstruct Finding Link:\n - \"Google: Visit statistics for all u.s. gov websites.\"\n - Analytics.usa.gov\n - https://analytics.usa.gov/#explanation (About the data)\n - quote::\n Not every government website is represented in this data.\n - Odd thoughts:\n - https://analytics.usa.gov/data/live/browsers.json (Browser breakdown)\n Who the hell is visiting this on a ps3?\n ``\"Nintendo Browser\": 46683``\n ``\"Playstation 3\": 29793``\n ``\"Dolfin\": 1601,`` (surprisingly low)\n - https://analytics.usa.gov/data/live/ie.json (Versions of internet explorer)\n\nIf I were to use this data, it would probably be either a good idea to dump the json to a database,\nor to find where I can make a GET request. In any case, it would be good to figure out when the data updates\nin order to set up a time for this to run and log the data.\n\"\"\"\n\n\ndef main(url=\"https://analytics.usa.gov/data/live/ie.json\"):\n \"\"\"\n Challenge Description:\n Retrieve the number of people who visited a U.S. government website using Internet Explorer 6.0\n in the last 90 days.\n\n Args:\n url (str): analytics.gov live data url for visits from different i.e. version\n\n Returns:\n (int) Number of views within last 90 days.\n \"\"\"\n r = requests.get(url)\n data = r.json()\n return data['totals']['ie_version']['6.0']\n\n\nif __name__ == '__main__':\n print('========== Challenge 3 ============')\n print('TIME REQUESTED (UTC): ', dt.utcnow().ctime())\n print('NUMBER OF REQUESTS IN LAST 90 DAYS: ', main())","sub_path":"scripts/3.py","file_name":"3.py","file_ext":"py","file_size_in_byte":2007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"519723522","text":"\nimport os.path\nfrom absl import app\nfrom absl import flags\nfrom absl import logging\nfrom typing import Any, Dict\n\nimport tensorflow as tf\nimport tensorflow.keras as keras\n\nimport uncertainty_baselines as ub\nimport uncertainty_metrics as um\n\nimport numpy as np\n# import sklearn.isotonic\n# import sklearn.neural_network\n\nfrom metrics import BrierScore\nfrom metrics import MMC\nfrom metrics import nll\n\n\ndef one_vs_all_loss_fn(dm_alpha: float = 1., from_logits: bool = True,reduction = tf.keras.losses.Reduction.SUM,one_hot=False):\n \"\"\"Requires from_logits=True to calculate correctly.\"\"\"\n if not from_logits:\n raise ValueError('One-vs-all loss requires inputs to the '\n 'loss function to be logits, not probabilities.')\n\n def one_vs_all_loss(labels: tf.Tensor, logits: tf.Tensor,reduction=reduction):\n r\"\"\"Implements the one-vs-all loss function.\n\n As implemented in https://arxiv.org/abs/1709.08716, multiplies the output\n logits by dm_alpha (if using a distance-based formulation) before taking K\n independent sigmoid operations of each class logit, and then calculating the\n sum of the log-loss across classes. The loss function is calculated from the\n K sigmoided logits as follows -\n\n \\mathcal{L} = \\sum_{i=1}^{K} -\\mathbb{I}(y = i) \\log p(\\hat{y}^{(i)} | x)\n -\\mathbb{I} (y \\neq i) \\log (1 - p(\\hat{y}^{(i)} | x))\n\n Args:\n labels: Integer Tensor of dense labels, shape [batch_size].\n logits: Tensor of shape [batch_size, num_classes].\n\n Returns:\n A scalar containing the mean over the batch for one-vs-all loss.\n \"\"\"\n #eps = tf.keras.backend.epsilon()\n eps = 1e-6\n #eps = 1e-10\n logits = logits * dm_alpha\n n_classes = tf.cast(logits.shape[1], tf.float32)\n\n if one_hot:\n labels = tf.argmax(labels, axis=-1) #decode one_hot\n \n one_vs_all_probs = tf.math.sigmoid(logits)\n labels = tf.cast(tf.squeeze(labels), tf.int32)\n row_ids = tf.range(tf.shape(one_vs_all_probs)[0], dtype=tf.int32)\n idx = tf.stack([row_ids, labels], axis=1)\n\n # Shape of class_probs is [batch_size,].\n class_probs = tf.gather_nd(one_vs_all_probs, idx)\n \n s1 = tf.math.log(class_probs + eps)\n s2 = tf.reduce_sum(tf.math.log(1. - one_vs_all_probs + eps),axis=-1)\n s3 = - tf.math.log(1. - class_probs + eps)\n \n loss = -s1 - s2 - s3\n if reduction == tf.keras.losses.Reduction.NONE:\n return loss\n \n elif reduction == tf.keras.losses.Reduction.SUM:\n return tf.reduce_mean(loss)\n\n return one_vs_all_loss\n\n# def one_vs_all_loss_fn(dm_alpha: float = 1., from_logits: bool = True):\n# \"\"\"Requires from_logits=True to calculate correctly.\"\"\"\n# if not from_logits:\n# raise ValueError('One-vs-all loss requires inputs to the '\n# 'loss function to be logits, not probabilities.')\n\n# def one_vs_all_loss(labels: tf.Tensor, logits: tf.Tensor):\n# r\"\"\"Implements the one-vs-all loss function.\n\n# As implemented in https://arxiv.org/abs/1709.08716, multiplies the output\n# logits by dm_alpha (if using a distance-based formulation) before taking K\n# independent sigmoid operations of each class logit, and then calculating the\n# sum of the log-loss across classes. The loss function is calculated from the\n# K sigmoided logits as follows -\n\n# \\mathcal{L} = \\sum_{i=1}^{K} -\\mathbb{I}(y = i) \\log p(\\hat{y}^{(i)} | x)\n# -\\mathbb{I} (y \\neq i) \\log (1 - p(\\hat{y}^{(i)} | x))\n\n# Args:\n# labels: Integer Tensor of dense labels, shape [batch_size].\n# logits: Tensor of shape [batch_size, num_classes].\n\n# Returns:\n# A scalar containing the mean over the batch for one-vs-all loss.\n# \"\"\"\n# #eps = tf.keras.backend.epsilon()\n# eps = 1e-6\n# #eps = 1e-10\n# logits = logits * dm_alpha\n# n_classes = tf.cast(logits.shape[1], tf.float32)\n\n# one_vs_all_probs = tf.math.sigmoid(logits)\n# labels = tf.cast(tf.squeeze(labels), tf.int32)\n# row_ids = tf.range(tf.shape(one_vs_all_probs)[0], dtype=tf.int32)\n# idx = tf.stack([row_ids, labels], axis=1)\n\n# # Shape of class_probs is [batch_size,].\n# class_probs = tf.gather_nd(one_vs_all_probs, idx)\n\n# loss = (\n# tf.reduce_mean(tf.math.log(class_probs + eps)) +\n# n_classes * tf.reduce_mean(tf.math.log(1. - one_vs_all_probs + eps)) -\n# tf.reduce_mean(tf.math.log(1. - class_probs + eps)))\n\n# return -loss\n\n# return one_vs_all_loss\n\ndef _calc_certs(probs: tf.Tensor,\n certainty_variant: str = 'partial') -> tf.Tensor:\n\n #form Ci's\n #probs = tf.math.sigmoid(logits)\n probs_comp = 1-probs\n K = probs.shape[1]\n cert_list = []\n\n for i in range(K):\n proj_vec = np.zeros(K)\n proj_vec[i]=1\n proj_mat = np.outer(proj_vec,proj_vec)\n proj_mat_comp = np.identity(K)-np.outer(proj_vec,proj_vec)\n tproj_mat = tf.constant(proj_mat,dtype=tf.float32)\n tproj_mat_comp = tf.constant(proj_mat_comp,dtype=tf.float32)\n out = tf.tensordot(probs,tproj_mat,axes=1) + tf.tensordot(probs_comp,tproj_mat_comp,axes=1)\n cert_list+=[tf.reduce_prod(out,axis=1)]\n\n if certainty_variant == 'partial':\n certs = tf.stack(cert_list,axis=1,name='certs')\n\n elif certainty_variant == 'total':\n certs = tf.stack(cert_list,axis=1)\n certs_argmax = tf.one_hot(tf.argmax(certs,axis=1),depth=K)\n certs_reduce = tf.tile(tf.reduce_sum(certs,axis=1,keepdims=True),[1,K])\n certs = tf.math.multiply(certs_argmax,certs_reduce)\n\n elif certainty_variant == 'normalized':\n certs = tf.stack(cert_list,axis=1)\n certs_norm = tf.tile(tf.reduce_sum(certs,axis=1,keepdims=True),[1,K])\n certs = tf.math.divide(certs,certs_norm)\n\n else:\n raise ValueError(f'unknown certainty_variant={certainty_variant}') \n\n #certs.name = 'certs'\n return certs\n\ndef _calc_logits_from_certs(certs: tf.Tensor, \n eps: float = 1e-6) -> tf.Tensor:\n #logits_from_certs\n K = certs.shape[1]\n\n logcerts = tf.math.log(certs+eps)\n rs = tf.tile(logcerts[:,:1],[1,K])-logcerts #set first logit to zero (an arbitrary choice)\n logits_from_certs = -rs \n\n return logits_from_certs\n\n\n\n\ndef _activ(activation_type: str = 'relu'):\n activation = {'relu': tf.keras.layers.ReLU(), 'sin': tf.keras.backend.sin}\n if activation_type in activation.keys():\n return activation[activation_type]\n else:\n return activation['relu']\n\nclass resnetLayer(tf.keras.layers.Layer):\n def __init__(self,\n num_filters: int = 16,\n kernel_size: int = 3,\n strides: int = 1,\n use_activation: bool = True,\n activation_type: str = 'relu', #relu or sin!\n use_norm: bool = True,\n l2_weight: float = 1e-4):\n \n super(resnetLayer,self).__init__()\n \n self.use_activation = use_activation\n self.use_norm = use_norm\n \n self.kernel_regularizer = None\n if l2_weight:\n self.kernel_regularizer = tf.keras.regularizers.l2(l2_weight) \n# print(f' resnetLayer num_filters={num_filters}, strides={strides}, kernel_size={kernel_size}')\n self.conv_layer = tf.keras.layers.Conv2D(num_filters,\n kernel_size=kernel_size,\n strides=strides,\n padding='same',\n kernel_initializer='he_normal',\n kernel_regularizer=self.kernel_regularizer)\n \n self.batch_norm = tf.keras.layers.BatchNormalization()\n self.activation = _activ(activation_type)\n \n def call(self,\n inputs: tf.Tensor) -> tf.Tensor:\n\n x = self.conv_layer(inputs)\n if self.use_norm:\n x = self.batch_norm(x)\n if self.use_activation:\n x = self.activation(x)\n \n return x \n \nclass resnet20Block(tf.keras.layers.Layer):\n \n def __init__(self,\n stack: int,\n res_block: int,\n num_filters: int = 16,\n activation_type: str = 'relu', #relu or sin!\n l2_weight: float = 1e-4):\n \n super(resnet20Block,self).__init__()\n\n self.stack = stack\n self.res_block = res_block\n self.num_filters = num_filters\n self.activation_type = activation_type\n self.l2_weight = l2_weight\n \n# layers= 3 if self.stack > 0 and self.res_block == 0 else 2\n# print(f'resnetBlock: stack={stack}, res_block={res_block}, filters={num_filters}, number_layers={layers}')\n \n strides = 1\n if self.stack > 0 and self.res_block == 0:\n strides = 2\n\n self.l_1 = resnetLayer(num_filters=self.num_filters,\n strides=strides,\n l2_weight=self.l2_weight,\n activation_type=self.activation_type)\n \n self.l_2 = resnetLayer(num_filters=self.num_filters,\n l2_weight=self.l2_weight,\n use_activation=False)\n\n self.l_3 = resnetLayer(num_filters=self.num_filters,\n kernel_size=1,\n strides=strides,\n l2_weight=self.l2_weight,\n use_activation=False,\n use_norm=False)\n\n self.l_add = tf.keras.layers.Add()\n self.l_activation = _activ(self.activation_type)\n \n def call(self,inputs: tf.Tensor) -> tf.Tensor:\n y = self.l_1(inputs)\n y = self.l_2(y)\n x = self.l_3(inputs) if self.stack > 0 and self.res_block == 0 else inputs\n x = self.l_add([x, y])\n x = self.l_activation(x)\n return x\n \nclass DMLayer(tf.keras.layers.Layer):\n def __init__(self, units: int = 10, **kwargs):\n super(DMLayer, self).__init__(**kwargs)\n self.units = units\n\n def build(self, input_shape):\n self.w = self.add_weight(name='DMLayer_weight',\n shape=(input_shape[-1], self.units),\n initializer=\"he_normal\",\n trainable=True)\n\n def get_config(self):\n return {\"units\": self.units}\n \n def call(self, inputs):\n\n #tf.tile(inputs)\n# w_tiled = tf.tile(tf.reshape(self.w,shape=(1,)+self.w.shape),[inputs.shape[0],1,1])\n# inputs_tiled = tf.tile(tf.reshape(inputs,shape=inputs.shape+(1,)),[1,1,self.units])\n# out = tf.math.sqrt(tf.math.reduce_euclidean_norm(inputs_tiled-w_tiled,axis=1))\n\n# a = tf.random.normal(shape=(128,64))\n# b = tf.random.normal(shape=(64,10))\n be=tf.expand_dims(self.w,0)\n ae=tf.expand_dims(inputs,-1)\n out = -tf.math.sqrt(tf.math.reduce_euclidean_norm(be-ae,axis=1))\n \n return out\n\n\n\nclass resnet20(tf.keras.Model):\n def __init__(self,\n batch_size: int = 128,\n l2_weight: float = 0.0,\n activation_type: str = 'relu', #relu or sin\n certainty_variant: str = 'partial', #partial, total or normalized\n model_variant: str = '1vsall', #1vsall or vanilla\n logit_variant: str = 'affine', #affine or dm\n **params):\n super(resnet20,self).__init__()\n \n self.batch_size = batch_size\n self.l2_weight = l2_weight\n \n if activation_type in ['sin','relu']:\n self.activation_type = activation_type\n else:\n raise ValueError(f'unknown activation_type={activation_type}')\n \n if certainty_variant in ['partial','total','normalized']:\n self.certainty_variant = certainty_variant\n else:\n raise ValueError(f'unknown certainty_variant={certainty_variant}')\n \n if model_variant in ['1vsall','vanilla']:\n self.model_variant = model_variant\n else:\n raise ValueError(f'unknown model_variant={model_variant}')\n \n if logit_variant in ['affine','dm']:\n self.logit_variant = logit_variant\n else:\n raise ValueError(f'unknown logit_variant={logit_variant}')\n \n self.depth = 20\n self.num_res_blocks = int((self.depth - 2) / 6)\n num_filters = 16\n \n \n self.layer_init_1 = tf.keras.layers.InputLayer(input_shape=(32, 32, 3),\n batch_size=self.batch_size)\n \n self.layer_init_2 = resnetLayer(num_filters=num_filters,\n l2_weight=self.l2_weight,\n activation_type=self.activation_type)\n \n self.res_blocks = [[0 for stack in range(3)] for res_block in range(self.num_res_blocks)]\n\n for stack in range(3):\n for res_block in range(self.num_res_blocks):\n self.res_blocks[stack][res_block] = resnet20Block(stack = stack,\n res_block = res_block,\n num_filters = num_filters,\n activation_type = self.activation_type,\n l2_weight = self.l2_weight)\n num_filters *= 2\n \n self.layer_final_1 = tf.keras.layers.AveragePooling2D(pool_size=8)\n self.layer_final_2 = tf.keras.layers.Flatten()\n \n if self.logit_variant == 'dm':\n self.layer_final_3 = DMLayer(units=10)\n elif self.logit_variant == 'affine':\n self.layer_final_3 = tf.keras.layers.Dense(10, kernel_initializer='he_normal')\n else:\n raise ValueError(f'unknown logit_variant={self.logit_variant}') \n \n def call(self, \n inputs: tf.Tensor, \n trainable: bool = False) -> dict:\n\n x = self.layer_init_1(inputs)\n x = self.layer_init_2(x)\n \n for stack in range(3):\n for res_block in range(self.num_res_blocks):\n x = self.res_blocks[stack][res_block](x)\n\n x = self.layer_final_1(x)\n x = self.layer_final_2(x)\n \n logits = self.layer_final_3(x)\n \n if self.model_variant == '1vsall':\n probs = tf.math.sigmoid(logits)\n if self.logit_variant == 'dm':\n probs = 2*probs\n elif self.model_variant == 'vanilla':\n probs = tf.math.softmax(logits,axis=-1)\n else:\n raise ValueError(f'unknown model_variant={self.model_variant}')\n \n certs = _calc_certs(probs, certainty_variant = self.certainty_variant)\n logits_from_certs = _calc_logits_from_certs(certs = certs)\n \n return {'logits':logits,'probs':probs,'certs':certs,'logits_from_certs':logits_from_certs}\n\n \n def train_step(self, data):\n # Unpack the data. Its structure depends on your model and\n # on what you pass to `fit()`.\n x, y = data\n with tf.GradientTape() as tape:\n y_pred = self(x, training=True) # Forward pass\n # Compute the loss value\n # (the loss function is configured in `compile()`)\n loss = self.compiled_loss(y, y_pred, regularization_losses=self.losses)\n\n # Compute gradients\n trainable_vars = self.trainable_variables\n gradients = tape.gradient(loss, trainable_vars)\n # Update weights\n self.optimizer.apply_gradients(zip(gradients, trainable_vars))\n # Update metrics (includes the metric that tracks the loss)\n self.compiled_metrics.update_state(y, y_pred)\n # Return a dict mapping metric names to current value\n return {m.name: m.result() for m in self.metrics}\n \nclass resnet50Block(tf.keras.layers.Layer):\n \n def __init__(self,\n stack: int,\n res_block: int,\n num_filters: int = 16,\n activation_type: str = 'relu', #relu or sin!\n l2_weight: float = 1e-4):\n \n super(resnet50Block,self).__init__()\n\n self.stack = stack\n self.res_block = res_block\n self.num_filters = num_filters\n self.activation_type = activation_type\n self.l2_weight = l2_weight\n \n\n \n strides = 1\n if self.stack > 0 and self.res_block == 0:\n strides = 2\n# print(f'resnet50Block: stack={stack}, res_block={res_block}, filters={num_filters}')\n \n self.l_1 = resnetLayer(num_filters=self.num_filters,\n kernel_size=1,\n strides=strides,\n l2_weight=self.l2_weight,\n activation_type=self.activation_type)\n\n self.l_2 = resnetLayer(num_filters=self.num_filters,\n kernel_size=3,\n l2_weight=self.l2_weight,\n activation_type=self.activation_type)\n \n self.l_3 = resnetLayer(num_filters=4*self.num_filters,\n kernel_size=1,\n l2_weight=self.l2_weight,\n use_activation=False,\n use_norm=True)\n\n self.l_4 = resnetLayer(num_filters=4*self.num_filters,\n kernel_size=1,\n strides=strides,\n l2_weight=self.l2_weight,\n use_activation=False)\n\n self.l_add = tf.keras.layers.Add()\n self.l_activation = _activ(self.activation_type)\n \n def call(self,inputs: tf.Tensor) -> tf.Tensor:\n y = self.l_1(inputs)\n y = self.l_2(y)\n y = self.l_3(y)\n if self.res_block == 0:\n x = self.l_4(inputs)\n else:\n x = inputs\n \n x = self.l_add([x, y])\n x = self.l_activation(x)\n return x\n\n#agreed with tf.keras.applications.ResNet50\nclass resnet50(tf.keras.Model):\n def __init__(self,\n batch_size: int = 128,\n l2_weight: float = 0.0,\n activation_type: str = 'relu', #relu or sin\n certainty_variant: str = 'partial', #partial, total or normalized\n model_variant: str = '1vsall', #1vsall or vanilla\n logit_variant: str = 'affine', #affine or dm\n **params):\n super(resnet50,self).__init__()\n \n self.batch_size = batch_size\n self.l2_weight = l2_weight\n \n if activation_type in ['sin','relu']:\n self.activation_type = activation_type\n else:\n raise ValueError(f'unknown activation_type={activation_type}')\n \n if certainty_variant in ['partial','total','normalized']:\n self.certainty_variant = certainty_variant\n else:\n raise ValueError(f'unknown certainty_variant={certainty_variant}')\n \n if model_variant in ['1vsall','vanilla']:\n self.model_variant = model_variant\n else:\n raise ValueError(f'unknown model_variant={model_variant}')\n \n if logit_variant in ['affine','dm']:\n self.logit_variant = logit_variant\n else:\n raise ValueError(f'unknown logit_variant={logit_variant}')\n \n\n# self.num_res_blocks = int((self.depth - 2) / 6)\n self.num_res_blocks = [3,4,6,3]\n num_filters = 64\n \n self.layer_init_1 = tf.keras.layers.InputLayer(input_shape=(224, 224, 3),\n batch_size=self.batch_size)\n\n self.layer_init_2 = resnetLayer(num_filters=num_filters,\n kernel_size=7,\n strides=2,\n l2_weight=self.l2_weight,\n activation_type=self.activation_type)\n \n self.layer_init_3 = tf.keras.layers.MaxPooling2D(pool_size=3,strides=2)\n \n #self.res_blocks = [[0 for stack in range(4)] for res_block in range(max(self.num_res_blocks))]\n self.res_blocks = [[0 for res_block in range(max(self.num_res_blocks))] for stack in range(4)] \n\n for stack in range(4):\n for res_block in range(self.num_res_blocks[stack]):\n self.res_blocks[stack][res_block] = resnet50Block(stack = stack,\n res_block = res_block,\n num_filters = num_filters,\n activation_type = self.activation_type,\n l2_weight = self.l2_weight)\n num_filters *= 2 \n \n self.layer_final_1 = tf.keras.layers.AveragePooling2D(7)\n self.layer_final_2 = tf.keras.layers.Flatten()\n \n if self.logit_variant == 'dm':\n self.layer_final_3 = DMLayer(units=1000)\n elif self.logit_variant == 'affine':\n self.layer_final_3 = tf.keras.layers.Dense(1000, kernel_initializer='he_normal')\n else:\n raise ValueError(f'unknown logit_variant={self.logit_variant}') \n \n def call(self, \n inputs: tf.Tensor, \n trainable: bool = False) -> dict:\n\n x = self.layer_init_1(inputs)\n x = self.layer_init_2(x)\n x = self.layer_init_3(x)\n \n for stack in range(4):\n for res_block in range(self.num_res_blocks[stack]):\n x = self.res_blocks[stack][res_block](x)\n\n x = self.layer_final_1(x)\n x = self.layer_final_2(x)\n \n logits = self.layer_final_3(x)\n \n if self.model_variant == '1vsall':\n probs = tf.math.sigmoid(logits)\n if self.logit_variant == 'dm':\n probs = 2*probs\n elif self.model_variant == 'vanilla':\n probs = tf.math.softmax(logits,axis=-1)\n else:\n raise ValueError(f'unknown model_variant={self.model_variant}')\n \n certs = _calc_certs(probs, certainty_variant = self.certainty_variant)\n logits_from_certs = _calc_logits_from_certs(certs = certs)\n \n return {'logits':logits,'probs':probs,'certs':certs,'logits_from_certs':logits_from_certs}\n\n def train_step(self, data):\n # Unpack the data. Its structure depends on your model and\n # on what you pass to `fit()`.\n x, y = data\n with tf.GradientTape() as tape:\n y_pred = self(x, training=True) # Forward pass\n # Compute the loss value\n # (the loss function is configured in `compile()`)\n loss = self.compiled_loss(y, y_pred, regularization_losses=self.losses)\n\n # Compute gradients\n trainable_vars = self.trainable_variables\n gradients = tape.gradient(loss, trainable_vars)\n # Update weights\n self.optimizer.apply_gradients(zip(gradients, trainable_vars))\n # Update metrics (includes the metric that tracks the loss)\n self.compiled_metrics.update_state(y, y_pred)\n # Return a dict mapping metric names to current value\n \n #garbage collection\n return {m.name: m.result() for m in self.metrics} \n \nclass dummymodel(tf.keras.Model):\n def __init__(self,\n batch_size:int = 128,\n **params):\n super(dummymodel,self).__init__()\n self.batch_size = batch_size\n \n self.layer_1 = tf.keras.layers.InputLayer(input_shape=(224, 224, 3),\n batch_size=self.batch_size)\n self.layer_2 = tf.keras.layers.Flatten()\n self.layer_3 = tf.keras.layers.Dense(1000, kernel_initializer='he_normal')\n\n def call(self, \n inputs: tf.Tensor, \n trainable: bool = False) -> dict:\n\n x = self.layer_1(inputs)\n x = self.layer_2(x)\n logits = self.layer_3(x)\n \n probs = tf.math.sigmoid(logits)\n \n return {'logits':logits,'probs':probs,'certs':probs,'logits_from_certs':logits}\n \n \n# def create_model(batch_size: int,\n# l2_weight: float = 0.0,\n# activation_type: str = 'relu', #relu or sine\n# certainty_variant: str = 'partial', # total, partial or normalized\n# model_variant: str = '1vsall', #1vsall or vanilla\n# logit_variant: str = 'affine', #affine or dm\n# **unused_kwargs: Dict[str, Any]) -> tf.keras.models.Model:\n \n# return resnet20(batch_size=batch_size,\n# l2_weight=l2_weight,\n# activation_type=activation_type,\n# certainty_variant=certainty_variant,\n# model_variant=model_variant,\n# logit_variant=logit_variant)\n\n\n# based on um.numpy.plot_diagram, um.numpy.reliability_diagram\ndef _extract_conf_acc(probs,labels,bins=0,one_hot=False):\n\n probs = np.array(probs)\n labels = np.array(labels)\n if not one_hot:\n labels_matrix = um.numpy.visualization.one_hot_encode(labels, probs.shape[1])\n else:\n labels_matrix = labels\n\n # plot_diagram(probs.flatten(), labels_matrix.flatten(), y_axis))\n\n probs = probs.flatten()\n labels = labels_matrix.flatten()\n\n probs_labels = [(prob, labels[i]) for i, prob in enumerate(probs)]\n probs_labels = np.array(sorted(probs_labels, key=lambda x: x[0]))\n window_len = int(len(labels)/100.)\n calibration_errors = []\n confidences = []\n accuracies = []\n # More interesting than length of the window (which is specific to this\n # window) is average distance between datapoints. This normalizes by dividing\n # by the window length.\n distances = []\n for i in range(len(probs_labels)-window_len):\n distances.append((\n probs_labels[i+window_len, 0] - probs_labels[i, 0])/float(window_len))\n # It's pretty sketchy to look for the 100 datapoints around this one.\n # They could be anywhere in the probability simplex. This introduces bias.\n mean_confidences = um.numpy.visualization.mean(probs_labels[i:i + window_len, 0])\n confidences.append(mean_confidences)\n class_accuracies = um.numpy.visualization.mean(probs_labels[i:i + window_len, 1])\n accuracies.append(class_accuracies)\n calibration_error = class_accuracies-mean_confidences\n calibration_errors.append(calibration_error)\n if bins>0:\n delta = int((len(probs_labels)-window_len)/bins)\n return confidences[::delta],accuracies[::delta]\n else:\n return confidences, accuracies\n\n \n \n \n \n# nonlinear calibration\nclass calLayer(tf.keras.layers.Layer):\n def __init__(self,\n basis_type: str = 'uniform',\n basis_params: list = [-20,20,20],\n basis_list: list = [-2,-1,0,1,2],\n train_basis=True):\n super(calLayer,self).__init__()\n self.basis_type = basis_type\n self.basis_params = basis_params\n self.basis_list = basis_list\n self.train_basis = train_basis\n \n def build(self, input_shape):\n# if input_shape[-1]!=1:\n# raise ValueError('input_shape != 1')\n\n if self.basis_type=='uniform':\n self.basis_exponents = np.linspace(*self.basis_params)\n else:\n self.basis_exponents = self.basis_list\n \n self.basis_exponents = tf.convert_to_tensor(self.basis_exponents,dtype=tf.float32)\n self.alphas = tf.exp(self.basis_exponents) \n #self.alphas = tf.cast(self.alphas,dtype=tf.float32)\n self.alphas = tf.Variable(name='calLayer_alphas',\n initial_value=self.alphas,\n trainable=self.train_basis)\n self.W1 = self.add_weight(name='calLayer_weights',\n shape=(len(self.basis_exponents),),\n initializer=\"he_normal\",\n trainable=True)\n \n def get_config(self):\n return {\"basis_type\": self.basis_type,\n \"basis_params\": self.basis_params,\n \"basis_list\": self.basis_list,\n \"train_basis\": self.train_basis}\n\n def call(self,inputs):\n inputs_shape = tf.shape(inputs)\n inputs_r = tf.reshape(inputs,shape=(-1,1))\n self.beta = tf.nn.softmax(self.W1)\n #print(self.alphas)\n eps = 1e-10\n x_alpha = tf.pow(inputs_r+eps,self.alphas)\n out = tf.reduce_sum(self.beta*x_alpha,axis=-1)\n \n return tf.reshape(out,shape=inputs_shape)\n\ndef _form_cal_dataset(uncal_model:tf.keras.Model,\n output_name:str,\n train_dataset,\n dataset_bins:int,\n steps:int,\n append_random:bool = False,\n random_frac:float = 0.1):\n\n cal_dataset = dict()\n #FLAGS = exp1.FLAGS\n #self.cal_dataset = train_dataset\n #dataset = exp1.datasets['cifar10']['val']\n labels = np.empty(0)\n probs = None\n\n for i,(x,y) in enumerate(train_dataset):\n if i>steps: break\n\n out = uncal_model(x)[output_name].numpy()\n labels = np.append(labels,y.numpy().astype('int32'))\n probs = out if type(probs)==type(None) else np.concatenate((probs,out))\n \n if append_random:\n print(labels.shape,probs.shape)\n \n random_frac = random_frac\n random_mean = 0.5\n random_std = 0.33\n batch_size = next(iter(train_dataset))[0].shape[0]\n val_examples = steps*batch_size\n random_size = int(val_examples*random_frac)\n\n #random_x = np.sqrt(random_std)*np.random.randn(random_size,32,32,3) + random_mean\n random_x = np.random.rand(random_size,32,32,3)\n random_probs = uncal_model(random_x)[output_name].numpy()\n #random_labels_onehot = np.zeros(shape=(random_size,random_probs.shape[1]))\n random_labels_onehot = np.ones(shape=(random_size,random_probs.shape[1]))\n #random_labels_onehot = np.random.binomial(1,0.5,size=(random_size,random_probs.shape[1]))\n #random_labels_onehot = np.ones(shape=(random_size,random_probs.shape[1]))\n #random_labels_onehot = np.random.randint(low=0,high=2,size=(random_size,random_probs.shape[1])).astype('float32')\n \n labels_onehot = um.numpy.visualization.one_hot_encode(labels.astype('int32'), probs.shape[1])\n \n# print(labels_onehot.shape)\n# print(random_labels_onehot.shape)\n# print(labels_onehot.dtype)\n# print(random_labels_onehot.dtype)\n# print(random_labels_onehot2.dtype)\n# print(random_labels_onehot[0])\n# print(random_labels_onehot2[0])\n labels_onehot = np.concatenate((labels_onehot,random_labels_onehot))\n probs = np.concatenate((probs,random_probs))\n print(labels_onehot.shape,probs.shape)\n \n confidences, accuracies = _extract_conf_acc(probs=probs,\n labels=labels_onehot,\n bins=dataset_bins,\n one_hot=True)\n \n else:\n confidences, accuracies = _extract_conf_acc(probs=probs,\n labels=labels.astype('int32'),\n bins=dataset_bins,\n one_hot=False)\n\n cal_dataset['x'] = tf.convert_to_tensor(confidences,dtype=tf.float32)\n cal_dataset['y'] = tf.convert_to_tensor(accuracies,dtype=tf.float32) \n\n return cal_dataset\n \nclass nonlin_calibrator(tf.keras.Model):\n def __init__(self,\n basis_type: str = 'uniform',\n basis_params: list = [-20,20,10],\n basis_list: list = [-2,-1,0,1,2],\n train_basis: bool = True):\n \n super(nonlin_calibrator,self).__init__()\n self.layer = calLayer(basis_type = basis_type,\n basis_params = basis_params,\n basis_list = basis_list,\n train_basis = train_basis)\n\n def call(self, \n inputs: tf.Tensor, \n training: bool = False) -> tf.Tensor:\n x = self.layer(inputs)\n return x\n\nclass cal_model(tf.keras.Model):\n def __init__(self,\n uncal_model: tf.keras.Model,\n calibrator: tf.keras.Model,\n output_name: str):\n super(cal_model,self).__init__()\n \n #self.inp = tf.keras.layers.Input(shape=(32,32,3))\n self.uncal_model = uncal_model\n self.calibrator = calibrator\n self.output_name = output_name\n \n def call(self,\n inputs:tf.Tensor):\n x = self.uncal_model(inputs)[self.output_name]\n x = self.calibrator(x)\n \n return {self.output_name: x}\n \n \ndef calibrate_model_nonlin(model,\n dataset,\n FLAGS,\n output='certs',\n epochs=10000,\n verbose=False,\n bins=4000,\n basis_type='uniform', # or list\n basis_params={-20,20,60},\n basis_list = [-2,-1,0,1,2]\n ): \n \n def feature_create(x,basis_exponents):\n x_feat = tf.tile(tf.reshape(x,shape=(-1,1)),[1,len(basis_exponents)])\n be_tf = tf.convert_to_tensor(basis_exponents,dtype=tf.float32)\n return tf.pow(x_feat,tf.exp(be_tf))\n \n def cal_out(W1,x,basis_exponents):\n \n size = len(basis_exponents)\n x_shape = tf.shape(x) \n# print(x_shape)\n xr = tf.reshape(x,shape=(-1,))\n# print(xr.shape)\n W1_tile = tf.tile(tf.reshape(tf.nn.softmax(W1),[1,size]),[tf.shape(xr)[0],1])\n x_feat = feature_create(xr,basis_exponents)\n # print(W1_tile.shape)\n # print(x_feat.shape)\n out = tf.reduce_sum(W1_tile*x_feat,axis=-1)\n return tf.reshape(out,shape=x_shape)\n\n\n def cost(W1, x, y):\n\n yhats = cal_out(W1,x,basis_exponents)\n# print(yhats.shape)\n# print(y.shape)\n cost_value = tf.keras.losses.MSE(y_true=y,\n y_pred=yhats)\n\n return cost_value\n\n def grad(W1, x, y):\n\n with tf.GradientTape() as tape:\n cost_value = cost(W1, x, y)\n\n return cost_value, tape.gradient(cost_value, W1)\n\n\n if basis_type=='uniform':\n basis_exponents = np.linspace(*basis_params)\n else:\n basis_exponents = basis_list\n \n \n W1 = tf.Variable(tf.random.normal(shape=(len(basis_exponents),)))\n \n optimizer = ub.optimizers.get(optimizer_name='adam',\n learning_rate_schedule='constant',\n learning_rate=0.1,\n weight_decay=None) \n \n #number of classes\n K = FLAGS['no_classes']\n \n labels = np.empty(0)\n probs = np.empty((0,K))\n \n for i,(x,y) in enumerate(dataset):\n if i>FLAGS['validation_steps']: break\n\n out = model(x)[output].numpy()\n labels = np.append(labels,y.numpy().astype('int32'))\n probs = np.concatenate((probs,out))\n\n confidences, accuracies = _extract_conf_acc(probs=probs,labels=labels.astype('int32'),bins=bins)\n \n X_train = tf.convert_to_tensor(confidences,dtype=tf.float32)\n y_train = tf.convert_to_tensor(accuracies,dtype=tf.float32)\n \n for i in range(epochs):\n train_cost, grads = grad(W1,X_train,y_train)\n optimizer.apply_gradients(zip([grads], [W1]))\n# if i % 50 == 0: \n# print(train_cost.numpy())\n\n def model_return():\n inp = tf.keras.layers.Input(shape=(32,32,3))\n out_model = model(inp)\n out_calibr = cal_out(W1,out_model[output],basis_exponents=basis_exponents)\n out_model[output+'_cal'] = out_calibr\n \n return tf.keras.Model(inputs=inp,outputs=out_model)\n \n# def cal_model(x):\n \n# #out = tf.keras.models.Model(model.layers[0].input, model.output[output])(x)\n# out = model(x)[output]\n# out_shape = out.shape\n# out_calibr = cal_out(W1,out,basis_exponents=basis_exponents)\n \n# return {output+'_cal':out_calibr}\n \n return model_return(),W1","sub_path":"experimental/multihead/resnet.py","file_name":"resnet.py","file_ext":"py","file_size_in_byte":37301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"63809802","text":"import sys, os.path\narr = sys.argv[:] # Сохраняет в переменную имя файла\nprint(arr)\nfor n in arr:\n n_1 = list(n)\n n_2 = list(n)\n n_2 = n[4:6]\n n_2 = str(int(n_2) + 1)\n n_1 = n_1[0:4]\n n_1 = \"\".join(n_1)\n v_1 = n_1 + n_2 + \".\" + \"py\"\n\n\ntry:\n opath_1 = os.path.abspath(v_1)\n open(opath_1)\nexcept:\n with open(\"{0}\".format(v_1), \"a\", encoding=\"utf-8\") as f:\n f.write(\"import test46\\n\") # Записываем строку в конец файл\n\n\n","sub_path":"test46.py","file_name":"test46.py","file_ext":"py","file_size_in_byte":508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"625441241","text":"import pymongo\nimport numpy as np\nimport pandas as pd\nimport redis \n\n\nPOOL = redis.ConnectionPool(host='127.0.0.1', port=6379, max_connections=100)\nclient_redis = redis.Redis(connection_pool=POOL)\n\n\nHOT_MOVIES = [\n {\n 'name': 'Toy Story',\n 'score': 90,\n 'picUrl': 'http://image.tmdb.org/t/p/w780/dji4Fm0gCDVb9DQQMRvAI8YNnTz.jpg',\n 'movieId': 1\n },\n {\n 'name': 'Jumanji',\n 'score': 93,\n 'picUrl': 'http://image.tmdb.org/t/p/w780/7k4zEgUZbzMHawDaMc9yIkmY1qR.jpg',\n 'movieId': 2\n },\n {\n 'name': 'Grumpier Old Men',\n 'score': 60,\n 'picUrl': 'http://image.tmdb.org/t/p/w780/1ENbkuIYK2taNGGKNMs2hw6SaJb.jpg',\n 'movieId': 3\n },\n {\n 'name': 'Waiting to Exhale',\n 'score': 80,\n 'picUrl': 'http://image.tmdb.org/t/p/w780/u0hQzp4xfag3ZhsKKBBdgyIVvCl.jpg',\n 'movieId': 4\n },\n {\n 'name': 'Father of the Bride Part II',\n 'score': 95,\n 'picUrl': 'http://image.tmdb.org/t/p/w780/cZs50rEk4T13qWedon0uCnbYQzW.jpg',\n 'movieId': 5\n }\n]\n\ndef get_json(row):\n json = {}\n json['name'] = row['moviename']\n json['score'] = int(row['averating'] / 5.0 * 100)\n json['picUrl'] = row['picture']\n json['movieId'] = row['movieId']\n json['director'] = row['director']\n json['leadactors'] = row['leadactors']\n json['backpost'] = row['backpost']\n json['genres'] = row['genres']\n return json\n\ndef prepare_data():\n client_mongo = pymongo.MongoClient(\"mongodb://localhost:27017\")\n db_fishmovie = client_mongo['favormovies']\n col_hot = db_fishmovie['hot']\n col_all_movies = db_fishmovie['movieinfo']\n df_hot_movies = pd.read_csv('../../data/hot_movies.csv', index_col=0)\n df_all_movies = pd.read_csv('../../data/movies_v2.csv', index_col=0)\n df_hot_movies['json'] = df_hot_movies.apply(get_json, axis=1)\n json_hot_movies = df_hot_movies['json'].values.tolist()\n col_hot.insert_many(json_hot_movies)\n df_all_movies['json'] = df_all_movies.apply(get_json, axis=1)\n json_all_movies = df_all_movies['json'].values.tolist()\n col_all_movies.insert_many(json_all_movies)\n hot_ids = [movie['movieId'] for movie in json_hot_movies]\n client_redis.rpush('hot', *hot_ids)\n df_sim_movies = pd.read_csv('../../data/similar_movies.csv', index_col=0)\n for i in range(0, df_sim_movies.shape[0]):\n client_redis.rpush('similar_{}'.format(df_sim_movies['movieId'].iloc[0]),\n *df_sim_movies.filter(regex='sim_').iloc[0].values.tolist())\n\ndef main():\n prepare_data()\n\nif __name__ == '__main__':\n prepare_data()\n","sub_path":"code/server/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":2656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"25243338","text":"import tensorflow as tf\nfrom google.protobuf.json_format import MessageToJson\nimport json\nimport networkx as nx\nimport struct, math\nimport numpy as np\nimport os, sys\nfrom byteps.tensorflow.ops import local_rank, rank\nfrom tensorflow.python.client import timeline\nimport threading\nimport time\n\nclass _SecondOrStepTimer(tf.train.SecondOrStepTimer):\n def __init__(self, every_secs=None, every_steps=None, step_bound=None):\n if step_bound is not None:\n if not (isinstance(step_bound, list) or isinstance(step_bound, tuple)):\n raise ValueError(\"step bound must be a list or a tuple, but {} is given\".format(step_bound))\n self._start_step = step_bound[0]\n self._end_step = step_bound[1]\n if self._start_step > self._end_step:\n raise ValueError(\"Profiling start step must be smaller than the end step.\")\n else:\n self._start_step = self._end_step = None\n\n super(_SecondOrStepTimer, self).__init__(every_secs, every_steps)\n\n def should_trigger_for_step(self, step):\n if self._start_step is not None:\n if step < self._start_step or step >= self._end_step:\n return False\n\n return super(_SecondOrStepTimer, self).should_trigger_for_step(step)\n\nclass TimelineHook(tf.train.ProfilerHook):\n def __init__(self, _summary=False, batch_size=None):\n self.trace_dir = os.path.join(os.environ.get(\"BYTEPS_TRACE_DIR\", \".\"), str(local_rank()))\n if not os.path.exists(self.trace_dir):\n os.makedirs(self.trace_dir)\n\n if os.environ.get(\"BYTEPS_TRACE_ON\", \"\") != '1':\n self._end_trace = True\n self.start_step = self.end_step = 0\n else:\n self._end_trace = False\n self.start_step = int(os.environ.get(\"BYTEPS_TRACE_START_STEP\", \"20\"))\n self.end_step = int(os.environ.get(\"BYTEPS_TRACE_END_STEP\", \"30\"))\n \n if not self._end_trace and self.start_step < 1:\n raise ValueError(\"BYTEPS_TRACE_START_STEP must be larger than 1\")\n if not self._end_trace and self.end_step <= self.start_step:\n raise ValueError(\"BYTEPS_TRACE_END_STEP must be larger than BYTEPS_TRACE_START_STEP\")\n \n print(\"TimelineHook enable: {} start_step: {} end_step: {}\".format(not self._end_trace, self.start_step, self.end_step))\n self.dag = None\n self.has_data = False\n\n self.shape_dict = {}\n self.run_metadata = None\n self.partition_dag = None\n self.step_stats = []\n\n self._output_file = os.path.join(self.trace_dir, \"timeline-{}.json\")\n self._file_writer = tf.summary.FileWriterCache.get(self.trace_dir) if _summary else None\n self._show_dataflow = True\n self._show_memory = False\n self._timer = _SecondOrStepTimer(\n every_secs=None, every_steps=1, step_bound=(self.start_step, self.end_step))\n self.batch_size = batch_size\n assert self.batch_size is not None\n\n def before_run(self, run_context):\n t = time.time()\n if not self._end_trace:\n self._request_summary = (\n self._next_step is not None and\n self._timer.should_trigger_for_step(self._next_step))\n \n if self._request_summary and not self.has_data:\n ### the first step to collect traces, self.has_data tells there are data that need outputing\n self.has_data = True\n if self.has_data and not self._request_summary:\n ### the step after the last trace step, output data\n self._end_trace = True\n partition_graphs = []\n for idx in range(len(self.run_metadata.partition_graphs)):\n graph_def = self.run_metadata.partition_graphs[idx]\n partition_graphs.append(graph_def)\n _t = threading.Thread(target=self.output_traces, args=(tf.get_default_graph().get_operations(), partition_graphs))\n _t.start()\n else:\n self._request_summary = False\n \n requests = {\"global_step\": self._global_step_tensor}\n opts = (tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE, output_partition_graphs=True)\n if self._request_summary else None)\n\n t = time.time() - t\n # print(\"Before run takes: {} seconds\".format(t))\n return tf.train.SessionRunArgs(requests, options=opts)\n\n def after_run(self, run_context, run_values):\n t = time.time()\n stale_global_step = run_values.results[\"global_step\"]\n if self._next_step is None:\n # Update the timer so that it does not activate until N steps or seconds\n # have passed.\n self._timer.update_last_triggered_step(stale_global_step)\n global_step = stale_global_step + 1\n if self._request_summary:\n self.run_metadata = run_values.run_metadata\n self._timer.update_last_triggered_step(global_step)\n # _t = multiprocessing.Process(target=self._save, args=(global_step, self._output_file.format(global_step),\n # run_values.run_metadata.step_stats))\n # _t.start()\n self.step_stats.append(run_values.run_metadata.step_stats)\n # self._save(global_step, self._output_file.format(global_step),\n # run_values.run_metadata.step_stats)\n # get shapes from step_stats\n if rank() == 0 and local_rank() == 0:\n if not self.shape_dict:\n for dev_stats in run_values.run_metadata.step_stats.dev_stats:\n for node_stats in dev_stats.node_stats:\n for node_outputs in node_stats.output:\n slot = node_outputs.slot\n dtype = node_outputs.tensor_description.dtype\n shape = []\n if node_outputs.tensor_description.shape.unknown_rank:\n shape.append(\"Unknown\")\n else:\n for shape_in_dim in node_outputs.tensor_description.shape.dim:\n shape.append(shape_in_dim.size)\n if node_stats.node_name+\":{}\".format(slot) not in self.shape_dict:\n self.shape_dict[node_stats.node_name+\":{}\".format(slot)] = {}\n self.shape_dict[node_stats.node_name+\":{}\".format(slot)][\"shape\"] = shape\n self.shape_dict[node_stats.node_name+\":{}\".format(slot)][\"dtype\"] = dtype\n if self._file_writer is not None:\n self._file_writer.add_run_metadata(run_values.run_metadata,\n \"step_%d\" % global_step)\n self._next_step = global_step + 1\n t = time.time() - t\n # print(\"After run takes: {} seconds\".format(t))\n\n def output_traces(self, ops, partition_graphs):\n self.traces = {\"traceEvents\":[]}\n ### the ProfilerHook of tensorflow will output the timeline to self.trace_dir/timeline-{global_step}.json\n # for file in sorted(os.listdir(self.trace_dir)):\n # if file.startswith('timeline-'):\n # with open(os.path.join(self.trace_dir, file), 'r') as fp:\n # ctf = json.load(fp)\n # convert_traces = self.chome_trace_MBE2X(ctf[\"traceEvents\"])\n # self.traces[\"traceEvents\"] += convert_traces \n\n for step_stats in self.step_stats:\n trace = timeline.Timeline(step_stats)\n events_str = trace.generate_chrome_trace_format(\n show_dataflow=self._show_dataflow, show_memory=self._show_memory)\n events = json.loads(events_str)\n self.traces[\"traceEvents\"] += self.chome_trace_MBE2X(events[\"traceEvents\"])\n \n with open(os.path.join(self.trace_dir, \"temp.json\"), \"w\") as fp:\n json.dump(self.traces, fp, indent=4)\n\n if os.getenv(\"BYTEPS_PURE_TF_TRACE\", '1') == '1':\n ### delete all intermediate redults\n _output_files = os.path.join(self.trace_dir, \"timeline-*.json\")\n os.system('rm {}'.format(_output_files))\n\n def serialize_tensor(t):\n _shape = t.shape.as_list() if t.shape.dims is not None else []\n if len(_shape) > 0 and _shape[0] is None:\n _shape[0] = self.batch_size\n return {\n \"name\": t.name,\n \"shape\": _shape,\n \"dtype\": t.dtype.name\n }\n\n for idx, graph_def in enumerate(partition_graphs):\n graph_json = json.loads(MessageToJson(graph_def))\n with open(os.path.join(self.trace_dir, \"partition_def_{}.json\".format(idx)), \"w\") as f:\n json.dump(graph_json, f, indent=4)\n \n if idx == 0:\n # generate dag\n self.partition_dag = nx.DiGraph()\n # clean node names in graph def\n pruned_node = set()\n all_node_names = set([node[\"name\"] if node[\"name\"][0] != \"_\" else node[\"name\"][1:] \\\n for node in graph_json[\"node\"]])\n for node in graph_json[\"node\"]:\n if node[\"name\"][0] == \"_\":\n node[\"name\"] = node[\"name\"][1:]\n last_slash_pos = node[\"name\"].rfind(\"/\")\n if last_slash_pos != -1 and last_slash_pos < len(node[\"name\"])-1 \\\n and node[\"name\"][last_slash_pos+1] == \"_\":\n if node[\"name\"][:last_slash_pos] in all_node_names:\n pruned_node.add(node[\"name\"])\n continue\n else:\n node[\"name\"] = node[\"name\"][:last_slash_pos]\n if \"input\" in node:\n for idx, input_node in enumerate(node[\"input\"]):\n if input_node[0] == \"_\":\n node[\"input\"][idx] = input_node[1:]\n input_node = input_node[1:]\n last_slash_pos = input_node.rfind(\"/\")\n if last_slash_pos != -1 and last_slash_pos < len(input_node)-1 \\\n and input_node[last_slash_pos+1] == \"_\":\n node[\"input\"][idx] = input_node[:last_slash_pos]\n self.partition_dag.add_edge(node[\"input\"][idx].split(\":\")[0], node[\"name\"])\n\n if rank() == 0:\n ### Only dump these info for rank 0 \n op_dict = {}\n for op in ops:\n op_dict[op.name] = {\n \"output\":[serialize_tensor(e) for e in op.outputs],\n \"input\": [serialize_tensor(e) for e in op.inputs._inputs],\n \"op\": op.type\n }\n with open(os.path.join(self.trace_dir, \"metadata.json\"), \"w\") as f:\n json.dump(op_dict, f, indent=4)\n\n if self.partition_dag is not None:\n nx.write_gml(self.partition_dag, os.path.join(self.trace_dir, \"dag.gml\"), lambda x: str(x))\n \n with open(os.path.join(self.trace_dir, \"tensor_shapes.json\"), \"w\") as f:\n json.dump(self.shape_dict, f, indent=4)\n\n print(\"Stop tracing, output trace at %s\" % self.trace_dir)\n\n def chome_trace_MBE2X(self, raw_traces):\n ret = []\n pid_table = {}\n if self.dag is None:\n _dag = nx.DiGraph()\n for trace in raw_traces:\n ### Create the DAG\n if self.dag is None:\n if trace[\"ph\"] == \"M\" or \"args\" not in trace:\n continue\n op = trace[\"args\"][\"op\"]\n name = trace[\"args\"][\"name\"]\n if name.startswith(\"^\"):\n name = name[1:]\n ### Add dependency info\n for k, v in trace[\"args\"].items():\n if \"input\" in k:\n if v.startswith(\"^\"):\n v = v[1:]\n _dag.add_edge(v, name)\n \n if trace[\"ph\"] == \"M\":\n if trace[\"name\"] == \"process_name\":\n assert trace[\"pid\"] not in pid_table\n if trace[\"args\"][\"name\"] == \"\":\n continue\n process_name = trace[\"args\"][\"name\"]\n if \"stream:all Compute\" in process_name and \"device:GPU\" in process_name:\n pid_table[trace[\"pid\"]] = {\"process_name\": process_name}\n else:\n pass\n elif trace[\"ph\"] == \"i\":\n trace[\"pid\"] = trace[\"tid\"] = \"mark\"\n ret.append(trace)\n elif trace[\"pid\"] in pid_table and trace[\"ph\"] == \"X\":\n cur_pid = pid_table[trace[\"pid\"]]\n trace[\"pid\"] = cur_pid[\"process_name\"]\n ret.append(trace)\n else:\n pass\n if self.dag is None:\n self.dag = _dag\n return ret\n","sub_path":"byteps/tensorflow/recorder.py","file_name":"recorder.py","file_ext":"py","file_size_in_byte":13364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"106536667","text":"import time\r\nimport devicemanager\r\n\r\nclass controller:\r\n def __init__(self, ip, port, stations):\r\n self.ip = ip\r\n self.port = port\r\n self.manager = devicemanager.deviceManager(ip, port)\r\n if (stations == None):\r\n self.stationAware = False\r\n else:\r\n self.stationAware = True\r\n self.stations = []\r\n self.validateStations(stations)\r\n\r\n def __del__(self):\r\n del self.manager\r\n \r\n def validateStations(self, orderedStationIds):\r\n self.manager.refreshDeviceList()\r\n devices = self.manager.getDevices()\r\n while len(devices) < len(orderedStationIds):\r\n devices = self.manager.getDevices()\r\n\r\n for stationId in orderedStationIds:\r\n if not any(device[\"id\"] == stationId for device in devices):\r\n print(\"device not found: \" + stationId)\r\n time.sleep(1)\r\n self.validateStations(orderedStationIds)\r\n else:\r\n for device in devices:\r\n if device[\"id\"] == stationId:\r\n self.stations.append(device)\r\n print(\"All devices found\")\r\n\r\n def setLightStationColor(self, id, colorData):\r\n ip = None\r\n for station in self.stations:\r\n if station[\"id\"] == id:\r\n ip = station[\"ip\"]\r\n if ip == None:\r\n print(\"Big oof\")\r\n return\r\n self.manager.sendColorCommand(ip, 1, colorData[\"r\"])\r\n self.manager.sendColorCommand(ip, 2, colorData[\"g\"])\r\n self.manager.sendColorCommand(ip, 3, colorData[\"b\"])\r\n\r\n def setAllLightStationColor(self, colorData):\r\n self.manager.sendColorCommand(self.ip, 1, colorData[\"r\"])\r\n self.manager.sendColorCommand(self.ip, 2, colorData[\"g\"])\r\n self.manager.sendColorCommand(self.ip, 3, colorData[\"b\"])\r\n\r\n\r\ndef getStations(ip, port):\r\n manager = devicemanager.deviceManager(ip, port)\r\n manager.refreshDeviceList()\r\n time.sleep(6)\r\n return manager.getDevices()","sub_path":"Controller/controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":2046,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"290191493","text":"#!/usr/bin/env python\n\n## -*-Pyth-*-\n # ###################################################################\n # FiPy - Python-based finite volume PDE solver\n # \n # FILE: \"linearLUSolver.py\"\n #\n # Author: Jonathan Guyer \n # Author: Daniel Wheeler \n # Author: James Warren \n # mail: NIST\n # www: http://www.ctcms.nist.gov/fipy/\n # \n # ========================================================================\n # This software was developed at the National Institute of Standards\n # and Technology by employees of the Federal Government in the course\n # of their official duties. Pursuant to title 17 Section 105 of the\n # United States Code this software is not subject to copyright\n # protection and is in the public domain. FiPy is an experimental\n # system. NIST assumes no responsibility whatsoever for its use by\n # other parties, and makes no guarantees, expressed or implied, about\n # its quality, reliability, or any other characteristic. We would\n # appreciate acknowledgement if the software is used.\n # \n # This software can be redistributed and/or modified freely\n # provided that any derivative works bear some notice that they are\n # derived from it, and any modified versions bear some notice that\n # they have been modified.\n # ========================================================================\n # \n # ###################################################################\n ##\n\n__docformat__ = 'restructuredtext'\n\nimport os\n\nfrom scipy.sparse.linalg import splu\n\nfrom fipy.solvers.scipy.scipySolver import _ScipySolver\nfrom fipy.tools import numerix\n\n__all__ = [\"LinearLUSolver\"]\n\nclass LinearLUSolver(_ScipySolver):\n \"\"\"\n The `LinearLUSolver` solves a linear system of equations using\n LU-factorisation. The `LinearLUSolver` is a wrapper class for the\n the Scipy `scipy.sparse.linalg.splu` moduleq.\n \"\"\"\n \n def _solve_(self, L, x, b):\n diag = L.takeDiagonal()\n maxdiag = max(numerix.absolute(diag))\n\n L = L * (1 / maxdiag)\n b = b * (1 / maxdiag)\n\n LU = splu(L.matrix.asformat(\"csc\"), diag_pivot_thresh=1.,\n drop_tol=0.,\n relax=1,\n panel_size=10,\n permc_spec=3)\n\n error0 = numerix.sqrt(numerix.sum((L * x - b)**2))\n\n for iteration in range(min(self.iterations, 10)):\n errorVector = L * x - b\n\n if (numerix.sqrt(numerix.sum(errorVector**2)) / error0) <= self.tolerance:\n break\n\n xError = LU.solve(errorVector)\n x[:] = x - xError\n \n if 'FIPY_VERBOSE_SOLVER' in os.environ:\n from fipy.tools.debug import PRINT \n PRINT('iterations: %d / %d' % (iteration+1, self.iterations))\n PRINT('residual:', numerix.sqrt(numerix.sum(errorVector**2)))\n\n return x\n","sub_path":"Class Project/FiPy-3.1.3 2/fipy/solvers/scipy/linearLUSolver.py","file_name":"linearLUSolver.py","file_ext":"py","file_size_in_byte":3007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"484262169","text":"# on A, C, of B was sold\n\nimport openpyxl\n\nfilename = \"itp_week_3\\day_1\\lecture.xlsx\"\nwb = openpyxl.load_workbook(filename)\nprint(type(wb))\n\nsheet = wb['Sheet1']\nprint(sheet.max_row) # 7\n\nfor i in range(1, sheet.max_row + 1): #\"sheet.max_row + 1\" makes sure last row is included\n # on the date of A, C amount of B were sold.\n date = \"A\" + str(i)\n date_cell = sheet[date]\n\n amount = \"C\" + str(i)\n amount_cell = sheet[amount]\n\n fruit = \"B\" + str(i)\n fruit_cell = sheet[fruit]\n\n print(\"On the Date of \" + str(date_cell.value) + \", \" + str(amount_cell.value) + \" amount of \" + fruit_cell.value + \" were sold!\")\n\n\n# import openpyxl\n\n\n# filename = \"itp_week_3\\day_1\\lecture.xlsx\"\n# wb = openpyxl.load_workbook(filename)\n\n# for i in range(1, 8):\n# print(i, my_sheet.cell(row = i, column =2).value)","sub_path":"day_1/practice.py","file_name":"practice.py","file_ext":"py","file_size_in_byte":819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"585645153","text":"\ndef split_this():\n a = []\n c = \"102 454 8541\"\n b = input(c)\n print(c.split())\n lst = c.split()\n print(lst)\n\n# split_this()\n\n\na = [\"1, 2, 3, 4\"]\nb = [\"5, 6, 7, 8\"]\nprint(\"a:\", type(a))\nfor x, y in zip(a, b):\n print(x, y)\n p1 = a[0]\n p2 = b[0]\n if p1 < p2:\n print(\"Yes\")\n print(\"tipo: \", type(x))\n\n\ndef f():\n return True, False\n\n\nx, y = f()\nprint(x)\nprint(y)\n\nbb = 13.1231\nformated = format(bb, \".2f\")\nformated = float(formated)\nprint(type(formated))\n","sub_path":"Actividades/pruebas/Study/tests_reto3.py","file_name":"tests_reto3.py","file_ext":"py","file_size_in_byte":493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"242860561","text":"# coding=utf-8\n# Copyright 2020 Google LLC..\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\"\"\"Loads the data into BigQuery needed to run Fractribution.\"\"\"\n\nimport base64\nimport datetime\nimport json\nimport os\nimport re\nfrom typing import Any, Dict, List, Mapping\nimport jinja2\nfrom google.cloud import bigquery\nimport fractribution\n\n_FULLVISITORID_USERID_MAP_TABLE = 'fullvisitorid_userid_map_table'\n_GA_SESSIONS_TABLE = 'ga_sessions_table'\n_PATHS_TO_CONVERSION_TABLE = 'paths_to_conversion_table'\n_PATHS_TO_NON_CONVERSION_TABLE = 'paths_to_non_conversion_table'\n_PATH_SUMMARY_TABLE = 'path_summary_table'\n_CHANNEL_COUNTS_TABLE = 'channel_counts_table'\n_REPORT_TABLE = 'report_table'\n_CONVERSIONS_BY_CUSTOMER_ID_TABLE = 'ConversionsByCustomerId'\n_SESSIONS_BY_CUSTOMER_ID_TABLE = 'SessionsByCustomerId'\n_PATH_TRANSFORMS_MAP = {\n 'unique': 'Unique',\n 'exposure': 'Exposure',\n 'first': 'First',\n 'frequency': 'Frequency'\n}\n_REPORT_TABLE_PARTITION_EXP_MS = 7776000000 # 90 days\n\nVALID_CHANNEL_NAME_PATTERN = re.compile(r'^[a-zA-Z_]\\w+$', re.ASCII)\n\nenv = jinja2.Environment(\n loader=jinja2.FileSystemLoader(\n os.path.join(os.path.dirname(__file__), 'templates')))\n\n\ndef _strip_sql(sql: str) -> str:\n \"\"\"Returns a copy of sql with empty lines and -- comments stripped.\n\n Args:\n sql: A SQL string.\n Returns:\n A copy of sql with empty lines and -- comments removed.\n \"\"\"\n lines = []\n for line in sql.split('\\n'):\n line = re.sub(r'\\s*--.*', '', line)\n if line.strip():\n lines.append(line)\n return '\\n'.join(lines)\n\n\ndef _is_valid_column_name(column_name: str) -> bool:\n \"\"\"Returns True if the column_name is a valid BigQuery column name.\"\"\"\n return VALID_CHANNEL_NAME_PATTERN.match(column_name) is not None\n\n\ndef _get_flag_or_die(flags: Mapping[str, Any], flag: str) -> Any:\n \"\"\"Returns value of given flag. Dies with user-formatted message not defined.\n\n Args:\n flags: Dictionary of all flag names to flag values.\n flag: Name of the flag to get the value of.\n Returns:\n Value of the given flag.\n Raises:\n ValueError: User formatted message on error.\n \"\"\"\n value = flags.get(flag, None)\n if not value:\n raise ValueError('Missing flag: %s' % flag)\n return value\n\n\ndef _get_table_name(\n project: str, dataset: str, table: str, date_suffix: str) -> str:\n \"\"\"Returns the name of the table in dotted format.\"\"\"\n return '{}.{}.{}_{}'.format(project, dataset, table, date_suffix)\n\n\ndef _update_table_name_flags(flags: Dict[str, Any]) -> None:\n \"\"\"Updates flags to contain all the required table names.\n\n Side-effect: Adds standard table names to the flags.\n\n Args:\n flags: Dictionary of all flag names to flag values.\n Raises:\n ValueError: User formatted message on error.\n \"\"\"\n ga_sessions_table = _get_flag_or_die(flags, _GA_SESSIONS_TABLE)\n if ga_sessions_table[-2:] != '_*':\n raise ValueError('ga_sessions_table flag must end in _*')\n project_id = _get_flag_or_die(flags, 'project_id')\n dataset = _get_flag_or_die(flags, 'dataset')\n date_suffix = datetime.datetime.strptime(\n _get_flag_or_die(flags, 'conversion_window_end_date'),\n '%Y-%m-%d').strftime('%Y%m%d')\n flags[_FULLVISITORID_USERID_MAP_TABLE] = _get_table_name(\n project_id, dataset, _FULLVISITORID_USERID_MAP_TABLE, date_suffix)\n flags[_PATHS_TO_CONVERSION_TABLE] = _get_table_name(\n project_id, dataset, _PATHS_TO_CONVERSION_TABLE, date_suffix)\n flags[_PATHS_TO_NON_CONVERSION_TABLE] = _get_table_name(\n project_id, dataset, _PATHS_TO_NON_CONVERSION_TABLE, date_suffix)\n flags[_PATH_SUMMARY_TABLE] = _get_table_name(\n project_id, dataset, _PATH_SUMMARY_TABLE, date_suffix)\n flags[_CHANNEL_COUNTS_TABLE] = _get_table_name(\n project_id, dataset, _CHANNEL_COUNTS_TABLE, date_suffix)\n flags[_REPORT_TABLE] = _get_table_name(\n project_id, dataset, _REPORT_TABLE, date_suffix)\n # Add internal tablenames for conversion and sessions.\n flags['conversions_by_customer_id_table'] = _CONVERSIONS_BY_CUSTOMER_ID_TABLE\n flags['sessions_by_customer_id_table'] = _SESSIONS_BY_CUSTOMER_ID_TABLE\n\n\ndef _update_conversion_window_date_flags(flags: Dict[str, Any]) -> None:\n \"\"\"Updates the conversion window date flags in flags.\n\n Side-effect: Adds conversion_window_start_date and conversion_window_end_date\n to the flags.\n\n Args:\n flags: Dictionary of all flag names to flag values.\n Raises:\n ValueError: User formatted message on error.\n \"\"\"\n conversion_window_length = int(flags['conversion_window_length'])\n if conversion_window_length < 0:\n raise ValueError('conversion_window_length must be non-negative.')\n flags['conversion_window_length'] = conversion_window_length\n if ('conversion_window_end_date' in flags) == (\n 'conversion_window_end_today_offset_days' in flags):\n raise ValueError('Specify either conversion_window_end_date or '\n 'conversion_window_end_today_offset_days')\n end_date = None\n if 'conversion_window_end_today_offset_days' in flags:\n offset_days = int(flags['conversion_window_end_today_offset_days'])\n if offset_days < 0:\n raise ValueError('conversion_window_end_today_offset_days is negative.')\n end_date = (datetime.date.today() - datetime.timedelta(days=offset_days))\n flags['conversion_window_end_date'] = end_date.isoformat()\n else:\n end_date = datetime.datetime.strptime(\n _get_flag_or_die(flags, 'conversion_window_end_date'),\n '%Y-%m-%d').date()\n if end_date > datetime.date.today():\n raise ValueError('conversion_window_end_date is in the future.')\n start_date = end_date - datetime.timedelta(days=conversion_window_length)\n flags['conversion_window_start_date'] = start_date.isoformat()\n\n\ndef _update_path_lookback_flags(flags: Dict[str, Any]) -> None:\n \"\"\"Updates the path lookback flags in flags.\n\n Side-effect: Adds a default no-limit path_lookback_steps to the flags.\n\n Args:\n flags: Dictionary of all flag names to flag values.\n Raises:\n ValueError: User formatted message on error.\n \"\"\"\n path_lookback_days = int(_get_flag_or_die(flags, 'path_lookback_days'))\n if path_lookback_days < 1:\n raise ValueError('path_lookback_days=%d must be a positive integer.'\n % path_lookback_days)\n flags['path_lookback_days'] = path_lookback_days\n if 'path_lookback_steps' in flags:\n path_lookback_steps = int(flags['path_lookback_steps'])\n if path_lookback_steps < 1:\n raise ValueError('path_lookback_steps=%d must be a positive integer.'\n % path_lookback_steps)\n flags['path_lookback_steps'] = path_lookback_steps\n else:\n flags['path_lookback_steps'] = 0\n\n\ndef _extract_channels(\n client: bigquery.client.Client, flags: Dict[str, Any]) -> List[str]:\n \"\"\"Updates the channel definitions from the channel flags.\n\n Args:\n client: BigQuery client.\n flags: Dictionary of all flag names to flag values.\n Returns:\n List of channel names.\n \"\"\"\n extract_channels_sql = env.get_template('extract_channels.sql').render(flags)\n return [row.channel for row in client.query(extract_channels_sql).result()]\n\n\ndef _check_channels_are_valid(channels: List[str]) -> None:\n \"\"\"Dies with user-formatted error if the input channel set is invalid.\n\n Args:\n channels: Complete list of channel names in the fractribution run.\n Raises:\n ValueError: User formatted message on error.\n \"\"\"\n if fractribution.UNMATCHED_CHANNEL not in channels:\n raise ValueError('Channel definitions must include %s.' %\n fractribution.UNMATCHED_CHANNEL)\n for channel in channels:\n if not _is_valid_column_name(channel):\n raise ValueError(\n 'Channel name %s is not a valid BigQuery column name.' % channel)\n\n\ndef _update_fullvisitorid_userid_map_flags(flags: Dict[str, Any]) -> None:\n \"\"\"Updates the flags related to the fullvisitorid_userid_map in flags.\n\n Side-effect: Adds a default update_fullvisitorid_userid_map=True to the flags.\n\n Args:\n flags: Dictionary of all flag names to flag values.\n Raises:\n ValueError: User formatted message on error.\n \"\"\"\n # Set the default behavior to update the id map.\n if 'update_fullvisitorid_userid_map' not in flags:\n flags['update_fullvisitorid_userid_map'] = True\n if 'userid_ga_custom_dimension_index' in flags:\n flags['userid_ga_custom_dimension_index'] = int(\n flags['userid_ga_custom_dimension_index'])\n if flags['userid_ga_custom_dimension_index'] < 1:\n raise ValueError(\n 'userid_ga_custom_dimension_index=%s must be a positive integer' %\n flags['userid_ga_custom_dimension_index'])\n else:\n flags['userid_ga_custom_dimension_index'] = 0\n if 'userid_ga_hits_custom_dimension_index' in flags:\n flags['userid_ga_hits_custom_dimension_index'] = int(\n flags['userid_ga_hits_custom_dimension_index'])\n if flags['userid_ga_hits_custom_dimension_index'] < 1:\n raise ValueError(\n 'userid_ga_hits_custom_dimension_index=%s must be a positive integer'\n % flags['userid_ga_hits_custom_dimension_index'])\n else:\n flags['userid_ga_hits_custom_dimension_index'] = 0\n\n\ndef update_input_flags(flags: Dict[str, Any]) -> None:\n \"\"\"Main function for augmenting and running precondition checks on all flags.\n\n Side-effect: Reforms the hostnames flag, if present, for SQL inclusion.\n\n Args:\n flags: Dictionary of all flag names to flag values.\n Raises:\n ValueError: User formatted message on error.\n \"\"\"\n _get_flag_or_die(flags, 'project_id')\n _get_flag_or_die(flags, 'dataset')\n _update_conversion_window_date_flags(flags)\n _update_table_name_flags(flags)\n _update_path_lookback_flags(flags)\n _update_fullvisitorid_userid_map_flags(flags)\n # Process the hostname restrictions.\n if 'hostnames' in flags:\n flags['hostnames'] = ', '.join(\n [\"'%s'\" % hostname for hostname in flags['hostnames'].split(',')])\n # Check the path_transform.\n path_transform = _get_flag_or_die(flags, 'path_transform')\n if path_transform not in _PATH_TRANSFORMS_MAP.keys():\n raise ValueError(\n 'Unknown path_transform. Use one of: ', _PATH_TRANSFORMS_MAP.keys())\n flags['path_transforms'] = _PATH_TRANSFORMS_MAP[path_transform]\n\n\ndef extract_fractribution_input_data(\n client: bigquery.client.Client, flags: Mapping[str, Any]) -> None:\n \"\"\"Extracts the input data for fractribution into BigQuery.\n\n Args:\n client: BigQuery client.\n flags: Dictionary of all flag names to flag values.\n \"\"\"\n extract_data_sql = _strip_sql(\n env.get_template('extract_data.sql').render(flags))\n # Issue the query, and call result() to wait for it to finish. No results\n # are returned as all output is stored on BigQuery.\n client.query(extract_data_sql).result()\n\n\ndef run_fractribution(\n client: bigquery.client.Client, flags: Mapping[str, Any]) -> None:\n \"\"\"Runs fractribution on the extract_fractribution_input_data BigQuery tables.\n\n Args:\n client: BigQuery client.\n flags: Dictionary of all flag names to flag values.\n \"\"\"\n\n # Step 1: Extract the paths from the path_summary_table.\n frac = fractribution.Fractribution(client.query(\n env.get_template('select_path_summary_query.sql').render(\n path_summary_table=flags['path_summary_table'])))\n # Step 2: Run Fractribution\n frac.run_fractribution()\n frac.normalize_channel_to_attribution_names()\n # Step 3: Create the path_summary_table and upload the results.\n create_path_summary_table_sql = env.get_template(\n 'create_path_summary_results_table.sql').render(flags)\n client.query(create_path_summary_table_sql).result()\n frac.upload_path_summary(client, flags['path_summary_table'])\n\n\ndef generate_report(\n client: bigquery.client.Client, flags: Mapping[str, Any]) -> None:\n \"\"\"Generates the final BigQuery Table with channel-level attribution and ROAS.\n\n Args:\n client: BigQuery client.\n flags: Dictionary of all flag names to flag values.\n \"\"\"\n client.query(env.get_template('generate_report.sql').render(flags)).result()\n\n\ndef run(flags) -> int:\n \"\"\"Main entry point to run Fractribution with the given flags.\n\n Args:\n flags: Dictionary of parameter name to value\n Returns:\n 0 on success and non-zero otherwise\n \"\"\"\n update_input_flags(flags)\n client = bigquery.Client(flags['project_id'])\n client.create_dataset(\n bigquery.Dataset('{}.{}'.format(flags['project_id'], flags['dataset'])),\n exists_ok=True)\n extract_fractribution_input_data(client, flags)\n # Extract the channel definitions into flags for use in later queries.\n flags['channels'] = _extract_channels(client, flags)\n _check_channels_are_valid(flags['channels'])\n run_fractribution(client, flags)\n generate_report(client, flags)\n return 0\n\n\ndef main(event, unused_context=None) -> int:\n \"\"\"Entry point for Cloud Function.\"\"\"\n flags = json.loads(base64.b64decode(event['data']).decode('utf-8'))\n return run(flags)\n","sub_path":"py/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":13372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"219902601","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Nov 4 15:45:38 2015\n\n@author: ce221\n\"\"\"\n\n\nimport string\nfrom operator import itemgetter\n\n\ndef add_word( word_map, word ):\n \n \"\"\"\n Adds the word and tallies the count\n after each successive iteration in\n the word_map\n \"\"\"\n\n #loop throuhgh document, find all the words \n #in the document that aren't in the word map\n if word not in word_map:\n word_map[ word ] = 0\n\n #if the word is there, add 1 to it's count\n word_map[ word ] += 1\n \n\ndef build_map( in_file, word_map ):\n \n \"\"\"\n loops through supplied file, makes a list of words\n by splitton on space. Then loops through newly made \n list and makes punctuated words their own word to count\n \"\"\" \n \n empty_str = \"\"\n \n for line in in_file:\n\n #make a list that contains each of the words\n #of this line, to retrieve all the words\n word_list = line.split()\n\n for word in word_list:\n\n #make the words split on the spaces/punctuations\n #use the add_word function above to add the stripped \n #words to the dic\n word = word.strip().strip(string.punctuation)\n word = word.lower()\n if word != empty_str:\n add_word( word_map, word )\n \n\ndef display_map( word_map ):\n \n \"\"\"\n display_map initalizes the word_list, and loops through\n each succive key and value in the word_map supplied\n to the function. In turn the results become sorted \n increasingly, and the particular kay and it's value are\n stored as a tuple and appended to the bigger list. \n The file is then formatted and printed accordingly.\n \"\"\"\n\n word_list = list()\n\n #retrieve the particular word, and the count\n #of the word, store as tuple, append to big list\n for word, count in word_map.items():\n word_list.append( (word, count) )\n\n #sort the word list to go in increasing order\n #print in a pretty format, also get alphabetical\n freq_list = sorted( word_list, key=itemgetter(1,0) )\n alphabetical = sorted( word_list, key=itemgetter(0,1) )\n highest = sorted( word_list, key=itemgetter(1,0), reverse=True )\n high_alph = sorted( highest, key=itemgetter(0,1) )\n\n\n print(\"\\nFrequency List\")\n print( \"\\n{:15s}{:5s}\".format( \"Word\", \"Count\" ) )\n print( \"-\"*20 )\n for item in freq_list:\n print( \"{:15s}{:>5d}\".format( item[0], item[1] ) )\n \n print(\"\\nAlphabetical List\")\n print( \"\\n{:15s}{:5s}\".format( \"Word\", \"Count\" ) )\n print( \"-\"*20 )\n for item in alphabetical:\n print( \"{:15s}{:>5d}\".format( item[0], item[1] ) )\n \n print(\"\\nHighFreq, Alphabetical List\")\n print( \"\\n{:15s}{:5s}\".format( \"Word\", \"Count\" ) )\n print( \"-\"*20 )\n for item in high_alph:\n print( \"{:15s}{:>5d}\".format( item[0], item[1] ) )\n \n\ndef open_file():\n \n \"\"\"\n Open a particular file, if it doesn't work then\n catch the file.\n \"\"\"\n\n try:\n \n user_file = input(\"Enter a file you would like to know the count of each word for: \")\n in_file = open( user_file, \"r\" )\n \n except IOError:\n print( \"\\n*** unable to open file ***\\n\" )\n in_file = None\n\n return in_file\n\n\ndef main():\n \n \"\"\"\n utilize all the above functions. Initialize the dictionary\n word_map, and the variable in_file from the open_file funciton.\n Then, as long as the file contains information, use the build_map\n function using the dictionary and the file supplied. Use the \n display_map using the new word_map after the build_map function\n has acted on it. And be sure to close the file!\n \"\"\"\n\n word_map = dict()\n in_file = open_file()\n\n if in_file != None:\n \n build_map( in_file, word_map )\n display_map( word_map )\n in_file.close()\n\n\nmain()","sub_path":"labs/lab10.partc.py","file_name":"lab10.partc.py","file_ext":"py","file_size_in_byte":3880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"472829818","text":"from typing import Dict\n\nfrom .time import Time\nfrom .creator import Creator\n\nclass Event:\n def __init__(self,\n _id: str,\n summary: str,\n start: Dict,\n end: Dict,\n kind: str = None,\n status: str = None,\n created: str = None,\n updated: str = None,\n creator: Dict = None,\n organizer: Dict = None,\n reminders: any = None,\n **kwargs):\n self.id = _id\n self.summary = summary\n self.start = Time(start['dateTime'])\n self.end = Time(end['dateTime'])\n self.kind = kind\n self.status = status\n self.created = created\n self.updated = updated\n if creator:\n self.creator = Creator(creator.get('email'))\n if organizer:\n self.organizer = Creator(organizer.get('email'))\n self.reminders = reminders\n\n","sub_path":"src/db/entities/event.py","file_name":"event.py","file_ext":"py","file_size_in_byte":977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"161812029","text":"#!/root/miniconda3/bin/python\n# -*- coding: utf-8 -*-\nimport sys\nimport logging\nfrom pushbullet.messenger import Messenger\n\nFORMAT = '[%(asctime)-15s] @%(levelname)-7s ->%(message)s'\nlogging.basicConfig(level=logging.INFO,format=FORMAT,filename='M_run.log',filemode='w')\n\ndef test_messenger(filename):\n M = Messenger()\n M.test()\n with open(filename,'r') as f: \n for line in f.readlines():\n M.message_buffer(line)\n # M.send_all() \n M.test(\"Nothing New. :)\")\n\ndef test_env():\n\n M = Messenger()\n M.test()\n # for line in sys.stdin:\n # M.message_buffer(line)\n # M.send_all() \n # M.test(\"Nothing New. :)\")\n\nif __name__ == '__main__':\n test_env()\n# test_messenger('./backup/bb.log')\n","sub_path":"testEnv.py","file_name":"testEnv.py","file_ext":"py","file_size_in_byte":743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"584124565","text":"'''star module'''\n\nimport logging\nimport json\n\nfrom T5_worldgen.util import Die, Flux, Table\n\nLOGGER = logging.getLogger(__name__)\nLOGGER.setLevel(logging.CRITICAL)\n\nD2 = Die(2)\nD5 = Die(5)\nD6 = Die(6)\nD10 = Die(10)\nFLUX = Flux()\n\n\nclass _Star(object):\n '''Star base class'''\n # Spectral type\n spectral_type_table = Table()\n spectral_type_table.add_row(-6, 'OB')\n spectral_type_table.add_row((-5, -4), 'A')\n spectral_type_table.add_row((-3, -2), 'F')\n spectral_type_table.add_row((-1, 0), 'G')\n spectral_type_table.add_row((1, 2), 'K')\n spectral_type_table.add_row((3, 5), 'M')\n spectral_type_table.add_row((6, 8), 'BD')\n\n size_o_table = Table()\n size_o_table.add_row((-6, -5), 'Ia')\n size_o_table.add_row(-4, 'Ib')\n size_o_table.add_row(-3, 'II')\n size_o_table.add_row((-2, 0), 'III')\n size_o_table.add_row((1, 3), 'V')\n size_o_table.add_row(4, 'IV')\n size_o_table.add_row(5, 'D')\n size_o_table.add_row((6, 8), 'IV')\n\n # Size\n size_b_table = Table()\n size_b_table.add_row((-6, -5), 'Ia')\n size_b_table.add_row(-4, 'Ib')\n size_b_table.add_row(-3, 'II')\n size_b_table.add_row((-2, 1), 'III')\n size_b_table.add_row((2, 3), 'V')\n size_b_table.add_row(4, 'IV')\n size_b_table.add_row(5, 'D')\n size_b_table.add_row((6, 8), 'IV')\n\n size_a_table = Table()\n size_a_table.add_row((-6, -5), 'Ia')\n size_a_table.add_row(-4, 'Ib')\n size_a_table.add_row(-3, 'II')\n size_a_table.add_row(-2, 'III')\n size_a_table.add_row(-1, 'IV')\n size_a_table.add_row((0, 4), 'V')\n size_a_table.add_row(5, 'D')\n size_a_table.add_row((6, 8), 'V')\n\n size_f_table = Table()\n size_f_table.add_row((-6, -5), 'II')\n size_f_table.add_row(-4, 'III')\n size_f_table.add_row(-3, 'IV')\n size_f_table.add_row((-2, 3), 'V')\n size_f_table.add_row(4, 'VI')\n size_f_table.add_row(5, 'D')\n size_f_table.add_row((6, 8), 'VI')\n\n size_g_table = Table()\n size_g_table.add_row((-6, -5), 'II')\n size_g_table.add_row(-4, 'III')\n size_g_table.add_row(-3, 'IV')\n size_g_table.add_row((-2, 3), 'V')\n size_g_table.add_row(4, 'VI')\n size_g_table.add_row(5, 'D')\n size_g_table.add_row((6, 8), 'VI')\n\n size_k_table = Table()\n size_k_table.add_row((-6, -5), 'II')\n size_k_table.add_row(-4, 'III')\n size_k_table.add_row(-3, 'IV')\n size_k_table.add_row((-2, 3), 'V')\n size_k_table.add_row(4, 'VI')\n size_k_table.add_row(5, 'D')\n size_k_table.add_row((6, 8), 'VI')\n\n size_m_table = Table()\n size_m_table.add_row((-6, -3), 'II')\n size_m_table.add_row(-2, 'III')\n size_m_table.add_row((-1, 3), 'V')\n size_m_table.add_row(4, 'VI')\n size_m_table.add_row(5, 'D')\n size_m_table.add_row((6, 8), 'VI')\n\n # Habitable zone\n hz_orbit_o_table = Table()\n hz_orbit_o_table.add_row('Ia', 15)\n hz_orbit_o_table.add_row('Ib', 15)\n hz_orbit_o_table.add_row('II', 14)\n hz_orbit_o_table.add_row('III', 13)\n hz_orbit_o_table.add_row('IV', 12)\n hz_orbit_o_table.add_row('V', 11)\n hz_orbit_o_table.add_row('D', 1)\n\n hz_orbit_b_table = Table()\n hz_orbit_b_table.add_row('Ia', 13)\n hz_orbit_b_table.add_row('Ib', 13)\n hz_orbit_b_table.add_row('II', 12)\n hz_orbit_b_table.add_row('III', 11)\n hz_orbit_b_table.add_row('IV', 10)\n hz_orbit_b_table.add_row('V', 9)\n hz_orbit_b_table.add_row('D', 0)\n\n hz_orbit_a_table = Table()\n hz_orbit_a_table.add_row('Ia', 12)\n hz_orbit_a_table.add_row('Ib', 11)\n hz_orbit_a_table.add_row('II', 9)\n hz_orbit_a_table.add_row('III', 7)\n hz_orbit_a_table.add_row('IV', 7)\n hz_orbit_a_table.add_row('V', 7)\n hz_orbit_a_table.add_row('D', 0)\n\n hz_orbit_f_table = Table()\n hz_orbit_f_table.add_row('Ia', 11)\n hz_orbit_f_table.add_row('Ib', 10)\n hz_orbit_f_table.add_row('II', 9)\n hz_orbit_f_table.add_row('III', 6)\n hz_orbit_f_table.add_row('IV', 6)\n hz_orbit_f_table.add_row('V', 5)\n hz_orbit_f_table.add_row('VI', 3)\n hz_orbit_f_table.add_row('D', 0)\n\n hz_orbit_g_table = Table()\n hz_orbit_g_table.add_row('Ia', 12)\n hz_orbit_g_table.add_row('Ib', 10)\n hz_orbit_g_table.add_row('II', 9)\n hz_orbit_g_table.add_row('III', 7)\n hz_orbit_g_table.add_row('IV', 5)\n hz_orbit_g_table.add_row('V', 3)\n hz_orbit_g_table.add_row('VI', 2)\n hz_orbit_g_table.add_row('D', 0)\n\n hz_orbit_k_table = Table()\n hz_orbit_k_table.add_row('Ia', 12)\n hz_orbit_k_table.add_row('Ib', 10)\n hz_orbit_k_table.add_row('II', 9)\n hz_orbit_k_table.add_row('III', 8)\n hz_orbit_k_table.add_row('IV', 5)\n hz_orbit_k_table.add_row('V', 2)\n hz_orbit_k_table.add_row('VI', 1)\n hz_orbit_k_table.add_row('D', 0)\n\n hz_orbit_m_table = Table()\n hz_orbit_m_table.add_row('Ia', 12)\n hz_orbit_m_table.add_row('Ib', 11)\n hz_orbit_m_table.add_row('II', 10)\n hz_orbit_m_table.add_row('III', 0)\n hz_orbit_m_table.add_row('V', 0)\n hz_orbit_m_table.add_row('VI', 0)\n hz_orbit_m_table.add_row('D', 0)\n\n def __init__(self):\n self.spectral_type = ''\n self.decimal = 0\n self.size = ''\n self.companion = None\n self.primary_rolls = {}\n self.habitable_zone = ''\n\n def __str__(self):\n return self.code()\n\n def code(self):\n '''Return spec type, decimal, size for this star only'''\n if self.spectral_type == 'BD':\n return 'BD'\n elif self.size == 'D':\n return 'D'\n else:\n return '{}{} {}'.format(\n self.spectral_type, self.decimal, self.size)\n\n def display(self):\n '''Combine spectral type, decimal, size'''\n resp = [str(self)]\n if self.companion is not None:\n resp.append(str(self.companion))\n return ' '.join(resp)\n\n def set_decimal(self):\n '''Set spectral decimal'''\n if self.spectral_type == 'F' and self.size == 'VI':\n self.decimal = D5.roll(1, -1)\n else:\n self.decimal = D10.roll(1, -1)\n\n def has_companion(self):\n '''Companion star?'''\n if FLUX.flux() >= 3:\n LOGGER.debug('Companion exists')\n self.companion = Secondary(self.primary_rolls)\n\n def json_import(self, jdata):\n '''Import from JSON'''\n LOGGER.setLevel(logging.ERROR)\n star_dict = json.loads(jdata)\n self.decimal = star_dict['decimal']\n self.habitable_zone = star_dict['habitable_zone']\n self.spectral_type = star_dict['spectral_type']\n self.size = star_dict['size']\n if star_dict['companion'] is not None:\n self.companion = Secondary({'Spectral type': 3, 'Size': 3})\n self.companion.json_import(star_dict['companion'])\n else:\n self.companion = None\n\n def set_hz(self):\n '''Set habitable zone orbit'''\n if self.spectral_type == 'O':\n self.habitable_zone = self.hz_orbit_o_table.lookup(self.size)\n elif self.spectral_type == 'B':\n self.habitable_zone = self.hz_orbit_b_table.lookup(self.size)\n elif self.spectral_type == 'A':\n self.habitable_zone = self.hz_orbit_a_table.lookup(self.size)\n elif self.spectral_type == 'F':\n self.habitable_zone = self.hz_orbit_f_table.lookup(self.size)\n elif self.spectral_type == 'G':\n self.habitable_zone = self.hz_orbit_g_table.lookup(self.size)\n elif self.spectral_type == 'K':\n self.habitable_zone = self.hz_orbit_k_table.lookup(self.size)\n elif self.spectral_type == 'M':\n self.habitable_zone = self.hz_orbit_m_table.lookup(self.size)\n\n\nclass Primary(_Star):\n '''Primary class'''\n def __init__(self):\n super(Primary, self).__init__()\n self.primary_rolls = {'Spectral type': 0, 'Size': 0}\n self.secondaries = {'Close': None, 'Near': None, 'Far': None}\n self.set_spectral_type()\n self.set_decimal()\n self.set_size()\n LOGGER.debug('Primary: primary_rolls = %s', self.primary_rolls)\n self.set_hz()\n self.has_companion()\n for zone in self.secondaries:\n self.has_secondary(zone)\n\n def display(self):\n '''Combine spectral type, decimal, size'''\n resp = [str(self)]\n if self.companion is not None:\n resp.append(str(self.companion))\n for zone in self.secondaries:\n if self.secondaries[zone] is not None:\n resp.append(str(self.secondaries[zone]))\n return ' '.join(resp)\n\n def set_spectral_type(self):\n '''Set spectral type'''\n roll = FLUX.flux()\n self.spectral_type = self.spectral_type_table.lookup(roll)\n if self.spectral_type == 'OB':\n # Decide randomly\n self.spectral_type = 'OB'[D2.roll(1, -1)]\n self.primary_rolls['Spectral type'] = roll\n\n def set_size(self):\n '''Set size'''\n roll = FLUX.flux()\n self.primary_rolls['Size'] = roll\n if self.spectral_type == 'O':\n self.size = self.size_o_table.lookup(roll)\n elif self.spectral_type == 'B':\n self.size = self.size_b_table.lookup(roll)\n elif self.spectral_type == 'A':\n self.size = self.size_a_table.lookup(roll)\n elif self.spectral_type == 'F':\n self.size = self.size_f_table.lookup(roll)\n elif self.spectral_type == 'G':\n self.size = self.size_g_table.lookup(roll)\n elif self.spectral_type == 'K':\n self.size = self.size_k_table.lookup(roll)\n elif self.spectral_type == 'M':\n self.size = self.size_m_table.lookup(roll)\n\n def has_secondary(self, zone):\n '''Secondary in zone?'''\n if FLUX.flux() >= 3:\n LOGGER.debug('Secondary in zone %s exists', zone)\n self.secondaries[zone] = Secondary(self.primary_rolls)\n\n def as_json(self):\n '''Return JSON representation of star'''\n star_dict = {\n 'spectral_type': self.spectral_type,\n 'decimal': self.decimal,\n 'size': self.size,\n 'habitable_zone': self.habitable_zone\n }\n if self.companion is not None:\n star_dict['companion'] = self.companion.as_json()\n else:\n star_dict['companion'] = None\n star_dict['secondaries'] = {}\n for zone in self.secondaries.keys():\n if self.secondaries[zone] is not None:\n star_dict['secondaries'][zone] = \\\n self.secondaries[zone].as_json()\n return json.dumps(star_dict)\n\n def json_import(self, jdata):\n '''Import from JSON'''\n LOGGER.setLevel(logging.ERROR)\n # Common elements (spectral_type, size, decmal, hz, companion)\n super(Primary, self).json_import(jdata)\n star_dict = json.loads(jdata)\n # Secondaries\n for zone in star_dict['secondaries'].keys():\n self.secondaries[zone] = Secondary({'Spectral type': 3, 'Size': 3})\n self.secondaries[zone].json_import(star_dict['secondaries'][zone])\n\n\n\nclass Secondary(_Star):\n '''Non-primary star class'''\n def __init__(self, primary_rolls):\n super(Secondary, self).__init__()\n self.primary_rolls = primary_rolls\n LOGGER.debug('Secondary: primary_rolls = %s', self.primary_rolls)\n self.set_spectral_type()\n self.set_decimal()\n self.set_size()\n self.set_hz()\n self.has_companion()\n\n def set_spectral_type(self):\n '''Set spectral type'''\n roll = D6.roll(1, -1)\n roll += self.primary_rolls['Spectral type']\n roll = min(roll, 8)\n roll = max(roll, -6)\n self.spectral_type = self.spectral_type_table.lookup(roll)\n if self.spectral_type == 'OB':\n # Decide randomly\n self.spectral_type = 'OB'[D2.roll(1, -1)]\n\n def set_size(self):\n '''Set size'''\n roll = D6.roll(1, -1)\n roll += self.primary_rolls['Size']\n roll = min(roll, 8)\n roll = max(roll, -6)\n if self.spectral_type == 'O':\n self.size = self.size_o_table.lookup(roll)\n elif self.spectral_type == 'B':\n self.size = self.size_b_table.lookup(roll)\n elif self.spectral_type == 'A':\n self.size = self.size_a_table.lookup(roll)\n elif self.spectral_type == 'F':\n self.size = self.size_f_table.lookup(roll)\n elif self.spectral_type == 'G':\n self.size = self.size_g_table.lookup(roll)\n elif self.spectral_type == 'K':\n self.size = self.size_k_table.lookup(roll)\n elif self.spectral_type == 'M':\n self.size = self.size_m_table.lookup(roll)\n\n def as_json(self):\n '''Return JSON representation'''\n star_dict = {\n 'spectral_type': self.spectral_type,\n 'decimal': self.decimal,\n 'size': self.size,\n 'habitable_zone': self.habitable_zone,\n }\n if self.companion is not None:\n star_dict['companion'] = self.companion.as_json()\n else:\n star_dict['companion'] = None\n\n return json.dumps(star_dict)\n","sub_path":"T5_worldgen/star.py","file_name":"star.py","file_ext":"py","file_size_in_byte":13111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"225613787","text":"class Solution(object):\n\n def compareVersion(self, version1, version2):\n \"\"\"\n :type version1: str\n :type version2: str\n :rtype: int\n \"\"\"\n ver1 = version1.split('.')\n ver2 = version2.split('.')\n len1, len2 = len(ver1), len(ver2)\n while len1 < len2:\n ver1.append(0)\n len1 += 1\n while len2 < len1:\n ver2.append(0)\n len2 += 1\n for i in xrange(len1):\n a, b = int(ver1[i]), int(ver2[i])\n if a > b:\n return 1\n if a < b:\n return -1\n return 0\n","sub_path":"165.py","file_name":"165.py","file_ext":"py","file_size_in_byte":628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"321278027","text":"import sys\r\nimport ccm\r\nfrom EmilyMotorModule import *\r\nfrom RTModule import *\r\nfrom ccm.lib.actr import *\r\nfrom random import randrange, uniform\r\n\r\n#####################\r\n##### The Agent #####\r\n#####################\r\n\r\nclass MyAgent(ACTR):\r\n\r\n# BUFFERS\r\n focus=Buffer()\r\n\r\n b_context = Buffer()\r\n b_plan_unit = Buffer()\r\n b_plan_unit_order = Buffer()\r\n b_unit_task = Buffer()\r\n b_method = Buffer()\r\n b_operator = Buffer()\r\n b_DM = Buffer()\r\n b_motor = Buffer()\r\n b_visual = Buffer()\r\n\r\n # visual = Buffer()\r\n\r\n# MODULES (import modules into agent, connect to buffers, and add initial content)\r\n\r\n # motor module - defined above\r\n motor = EmilyMotorModule(b_motor)\r\n\r\n # declarative memory module - from CCM suite\r\n DM = Memory(b_DM)\r\n\r\n # reation time module - used to record the reaction time of the agent\r\n RT = RTModule()\r\n\r\n # initial buffer contents\r\n b_context.set('status:unoccupied planning_unit:none')\r\n b_plan_unit.set('planning_unit:P unit_task:P state:P type:P')\r\n b_visual.set('00')\r\n focus.set('start')\r\n b_plan_unit_order.set('counter:oo first:oo second:oo third:oo fourth:oo')\r\n\r\n # initial memory contents\r\n\r\n\r\n\r\n########### create productions for choosing planning units ###########\r\n\r\n ## these productions are the highest level of SGOMS and fire off the context buffer\r\n ## they can take any ACT-R form (one production or more) but must eventually call a planning unit and update the context buffer\r\n\r\n def START_start(b_context='status:unoccupied planning_unit:none'):\r\n b_unit_task.set('unit_task:START state:running')\r\n b_context.modify(status='starting_game')\r\n print ('Look at code to determin new planning unit')\r\n motor.see_code()\r\n\r\n\r\n def START_AK(b_context='status:starting_game planning_unit:none',\r\n b_unit_task='unit_task:START state:running',\r\n b_method='state:finished',\r\n b_visual='AK'): \r\n b_plan_unit.modify(planning_unit='AK',unit_task='AK',state='begin_sequence',type='ordered')\r\n\r\n b_context.modify(status='occupied')\r\n print ('run_AK_PU')\r\n b_plan_unit_order.set('counter:one first:AK second:HW third:RP fourth:finished') ######## new buffer\r\n\r\n\r\n def START_RP(b_context='status:starting_game planning_unit:none',\r\n b_unit_task='unit_task:START state:running',\r\n b_method='state:finished',\r\n b_visual='RP'): \r\n b_plan_unit.modify(planning_unit='RP',unit_task='RP',state='begin_sequence',type='ordered')\r\n b_context.modify(status='occupied')\r\n print ('run_RP_PU')\r\n b_plan_unit_order.set('counter:one first:RP second:HW third:AK fourth:finished') ######## new buffer\r\n\r\n\r\n def START_HW(b_context='status:starting_game planning_unit:none',\r\n b_unit_task='unit_task:START state:running',\r\n b_method='state:finished',\r\n b_visual='HW'): \r\n b_plan_unit.modify(planning_unit='HW',unit_task='HW',state='begin_sequence',type='ordered')\r\n b_plan_unit_order.set('counter:one first:HW second:RP third:AK fourth:finished') ######## new buffer\r\n b_context.modify(status='occupied')\r\n print ('run_HW_PU')\r\n print\r\n\r\n########## unit task management productions ###########\r\n\r\n######################### these manage the sequence if it is an ordered planning unit stored in DM\r\n\r\n## removed to make the code easier to work with (for now)\r\n## because we do not think a fast game player retrieves unit tasks from DM\r\n## human results on this game suggest this\r\n## we think humans can store the unit tasks of a limited sized planning unit in a buffer for fast access\r\n\r\n######################### these manage the sequence if it is an ordered planning unit stored in buffer\r\n\r\n## here we assume that humans can store an ordered planning unit of up to 4 unit tasks in a buffer\r\n## we also assume that there is a different production for each unit task stored\r\n## an alternative model would be a couple of productions that cycle through\r\n## in theory, the system will move onto the next planning unit when this one is done\r\n## even if it has less than 4 unit tasks\r\n\r\n\r\n def setup_first_unit_task(b_plan_unit='unit_task:?unit_task state:begin_sequence type:ordered'):\r\n b_unit_task.set('unit_task:?unit_task state:start type:ordered')\r\n b_plan_unit.modify(state='running')\r\n print ('fast - start first unit task')\r\n\r\n def request_second_unit_task(b_plan_unit='state:running',\r\n b_unit_task='unit_task:?unit_task state:finished type:ordered',\r\n b_plan_unit_order='counter:one first:?first second:?second third:?third fourth:?fourth'):\r\n b_unit_task.set('unit_task:?second state:start type:ordered')\r\n b_plan_unit_order.modify(counter='two')\r\n print ('fast - start second unit task')\r\n\r\n def request_third_unit_task(b_plan_unit='state:running',\r\n b_unit_task='unit_task:?unit_task state:finished type:ordered',\r\n b_plan_unit_order='counter:two first:?first second:?second third:?third fourth:?fourth',):\r\n b_unit_task.set('unit_task:?third state:start type:ordered')\r\n b_plan_unit_order.modify(counter='three')\r\n print ('fast - start third unit task')\r\n\r\n def request_fourth_unit_task(b_plan_unit='state:running',\r\n b_unit_task='unit_task:?unit_task state:finished type:ordered',\r\n b_plan_unit_order='counter:three first:?first second:?second third:?third fourth:?fourth'):\r\n b_plan_unit_order.modify(counter='four')\r\n b_unit_task.set('unit_task:?fourth state:start type:ordered')\r\n print ('fast - start fourth unit task')\r\n\r\n########################## these manage planning units that are finished ###################\r\n\r\n def last_unit_task_ordered_plan(b_plan_unit='planning_unit:?planning_unit',\r\n b_unit_task='unit_task:finished state:start type:ordered'):\r\n print ('finished planning unit =');\r\n print (planning_unit)\r\n b_unit_task.set('stop')\r\n b_context.modify(status='unoccupied')\r\n ############################### referee\r\n choices = ['AK','RP','HW']\r\n x=random.choice(choices)\r\n motor.referee_action('display', 'state', x)\r\n ############################### referee\r\n\r\n\r\n#################\r\n##### AK UT #####\r\n#################\r\n\r\n# AK unit task AK-WM-SU-ZB-FJ\r\n\r\n## add condition to fire this production\r\n\r\n def AK_ordered(b_unit_task='unit_task:AK state:start type:ordered'):\r\n b_unit_task.modify(state='begin')\r\n print ('start unit task AK')\r\n\r\n def AK_start(b_unit_task='unit_task:AK state:begin'):\r\n b_unit_task.set('unit_task:AK state:running')\r\n focus.set('AK')\r\n target='responce'\r\n content='AK-AK-1234'\r\n motor.enter_response(target, content)\r\n\r\n def AK_WM(b_unit_task='unit_task:AK state:running',\r\n vision_finst='state:finished',\r\n focus='AK'):\r\n focus.set('WM')\r\n target='responce'\r\n content='AK-WM-1432'\r\n motor.enter_response(target, content)\r\n \r\n def AK_SU(b_unit_task='unit_task:AK state:running',\r\n vision_finst='state:finished',\r\n focus='WM'):\r\n focus.set('SU')\r\n target='responce'\r\n content='AK-SU-4123'\r\n motor.enter_response(target, content)\r\n\r\n def AK_ZB(b_unit_task='unit_task:AK state:running',\r\n vision_finst='state:finished',\r\n focus='SU'):\r\n focus.set('ZB')\r\n target='responce'\r\n content='AK-ZB-2143'\r\n motor.enter_response(target, content)\r\n\r\n def AK_FJ(b_unit_task='unit_task:AK state:running',\r\n vision_finst='state:finished',\r\n focus='ZB'):\r\n focus.set('done')\r\n target='responce'\r\n content='AK-FJ-3214'\r\n motor.enter_response(target, content)\r\n\r\n def AK_finished_ordered(b_unit_task='unit_task:AK state:running',\r\n vision_finst='state:finished',\r\n focus='done'):\r\n print ('finished unit task AK(ordered)')\r\n b_unit_task.set('unit_task:AK state:finished type:ordered')\r\n\r\n\r\n\r\n########################\r\n##### RP Unit Task #####\r\n########################\r\n\r\n# YP-FJ\r\n# RP unit task RP-SU<\r\n# ZB-WM\r\n\r\n def RP_ordered(b_unit_task='unit_task:RP state:start type:ordered'):\r\n b_unit_task.modify(state='begin')\r\n print ('start unit task RP')\r\n\r\n def RP_start(b_unit_task='unit_task:RP state:begin'):\r\n b_unit_task.set('unit_task:RP state:running')\r\n focus.set('RP')\r\n target='responce'\r\n content='RP-RP-4321'\r\n motor.enter_response(target, content)\r\n\r\n def RP_SU(b_unit_task='unit_task:RP state:running',\r\n vision_finst='state:finished',\r\n focus='RP'):\r\n focus.set('SU')\r\n target='responce'\r\n content='RP-SU-4123'\r\n motor.enter_response(target, content)\r\n\r\n ### Unkown code\r\n \r\n def RP_identify2(b_unit_task='unit_task:RP state:running',\r\n vision_finst='state:finished',\r\n focus='SU'):\r\n ############################### referee\r\n choices = ['YP','ZB']\r\n x=random.choice(choices)\r\n motor.referee_action('display', 'state', x)\r\n ############################### referee \r\n motor.see_code()\r\n focus.set('code_seen')\r\n print ('waiting to see if YP or ZB')\r\n\r\n def RP_YP(b_unit_task='unit_task:RP state:running',\r\n vision_finst='state:finished',\r\n focus='code_seen',\r\n b_visual='YP'):\r\n focus.set('done')\r\n target='responce'\r\n content='RP-YP-3412'\r\n motor.enter_response(target, content)\r\n\r\n def RP_ZB(b_unit_task='unit_task:RP state:running',\r\n vision_finst='state:finished',\r\n focus='code_seen',\r\n b_visual='ZB'):\r\n focus.set('done')\r\n target='responce'\r\n content='RP-ZB-2143'\r\n motor.enter_response(target, content)\r\n\r\n def RP_FJ(b_unit_task='unit_task:RP state:running',\r\n vision_finst='state:finished',\r\n focus='YP'):\r\n focus.set('done')\r\n target='responce'\r\n content='RP-FJ-3214'\r\n motor.enter_response(target, content)\r\n\r\n def RP_WM(b_unit_task='unit_task:RP state:running',\r\n vision_finst='state:finished',\r\n focus='ZB'):\r\n focus.set('done')\r\n target='responce'\r\n content='RP-WM-1432'\r\n motor.enter_response(target, content)\r\n\r\n def RP_finished_ordered(b_unit_task='unit_task:RP state:running',\r\n vision_finst='state:finished',\r\n focus='done'):\r\n print ('finished unit task RP(ordered)')\r\n b_unit_task.set('unit_task:RP state:finished type:ordered')\r\n\r\n########################\r\n##### HW Unit Task #####\r\n########################\r\n\r\n# / FJ\r\n# HW unit task HW-YP--- ZB\r\n# \\ SU\r\n\r\n def HW_ordered(b_unit_task='unit_task:HW state:start type:ordered'):\r\n b_unit_task.modify(state='begin')\r\n print ('start unit task HW')\r\n\r\n ## the first production in the unit task must begin this way\r\n def HW_start(b_unit_task='unit_task:HW state:begin'):\r\n b_unit_task.set('unit_task:HW state:running')\r\n focus.set('HW')\r\n target='responce'\r\n content='HW-HW-2341'\r\n motor.enter_response(target, content)\r\n\r\n def HW_YP(b_unit_task='unit_task:HW state:running',\r\n vision_finst='state:finished',\r\n focus='HW'):\r\n focus.set('YP')\r\n target='responce'\r\n content='HW-YP-3412'\r\n motor.enter_response(target, content)\r\n\r\n ### Unkown code\r\n \r\n def HW_identify3(b_unit_task='unit_task:HW state:running',\r\n vision_finst='state:finished',\r\n focus='YP'):\r\n ############################### referee\r\n choices = ['FJ','SU','ZB']\r\n x=random.choice(choices)\r\n motor.referee_action('display', 'state', x)\r\n ############################### referee \r\n motor.see_code()\r\n focus.set('code_seen')\r\n print ('waiting to see if FJ, SU, or ZB')\r\n \r\n\r\n #### FJ or SU or ZB then end\r\n \r\n def HW_FJ(b_unit_task='unit_task:HW state:running',\r\n vision_finst='state:finished',\r\n focus='code_seen',\r\n b_visual='FJ'):\r\n focus.set('done')\r\n target='responce'\r\n content='HW-FJ-3214'\r\n motor.enter_response(target, content)\r\n\r\n\r\n def HW_SU(b_unit_task='unit_task:HW state:running',\r\n vision_finst='state:finished',\r\n focus='code_seen',\r\n b_visual='SU'):\r\n focus.set('done')\r\n target='responce'\r\n content='HW-SU-4123'\r\n motor.enter_response(target, content)\r\n\r\n\r\n def HW_ZB(b_unit_task='unit_task:HW state:running',\r\n vision_finst='state:finished',\r\n focus='code_seen',\r\n b_visual='ZB'):\r\n focus.set('done')\r\n target='responce'\r\n content='HW-ZB-2143'\r\n motor.enter_response(target, content)\r\n\r\n def HW_finished_ordered(b_unit_task='unit_task:HW state:running',\r\n vision_finst='state:finished',\r\n focus='done'):\r\n print ('finished unit task HW(ordered)')\r\n b_unit_task.set('unit_task:HW state:finished type:ordered')\r\n\r\n","sub_path":"4ButtonExpert/Emily.py","file_name":"Emily.py","file_ext":"py","file_size_in_byte":13876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"336656833","text":"from glycopeptidepy.enzyme import cleave\nfrom glycopeptidepy.structure.sequence import PeptideSequence, list_to_sequence\nfrom glycopeptidepy.structure.parser import sequence_tokenizer_respect_sequons\n\n\ndef pair_rotate(sequence):\n \"\"\"Invert each token pair.\n\n ABCD -> BADC\n\n Parameters\n ----------\n sequence : iterable\n\n Returns\n -------\n list\n \"\"\"\n chunks = []\n gen = iter(sequence)\n while True:\n chunk = []\n try:\n chunk = [next(gen)]\n chunk.append(next(gen))\n chunks.append(chunk)\n except StopIteration:\n if len(chunk) > 0:\n chunks.append(chunk)\n break\n rev_seq = []\n for chunk in reversed(chunks):\n rev_seq.extend(chunk)\n return rev_seq\n\n\ndef edit_distance(s1, s2):\n if len(s1) > len(s2):\n s1, s2 = s2, s1\n\n distances = range(len(s1) + 1)\n for i2, c2 in enumerate(s2):\n distances_ = [i2 + 1]\n for i1, c1 in enumerate(s1):\n if c1 == c2:\n distances_.append(distances[i1])\n else:\n distances_.append(1 + min((distances[i1], distances[i1 + 1], distances_[-1])))\n distances = distances_\n return distances[-1]\n\n\ndef reverse_preserve_sequon(sequence, prefix_len=0, suffix_len=1, peptide_type=None):\n if peptide_type is None:\n peptide_type = PeptideSequence\n if isinstance(sequence, PeptideSequence):\n sequence = str(sequence)\n original = peptide_type(sequence)\n sequence_tokens = sequence_tokenizer_respect_sequons(sequence)\n pref = sequence_tokens[:prefix_len]\n if suffix_len == 0:\n suf = \"\"\n body = sequence_tokens[prefix_len:]\n else:\n suf = sequence_tokens[-suffix_len:]\n body = sequence_tokens[prefix_len:-suffix_len]\n body = body[::-1]\n rev_sequence = (list_to_sequence(pref + list(body) + suf))\n if str(list_to_sequence(sequence_tokens)) == str(rev_sequence):\n rot_body = pair_rotate(body)\n rev_sequence = (list_to_sequence(pref + list(rot_body) + suf))\n rev_sequence.n_term = original.n_term\n rev_sequence.c_term = original.c_term\n if original.glycan:\n rev_sequence.glycan = original.glycan.clone(propogate_composition_offset=False)\n return rev_sequence\n","sub_path":"glycopeptidepy/algorithm.py","file_name":"algorithm.py","file_ext":"py","file_size_in_byte":2295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"287132170","text":"#coding:utf-8\nimport shutil\nreadDir = \"/home/sleeve/桌面/TCwork_git/data/wikisql_tok1/test_tok/train_tok.jsonl\"\nwriteDir = \"/home/sleeve/桌面/TCwork_git/data/wikisql_tok1/test_tok/train_tok2.jsonl\"\nlines_seen = set()\noutfile=open(writeDir,\"w\")\nf = open(readDir,\"r\")\nfor line in f:\n if line not in lines_seen:\n outfile.write(line)\n lines_seen.add(line)\noutfile.close()\nprint (\"success\")\n","sub_path":"quchong.py","file_name":"quchong.py","file_ext":"py","file_size_in_byte":407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"183365998","text":"# credit: https://stackoverflow.com/questions/765736/using-pil-to-make-all-white-pixels-transparent\n\nfrom PIL import Image\n\nimg = Image.open(r'avatar-cropped-white-back.png')\nimg = img.convert(\"RGBA\")\ndatas = img.getdata()\n\nnewData = []\nthreshold = 220\nfor item in datas:\n if item[0] >= threshold and item[1] >= threshold and item[2] >= threshold:\n newData.append((255, 255, 255, 0))\n else:\n newData.append(item)\n\nimg.putdata(newData)\nimg.save(\"avatar-cropped.png\", \"PNG\")\n","sub_path":"Interfaces/Website/ArabicPoemGenerator/sig_ext.py","file_name":"sig_ext.py","file_ext":"py","file_size_in_byte":493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"244759372","text":"# -*- coding: utf-8 -*-\n\n\nfrom functools import update_wrapper\nfrom flask import make_response, request, current_app\nfrom .core import *\n\nLOG = logging.getLogger(__name__)\n\ndef crossorigin(*args, **kwargs):\n\n _options = kwargs\n\n def decorator(f):\n LOG.debug(\"Enabling %s for cross_origin using options:%s\", f, _options)\n\n if _options.get('automatic_options', True):\n f.required_methods = getattr(f, 'required_methods', set())\n f.required_methods.add('OPTIONS')\n f.provide_automatic_options = False\n\n def wrapped_function(*args, **kwargs):\n # Handle setting of Flask-Cors parameters\n options = get_cors_options(current_app, _options)\n\n if options.get('automatic_options') and request.method == 'OPTIONS':\n resp = current_app.make_default_options_response()\n else:\n resp = make_response(f(*args, **kwargs))\n\n set_cors_headers(resp, options)\n setattr(resp, FLASK_CORS_EVALUATED, True)\n return resp\n\n return update_wrapper(wrapped_function, f)\n return decorator\n","sub_path":"flaskcors/decorator.py","file_name":"decorator.py","file_ext":"py","file_size_in_byte":1135,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"253469622","text":"from django.shortcuts import render\nfrom django.views.generic import View\n\nfrom apps.back.models import Back_Menu\nfrom .models import Back_Module, Index_Module, Setup, Setup_Input\nfrom .forms import BackModuleForm, IndexModuleForm\n\nfrom utils import con_function, restful\n\ndef get_backmenu(request):\n backmenu = Back_Menu.objects.all()\n setup = Setup.objects.all()\n return {'base_backmenu': backmenu, 'setup': setup}\n\n\ndef backmodule(request):\n '''\n 开发者管理,后台模块名设置\n '''\n module = Back_Module.objects.all()\n return render(request, 'back/developer/backmodule.html', context={'module': module})\n \ndef backmodule_insert(request):\n form = BackModuleForm(request.POST)\n if form.is_valid():\n title = form.cleaned_data.get('title')\n module = form.cleaned_data.get('module')\n Back_Module.objects.create(title=title, module=module)\n return restful.ok('添加成功!')\n else :\n return restful.params_error(message=form.errors)\n\ndef backmodule_update(request):\n id = request.POST.get('id')\n form = BackModuleForm(request.POST)\n if form.is_valid():\n backmodule = Back_Module.objects.get(pk=id)\n backmodule.title = form.cleaned_data.get('title')\n backmodule.module = form.cleaned_data.get('module')\n backmodule.save()\n return restful.ok('修改成功!')\n else :\n return restful.params_error(message=form.errors)\n\ndef backmodule_delete(request):\n id = request.POST.get('id')\n module = Back_Module.objects.get(pk=id)\n module.delete()\n return restful.ok('删除成功!')\n\ndef indexmodule(request):\n '''\n 开发者管理,前台模块名设置\n '''\n module = Index_Module.objects.all()\n return render(request, 'back/developer/indexmodule.html', context={'module': module})\n \ndef indexmodule_insert(request):\n form = IndexModuleForm(request.POST)\n if form.is_valid():\n title = form.cleaned_data.get('title')\n module = form.cleaned_data.get('module')\n Index_Module.objects.create(title=title, module=module)\n return restful.ok('添加成功!')\n else :\n return restful.params_error(message=form.errors)\n\ndef indexmodule_update(request):\n id = request.POST.get('id')\n form = IndexModuleForm(request.POST)\n if form.is_valid():\n indexmodule = Index_Module.objects.get(pk=id)\n indexmodule.title = form.cleaned_data.get('title')\n indexmodule.module = form.cleaned_data.get('module')\n indexmodule.save()\n return restful.ok('修改成功!')\n else :\n return restful.params_error(message=form.errors)\n\ndef indexmodule_delete(request):\n id = request.POST.get('id')\n module = Index_Module.objects.get(pk=id)\n module.delete()\n return restful.ok('删除成功!')\n\n\ndef setup(request):\n '''\n 系统设置模块名\n '''\n setup_list = Setup.objects.all()\n for i in setup_list:\n i.input = Setup_Input.objects.filter(setup_id=i.id)\n return render(request, 'back/developer/setup.html', context={'setup_list': setup_list})\n\nclass SetupInsert(View):\n def get(self, request):\n setup_list = Setup.objects.all()\n return render(request, 'back/developer/setup_insert.html', context={'setup_list': setup_list})\n \n def post(self, request):\n title = request.POST.get('title')\n setup_id = request.POST.get('setup_id')\n if setup_id == '0': #模块 \n Setup.objects.create(title=title)\n else: #填写项\n if setup_id == '0':\n return restful.params_error(message='请选择模块!')\n setup = Setup.objects.get(pk=setup_id)\n Setup_Input.objects.create(title=title, setup=setup)\n return restful.ok('添加成功!')\n\nclass SetupUpdate(View):\n def get(self, request, type, id):\n setup_list = Setup.objects.all()\n if type == 'setup': #模块\n detail = Setup.objects.get(pk=id)\n detail.setup_id = 0\n else: #填写项\n detail = Setup_Input.objects.get(pk=id)\n return render(request, 'back/developer/setup_update.html', context={'setup_list': setup_list, 'detail': detail, 'type': type})\n\n def post(self, request, type, id):\n input_id = request.POST.get('input_id')\n input_type = request.POST.get('input_type')\n title = request.POST.get('title')\n setup_id = request.POST.get('setup_id')\n if input_type == 'setup': #模块\n item = Setup.objects.get(pk=id)\n item.title = title\n item.save()\n else: #填写项\n item = Setup_Input.objects.get(pk=input_id)\n item.title = title\n if setup_id == '0':\n return restful.params_error(message='请选择模块!')\n setup = Setup.objects.get(pk=setup_id)\n item.setup = setup\n item.save()\n return restful.ok('修改成功!')\n\ndef setup_delete(request):\n id = request.POST.get('id')\n setup_type = request.POST.get('type')\n if setup_type == 'setup': #模块\n item = Setup.objects.get(pk=id)\n else: #填写项\n item = Setup_Input.objects.get(pk=id)\n item.delete()\n return restful.ok('删除成功!')\n\ndef setup_input(request, id):\n '''\n 设置页面\n '''\n setup_input = Setup_Input.objects.filter(setup_id=id)\n return render(request, 'back/developer/setup_input.html', context={'setup_input': setup_input, 'setup_id': id})\n \n","sub_path":"apps/backbase/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"34880218","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Apr 8 21:48:33 2016\r\n\r\n@author: Leo\r\n\"\"\"\r\n\r\nimport numpy as np\r\n\r\ndef calculateMaxDD(cumret):\r\n highwatermark = np.zeros((len(cumret),))\r\n drawdown = np.zeros((len(cumret),))\r\n drawdownduration = np.zeros((len(cumret),))\r\n cumret_ = np.array(cumret)\r\n for t in range(1, len(cumret)):\r\n highwatermark[t,]=max(highwatermark[t-1,], cumret_[t,]); # all are [,0]\r\n drawdown[t,]=(1+cumret_[t,])/(1+highwatermark[t,])-1; # drawdown on each day\r\n if (drawdown[t,]==0):\r\n drawdownduration[t,]=0;\r\n else:\r\n drawdownduration[t,]=drawdownduration[t-1,]+1;\r\n maxDD=min(drawdown); # maximum drawdown\r\n maxDDD=max(drawdownduration); # maximum drawdown duration\r\n return (maxDD, maxDDD)","sub_path":"Utilities.py","file_name":"Utilities.py","file_ext":"py","file_size_in_byte":792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"481047098","text":"# -*- coding: utf-8 -*-\n\nimport sys\nimport os\nimport time\nimport string\nimport shutil\nimport subprocess\nimport signal\nimport argparse\n\nimport common\n\ndef getADBProgramPID(program):\n\tadbCmd\t= common.shellquote(common.ADB_BIN)\n\tpid\t\t= -1\n\n\tprocess = subprocess.Popen(\"%s shell ps\" % adbCmd, shell=True, stdout=subprocess.PIPE)\n\n\tfirstLine = True\n\tfor line in process.stdout.readlines():\n\t\tif firstLine:\n\t\t\tfirstLine = False\n\t\t\tcontinue\n\n\t\tfields = string.split(line)\n\t\tfields = filter(lambda x: len(x) > 0, fields)\n\n\t\tif len(fields) < 9:\n\t\t\tcontinue\n\n\t\tif fields[8] == program:\n\t\t\tassert pid == -1\n\t\t\tpid = int(fields[1])\n\n\tprocess.wait()\n\n\tif process.returncode != 0:\n\t\tprint(\"adb shell ps returned %s\" % str(process.returncode))\n\t\tpid = -1\n\n\treturn pid\n\ndef debug(\n\tadbCmd,\n\tdeqpCmdLine,\n\ttargetGDBPort,\n\thostGDBPort,\n\tjdbPort,\n\tjdbCmd,\n\tgdbCmd,\n\tbuildDir,\n\tdeviceLibs,\n\tbreakpoints\n\t):\n\n\tprogramPid\t\t\t= -1\n\tgdbServerProcess\t= None\n\tgdbProcess\t\t\t= None\n\tjdbProcess\t\t\t= None\n\tcurDir\t\t\t\t= os.getcwd()\n\tdebugDir\t\t\t= os.path.join(common.ANDROID_DIR, \"debug\")\n\n\tif os.path.exists(debugDir):\n\t\tshutil.rmtree(debugDir)\n\n\tos.makedirs(debugDir)\n\tos.chdir(debugDir)\n\n\ttry:\n\t\t# Start execution\n\t\tprint(\"Starting intent...\")\n\t\tcommon.execute(\"%s shell am start -W -D -n com.drawelements.deqp/android.app.NativeActivity -e cmdLine \\\"unused %s\\\"\" % (adbCmd, deqpCmdLine.replace(\"\\\"\", \"\\\\\\\"\")))\n\t\tprint(\"Intent started\")\n\n\t\t# Kill existing gdbservers\n\t\tprint(\"Check and kill existing gdbserver\")\n\t\tgdbPid = getADBProgramPID(\"lib/gdbserver\")\n\t\tif gdbPid != -1:\n\t\t\tprint(\"Found gdbserver with PID %i\" % gdbPid)\n\t\t\tcommon.execute(\"%s shell run-as com.drawelements.deqp kill -9 %i\" % (adbCmd, gdbPid))\n\t\t\tprint(\"Killed gdbserver\")\n\t\telse:\n\t\t\tprint(\"Couldn't find existing gdbserver\")\n\n\t\tprogramPid = getADBProgramPID(\"com.drawelements.deqp:testercore\")\n\n\t\tprint(\"Find process PID\")\n\t\tif programPid == -1:\n\t\t\tcommon.die(\"Couldn't get PID of testercore\")\n\t\tprint(\"Process running with PID %i\" % programPid)\n\n\t\t# Start gdbserver\n\t\tprint(\"Start gdbserver for PID %i redirect stdout to gdbserver-stdout.txt\" % programPid)\n\t\tgdbServerProcess = subprocess.Popen(\"%s shell run-as com.drawelements.deqp lib/gdbserver localhost:%i --attach %i\" % (adbCmd, targetGDBPort, programPid), shell=True, stdin=subprocess.PIPE, stdout=open(\"gdbserver-stdout.txt\", \"wb\"), stderr=open(\"gdbserver-stderr.txt\", \"wb\"))\n\t\tprint(\"gdbserver started\")\n\n\t\ttime.sleep(1)\n\n\t\tgdbServerProcess.poll()\n\n\t\tif gdbServerProcess.returncode != None:\n\t\t\tcommon.die(\"gdbserver returned unexpectly with return code %i see gdbserver-stdout.txt for more info\" % gdbServerProcess.returncode)\n\n\t\t# Setup port forwarding\n\t\tprint(\"Forwarding local port to gdbserver port\")\n\t\tcommon.execute(\"%s forward tcp:%i tcp:%i\" % (adbCmd, hostGDBPort, targetGDBPort))\n\n\t\t# Pull some data files for debugger\n\t\tprint(\"Pull /system/bin/app_process from device\")\n\t\tcommon.execute(\"%s pull /system/bin/app_process\" % adbCmd)\n\n\t\tprint(\"Pull /system/bin/linker from device\")\n\t\tcommon.execute(\"%s pull /system/bin/linker\" % adbCmd)\n\n\t\tfor lib in deviceLibs:\n\t\t\tprint(\"Pull library %s from device\" % lib)\n\t\t\tcommon.execute(\"%s pull %s\" % (adbCmd, lib))\n\n\t\tprint(\"Copy libtestercore.so from build dir\")\n\t\tshutil.copyfile(os.path.join(buildDir, \"libtestercore.so\"), \"libtestercore.so\")\n\n\t\t# Forward local port for jdb\n\t\tprint(\"Forward local port to jdb port\")\n\t\tcommon.execute(\"%s forward tcp:%i jdwp:%i\" % (adbCmd, jdbPort, programPid))\n\n\t\t# Connect JDB\n\t\tprint(\"Start jdb process redirectd stdout to jdb-stdout.txt\")\n\t\tjdbProcess = subprocess.Popen(\"%s -connect com.sun.jdi.SocketAttach:hostname=localhost,port=%i -sourcepath ../package\" % (jdbCmd, jdbPort), shell=True, stdin=subprocess.PIPE, stdout=open(\"jdb-stdout.txt\", \"wb\"), stderr=open(\"jdb-stderr.txt\", \"wb\"))\n\t\tprint(\"Started jdb process\")\n\n\t\t# Write gdb.setup\n\t\tprint(\"Write gdb.setup\")\n\t\tgdbSetup = open(\"gdb.setup\", \"wb\")\n\t\tgdbSetup.write(\"file app_process\\n\")\n\t\tgdbSetup.write(\"set solib-search-path .\\n\")\n\t\tgdbSetup.write(\"target remote :%i\\n\" % hostGDBPort)\n\t\tgdbSetup.write(\"set breakpoint pending on\\n\")\n\n\t\tfor breakpoint in breakpoints:\n\t\t\tprint(\"Set breakpoint at %s\" % breakpoint)\n\t\t\tgdbSetup.write(\"break %s\\n\" % breakpoint)\n\n\t\tgdbSetup.write(\"set breakpoint pending off\\n\")\n\t\tgdbSetup.close()\n\n\t\tprint(\"Start gdb\")\n\t\tgdbProcess = subprocess.Popen(\"%s -x gdb.setup\" % common.shellquote(gdbCmd), shell=True)\n\n\t\tgdbProcess.wait()\n\n\t\tprint(\"gdb returned with %i\" % gdbProcess.returncode)\n\t\tgdbProcess=None\n\n\t\tprint(\"Close jdb process with 'quit'\")\n\t\tjdbProcess.stdin.write(\"quit\\n\")\n\t\tjdbProcess.wait()\n\t\tprint(\"JDB returned %s\" % str(jdbProcess.returncode))\n\t\tjdbProcess=None\n\n\t\tprint(\"Kill gdbserver process\")\n\t\tgdbServerProcess.kill()\n\t\tgdbServerProcess=None\n\t\tprint(\"Killed gdbserver process\")\n\n\t\tprint(\"Kill program %i\" % programPid)\n\t\tcommon.execute(\"%s shell run-as com.drawelements.deqp -9 %i\" % (adbCmd, programPid))\n\t\tprint(\"Killed program\")\n\n\tfinally:\n\t\tif jdbProcess and jdbProcess.returncode == None:\n\t\t\tprint(\"Kill jdb\")\n\t\t\tjdbProcess.kill()\n\t\telif jdbProcess:\n\t\t\tprint(\"JDB returned %i\" % jdbProcess.returncode)\n\n\t\tif gdbProcess and gdbProcess.returncode == None:\n\t\t\tprint(\"Kill gdb\")\n\t\t\tgdbProcess.kill()\n\t\telif gdbProcess:\n\t\t\tprint(\"GDB returned %i\" % gdbProcess.returncode)\n\n\t\tif gdbServerProcess and gdbServerProcess.returncode == None:\n\t\t\tprint(\"Kill gdbserver\")\n\t\t\tgdbServerProcess.kill()\n\t\telif gdbServerProcess:\n\t\t\tprint(\"GDB server returned %i\" % gdbServerProcess.returncode)\n\n\t\tprint(\"Kill program %i\" % programPid)\n\t\tcommon.execute(\"%s shell run-as com.drawelements.deqp kill -9 %i\" % (adbCmd, programPid))\n\t\tprint(\"Killed program\")\n\n\t\tos.chdir(curDir)\n\nif __name__ == \"__main__\":\n\tparser = argparse.ArgumentParser()\n\n\tdefaultDeviceLibs = {\n\t\t\"nexus-4\" : [\n\t\t\t\"/system/lib/libgenlock.so\",\n\t\t\t\"/system/lib/libmemalloc.so\",\n\t\t\t\"/system/lib/libqdutils.so\",\n\t\t\t\"/system/lib/libsc-a3xx.so\"\n\t\t]\n\t}\n\n\tdefaultDevices = []\n\n\tfor device in defaultDeviceLibs:\n\t\tdefaultDevices += [device]\n\n\tparser.add_argument('--adb',\t\t\t\tdest='adbCmd',\t\t\tdefault=common.shellquote(common.ADB_BIN), help=\"Path to adb command. Use absolute paths.\")\n\tparser.add_argument('--deqp-commandline',\tdest='deqpCmdLine',\t\tdefault=\"--deqp-log-filename=/sdcard/TestLog.qpa\", help=\"Command line arguments passed to dEQP test binary.\")\n\n\tif common.getPlatform() == \"linux\":\n\t\tparser.add_argument('--gdb',\t\t\t\tdest='gdbCmd',\t\t\tdefault=common.shellquote(os.path.join(common.ANDROID_NDK_PATH, \"toolchains/arm-linux-androideabi-4.8/prebuilt/linux-x86/bin/arm-linux-androideabi-gdb\")), help=\"gdb command used by script. Use absolute paths\")\n\telse:\n\t\tparser.add_argument('--gdb',\t\t\t\tdest='gdbCmd',\t\t\tdefault=common.shellquote(os.path.join(common.ANDROID_NDK_PATH, \"toolchains/arm-linux-androideabi-4.8/prebuilt/windows/bin/arm-linux-androideabi-gdb\")), help=\"gdb command used by script. Use absolute paths\")\n\n\tparser.add_argument('--target-gdb-port',\tdest='targetGDBPort',\tdefault=60001, type=int, help=\"Port used by gdbserver on target.\")\n\tparser.add_argument('--host-gdb-port',\t\tdest='hostGDBPort',\t\tdefault=60002, type=int, help=\"Host port that is forwarded to device gdbserver port.\")\n\tparser.add_argument('--jdb',\t\t\t\tdest='jdbCmd',\t\t\tdefault=\"jdb\", help=\"Path to jdb command. Use absolute paths.\")\n\tparser.add_argument('--jdb-port',\t\t\tdest='jdbPort',\t\t\tdefault=60003, type=int, help=\"Host port used to forward jdb commands to device.\")\n\tparser.add_argument('--build-dir',\t\t\tdest='buildDir',\t\tdefault=\"../../../deqp-build-android-9-armeabi-v7a-debug\", help=\"Path to dEQP native build directory.\")\n\tparser.add_argument('--device-libs',\t\tdest='deviceLibs',\t\tdefault=[], nargs='+', help=\"List of libraries that should be pulled from device for debugging.\")\n\tparser.add_argument('--breakpoints',\t\tdest='breakpoints',\t\tdefault=[\"tcu::App::App\"], nargs='+', help=\"List of breakpoints that are set by gdb.\")\n\tparser.add_argument('--device',\t\t\t\tdest='device',\t\t\tdefault=None, choices=defaultDevices, help=\"Pull default libraries for this device.\")\n\n\targs = parser.parse_args()\n\n\tdebug(adbCmd=os.path.normpath(args.adbCmd),\n\t gdbCmd=os.path.normpath(args.gdbCmd),\n\t targetGDBPort=args.targetGDBPort,\n\t hostGDBPort=args.hostGDBPort,\n jdbCmd=os.path.normpath(args.jdbCmd),\n\t jdbPort=args.jdbPort,\n\t deqpCmdLine=args.deqpCmdLine,\n\t buildDir=args.buildDir,\n\t deviceLibs=[\"/system/lib/libc.so\", \"/system/lib/libdl.so\"] + args.deviceLibs + (defaultDeviceLibs[args.device] if args.device else []),\n\t breakpoints=args.breakpoints)\n","sub_path":"external/deqp/android/scripts/debug.py","file_name":"debug.py","file_ext":"py","file_size_in_byte":8525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"364006772","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jan 14 20:49:15 2015\n\n@author: weinfz18\n\"\"\"\n\nimport os\nimport numpy as np\nimport csv\nimport lxml.html\nfrom lxml import etree\ndef astext(elem):\n \"Return stripped text value of element\"\n return etree.tostring(elem, method='text').strip()\nyears = ['2012','2013','2014','2015']\ndata = {}\npo = 0\nfor year in years:\n site = 'http://www.basketball-reference.com/leagues/NBA_' + year +'_advanced.html'\n page = lxml.html.parse(site)\n rows = page.xpath('//tr')\n stuff = [row.xpath('*//text()') for row in rows]\n stuff = [[str(s) for s in t] for t in stuff]\n rid = []\n for i in range(len(stuff)):\n if len(stuff[i])!=27:\n rid.append(i)\n rid.sort(reverse=True)\n for a in rid:\n del stuff[a]\n \n #etree.tostring(elem, method='text').strip()\n #row.xpath('./*/text()')\n data[year] = stuff\n\n \n#%%\nimport string\ndef get_data(filename):\n '''function to read the data form the input csv file to use in the analysis'''\n with open(filename, 'r') as f:\n reader = csv.reader(f,delimiter=',') \n #returns all the data from the csv file in list form\\\n return list(reader)\n \npunct = set(string.punctuation)\nos.chdir(\"C:\\\\Users\\\\weinfz18\\\\Documents\\\\nba\\\\model\")\n\nplayers = get_data('oreb.csv')\nplayers = [x[1] for x in players]\nstats = [None]*len(players)\nfor i in range(len(players)):\n players[i] = 'Luc Mbah a Moute' if players[i]=='Luc Moute' else players[i]\n players[i] = 'Danny Green' if players[i]=='Daniel Green' else players[i]\n players[i] = 'Ish Smith' if players[i]=='Ishmael Smith' else players[i]\n players[i] = 'Jose Barea' if players[i]=='J.J. Barea' else players[i]\n players[i] = 'Louis Williams' if players[i]=='Lou Williams' else players[i]\n players[i] = 'Maurice Harkless' if players[i]=='Moe Harkless' else players[i]\n players[i] = 'Patrick Mills' if players[i]=='Patty Mills' else players[i]\n for year in years:\n for j in range(len(data[year])):\n if ''.join(x for x in (str(players[i]).lower()) if x not in punct) in ''.join(x for x in (str(data[year][j][1]).lower()) if x not in punct):\n stats[i]=[data[year][j]]\n continue\nmissing = [players[x] for x in range(len(players)) if stats[x] is None] \nstats = [stats[x][0] for x in range(len(stats)-2)] \nnot_right = [x for x in range(len(stats)) if len(stats[x])!=27]\nstats = np.array(stats) \n#%%\noreb = (stats[:,11].astype(np.float))/100\ndreb = (stats[:,12].astype(np.float))/100\noreb_avg = 25.5/100\ndreb_avg = 1-oreb_avg\nd_bayes = dreb + (4/5)*dreb_avg\no_bayes = oreb + (4/5)*oreb_avg\nd_intercept = np.log(dreb_avg/(1-dreb_avg))\no_intercept = np.log(oreb_avg/(1-oreb_avg))\nd_bayes = np.log(d_bayes/(1-d_bayes))\no_bayes = np.log(o_bayes/(1-o_bayes))\nd_bayes = d_bayes - d_intercept\no_bayes = o_bayes - o_intercept\nd_bayes[d_bayes>1]=1\no_bayes[o_bayes>1]=1\nplayers = np.array(players[:-2])\nd_bayes = np.vstack((players,d_bayes))\no_bayes = np.vstack((players,o_bayes))\nd_bayes = np.transpose(d_bayes)\no_bayes = np.transpose(o_bayes)\nos.chdir(\"C:\\\\Users\\\\weinfz18\\\\Documents\\\\nba\")\nnp.savetxt(\"dreb_priors.csv\",d_bayes,delimiter=\",\",fmt=\"%s\") \nnp.savetxt(\"oreb_priors.csv\",o_bayes,delimiter=\",\",fmt=\"%s\") \n#stats = np.array(stats[:-2]) \n#%% \n","sub_path":"get_prior_rate_stats.py","file_name":"get_prior_rate_stats.py","file_ext":"py","file_size_in_byte":3340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"272025741","text":"# Licensed under a 3-clause BSD style license - see LICENSE.rst\n\nimport os\n\n# Import DEVNULL for py3 or py3\ntry:\n from subprocess import DEVNULL\nexcept ImportError:\n DEVNULL = open(os.devnull, 'wb')\n\n# Check availability of some system tools\n# Exceptions are raised if not found\n\n\ndef gunzip(filename):\n \"\"\" Decompress a file with gzip.\n\n Parameters\n ----------\n filename : str\n Fully qualified path of the file to decompress.\n Returns\n -------\n filename : str\n Name of the decompressed file (or input filename if gzip is not\n available).\n \"\"\"\n import shutil\n import gzip\n\n # system-wide 'gzip' was removed, Python gzip used instead.\n # See #1538 : https://github.com/astropy/astroquery/issues/1538\n\n # \".fz\" denotes RICE rather than gzip compression\n if not filename.endswith('.fz'):\n with gzip.open(filename, 'rb') as f_in:\n with open(filename.rsplit(\".\", 1)[0], 'wb') as f_out:\n shutil.copyfileobj(f_in, f_out)\n return filename.rsplit(\".\", 1)[0]\n else:\n return filename\n\n# If there is an update issue of astropy#2793 that got merged, this should\n# be replaced with it.\n\n\ndef in_ipynb():\n try:\n cfg = get_ipython().config\n app = cfg['IPKernelApp']\n # ipython 1.0 console has no 'parent_appname',\n # but ipynb does\n if ('parent_appname' in app and\n app['parent_appname'] == 'ipython-notebook'):\n return True\n else:\n return False\n except NameError:\n # NameError will occur if this is called from python (not ipython)\n return False\n","sub_path":"astroquery/utils/system_tools.py","file_name":"system_tools.py","file_ext":"py","file_size_in_byte":1649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"345065175","text":"# -*- coding: utf-8 -*-\n\nimport httplib\ndef login(ip, usr, pwd):\n c = httplib.HTTPConnection(ip, 80, timeout=5)\n data = \"DDDDD=\" + usr + \"&upass=\" + pwd + \"&0MKKey=\"\n c.request(\"POST\", \"\", data)\n r = c.getresponse()\n if r.status != 200:\n return False\n s = r.read()\n if s.find(\"Msg=01\") != -1:\n return False\n return True\n\ndef state(ip):\n c = httplib.HTTPConnection(ip, 80, timeout=10)\n c.request(\"GET\", \"\")\n r = c.getresponse()\n if r.status != 200:\n return None\n s = r.read()\n data = dict()\n data[\"flux\"] = int(s[s.index(\"flow='\")+6:s.index(\"';fsele=\")])\n data[\"time\"] = int(s[s.index(\"time='\")+6:s.index(\"';flow\")])\n return data\n\nfrom util import log\nfrom datetime import timedelta\ndef main():\n exec(open(\"drcom.conf\").read())\n for i in range(3):\n log(\"Connecting to Dr.COM Server...\", \"bright yellow\")\n if login(server, username, password):\n info = state(server)\n log('login success!', 'bright green')\n log('INFO: flux: ' + str(info['flux']/1000.0) + ' MB, uptime: ' +\n str(timedelta(minutes=info['time'])), 'bright cyan')\n break\n elif i != 2:\n log(\"failed! retry...\", \"bright red\")\n else:\n log(\"login failed!\", \"bright red\")\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"wireless.py","file_name":"wireless.py","file_ext":"py","file_size_in_byte":1349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"307547750","text":"import logging; _L = logging.getLogger('openaddr.ci.collect')\n\nfrom ..compat import standard_library\n\nfrom argparse import ArgumentParser\nfrom os import environ\nfrom zipfile import ZipFile, ZIP_DEFLATED\nfrom os.path import splitext, exists, basename, join\nfrom urllib.parse import urlparse\nfrom operator import attrgetter\nfrom tempfile import mkstemp, mkdtemp\nfrom datetime import date\nfrom shutil import rmtree\n\nfrom .objects import read_latest_set, read_completed_runs_to_date\nfrom . import db_connect, db_cursor, setup_logger, render_index_maps, log_function_errors\nfrom .. import S3, iterate_local_processed_files\n\nparser = ArgumentParser(description='Run some source files.')\n\nparser.add_argument('-o', '--owner', default='openaddresses',\n help='Github repository owner. Defaults to \"openaddresses\".')\n\nparser.add_argument('-r', '--repository', default='openaddresses',\n help='Github repository name. Defaults to \"openaddresses\".')\n\nparser.add_argument('-b', '--bucket', default='data.openaddresses.io',\n help='S3 bucket name. Defaults to \"data.openaddresses.io\".')\n\nparser.add_argument('-d', '--database-url', default=environ.get('DATABASE_URL', None),\n help='Optional connection string for database. Defaults to value of DATABASE_URL environment variable.')\n\nparser.add_argument('-a', '--access-key', default=environ.get('AWS_ACCESS_KEY_ID', None),\n help='Optional AWS access key name. Defaults to value of AWS_ACCESS_KEY_ID environment variable.')\n\nparser.add_argument('-s', '--secret-key', default=environ.get('AWS_SECRET_ACCESS_KEY', None),\n help='Optional AWS secret key name. Defaults to value of AWS_SECRET_ACCESS_KEY environment variable.')\n\nparser.add_argument('--sns-arn', default=environ.get('AWS_SNS_ARN', None),\n help='Optional AWS Simple Notification Service (SNS) resource. Defaults to value of AWS_SNS_ARN environment variable.')\n\nparser.add_argument('-v', '--verbose', help='Turn on verbose logging',\n action='store_const', dest='loglevel',\n const=logging.DEBUG, default=logging.INFO)\n\nparser.add_argument('-q', '--quiet', help='Turn off most logging',\n action='store_const', dest='loglevel',\n const=logging.WARNING, default=logging.INFO)\n\n@log_function_errors\ndef main():\n ''' Single threaded worker to serve the job queue.\n '''\n args = parser.parse_args()\n setup_logger(args.sns_arn, log_level=args.loglevel)\n s3 = S3(args.access_key, args.secret_key, args.bucket)\n \n with db_connect(args.database_url) as conn:\n with db_cursor(conn) as db:\n set = read_latest_set(db, args.owner, args.repository)\n runs = read_completed_runs_to_date(db, set.id)\n\n render_index_maps(s3, runs)\n \n dir = mkdtemp(prefix='collected-')\n \n everything = CollectorPublisher(s3, _prepare_zip(set, join(dir, 'openaddresses-collected.zip')))\n us_northeast = CollectorPublisher(s3, _prepare_zip(set, join(dir, 'openaddresses-us_northeast.zip')))\n us_midwest = CollectorPublisher(s3, _prepare_zip(set, join(dir, 'openaddresses-us_midwest.zip')))\n us_south = CollectorPublisher(s3, _prepare_zip(set, join(dir, 'openaddresses-us_south.zip')))\n us_west = CollectorPublisher(s3, _prepare_zip(set, join(dir, 'openaddresses-us_west.zip')))\n europe = CollectorPublisher(s3, _prepare_zip(set, join(dir, 'openaddresses-europe.zip')))\n asia = CollectorPublisher(s3, _prepare_zip(set, join(dir, 'openaddresses-asia.zip')))\n\n for (sb, fn, sd) in iterate_local_processed_files(runs):\n everything.collect((sb, fn, sd))\n if is_us_northeast(sb, fn, sd): us_northeast.collect((sb, fn, sd))\n if is_us_midwest(sb, fn, sd): us_midwest.collect((sb, fn, sd))\n if is_us_south(sb, fn, sd): us_south.collect((sb, fn, sd))\n if is_us_west(sb, fn, sd): us_west.collect((sb, fn, sd))\n if is_europe(sb, fn, sd): europe.collect((sb, fn, sd))\n if is_asia(sb, fn, sd): asia.collect((sb, fn, sd))\n \n everything.publish()\n us_northeast.publish()\n us_midwest.publish()\n us_south.publish()\n us_west.publish()\n europe.publish()\n asia.publish()\n \n rmtree(dir)\n\ndef _prepare_zip(set, filename):\n '''\n '''\n zipfile = ZipFile(filename, 'w', ZIP_DEFLATED, allowZip64=True)\n \n sources_tpl = 'https://github.com/{owner}/{repository}/tree/{commit_sha}/sources'\n sources_url = sources_tpl.format(**set.__dict__)\n zipfile.writestr('README.txt', '''Data collected around {date} by OpenAddresses (http://openaddresses.io).\n\nAddress data is essential infrastructure. Street names, house numbers and\npostal codes, when combined with geographic coordinates, are the hub that\nconnects digital to physical places.\n\nData licenses can be found in LICENSE.txt.\n\nData source information can be found at\n{url}\n'''.format(url=sources_url, date=date.today()))\n \n return zipfile\n\nclass CollectorPublisher:\n ''' \n '''\n def __init__(self, s3, collection_zip):\n self.s3 = s3\n self.zip = collection_zip\n self.sources = dict()\n \n def collect(self, file_info):\n ''' Add file info (source_base, filename, source_dict) to collection zip.\n '''\n source_base, filename, source_dict = file_info\n\n _L.info(u'Adding {} to {}'.format(source_base, self.zip.filename))\n add_source_to_zipfile(self.zip, source_base, filename)\n self.sources[source_base] = {\n 'website': source_dict.get('website') or 'Unknown',\n 'license': source_dict.get('license') or 'Unknown'\n }\n \n def publish(self):\n ''' Create new S3 object with zipfile name and upload the collection.\n '''\n # Write a short file with source licenses.\n template = u'{source}\\nWebsite: {website}\\nLicense: {license}\\n'\n license_bits = [(k, v['website'], v['license']) for (k, v) in sorted(self.sources.items())]\n license_lines = [u'Data collected by OpenAddresses (http://openaddresses.io).\\n']\n license_lines += [template.format(source=s, website=w, license=l) for (s, w, l) in license_bits]\n self.zip.writestr('LICENSE.txt', u'\\n'.join(license_lines).encode('utf8'))\n\n self.zip.close()\n _L.info(u'Finished {}'.format(self.zip.filename))\n\n zip_key = self.s3.new_key(basename(self.zip.filename))\n zip_args = dict(policy='public-read', headers={'Content-Type': 'application/zip'})\n zip_key.set_contents_from_filename(self.zip.filename, **zip_args)\n _L.info(u'Uploaded {} to {}'.format(self.zip.filename, zip_key.name))\n\ndef add_source_to_zipfile(zip_out, source_base, filename):\n '''\n '''\n _, ext = splitext(filename)\n\n if ext == '.csv':\n zip_out.write(filename, source_base + ext)\n \n elif ext == '.zip':\n zip_in = ZipFile(filename, 'r')\n for zipinfo in zip_in.infolist():\n if zipinfo.filename == 'README.txt':\n # Skip README files when building collection.\n continue\n zip_out.writestr(zipinfo, zip_in.read(zipinfo.filename))\n zip_in.close()\n\ndef _is_us_state(abbr, source_base, filename, source_dict):\n for sep in ('/', '-'):\n if source_base == 'us{sep}{abbr}'.format(**locals()):\n return True\n\n if source_base.startswith('us{sep}{abbr}.'.format(**locals())):\n return True\n\n if source_base.startswith('us{sep}{abbr}{sep}'.format(**locals())):\n return True\n\n return False\n\ndef is_us_northeast(source_base, filename, source_dict):\n for abbr in ('ct', 'me', 'ma', 'nh', 'ri', 'vt', 'nj', 'ny', 'pa'):\n if _is_us_state(abbr, source_base, filename, source_dict):\n return True\n\n return False\n \ndef is_us_midwest(source_base, filename, source_dict):\n for abbr in ('il', 'in', 'mi', 'oh', 'wi', 'ia', 'ks', 'mn', 'mo', 'ne', 'nd', 'sd'):\n if _is_us_state(abbr, source_base, filename, source_dict):\n return True\n\n return False\n \ndef is_us_south(source_base, filename, source_dict):\n for abbr in ('de', 'fl', 'ga', 'md', 'nc', 'sc', 'va', 'dc', 'wv', 'al',\n 'ky', 'ms', 'ar', 'la', 'ok', 'tx', 'tn'):\n if _is_us_state(abbr, source_base, filename, source_dict):\n return True\n\n return False\n \ndef is_us_west(source_base, filename, source_dict):\n for abbr in ('az', 'co', 'id', 'mt', 'nv', 'nm', 'ut', 'wy', 'ak', 'ca', 'hi', 'or', 'wa'):\n if _is_us_state(abbr, source_base, filename, source_dict):\n return True\n\n return False\n \ndef _is_country(iso, source_base, filename, source_dict):\n for sep in ('/', '-'):\n if source_base == iso:\n return True\n\n if source_base.startswith('{iso}.'.format(**locals())):\n return True\n\n if source_base.startswith('{iso}{sep}'.format(**locals())):\n return True\n\n return False\n\ndef is_europe(source_base, filename, source_dict):\n for iso in ('be', 'bg', 'cz', 'dk', 'de', 'ee', 'ie', 'el', 'es', 'fr',\n 'hr', 'it', 'cy', 'lv', 'lt', 'lu', 'hu', 'mt', 'nl', 'at',\n 'pl', 'pt', 'ro', 'si', 'sk', 'fi', 'se', 'uk', 'gr', 'gb' ):\n if _is_country(iso, source_base, filename, source_dict):\n return True\n\n return False\n \ndef is_asia(source_base, filename, source_dict):\n for iso in ('af', 'am', 'az', 'bh', 'bd', 'bt', 'bn', 'kh', 'cn', 'cx',\n 'cc', 'io', 'ge', 'hk', 'in', 'id', 'ir', 'iq', 'il', 'jp',\n 'jo', 'kz', 'kp', 'kr', 'kw', 'kg', 'la', 'lb', 'mo', 'my',\n 'mv', 'mn', 'mm', 'np', 'om', 'pk', 'ph', 'qa', 'sa', 'sg',\n 'lk', 'sy', 'tw', 'tj', 'th', 'tr', 'tm', 'ae', 'uz', 'vn',\n 'ye', 'ps',\n \n 'as', 'au', 'nz', 'ck', 'fj', 'pf', 'gu', 'ki', 'mp', 'mh',\n 'fm', 'um', 'nr', 'nc', 'nz', 'nu', 'nf', 'pw', 'pg', 'mp',\n 'sb', 'tk', 'to', 'tv', 'vu', 'um', 'wf', 'ws', 'is'):\n if _is_country(iso, source_base, filename, source_dict):\n return True\n\n return False\n\nif __name__ == '__main__':\n exit(main())\n","sub_path":"openaddr/ci/collect.py","file_name":"collect.py","file_ext":"py","file_size_in_byte":10265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"313548148","text":"import jieba\nimport re\nimport json\n# import sys\nimport collections\nfrom collections import Counter\n# sys.path.append(\"c:\")\n# import stats_word\n\n# with open(\"mymodule/tang300.json\", \"r\", encoding=\"utf-8\") as file:\n# try:\n# read_data = file.read()\n# except ValueError as e:\n# print(e)\ndef stats_text_en(en,count) :\n ''' 1. 英文词频统计:使用正则表达式过滤英文字符,使用Counter统计并排序。\n 2. 参数类型检查,不为字符串抛出异常。\n '''\n if type(en) == str : \n text_en = re.sub(\"[^A-Za-z]\", \" \", en.strip())\n # text_en = ''.join(text_en) \n enList = text_en.split( )\n return collections.Counter(enList).most_common(count)\n else : \n raise ValueError ('type of argumengt is not str')\n# print(stats_text_en(read_data, 4))\n\ndef stats_text_cn(cn,count) :\n ''' 1. 使用jieba第三方库精确模式分词。\n 2. 使用正则表达式过滤汉字字符。\n 3. 使用for循环判断分词后词频列表元素长度大于等于2的生成新列表。\n 4. 使用标准库collections.Counter()统计词频并限制统计数量。 \n 5. 参数类型检查,不为字符串抛出异常。\n '''\n if type(cn) == str : \n cnList = re.findall(u'[\\u4e00-\\u9fff]+', cn.strip())\n \n cnString = ''.join(cnList)\n \n segList = jieba.cut(cnString,cut_all=False)\n \n cnnewList = []\n for i in segList :\n if len(i) >= 2 :\n cnnewList.append(i)\n else :\n pass \n return collections.Counter(cnnewList).most_common(count)\n \n else :\n raise ValueError ('type of argumengt is not str')\n# print(stats_text_cn(read_data, 2))\n\ndef stats_text(text_en_cn,count_en_cn) :\n ''' 1. 合并英汉词频统计:调用stats_text_en()和stats_text_cn()并合并其结果。\n 2. 参数类型检查,不为字符串抛出异常。\n '''\n if type(text_en_cn) == str : \n return stats_text_en(text_en_cn,count_en_cn)+stats_text_cn(text_en_cn,count_en_cn)\n else :\n raise ValueError ('type of argumengt is not str')\n\n# print('输出词频最高的前20个中文词:\\n ', stats_text_cn(read_data,20))","sub_path":"exercises/1901040051/day13/mymodule/stats_word.py","file_name":"stats_word.py","file_ext":"py","file_size_in_byte":2376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"608570990","text":"import logging\nimport os\n\nfrom aiohttp import web, WSMsgType\nfrom aiohttp.web_response import Response\nfrom jsonrpcserver.aio import methods\n\nfrom sn_agent import ontology\nfrom sn_agent.api.job import can_perform_service, perform_job\nfrom sn_agent.job.job_descriptor import JobDescriptor\nfrom sn_agent.ontology.service_descriptor import ServiceDescriptor\n\nlogger = logging.getLogger(__name__)\n\nWS_FILE = os.path.join(os.path.dirname(__file__), 'websocket.html')\n\n\n@methods.add\nasync def can_perform(service_node_id=None, context=None):\n # figure out what we are being asked to perform and answer\n service = ServiceDescriptor(service_node_id)\n app = context\n return await can_perform_service(app, service)\n\n\n@methods.add\nasync def perform(service_node_id=None, job_params=None, context=None):\n service_descriptor = ServiceDescriptor(service_node_id)\n\n job = JobDescriptor(service_descriptor, job_params)\n app = context\n\n result = await perform_job(app, job)\n logging.debug('Result of perform was %s', result)\n return result\n\n\nasync def http_handler(request):\n app = request.app\n request_text = await request.text()\n\n response = await methods.dispatch(request_text, app)\n if response.is_notification:\n return web.Response()\n else:\n return web.json_response(response, status=response.http_status)\n\n\nasync def ws_handler(request):\n logger.debug('WebSocket Handler started')\n\n app = request.app\n\n resp = web.WebSocketResponse()\n\n ok, protocol = resp.can_prepare(request)\n if not ok:\n with open(WS_FILE, 'rb') as fp:\n return Response(body=fp.read(), content_type='text/html')\n\n await resp.prepare(request)\n\n logger.debug('WebSocket data received')\n\n try:\n\n request.app['sockets'].append(resp)\n\n async for msg in resp:\n\n logger.debug('Processing WebSocket message: %s', msg.type)\n\n if msg.type == WSMsgType.TEXT:\n\n response = await methods.dispatch(msg.data, app)\n if not response.is_notification:\n await resp.send_str(str(response))\n\n elif msg.type == WSMsgType.ERROR:\n logger.debug('ws connection closed with exception %s' % resp.exception())\n\n else:\n logger.debug(\"Unhandled message type\")\n return resp\n return resp\n\n finally:\n request.app['sockets'].remove(resp)\n logger.debug('Someone disconnected.')\n\n\nasync def on_shutdown(app):\n for ws in app['sockets']:\n await ws.close()\n\n\ndef setup_api(app):\n app['sockets'] = []\n app.router.add_post('/api', http_handler)\n app.router.add_get('/api/ws', ws_handler)\n app.on_shutdown.append(on_shutdown)\n","sub_path":"agent/sn_agent/api/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"455533495","text":"\"\"\"\nCreated 30/04/18\nDeveloped by Fraser Love\n\"\"\"\nfrom pynput.keyboard import Key, Listener\n\ndef user_input(inpt):\n text = []\n if inpt.isdigit() == False:\n for i in inpt: text.append(ord(i))\n else: text.append(int(inpt))\n calculate(text)\n\ndef calculate(text):\n for j in range(0,len(text)): text[j] = bin(text[j])\n display(text)\n\ndef display(text):\n for c in text: c = str(c).split(\"0b\"); print(c[1],end=\"\")\n retry = str(input(\"\\n\\nPress space to convert again...\"))\n if retry == \" \": user_input(inpt = str(input(\"\\nWhat would you like to convert: \"))) \n\nuser_input(inpt = str(input(\"\\nWhat would you like to convert: \")))\n","sub_path":"tools/binary_calculator_2.0.py","file_name":"binary_calculator_2.0.py","file_ext":"py","file_size_in_byte":666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"16033798","text":"#!usr/bin/env python\n# coding: utf-8\n\nimport os.path\nimport tornado.httpserver\nimport tornado.ioloop\nimport tornado.web\nfrom tornado.options import options, define, parse_command_line\nfrom db import Connection\nfrom settings import config\n\nfrom urls import urls\n\n\ndefine(\"port\", default=8888, help=\"run on the given port\", type=int)\n\n\nclass Application(tornado.web.Application):\n\n def __init__(self):\n handlers = urls\n settings = dict(\n template_path=os.path.join(os.path.dirname(__file__), \"templates\"),\n static_path=os.path.join(os.path.dirname(__file__), \"static\"),\n # ui_modules={\"Entry\": EntryModule},\n xsrf_cookies=True,\n cookie_secret=\"roCZLecuTxyzZGjYDlsB/OnrBp/LRUDTgokaFCZdK4A=\",\n login_url=\"/auth/login\",\n debug=True,\n # autoreload=False,\n )\n tornado.web.Application.__init__(self, handlers, **settings)\n self.db = Connection(**config)\n\n\ndef main():\n parse_command_line()\n http_server = tornado.httpserver.HTTPServer(Application())\n # http_server.bind(options.port)\n # http_server.start(0)\n # tornado.ioloop.IOLoop.current().start()\n\n http_server.listen(options.port)\n tornado.ioloop.IOLoop.instance().start()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"249836045","text":"import os\nfrom Unit51 import Unit51\nfrom misc.Lighting import *\nfrom misc.Gui import HPmeter\nfrom Particles import *\nfrom Methods import ResLoader\nimport Entity\nimport logging\n\nfocused = True\nglobalCam = None\n\ncwd = os.getcwd()\n\nclass Level(object):\n\n lightingEnabled = True\n tempSurfaceClearColor = sf.Color(0,0,0,0) #transparency\n\n def __init__(self,name,image,collisionRects,entities,surface,lightMap,paraBG = None, color = sf.Color.BLACK):\n self.name = name\n self.image = sf.Sprite(sf.Texture.from_image(image))\n self.collisionRects = []\n self.surface = surface\n self.tempSurface = sf.RenderTexture(self.image.global_bounds.width, self.image.global_bounds.height)\n\n self.color = color\n for rect in collisionRects:\n x = int(rect.attrib['x'])\n y = int(rect.attrib['y'])\n width = int(rect.attrib['w'])\n height = int(rect.attrib['h'])\n self.collisionRects.append(sf.Rectangle(sf.Vector2(x,y),sf.Vector2(width,height)))\n\n self.entities = entities\n self.guientities = []\n self.u51 = self.get51()\n self.lightMap = lightMap\n\n if self.u51 is not None:\n hpm = HPmeter(0,0,self.surface)\n self.guientities.append(hpm)\n hpm.set51(self.u51)\n\n\n\n # REMOVE THIS\n self.tempEM = Emitter(300,300,surface,RectParticle)\n self.entities.append(self.tempEM)\n self.track = \"Trial\"\n import misc.Gui\n self.testDialogue = misc.Gui.Dialogue(50,50,self.surface,\"TestSpeech1.xml\")\n self.testDialogue.setLevel(self)\n self.testDialogue.begin()\n self.guientities.append(self.testDialogue)\n if paraBG is None:\n self.paraBG = ParallaxBG(0,0,surface,\"goldcircuit.png\",True,depthFactor=10)\n else:\n self.paraBG = paraBG\n\n\n for e in self.entities:\n try:\n e.setLevel(self) # give them a reference to the level\n except AttributeError:\n pass\n try:\n e.setTarget(self.u51) # give them unit 51\n except AttributeError:\n pass\n\n # also remove this\n self.tempEM.burst()\n\n\n def update(self,frameTime):\n # clean up entities if they're deletable\n # give each entity the references they need\n for e in self.entities:\n try:\n e.collideRects = self.collisionRects # give them level collisions\n except AttributeError:\n pass\n\n self.entities = [e for e in self.entities if not e.deletable]\n if self.lightMap is not None:\n self.lightMap.update(frameTime)\n\n if self.paraBG is not None:\n self.paraBG.update(frameTime)\n\n for e in self.entities:\n e.setLevel(self)\n if e.hitch is None:\n e.update(frameTime)\n\n def draw(self):\n regularEnts = [entity for entity in self.entities if not isinstance(entity,Bulb) and entity.lightAffected]\n lightingEnts = [entity for entity in self.entities if isinstance(entity,Bulb)]\n foregroundEnts = [entity for entity in self.entities if not entity.lightAffected]\n\n self.tempSurface.clear(self.tempSurfaceClearColor)\n\n if self.paraBG is not None:\n if self.paraBG.lightAffected:\n self.paraBG.draw(self.tempSurface)\n else:\n self.paraBG.draw(self.surface)\n\n # draw the entities\n self.tempSurface.draw(self.image)\n for entity in sorted(regularEnts, key=lambda ent:ent.layer):\n if entity.hitch is None:\n if self.u51 is not None:\n if Methods.distance(self.u51.position,entity.position) < 1000:\n entity.draw(self.tempSurface)\n else: # use the world position of the mouse as a backup\n mousePos = self.surface.map_pixel_to_coords(sf.Mouse.get_position(self.surface))\n if Methods.distance(mousePos,entity.position) < 1000:\n entity.draw()\n\n # now draw the lighting\n if self.lightingEnabled:\n self.lightMap.texture.clear(self.lightMap.color)\n offset = sf.Vector2(self.lightMap.texture.width/2, self.lightMap.texture.height/2)\n for e in lightingEnts:\n e.sprite.sprite.position = e.originalPosition - self.lightMap.position + offset\n self.lightMap.texture.draw(e.sprite.sprite,sf.RenderStates(sf.BlendMode.BLEND_ADD))\n self.lightMap.texture.display()\n self.tempSurface.draw(self.lightMap.sprite,sf.RenderStates(sf.BlendMode.BLEND_MULTIPLY))\n\n # now draw all the entities that aren't light affected (in the foreground)\n for entity in foregroundEnts:\n if self.u51 is not None:\n if Methods.distance(self.u51.position,entity.position) < 1000:\n entity.draw(self.tempSurface)\n else: # use the world position of the mouse as a backup\n mousePos = self.surface.map_pixel_to_coords(sf.Mouse.get_position(self.surface))\n if Methods.distance(mousePos,entity.position) < 1000:\n entity.draw(self.tempSurface)\n\n self.tempSurface.display()\n tempSurfaceSprite = sf.Sprite(self.tempSurface.texture)\n self.surface.draw(tempSurfaceSprite)\n\n\n def get51(self):\n for e in self.entities:\n if type(e) is Unit51: return e\n\n # returns the darkness object, which has a rendertexture for doing lighting\n def getDarkness(self):\n for e in self.entities:\n if type(e) is Darkness:\n return e\n\n def updateGui(self,frameTime):\n self.guientities = [x for x in self.guientities if not x.deletable]\n for e in self.guientities:\n e.update(frameTime)\n\n def drawGui(self):\n for e in sorted(self.guientities, key=lambda x:x.layer):\n e.draw(self.surface)","sub_path":"Level.py","file_name":"Level.py","file_ext":"py","file_size_in_byte":6036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"155287483","text":"from django.shortcuts import render\nfrom feedback1app.models import Feedback1Data\nfrom feedback1app.forms import Feedback1Form\nfrom django.http.response import HttpResponse\nimport datetime\n\ndate=datetime.datetime.now()\ndef Feedback_view(request):\n if request.method=='POST':\n fform1=Feedback1Form(request.POST)\n if fform1.is_valid():\n name1=request.POST.get('Name')\n rating1=request.POST.get('Rating')\n mobile1=request.POST.get('Mobile')\n mail1=request.POST.get('Email')\n feedback2=request.POST.get('Feedback')\n\n data=Feedback1Data(\n Name=name1,\n Rating=rating1,\n Mobile=mobile1,\n Email=mail1,\n Date=date,\n feeb=feedback2\n )\n data.save()\n feedback1=Feedback1Data.objects.all()\n fform1=Feedback1Form()\n return render(request,'feedback1.html',{'fform1':fform1,'feedback1':feedback1})\n else:\n feedback1=Feedback1Data.objects.all()\n fform1=Feedback1Form()\n return render(request,'feedback1.html',{'fform1':fform1,'feedback1':feedback1})\n\n","sub_path":"feedback1app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"525274793","text":"import math\n\nclass Point:\n\n def __init__(self, x, y):\n self.x = x\n self.y = y\n \ndef Distance(f, s):\n a = f.x - s.x\n b = f.y - s.y\n c = pow(a, 2) + pow(b, 2)\n return math.sqrt(c)\n\nfPoints = input('x1, y1 = ')\nsPoints = input('x2, y2 = ')\nx1, y1 = [int(x) for x in fPoints.split()]\nx2, y2 = [int(x) for x in sPoints.split()]\n\np1 = Point(x1, y1)\np2 = Point(x2, y2)\n\ndist = Distance(p1, p2)\n\nprint(f'Distance is {dist:.3f}')\n","sub_path":"SoftUni Exercises/Distance Between Points.py","file_name":"Distance Between Points.py","file_ext":"py","file_size_in_byte":453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"390990374","text":"low=input(\"enter lower limit:\")\nup=input(\"enter upper limit:\")\nprint(\"prime number between low and upper limit:\")\n\nfor n in range(low,up+1):\n\n if n> 1:\n for i in range(2,n):\n if ((n%i)==0):\n break\n else:\n print(n)\n","sub_path":"beginner/prime_intervals.py","file_name":"prime_intervals.py","file_ext":"py","file_size_in_byte":262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"436420257","text":"# -*- coding: utf-8 -*-\n##########################################################################\n# NSAp - Copyright (C) CEA, 2021\n# Distributed under the terms of the CeCILL-B license, as published by\n# the CEA-CNRS-INRIA. Refer to the LICENSE file or to\n# http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html\n# for details.\n##########################################################################\n\n\"\"\"\nDefinition of the Cortical Spherical Variational Auto-Encoder (SVAE) loss.\n\"\"\"\n\n# Imports\nimport torch\nfrom torch.nn import functional as func\nfrom torch.distributions import Normal, kl_divergence\n\n\nclass SphericalVAELoss(object):\n \"\"\" Spherical VAE Loss.\n \"\"\"\n def __init__(self, beta=9, left_mask=None, right_mask=None):\n \"\"\" Init class.\n\n Parameters\n ----------\n beta: float, default 9\n weight of the kl divergence.\n left_mask: Tensor (azimuth, elevation), default None\n left cortical binary mask.\n right_mask: Tensor (azimuth, elevation), default None\n right cortical binary mask.\n \"\"\"\n super(SphericalVAELoss, self).__init__()\n self.beta = beta\n self.left_mask = left_mask\n self.right_mask = right_mask\n self.layer_outputs = None\n\n def __call__(self, left_recon_x, right_recon_x, left_x, right_x):\n \"\"\" Compute loss.\n \"\"\"\n if self.layer_outputs is None:\n raise ValueError(\n \"This loss needs intermediate layers outputs. Please register \"\n \"an appropriate callback.\")\n q = self.layer_outputs[\"q\"]\n z = self.layer_outputs[\"z\"]\n if self.left_mask is None:\n device = left_x.device\n self.left_mask = torch.ones(\n (left_x.shape[-2], left_x.shape[-1]), dtype=int).to(device)\n self.right_mask = torch.ones(\n (right_x.shape[-2], right_x.shape[-1]), dtype=int).to(device)\n\n # Reconstruction loss term i.e. the mean squared error\n left_mse = func.mse_loss(\n left_recon_x * self.left_mask.detach(),\n left_x * self.left_mask.detach(), reduction=\"mean\")\n right_mse = func.mse_loss(\n right_recon_x * self.right_mask.detach(),\n right_x * self.right_mask.detach(), reduction=\"mean\")\n\n # Latent loss between approximate posterior and prior for z\n kl_div = kl_divergence(q, Normal(0, 1)).mean(dim=0).sum()\n\n # Need to maximise the ELBO with respect to these weights\n loss = left_mse + right_mse + self.beta * kl_div\n\n return loss, {\"left_mse\": left_mse, \"right_mse\": right_mse,\n \"kl_div\": kl_div}\n","sub_path":"surfify/losses/vae.py","file_name":"vae.py","file_ext":"py","file_size_in_byte":2693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"235768493","text":"#!/usr/bin/env python2.7\n#\n# 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\n\n\"\"\"Module for GePlaces Search WSGI application.\"\"\"\n\nfrom search.common import exceptions\nfrom search.plugin import geplaces_search_handler\n\n\nclass GePlacesSearchApp(object):\n \"\"\"GePlacesSearchApp implements the callable method.\n\n WSGI Application class interfaces with the web server and\n receives the search queries in the form of URL parameters.\n Web server calls the callable method __call__ to start the application.\n \"\"\"\n\n def __init__(self):\n \"\"\"Inits the status and response_headers for the HTTP response.\"\"\"\n\n self._status = \"%s\"\n self._geplaces = geplaces_search_handler.PlacesSearch()\n\n def __call__(self, environ, start_response):\n \"\"\"Callable method for the WSGI application.\n\n Callable method which performs a places search and returns the\n KML/JSONP format output back in the HTTP response.\n\n Args:\n environ: A list which contains the WSGI environment information.\n start_response: callable for setting the HTTP headers and status.\n Returns:\n response_body: Search Results sent back to the client wrapped in a list.\n \"\"\"\n response_headers = []\n\n content_type = \"\"\n status = \"\"\n response_body = \"\"\n response_type = \"\"\n\n try:\n response_body, response_type = self._geplaces.HandleSearchRequest(environ)\n\n content_type = self._geplaces.utils.GetContentType(response_type)\n\n status = self._status % (\"200 OK\")\n except exceptions.PoolConnectionException as e:\n # Catch PoolConnectionException when connections\n # are not available in the pool.\n content_type = self._geplaces.utils.content_type % (\"text/plain\")\n status = self._status % (\"500 Internal Server Error\")\n self._geplaces.logger.debug(\n \"%s, status %s sent back to client.\", e, status)\n response_body = \"Client Connections exceeded\"\n except Exception as e:\n # Any kind of Exception/Error occurs,then send \"500 Internal Server Error\"\n content_type = self._geplaces.utils.content_type % (\"text/plain\")\n status = self._status % (\"500 Internal Server Error\")\n self._geplaces.logger.debug(\n \"%s, status %s sent back to client.\", e, status)\n response_body = \"%s\" % e\n\n response_headers.append(tuple(content_type.split(\",\")))\n\n start_response(status, response_headers)\n\n return [response_body]\n\n\napplication = GePlacesSearchApp()\n\n\ndef main():\n application()\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"earth_enterprise/src/server/wsgi/search/plugin/geplaces_search_app.py","file_name":"geplaces_search_app.py","file_ext":"py","file_size_in_byte":3039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"557366977","text":"\"\"\"\n데이터베이스 기반 애플리케이션에서 싱글톤 패턴을 적용한 사례\n\n여러 서비스가 한 개의 DB를 공유하는 구조.\n안정된 클라우드 서비스를 설계하려면 다음 사항들을 반드시 명심해야 한다.\n - 데이터베이스의 일관성을 보존해야 한다. 연산 간의 충돌이 없어야 한다.\n - 다수의 DB 연산을 처리하려면 메모리와 CPU를 효율적으로 사용해야 한다.\n\"\"\"\nimport sqlite3\n\n\nclass MetaSingleton(type):\n _instances = {}\n def __call__(cls, *args, **kwargs):\n if cls not in cls._instances:\n cls._instances[cls] = super(MetaSingleton, cls).__call__(*args, **kwargs)\n return cls._instances[cls]\n\n\nclass Database(metaclass=MetaSingleton):\n connection = None\n def connect(self):\n if self.connection is None:\n self.connection = sqlite3.connect(\"db.sqlite3\")\n self.cursorobj = self.connection.cursor()\n return self.cursorobj\n\n\ndb1 = Database().connect()\ndb2 = Database().connect()\n\nprint(\"Database Objects DB1\", db1)\nprint(\"Database Objects DB2\", db2)\n\n\n\"\"\"\n실행결과 예시\nDatabase Objects DB1 \nDatabase Objects DB2 \n\"\"\"\n\n\n# 코드 살펴보기\n\n\"\"\"\n1. MetaSingleton이라는 메타클래스를 생성한다. __call__ 파이썬 메소드를 사용해 싱글톤을 생성한다.\n2. Database 클래스는 MetaSingleton 메타클래스의 도움으로 싱글톤 역할을 한다. 단 한 개의 database 클래스 객체만 생성한다.\n3. 웹 앱이 DB 연산을 요청할 때마다 database 클래스를 생성하지만 내부적으로는 한 개의 객체만 생성된다.\n 따라서 데이터베이스의 동기화가 보장된다. 리소스를 적게 사용해 메모리와 CPU 사용량을 최적화할 수 있다.\n \n**이제 단일 웹 앱 형태가 아닌 여러 웹 앱이 같은 DB에 접속하는 상황을 생각해보자**\n이 경우 각 웹 앱이 DB에 접근하는 싱글톤을 생성하기 때문에 싱글톤 패턴에 적합하지 않다.\nDB 동기화가 어렵고 리소스 사용량이 많은 경우다.\n싱글톤 패턴보다 연결 풀링 기법을 사용하는 것이 더 효율적이다.\n\"\"\"","sub_path":"generation_pattern/singleton/use_case/singleton_use_case1.py","file_name":"singleton_use_case1.py","file_ext":"py","file_size_in_byte":2277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"607724011","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Apr 18 16:06:46 2019\n\n@author: nooteboom\n\"\"\"\n\nimport numpy as np\nfrom netCDF4 import Dataset\nimport matplotlib.pylab as plt\n\n# Read the bathymetry and the grid file\ntopbathfile = Dataset('interp_kmt/TopoBathy38.nc')\ngridfile = Dataset('grid_coordinates_pop_tx0.1.nc')\n\nZ = topbathfile['Z'][:]\nlon = topbathfile['longitude'][:]\nlat = topbathfile['latitude'][:]\n\ngridlon = gridfile['T_LON_2D'][:]\ngridlon[gridlon>180] -= 360\ngridlat = gridfile['T_LAT_2D'][:]\nidi = gridfile['i_index'][:]\n\ngridlontemp = gridfile['U_LON_2D'][:]\ngridlattemp = gridfile['U_LAT_2D'][:]\n\n# Read the kmt file \nkmtf = Dataset('interp_kmt/kmt_pbc.p1_tripole.s2.0-og.20060315.no_caspian_or_black.nc')\nkmtlon = kmtf['ULON'][:]\nkmtlat = kmtf['ULAT'][:]\nhtn = kmtf['HTN'][:]\nhte = kmtf['HTE'][:]\nhus = kmtf['HUS'][:]\nhuw = kmtf['HUW'][:]\nangle = kmtf['ANGLE'][:]\n#%%\n# Compare longitudes and latitudes of kmt and grid files\nplt.plot(kmtlon[-1,:])\nplt.plot(kmtlon[-2,:])\nplt.plot(gridlon[-1,:], '--')\nplt.show()\nplt.plot(kmtlat[-1,:], label='kmt')\nplt.plot(kmtlat[-2,:], label='kmt 2')\nplt.plot(gridlattemp[-1,:], '--', label='grid')\nplt.legend()\nplt.show()\n\n# Plot grids\ngridlon = gridlon[::10,::10]\ngridlat = gridlat[::10,::10]\nplt.figure(figsize=(15,15))\nplt.contourf(lon, lat, Z, [-10000,-0.1,0.1,10000], cmap='Spectral')\nplt.colorbar()\nplt.scatter(gridlon.flatten(), gridlat.flatten(), s=1, c='k')\nplt.show()\n\ngridlon = gridlon + 25\ngridlon[gridlon>180] -= 360\nplt.figure(figsize=(15,15))\nplt.contourf(lon, lat, Z, [-10000,-0.1,0.1,10000], cmap='Spectral')\nplt.colorbar()\nplt.scatter(gridlon.flatten(), gridlat.flatten(), s=1, c='k')\nplt.show()\n\n#%%\ngridlon = gridfile['T_LON_2D'][:]\ngridlon[gridlon>180] -= 360\ngridlat = gridfile['T_LAT_2D'][:]\ngridlon2 = gridfile['U_LON_2D'][:]\ngridlon2[gridlon2>180] -= 360\ngridlat2 = gridfile['U_LAT_2D'][:]\nidi = gridfile['i_index'][:]\nidj = gridfile['j_index'][:]\n\n#Determine 'minlat' the lowest latitude where there is ocean\nminlat = 20\nfor lo in range(len(lon)):\n dep = Z[:,lo]\n bo = True\n la = 0\n while(bo):\n if(dep[la]<0):\n bo = False\n if minlat>lat[la]:\n minlat = lat[la]\n la += 1\n \nminlatold = gridlat[0,0]\nminlatold2 = gridlat2[0,0]\nlatstep = 0.04225922\n\ndef concatenate_south(newlats, old):\n new = np.zeros((len(newlats),3600));\n for i in range(len(newla)): new[i,:] = old[0,:];\n res = np.concatenate((new,old),axis=0)\n return res\n\n#concatenate latitudes south of the grid\n#For the latitudes of the grid (for U-grid and T-grid):\nnewlats = np.flip(-np.arange(-minlatold+latstep,-minlat+2*latstep, latstep))\nnewla = np.zeros((len(newlats),3600)); \nfor i in range(3600): newla[:,i] = newlats;\ngridlat = np.concatenate((newla,gridlat), axis=0)\n\nnewlats2 = np.flip(-np.arange(-minlatold2+latstep,-minlat+latstep, latstep))\nnewla = np.zeros((len(newlats),3600)); \nfor i in range(3600): newla[:,i] = newlats2;\ngridlat2 = np.concatenate((newla,gridlat2), axis=0)\n\n#For the longitudes of the grid (for U-grid and T-grid):\nnewlo = np.zeros((len(newlats),3600));\nfor i in range(3600): newlo[:,i] = np.full(len(newlats), gridlon[0,i]);\ngridlon = np.concatenate((newlo,gridlon),axis=0)\nnewlo = np.zeros((len(newlats),3600));\nfor i in range(3600): newlo[:,i] = np.full(len(newlats), gridlon2[0,i]);\ngridlon2 = np.concatenate((newlo,gridlon2),axis=0)\n\n# Also concatenate for the other grids: (leave the last latitude out)\nhtn = concatenate_south(newlats, htn[:-1])\nhte = concatenate_south(newlats, hte[:-1])\nhus = concatenate_south(newlats, hus[:-1])\nhuw = concatenate_south(newlats, huw[:-1])\nangle = concatenate_south(newlats, angle[:-1])\n\nnew_j_index = np.append(np.arange(1,len(newlats)+1),idj+149)\n\ngridlon = gridlon + 25\ngridlon[gridlon>180] -= 360\n\ngridlonplot = gridlon[::10,::10]\ngridlatplot = gridlat[::10,::10]\n\nplt.figure(figsize=(15,15))\nplt.contourf(lon, lat, Z, [-10000,-0.1,0.1,10000], cmap='Spectral')\nplt.colorbar()\nplt.scatter(gridlonplot.flatten(), gridlatplot.flatten(), s=1, c='k')\nplt.show()\n\nplt.figure(figsize=(5,5))\nplt.contourf(gridlonplot)\nplt.colorbar()\nplt.title('gridlons')\nplt.show()\n\n#%% Calculate the area of every grid cell\ntarea = np.full(htn.shape, np.nan)\n\nfor j in range(htn.shape[0]):\n if(j%300==0):\n print(j/float(htn.shape[0]))\n for i in range(htn.shape[1]):\n dxt = (htn[j,i] + htn[j,(i+1)%htn.shape[0],]) / 2.\n dyt = (hte[j,i] + hte[j,i-1]) / 2.\n tarea[j,i] = dxt * dyt\n \nassert ~np.isnan(tarea).any(), 'some area is NaN'\n#%% Write new netcdf file with new grid\ndataset = Dataset('grid_coordinates_pop_tx0.1_38ma.nc', 'w')\n\ni_indexs = dataset.createDimension('i_index', 3600)\nj_indexs = dataset.createDimension('j_index', 2400+len(newlats))\ndepth_ts = dataset.createDimension('depth_t', 42)\nw_deps = dataset.createDimension('w_dep', 43)\n\nins = dataset.createVariable('i_index', np.float32,('i_index',))\njns = dataset.createVariable('j_index', np.float32,('j_index',))\ndepth_tns = dataset.createVariable('depth_t', np.float32,('depth_t',))\nw_depns = dataset.createVariable('w_dep', np.float32,('w_dep',))\nlatitudes = dataset.createVariable('T_LAT_2D', np.float32,('j_index','i_index',))\nlongitudes = dataset.createVariable('T_LON_2D', np.float32,('j_index','i_index',))\nlatitudes2 = dataset.createVariable('U_LAT_2D', np.float32,('j_index','i_index',))\nlongitudes2 = dataset.createVariable('U_LON_2D', np.float32,('j_index','i_index',))\n\nhtns = dataset.createVariable('HTN', np.float32,('j_index','i_index',))\nhtes = dataset.createVariable('HTE', np.float32,('j_index','i_index',))\nhuss = dataset.createVariable('HUS', np.float32,('j_index','i_index',))\nhuws = dataset.createVariable('HUW', np.float32,('j_index','i_index',))\nangles = dataset.createVariable('ANGLE', np.float32,('j_index','i_index',))\ntareas = dataset.createVariable('TAREA', np.float32,('j_index','i_index',))\n\n# Write data\nins[:] = idi\njns[:] = new_j_index\ndepth_tns[:] = gridfile['depth_t'][:]\nw_depns[:] = gridfile['w_dep'][:]\nlatitudes[:] = gridlat\nlongitudes[:] = gridlon\nlatitudes2[:] = gridlat2\nlongitudes2[:] = gridlon2\n\nhtns[:] = htn\nhtes[:] = hte\nhuss[:] = hus\nhuws[:] = huw\nangles[:] = angle\ntareas[:] = tarea\n\n#Attributes:\nlatitudes.long_name = 'latitude on t-grid'\nlatitudes.units = 'degrees N'\nlongitudes.long_name = 'longitude on t-grid'\nlongitudes.units = 'degrees N'\nlatitudes2.long_name = 'latitude on u-grid'\nlatitudes2.units = 'degrees N'\nlongitudes2.long_name = 'longitude on u-grid'\nlongitudes2.units = 'degrees N'\nw_depns.units = 'meters'\nw_depns.long_name = 'T-grid depth'\ndepth_tns.units = 'meters'\ndepth_tns.long_name = 'T-grid depth'\nins.long_name = 'i-coordinate index'\njns.long_name = 'j-coordinate index'\n\n\ndataset.close()\n\n\n\n","sub_path":"prepare_simulation/make_grid_pop_tx0.1_38ma.py","file_name":"make_grid_pop_tx0.1_38ma.py","file_ext":"py","file_size_in_byte":6761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"}