diff --git "a/6394.jsonl" "b/6394.jsonl" new file mode 100644--- /dev/null +++ "b/6394.jsonl" @@ -0,0 +1,660 @@ +{"seq_id":"216566661","text":"class Singleton(object):\n #如果该类已经有了一个实例则直接返回,否则创建一个全局唯一的实例\n def __new__(cls, *args, **kwargs):\n if not hasattr(cls,'_instance'):\n # cls._instance = super(Singleton,cls).__new__(cls)\n cls._instance = object.__new__(cls)\n return cls._instance\n\ns1 = Singleton()\ns2 = Singleton()\ns3 = Singleton()\ns1.name = 'ww'\n\nprint(s1.name,s2.name,s3.name)\n","sub_path":"1203_单例模式.py","file_name":"1203_单例模式.py","file_ext":"py","file_size_in_byte":442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"610928277","text":"from django.urls import path\nfrom .views import SignUpView, ProfileUpdate, EmailUpdate\nfrom django.contrib.auth import views as auth_views\n\nurlpatterns = [\n path('signup/', SignUpView.as_view(), name=\"signup\"),\n path('login/', auth_views.LoginView.as_view(), name=\"login\"),\n path('logout/', auth_views.LogoutView.as_view(), name=\"logout\"),\n path('profile/', ProfileUpdate.as_view(), name=\"profile\"),\n path('profile/email/', EmailUpdate.as_view(), name=\"profile_email\"),\n]","sub_path":"registration/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"81067425","text":"from pymongo import MongoClient, errors\nimport lxml.html\nfrom urllib import request\n\n\nclass ScrapeCallback:\n def __init__(self, client=None, ):\n self.client = MongoClient('localhost', 27017) if client is None else client\n self.db = self.client.article\n\n def __call__(self, html=None, url=None):\n print('进入ScrapeCallback')\n tree = lxml.html.fromstring(html)\n fixed = lxml.html.tostring(tree, pretty_print=True)\n img_url = [a.get('src') for a in tree.cssselect('#blog_userface > a > img')]\n if img_url:\n path = 'D:/picture/'\n user = str(url).split('/')[3]\n name = path + user + '.jpg'\n conn = request.urlopen(img_url[0])\n file = open(name, 'wb')\n file.write(conn.read())\n file.close()\n else:\n pass\n print(img_url)\n","sub_path":"scrape_callback.py","file_name":"scrape_callback.py","file_ext":"py","file_size_in_byte":873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"366825940","text":"import numpy as np\nfrom scipy import signal\n\n\ndef get_ricker_wave(t, s=1):\n '''\n https://en.wikipedia.org/wiki/Mexican_hat_wavelet\n '''\n return 2 * (1-(t/s)**2) * np.e**(-t**2/(2*s**2)) / (np.sqrt(3*s)*np.pi**0.25)\n\ndef ricker(width, a):\n x = (np.arange(width) - int(width / 2)) / a\n return get_ricker_wave(x)\n\ndef sumple_chirp():\n return signal.chirp(np.arange(0, 10, 1/44100), f0=10, f1=4000, t1=10)\n\ndef step_cwt(x, mw, A, step=1):\n \"\"\"\n continuous wavelet transform with regulation of convolution step.\n\n Parameters\n ----------\n x: list[froat]\n input signal\n mw: function\n mother wavelet\n plz input 'ricker'\n A: list[int]\n scale\n step: int \n frequency of convolution\n \n Returns\n -------\n wavelet_metrix: ndarray\n [scale: int, wavelet_transformed_value: float]\n\n Examples\n --------\n >>> import cwt\n >>> import matplotlib.pyplot as plt\n >>> cwtmatr = cwt.step_cwt(cwt.sumple_chirp(), cwt.ricker, [1, 2, 3, 4, 5, 6], step=10)\n >>> plt.imshow(cwtmatr, extent=[0, 10, 1, 6], aspect='auto')\n\n output.shape is proportional to 'step' and 'A'\n >>> cwt.sumple_chirp.shape\n (441000,)\n >>> cwt.step_cwt(cwt.sumple_chirp(), cwt.ricker, [1, 2, 3, 4, 5, 6], step=1).shape\n (6, 441000)\n >>> cwt.step_cwt(cwt.sumple_chirp(), cwt.ricker, [1, 2, 3, 4, 5, 6], step=100).shape\n (6, 4410)\n \"\"\"\n rows = []\n for a in A:\n wave = mw(min(10*a, len(x)), a)\n if step==1:\n rows.append(np.convolve(x, wave, mode='same'))\n else:\n n_wave = len(wave)\n n_step = len(x) // step - 1\n columns = []\n padding_l = np.zeros([n_wave//2])\n padding_r = np.zeros([(n_wave-1)//2])\n _x = np.hstack([padding_l, x, padding_r])\n for i in range(n_step):\n cell = np.sum(_x[step*i:step*i+n_wave] * wave[::-1])\n columns.append(cell)\n rows.append(columns)\n return np.array(rows)\n\ndef cwt(x, mw, A):\n return step_cwt(x, mw, A, step=1)","sub_path":"Wavelet/cwt.py","file_name":"cwt.py","file_ext":"py","file_size_in_byte":2084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"520635648","text":"import mock\nfrom urlparse import parse_qsl\nfrom utils import send_message, build_message\n\n\ndef test_build_message_adds_timestamp():\n response_encoded = build_message('Test message', 'Test level')\n response = dict(parse_qsl(response_encoded))\n\n assert 'timestamp' in response\n\n\ndef test_send_messages_sends_message():\n with mock.patch('messages_app.utils.urlopen') as urlopen:\n send_message('Test message', 'Test level')\n\n urlopen.assert_called_once()\n","sub_path":"messages_app/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"390441622","text":"import pytest\n\n\n@pytest.fixture\ndef lab_base(testapp):\n item = {\n 'title': 'Other lab',\n 'name': 'other-lab',\n 'uuid': '32072c56-83af-4693-8545-0117fb9fa159'\n }\n return testapp.post_json('/lab', item, status=201).json['@graph'][0]\n","sub_path":"src/encoded/tests/fixtures/schemas/lab.py","file_name":"lab.py","file_ext":"py","file_size_in_byte":261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"353006514","text":"from config import vuln_app\n\n'''\n Decide if you want to server a vulnerable version or not!\n DO NOTE: some functionalities will still be vulnerable even if the value is set to 0\n as it is a matter of bad practice. Such an example is the debug endpoint.\n'''\nvuln = 1\n\n# token alive for how many seconds?\nalive = 10\n\nif __name__ == '__main__':\n vuln_app.run(host='0.0.0.0', port=5000, debug=True)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"270846251","text":"from django.urls import path\nfrom rest_framework.routers import SimpleRouter\nfrom rides.views import RideViewSet, RideAPi\n\n\nrouter = SimpleRouter()\nrouter.register('', RideViewSet)\n\nride_urls = [\n path('by-user/', RideAPi.ride_history_by_user),\n path('by-scan/', RideAPi.ride_by_scan),\n path('stop-ride/', RideAPi.stop_ride)\n ] + router.urls\n","sub_path":"rides/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"280726212","text":"from django.test import TestCase\nfrom django.urls import reverse, resolve\nimport requests\nfrom .models import *\nfrom .views import *\n\n# Create your tests here.\n\nBASE_URL = 'http://127.0.0.1:8000/'\nURLS = ['home_view', 'about_view', 'menu_view', 'confirmation_view', 'order_view', 'checkout_view']\nURLS_ARGS = ['amount_view']\n\nclass TestURLs(TestCase):\n\n def urlCallback(self, name_url):\n response = self.client.get(reverse(name_url))\n self.assertEqual(response.status_code, 200)\n print(f'Url {name_url} works')\n\n def urlCallbackArgs(self, name_url, amount):\n response = self.client.get(reverse(name_url, args=[amount]))\n self.assertEqual(response.status_code, 302)\n print(f'Url {name_url} works')\n\n def test_url(self):\n for url in URLS_ARGS:\n self.urlCallbackArgs(url, 50)\n\n for url in URLS:\n self.urlCallback(url)\n\nclass TestModels(TestCase):\n\n def setUp(self):\n self.product = AddProduct.objects.create(\n title='product1',\n price=50,\n )\n\n def test_validate_amount(self):\n with self.assertRaises(Exception):\n self.broodje = Broodje_vdw.objects.create(\n title='product2',\n price=55,\n )\n self.broodje2 = Broodje_vdw.objects.create(\n title='product3',\n price=105,\n )\n\n self.clean = Broodje_vdw.clean(self.broodje2)\n\nif __name__ == '__main__':\n TestCase\n","sub_path":"Main/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":1505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"561619133","text":"from __future__ import annotations\nimport itertools\nimport random\nfrom enum import Enum\nfrom abc import ABC\nfrom typing import TypeVar, NewType, Union, Callable, Tuple, Any, Dict, get_type_hints, List, Optional\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport cv2\nimport pandas as pd\nfrom scipy.stats import mode\nimport scipy.ndimage as ndimage\nfrom scipy.ndimage.interpolation import shift\nfrom scipy.signal import convolve2d\nfrom skimage.filters import rank_order\nimport skimage.measure as sk_measure\nfrom skimage.metrics import structural_similarity as ssim\nfrom skimage.future import manual_lasso_segmentation\nfrom scipy.ndimage import label\nfrom skimage.measure import block_reduce\nimport skimage.filters.rank as ranks\nfrom skimage.transform import downscale_local_mean\n\nimport trainer.lib as lib\nimport trainer.ml as ml\nfrom trainer.demo_data.arc import Value, plot_as_heatmap, game_from_subject\nfrom trainer.cg.dsl_utils import general_transform, ortho_filter, full_filter, diag_filter, colour_converter, zoom_in, \\\n objects_from_labels, select_objects, get_lbl_lu\nfrom trainer.cg.samplers import RandomInteger\n\nBoolFilter = NewType('BoolFilter', np.ndarray)\n\nValueGrid = NewType('ValueGrid', np.ndarray)\nBoolGrid = NewType('BoolGrid', np.ndarray)\nIntGrid = NewType('IntGrid', np.ndarray)\nRealGrid = NewType('RealGrid', np.ndarray)\nObjectLabels = NewType('ObjectLabels', Tuple[np.ndarray, np.ndarray])\nSingleObject = NewType('SingleObject', Tuple[np.ndarray, np.ndarray])\n\nIntLine = NewType('IntLine', np.ndarray)\n\nPosition = NewType('Position', Tuple[int, int])\nOffset = NewType('Offset', Tuple[int, int])\nNonZeroNumber = NewType('NonZeroNumber', int)\n\n\nclass Orientation(Enum):\n horizontal, vertical, diagonal_dota, diagonal_other = range(4)\n\n\nclass B(Enum):\n T, F = range(2)\n\n\ndef is_value(arr: ValueGrid, v: Value) -> BoolGrid:\n return arr == v.value\n\n\ndef value_to_arr(v: Value) -> ValueGrid:\n arr = np.zeros((30, 30))\n arr[:, :] = v.value\n return arr\n\n\ndef negated_arr(arr: BoolGrid, negated: B) -> BoolGrid:\n if negated == B.T:\n return ~arr\n else:\n return arr\n\n\ndef sorted_values(grid: ValueGrid) -> List[Value]:\n numbers, counts = np.unique(grid, return_counts=True)\n c_sort = np.flip(np.argsort(counts))\n res = list(numbers[c_sort])\n v_res = [colour_converter[v] for v in res]\n return v_res\n\n\ndef pick_from_values(values: List[Value], count_index: RandomInteger, reverted: B) -> Value:\n i = count_index % len(values)\n if reverted == B.F:\n return values[i]\n else:\n return values[len(values) - 1 - i]\n\n\ndef coord(grid: ValueGrid, modulo: RandomInteger) -> IntLine:\n output = np.arange(grid.shape[0])\n if modulo != 0:\n return np.mod(output, modulo)\n else:\n return output\n\n\ndef different_cells_in_line(grid: ValueGrid, orientation: Orientation) -> IntLine:\n output = np.zeros(grid.shape[0])\n\n # Populate output with the number of different colors in that particular line\n if orientation == Orientation.vertical:\n for i in range(grid.shape[1]):\n output[i] = len(np.unique(grid[:, i]))\n elif orientation == Orientation.horizontal:\n for i in range(grid.shape[0]):\n output[i] = len(np.unique(grid[i, :]))\n return output\n\n\ndef arr_from_line(line: IntLine, orientation: Orientation) -> IntGrid:\n output = np.zeros((line.shape[0], line.shape[0]))\n\n if orientation == Orientation.vertical or orientation == Orientation.diagonal_dota:\n for i in range(line.shape[0]):\n output[:, i] = line[i]\n else:\n for i in range(line.shape[0]):\n output[i, :] = line[i]\n\n return output\n\n\n###############################################\n# Objectness\n###############################################\n\nclass RegionProp(Enum):\n area, bbox_area, convex_area, eccentricity, equivalent_diameter, euler_number, extent, filled_area = range(8)\n centroid_row, centroid_column, major_axis_length, minor_axis_length, orientation, perimeter, solidity = range(9, 16)\n\n\ndef compute_region_prop(prop, rp: RegionProp) -> float:\n if rp == RegionProp.area:\n p = prop.area\n elif rp == RegionProp.bbox_area:\n p = prop.bbox_area\n elif rp == RegionProp.convex_area:\n p = prop.convex_area\n elif rp == RegionProp.eccentricity:\n p = prop.eccentricity\n elif rp == RegionProp.equivalent_diameter:\n p = prop.equivalent_diameter\n elif rp == RegionProp.euler_number:\n p = prop.euler_number\n elif rp == RegionProp.extent:\n p = prop.extent\n elif rp == RegionProp.filled_area:\n p = prop.filled_area\n elif rp == RegionProp.centroid_row:\n p = prop.centroid[0]\n elif rp == RegionProp.centroid_column:\n p = prop.centroid[1]\n elif rp == RegionProp.major_axis_length:\n p = prop.major_axis_length\n elif rp == RegionProp.minor_axis_length:\n p = prop.major_axis_length\n elif rp == RegionProp.orientation:\n p = prop.orientation\n elif rp == RegionProp.perimeter:\n p = prop.perimeter\n elif rp == RegionProp.solidity:\n p = prop.solidity\n else:\n raise Exception(f\"rp has an invalid value {rp}\")\n return p\n\n\ndef reg_quantity(labels: ObjectLabels, rp: RegionProp) -> RealGrid:\n # First label connected regions\n # Then output properties of each region\n props = sk_measure.regionprops(labels[1])\n res = np.zeros_like(labels[0])\n for i, prop in enumerate(props):\n res[labels[1] == i + 1] = compute_region_prop(prop, rp)\n return res\n\n\nclass Structs(Enum):\n Orthogonal, Full = 1, 2\n\n\ndef lbl_connected(arr: ValueGrid, structure: Structs, background: Value) -> ObjectLabels:\n bg = background.value\n # labels, num = label(arr, structure=structure)\n labels = sk_measure.label(arr, background=bg, connectivity=structure.value)\n return arr, labels\n\n\ndef lbl_by_bg(arr: ValueGrid, structure: Structs, background: Value) -> ObjectLabels:\n bg_arr = ((arr != background.value) & (arr != 0)).astype(np.uint8)\n labels = sk_measure.label(bg_arr, background=0, connectivity=structure.value)\n return arr, labels\n\n\ndef lbl_by_bool(grid: ValueGrid, arr: BoolGrid) -> ObjectLabels:\n return grid, arr.astype(np.uint8)\n\n\ndef object_by_ordering(objts: ObjectLabels, prop: RegionProp, count_index: RandomInteger, reverted: B) -> SingleObject:\n res = select_objects(objts, lambda lbl: compute_region_prop(sk_measure.regionprops(lbl)[0], prop), count_index,\n reverted == B.F)\n return res\n\n\ndef origin() -> Position:\n return 0, 0\n\n\ndef get_obj_lu(obj: SingleObject) -> Position:\n \"\"\"\n :param grid: Zero-padded object\n :return: (x, y) coordinate of the left upper corner of a zero-padded object\n \"\"\"\n if np.max(obj[1]) == 0:\n return 0, 0\n obj_indices = np.argwhere(obj[1])\n return tuple(np.min(obj_indices, axis=0))\n\n\ndef object_by_spatial(objts: ObjectLabels, count_index: RandomInteger, reverted: B) -> SingleObject:\n def lbl_to_priority(lbl: np.ndarray):\n x, y = get_lbl_lu(lbl)\n return x + y * 30\n\n # pos_to_priority = lambda x: x[0] + x[1] * 30\n res = select_objects(objts, lbl_to_priority, count_index, reverted == B.F)\n return res\n\n\ndef move_to(obj: SingleObject, location: Position) -> SingleObject:\n # If there is no Empty space, moving makes no sense even though its a valid operation\n assert obj[0].shape == (30, 30) and obj[1].shape == (30, 30)\n if np.max(np.unique(obj[1])) == 0:\n return obj\n reduced, reducedatt, (l, r, b, t) = ml.reduce_by_attention(obj[0], obj[1])\n res, res_mask = np.zeros_like(obj[0]), np.zeros_like(obj[1])\n res = ml.insert_np_at(res, reduced, location)\n res_mask = ml.insert_np_at(res_mask, reducedatt, location)\n return res, res_mask\n\n\n###############################################\n# Numbers\n###############################################\n\ndef non_zero_num(x: RandomInteger, b: B) -> NonZeroNumber:\n if b == B.T:\n return x\n else:\n return -1 * x\n\n\ndef measure_grid(grid: ValueGrid, orientation: Orientation) -> RandomInteger:\n if len(np.unique(grid)) == 1:\n # return np.random.random(grid.shape)\n return random.randint(0, 30)\n reduced, reducedatt, (l, r, b, t) = ml.reduce_by_attention(grid, grid != 0)\n if orientation == Orientation.horizontal or orientation == Orientation.diagonal_dota:\n return reduced.shape[1]\n else:\n return reduced.shape[0]\n\n\ndef measure_grid_b(grid: BoolGrid, orientation: Orientation) -> RandomInteger:\n return measure_grid(grid, orientation)\n\n\ndef hist(grid: ValueGrid) -> IntGrid:\n vals, nums = np.unique(grid, return_counts=True)\n res = np.zeros_like(grid, dtype=np.int)\n for i, v in enumerate(vals):\n res[grid == v] = nums[i]\n return res\n\n\n###############################################\n# Everything concerned with transformations\n###############################################\n\nclass OneShotTransform(Enum):\n Identity, Rot90, Rot180, Rot270 = range(4)\n FlipLR, FlipUD = range(10, 12)\n\n\ndef transform(labelling: ObjectLabels, t_type: OneShotTransform) -> ValueGrid:\n \"\"\"\n Every coherent region is transformed independently.\n\n If objects are classified by their color it works fine to transform the input directly.\n If not first foreground needs to be separated from background by a labelling strategy.\n \"\"\"\n\n if t_type == OneShotTransform.Rot90:\n f = np.rot90\n elif t_type == OneShotTransform.Rot180:\n f = lambda x: np.rot90(x, k=2)\n elif t_type == OneShotTransform.Rot270:\n f = lambda x: np.rot90(x, k=3)\n elif t_type == OneShotTransform.FlipLR:\n f = np.fliplr\n elif t_type == OneShotTransform.FlipUD:\n f = np.flipud\n else:\n assert t_type == OneShotTransform.Identity\n # f = lambda x: x\n return labelling[0]\n return general_transform(labelling[0], labels=labelling[1], f=f)\n\n\ndef direction_step(step_size: NonZeroNumber, direction: Orientation) -> Offset:\n if direction == Orientation.horizontal:\n return 0, step_size\n elif direction == Orientation.vertical:\n return step_size, 0\n elif direction == Orientation.diagonal_dota:\n return -1 * step_size, step_size\n else:\n return step_size, step_size\n\n\ndef make_offset(x: NonZeroNumber, y: NonZeroNumber) -> Offset:\n return x, y\n\n\ndef shift_val_arr(grid: ValueGrid, offset: Offset) -> ValueGrid:\n return np.roll(grid, offset, axis=(0, 1))\n\n\ndef zoom_valgrid(grid: ValueGrid, factor: RandomInteger) -> ValueGrid:\n return zoom_in(grid, factor)\n\n\ndef zoom_boolgrid(grid: BoolGrid, factor: RandomInteger) -> BoolGrid:\n return zoom_in(grid, factor)\n\n\n###############################################\n# Custom Filtering\n###############################################\n\nclass RFilters(Enum):\n Modal, Majority = range(2)\n\n\ndef filter_3x3(middle: B, ortho: B, diag: B) -> BoolFilter:\n n_filter = np.zeros((3, 3), dtype=np.uint8)\n if ortho == B.T:\n n_filter = n_filter | ortho_filter\n if diag == B.T:\n n_filter = n_filter | diag_filter\n n_filter[1, 1] = 1 if middle == B.T else 0\n return n_filter\n\n\ndef rfilt(arr: ValueGrid, rfilter: RFilters, s: BoolFilter) -> ValueGrid:\n # if neighbourhood == Structs.Orthogonal:\n # s = ndimage.generate_binary_structure(2, 1)\n # else:\n # s = ndimage.generate_binary_structure(2, 2)\n if rfilter == RFilters.Modal:\n return ranks.modal(arr.astype(np.uint8), selem=s)\n else:\n return ranks.majority(arr.astype(np.uint8), selem=s)\n\n\ndef apply_boolf(im: BoolGrid, filt: BoolFilter) -> IntGrid:\n \"\"\"\n Filters 3x3 patches using the given filter\n \"\"\"\n return convolve2d(im, filt, mode='same')\n\n\ndef ident_neigh(arr: ValueGrid) -> IntGrid:\n \"\"\"Outputs the number of identical values in the input for each neighbourhood\"\"\"\n\n def f(patch: np.ndarray):\n # Patch is flattened\n rel_colour = patch[4]\n\n return np.sum(patch == rel_colour) - 1\n\n assert arr.shape == (30, 30)\n res = ndimage.generic_filter(\n arr,\n f,\n size=3,\n mode='constant',\n # extra_arguments=\n )\n assert res.shape == (30, 30)\n return res\n\n\n###############################################\n# Misc\n###############################################\n\ndef tiled(arr: ValueGrid) -> ValueGrid:\n size = (30, 30)\n if len(np.unique(arr)) == 1:\n return arr\n reduced, reducedatt, (l, r, b, t) = ml.reduce_by_attention(arr, arr != 0)\n row_multiplier = size[0] // reduced.shape[0] + 1\n column_multiplier = size[1] // reduced.shape[1] + 1\n return np.tile(reduced, (row_multiplier, column_multiplier))[:size[0], :size[1]]\n\n\n###############################################\n# Output Helpers\n###############################################\n\ndef obj_to_valgrid(obj: SingleObject) -> ValueGrid:\n return obj[0]\n\n\ndef obj_to_boolgrid(obj: SingleObject) -> BoolGrid:\n return obj[1]\n\n\ndef int_to_real(int_arr: IntGrid) -> RealGrid:\n return int_arr\n\n\ndef bool_to_real(b_arr: BoolGrid) -> RealGrid:\n return b_arr.astype(np.float32)\n\n\nif __name__ == '__main__':\n sess = lib.Session()\n # test_subject = sess.query(lib.Subject).filter(lib.Subject.name == '228f6490').first()\n test_subject = sess.query(lib.Subject).filter(lib.Subject.name == '1cf80156').first()\n # test_subject = sess.query(lib.Subject).filter(lib.Subject.name == 'd037b0a7').first()\n game = game_from_subject(test_subject)\n pair = game.train_pairs[0]\n\n fig, (ax1, ax2) = plt.subplots(2, 1)\n pair.visualize(ax1, ax2)\n fig.show()\n\n # x = lbl_by_bg(pair.get_situation(), structure=Structs.Orthogonal, background=Value.Empty)\n # x = apply_boolf(pair.get_situation() == 1) # , RFilters.Modal, Structs.Orthogonal)\n # sns.heatmap(x);\n # plt.show()\n # l = coord(pair.get_situation(), 2)\n # l2 = different_cells_in_line(pair.get_situation(), Orientation.horizontal)\n # g = arr_from_line(l, Orientation.vertical)\n # f = filter_3x3(B.F, B.T, B.F)\n labels = lbl_connected(pair.get_situation(), Structs.Full, background=Value.Empty)\n im, mask = object_by_spatial(labels, 0, B.T)\n h = hist(pair.get_situation())\n","sub_path":"trainer/cg/grid_dsl.py","file_name":"grid_dsl.py","file_ext":"py","file_size_in_byte":14295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"408291436","text":"import tingbot\nfrom tingbot import screen\nfrom tingbot.graphics import Image\n\nip_address = None\n\n@tingbot.every(seconds=10)\ndef get_ip_address():\n global ip_address\n try:\n import socket\n s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n s.connect(('8.8.8.8', 1))\n ip_address = s.getsockname()[0]\n except:\n ip_address = None\n\nscreen.fill('black')\nno_network_image = Image.load('NetworkNotFound.jpg')\nready_image = Image.load('ReadyScreen.gif')\n\ndef loop():\n # drawing code here\n if ip_address:\n screen.image(ready_image)\n screen.text(\n ip_address,\n xy=(10, 230),\n align='bottomleft',\n color='white',\n font_size=10,\n )\n else:\n screen.image(no_network_image)\n \n# run the app\ntingbot.run(loop)\n","sub_path":"root/apps/ready.tingapp/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"26150948","text":"# --- coding: UTF-8 ---\n\n'''\nsendHexData.py\n\nCopyright (c) 2016 Kimihito Tanaka\n\nThis software is released under the MIT License.\nhttp://opensource.org/licenses/mit-license.php\n\n'''\n\n# Version: Ver1.0\n\nfrom __future__ import print_function\nimport sys\nimport socket\nfrom contextlib import closing\nfrom array import array\nimport click\nimport re\n\nclass SyntaxHandler():\n u''' This class handles command arguments '''\n \n def __init__(self, arg):\n for i in range(len(sys.argv)):\n if sys.argv[i] == '-h' or sys.argv[i] == '--help':\n print ('')\n print ('Syntax: python xxxx.py -a ')\n print ('')\n print ('HOST : hostname or ip address of the server')\n print ('PORT : TCP port number of the server')\n print ('Option :')\n print (' -a Array option. Supply array file path')\n sys.exit()\n \nclass SendHex():\n \n def __init__(self, host, port, url, data_to_send):\n # Constructing socket\n self.host = host\n self.port = int(port)\n self.bufsize = 4096\n self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\n # Constructing data\n self.data_to_send = data_to_send\n \n def run(self):\n with closing(self.sock):\n self.sock.connect((self.host, self.port))\n \n self.sock.send(self.data_to_send)\n self.sock.recv(self.bufsize)\n return \n\nclass DataHandler():\n \n def __init__(self, op, data):\n self.arrdata = array('B', []) # This is the final data to send\n if op == '-a':\n self.readArray(data)\n self.genArrayFromHex()\n \n def readArray(self, file):\n self.f = file\n self.hexlist = self.f.read()\n self.hexlist = self.hexlist.replace(' ', '')\n self.hexlist = self.hexlist.replace('\\n', '')\n self.hexlist = self.hexlist.split(',')\n \n def genArrayFromHex(self): # -a\n for hex in self.hexlist:\n self.arrdata.append(int(hex, 16))\n \n def getArray(self):\n #print (self.arrdata)\n return self.arrdata\n \n@click.command()\n@click.argument('HOST')\n@click.argument('PORT')\n@click.argument('URL')\n@click.option('-a', '--array', type=click.File('r'), help='Give a path of frame hex data')\ndef syntax_parser(host, port, url, array):\n url = re.sub(r'^/', '', url)\n if array:\n opcode = '-a'\n data = array\n data_handler = DataHandler(opcode, data)\n data_to_send = data_handler.getArray()\n print(data_to_send)\n client = SendHex(host, port, url, data_to_send).run()\n\nif __name__ == '__main__':\n syntax_parser()\n","sub_path":"sendHexData.py","file_name":"sendHexData.py","file_ext":"py","file_size_in_byte":2761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"646910080","text":"def resolve():\n n, m = map(int, input().split())\n AB = []\n for i in range(m):\n AB.append(list(map(int, input().split())))\n k = int(input())\n K = set()\n for i in range(k):\n c, d = map(int, input().split())\n if c not in K:\n K.add(c)\n else:\n if d not in K:\n K.add(d)\n ans = 0\n for a, b in AB:\n if a in K and b in K:\n ans += 1\n print(ans)\n\nif __name__ == \"__main__\": # 提出時のみ復活させる\n resolve()\n\n\nimport sys\nfrom io import StringIO\nimport unittest\n\n\nclass TestClass(unittest.TestCase):\n def assertIO(self, input, output):\n stdout, stdin = sys.stdout, sys.stdin\n sys.stdout, sys.stdin = StringIO(), StringIO(input)\n resolve()\n sys.stdout.seek(0)\n out = sys.stdout.read()[:-1]\n sys.stdout, sys.stdin = stdout, stdin\n self.assertEqual(out, output)\n\n def test_入力例_1(self):\n input = \"\"\"4 4\n1 2\n1 3\n2 4\n3 4\n3\n1 2\n1 3\n2 3\"\"\"\n output = \"\"\"2\"\"\"\n self.assertIO(input, output)\n\n def test_入力例_2(self):\n input = \"\"\"4 4\n1 2\n1 3\n2 4\n3 4\n4\n3 4\n1 2\n2 4\n2 4\"\"\"\n output = \"\"\"4\"\"\"\n self.assertIO(input, output)\n\n def test_入力例_3(self):\n input = \"\"\"6 12\n2 3\n4 6\n1 2\n4 5\n2 6\n1 5\n4 5\n1 3\n1 2\n2 6\n2 3\n2 5\n5\n3 5\n1 4\n2 6\n4 6\n5 6\"\"\"\n output = \"\"\"9\"\"\"\n self.assertIO(input, output)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"abc-c/abc190-c.py","file_name":"abc190-c.py","file_ext":"py","file_size_in_byte":1470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"128479180","text":"import re\ndef myAtoi(s):\n '''\n strip returns a copy of the string with both leading\n and trailing characters removed\n \" -4102 \" = \"-4102\"\n '''\n s = s.strip()\n '''\n findall is used when you want to iterate over the lines of the file\n return a list of all the matches in a single step\n\n \"^\": this expression matches the start of the string\n \\D: anything but a number( a non digit )\n \\d: any number ( a digit )\n \\*: 0 or more\n .+*?[]$^()[]|\\ : escape required - for \\d\n '''\n s = re.findall('(^[\\+\\-0]*\\d+)\\D*',s)\n\n '''\n try block lets you test a lobkc of code for errors\n except block lets you handle the error\n finally block lets you execute code, regardless of the result\n of the try- and except blocks\n '''\n\n try:\n result = int(''.join(s))\n return max((pow(-2,31), min(result, pow(2,31)-1)))\n except:\n return 0\n","sub_path":"strings/atoi.py","file_name":"atoi.py","file_ext":"py","file_size_in_byte":915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"451406805","text":"import os\nimport sys\n\nwork_dir = os.path.abspath(\"./Ultra-Light-Fast-Generic-Face-Detector-1MB\")\nsys.path.append(work_dir)\nfrom vision.ssd.config.fd_config import define_img_size\nfrom vision.ssd.mb_tiny_RFB_fd import (\n create_Mb_Tiny_RFB_fd,\n create_Mb_Tiny_RFB_fd_predictor,\n)\nimport numpy as np\n\nthreshold = 0.7\ncandidate_size = 1500\ndefine_img_size(640)\ntest_device = \"cpu\"\n\nlabel_path = os.path.join(work_dir, \"models/voc-model-labels.txt\")\ntest_device = test_device\n\nclass_names = [name.strip() for name in open(label_path).readlines()]\n\nmodel_path = os.path.join(work_dir, \"models/pretrained/version-RFB-320.pth\")\nnet = create_Mb_Tiny_RFB_fd(len(class_names), is_test=True, device=test_device)\npredictor = create_Mb_Tiny_RFB_fd_predictor(\n net, candidate_size=candidate_size, device=test_device\n)\nnet.load(model_path)\n\n# The variable \"image\" is sent from the konduit client in \"konduit_server.py\", i.e. in our example \"encoded_image\"\nprint(\">>> Server side shape\")\nprint(image.shape)\nimage = np.squeeze(image)\nboxes, _, _ = predictor.predict(image, candidate_size / 2, threshold)\n\n# \"num_boxes\" is then picked up again from here and returned to the client\nnum_boxes = np.array(len(boxes))\n","sub_path":"python/examples/face_detection_pytorch/detect_image.py","file_name":"detect_image.py","file_ext":"py","file_size_in_byte":1205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"372477489","text":"import pickle\nfrom redis import Redis as _Redis\nfrom bbs.config import REDIS\n\n\nclass Redis(_Redis):\n\n def get(self, name):\n pickle_value = super().get(name)\n if pickle_value is None:\n return None\n else:\n try:\n value = pickle.loads(pickle_value)\n except pickle.UnpicklingError:\n return pickle_value\n else:\n return value\n\n def set(self, name, value, ex=60, px=None, nx=False, xx=False, keepttl=False):\n pickle_value = pickle.dumps(value, pickle.HIGHEST_PROTOCOL)\n return super().set(name, pickle_value, ex, px, nx, xx, keepttl)\n\n\nrds = Redis(**REDIS)","sub_path":"utils/bbscache.py","file_name":"bbscache.py","file_ext":"py","file_size_in_byte":678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"516929043","text":"#######################################################################################################\n## Arval Service Lease\n## Author: W Jouanne\n## Modified: January 07, 2013\n## Description:\n## This script attempts to connect to a given node manager, and to start a admin server.\n##\n## Usage: java weblogic.WLST stopstart_server.py mycommand myhost mynmport myuserconfigfile myuserkeyfile mydomainname mydomaindir mynmtype myserver\n##\t\t\t\t\t\t 1 2 3 4 5 6 7 8 9\n##\n## Ref. doc. :http://docs.oracle.com/cd/E14571_01/web.1111/e13813/reference.htm\n##\n## Error List : 0=OK ; 1=Node Manager problem ; 2= Other Error\n##\n#######################################################################################################\n\nimport sys\nimport time\n\nhost = sys.argv[1]\nnmport = sys.argv[2]\nuserconfigfile = sys.argv[3]\nuserkeyfile = sys.argv[4]\ndomainname = sys.argv[5]\ndomaindir = sys.argv[6]\nnmtype = sys.argv[7]\ncommand = sys.argv[8]\nservername = sys.argv[9]\n\nusage=\"java weblogic.WLST manage_server.py mycommand myhost mynmport myuserconfigfile myuserkeyfile mydomainname mydomaindir mynmtype myserver\"\n\nif command == \"start\":\n\ttry:\n\t\tnmConnect(userConfigFile=userconfigfile, userKeyFile=userkeyfile , host=host, port=nmport, domainName=domainname, domainDir=domaindir, mType=nmtype)\n\texcept:\n\t\tsys.exit(1)\n\ttry:\n\t\tnmStart(servername)\n\texcept:\n\t\tsys.exit(2)\n\ttry:\n\t\tnmDisconnect()\n\texcept:\n\t\tsys.exit(1)\nelif command == \"stop\":\n\ttry:\n\t\tnmConnect(userConfigFile=userconfigfile, userKeyFile=userkeyfile , host=host, port=nmport, domainName=domainname, domainDir=domaindir, mType=nmtype)\n\texcept:\n\t\tsys.exit(1)\n\ttry: \n\t\tnmKill(servername)\n\texcept:\n\t\tsys.exit(2)\n\ttry:\n\t\tnmDisconnect()\n\texcept:\n\t\tsys.exit(1)\nelif command == \"status\":\n\ttry:\n\t\tnmConnect(userConfigFile=userconfigfile, userKeyFile=userkeyfile , host=host, port=nmport, domainName=domainname, domainDir=domaindir, mType=nmtype)\n\texcept:\n\t\tsys.exit(1)\n\tserverStatus=nmServerStatus(servername)\n\tif serverStatus == \"SHUTDOWN\":\n\t\tsys.exit(10)\n\telif serverStatus == \"STARTING\":\n\t\tsys.exit(11)\n\telif serverStatus == \"STANDBY\":\n\t\tsys.exit(12)\n\telif serverStatus == \"ADMIN\":\n\t\tsys.exit(13)\n\telif serverStatus == \"RESUMING\":\n\t\tsys.exit(14)\n\telif serverStatus == \"RUNNING\":\n\t\tsys.exit(15)\n\telif serverStatus == \"SUSPENDING\":\n\t\tsys.exit(16)\n\telif serverStatus == \"FORCE_SUSPENDING\":\n\t\tsys.exit(17)\n\telif serverStatus == \"SHUTTING_DOWN\":\n\t\tsys.exit(18)\n\telif serverStatus == \"FAILED\":\n\t\tsys.exit(19)\n\telse:\n\t\tsys.exit(20)\n\ttry:\n\t\tnmDisconnect()\n\texcept:\n\t\tsys.exit(1)\nelse:\n\tprint(usage)\nexit()\n","sub_path":"weblogic/StartupServices/manage_server.py","file_name":"manage_server.py","file_ext":"py","file_size_in_byte":2612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"218522489","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[2]:\n\n\nimport random\n\nwith open('random_number.txt','w') as f:\n for i in range(0,1000):\n f.write(str(random.randint(1,100))+'\\n')\n\n","sub_path":"Random_Numbers.py","file_name":"Random_Numbers.py","file_ext":"py","file_size_in_byte":184,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"154330673","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport webbrowser\nimport urllib.parse\n\nstr = '测试'\nprint(str)\n# print(dir(urllib3))\n\nstr2 = urllib.parse.quote(str)\n\nprint(str2)\n\nurl = \"https://www.baidu.com/s?wd=\" + str3\n\n# print(urllib.quote(str.encode('utf8')))\n\nwebbrowser.open(url)","sub_path":"Python/PyCharm/123.py","file_name":"123.py","file_ext":"py","file_size_in_byte":286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"251767321","text":"import torch.optim\nimport torch.nn as nn\n\nfrom .multireso_net import Multireso_Net\n\nclass Base_Model():\n def __init__(self, device, net, loss, optimizer):\n self.net = net.to(device)\n self.loss = loss.to(device)\n self.optimizer = optimizer\n\n def load_ckpt(self, ckpt):\n self.net.load_state_dict(ckpt['model_state_dict'])\n self.optimizer.load_state_dict(ckpt['optimizer_state_dict'])\n\ndef get_multireso_model(device, lr=0.0003):\n net = Multireso_Net([64, 96, 128])\n loss = nn.MSELoss()\n optimizer = torch.optim.Adam(net.parameters(), lr=lr)\n return Base_Model(device, net, loss, optimizer)\n","sub_path":"old_stuff/code/hpe-feb2019/qi2016/holi_multi_reso/src/models/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"343892096","text":"# %%spark\nfrom pyspark import SparkContext\nfrom pyspark.sql import SparkSession\nfrom pyspark.sql import functions as sf\nfrom pyspark.sql.types import *\nfrom pyspark import SQLContext\nfrom datetime import date,datetime,timedelta\nfrom pytz import timezone\nfrom pyspark.sql.functions import *\nfrom pyspark.sql.window import Window\nimport boto3\nimport sys\nimport uuid\n\n##########################################################################################################\n\n#Create function and register udf\ndef funcTZConversion (ip_dt_str,from_tz,to_tz):\n fmt = \"%Y-%m-%d %H:%M:%S\"\n datetime_obj_naive = datetime.strptime(ip_dt_str,fmt)\n datetime_obj_tz = timezone(from_tz).localize(datetime_obj_naive)\n tgt_tz = timezone(to_tz)\n tgt_dtime = datetime_obj_tz.astimezone(tgt_tz)\n return tgt_dtime.strftime(fmt)\n\nudf_TZConversion = udf(funcTZConversion)\n\n##########################################################################################################\n\n# bucket = \"\"\n# access_key = \"\"\n# secret_key = \"\"\n# vendor = \"\"\n# date = \"1900-01-01\"\n\nbucket = sys.argv[1]\naccess_key = sys.argv[2]\nsecret_key = sys.argv[3]\nvendor = sys.argv[4]\ndate = sys.argv[5]\nenriched_path = sys.argv[6]\nappNameSuffix = vendor + \"Spark_JSON_Parquet\"\n\nyear = date.split('-',1)[0]\nmonth = date.split('-',2)[1]\nday = date.split('-',3)[2]\n\n# If you run in pyspark, ignore sc = SparkContext(). Else if you run via spark-submit, uncomment this.\nsc = SparkContext()\nsc._jsc.hadoopConfiguration().set(\"fs.s3.awsAccessKeyId\", \"\" + access_key + \"\")\nsc._jsc.hadoopConfiguration().set(\"fs.s3.awsSecretAccessKey\", \"\"+ secret_key + \"\")\nsc._jsc.hadoopConfiguration().set(\"hadoop.tmp.dir\", \"/mnt/var/lib/hadoop/tmp/\"+str(uuid.uuid4()))\n\nsparkSession = (SparkSession\n .builder\n .appName('SparkApp_' + appNameSuffix)\n # .config(\"spark.hadoop.fs.s3.enableServerSideEncryption\", \"true\")\n # .config(\"spark.hadoop.fs.s3.serverSideEncryptionAlgorithm\", \"aws:kms\")\n # .config(\"spark.hadoop.fs.s3.impl\", \"org.apache.hadoop.fs.s3native.NativeS3FileSystem\")\n .config(\"spark.sql.parquet.filterPushdown\", \"true\")\n .config(\"spark.sql.parquet.mergeSchema\", \"true\")\n .config(\"spark.sql.caseSensitive\",\"true\")\n .config(\"spark.sql.shuffle.partitions\",\"5\")\n .config(\"spark.sql.sources.partitionOverwriteMode\",\"dynamic\")\n .getOrCreate())\n\nclient = boto3.client('s3',aws_access_key_id=access_key, aws_secret_access_key=secret_key, region_name=\"us-west-2\")\n\nsrcfilePath = \"s3://\" + bucket + \"/\" + enriched_path + vendor + \"/JSON/\" + year + \"/\" + month + \"/\" + day +\"\"\n\ntgtfilePath = \"s3://\" + bucket + \"/\" + enriched_path + vendor + \"/Parquet/\"\n\ndfjson = sparkSession.read.format(\"json\").option(\"multiline\", \"true\").option(\"inferSchema\", \"true\").load(srcfilePath)\n\n#data = dfjson.select(explode(\"DATA\").alias(\"data\"))\ndata = dfjson.withColumn(\"data\", explode(\"DATA\")).select(\"data.*\")\n\n# dfPT = data.withColumn(\"createdDatePT\",sf.to_timestamp(udf_TZConversion(sf.regexp_replace(data.createdDate,\"T\",\" \").cast(\"string\"),sf.lit(\"UTC\"),sf.lit(\"US/Pacific\")),\"yyyy-MM-dd HH:mm:ss\"))\ndfPT = data.withColumn(\"createdDatePT\",sf.from_utc_timestamp(sf.regexp_replace(data.createdDate,\"T\",\" \"),\"US/Pacific\"))\n\ndf = dfPT.withColumn(\"year\",sf.split(\"createdDate\",\"\\-\")[0]) \\\n .withColumn(\"month\",sf.split(\"createdDate\",\"\\-\")[1]) \\\n .withColumn(\"day\",sf.split((sf.split((sf.split(\"createdDate\",\"\\-\")[2]),\"T\")[0]),\" \")[0])\n\ndfbaseData = df.select([col for col in df.columns])\n\n#dfbaseData.show(10,False)\n\n# dfrankedId = dfbaseData.withColumn(\"row_num\", sf.row_number().over(Window.partitionBy(\"id\").orderBy(sf.asc(\"updatedAt\")))) \\\n # .where(sf.col(\"row_num\") == 1) \\\n # .select(dfbaseData[\"*\"])\n\ndfbaseData.repartition(sf.col(\"year\"),sf.col(\"month\"),sf.col(\"day\")) \\\n .write.format(\"parquet\") \\\n .partitionBy(\"year\",\"month\",\"day\") \\\n .mode(\"overwrite\") \\\n .save(tgtfilePath)","sub_path":"quovoTransaction/quovoTransaction_JSON_Parquet_Inc.py","file_name":"quovoTransaction_JSON_Parquet_Inc.py","file_ext":"py","file_size_in_byte":4116,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"516016140","text":"# -*- coding: utf-8 -*-\n\"\"\"\n-------------------------------------------------\n File Name: 小波降噪\n Description :\n Author : haoyuan.m\n date: 2018/10/25\n-------------------------------------------------\n Change Activity:\n 2018/10/25:\n-------------------------------------------------\n\"\"\"\n__author__ = 'haoyuan.m'\nimport pywt\nfrom atrader import *\nimport numpy as np\nimport sys\n\ntry:\n import talib\nexcept:\n print('请安装TA-Lib库')\n sys.exit(-1)\n\n\ndef init(context):\n set_backtest(initial_cash=10000000)\n reg_kdata('min', 30)\n context.N = 30\n context.n1 = 5\n context.n2 = 20\n context.initial = 10000000\n context.barlength = 420\n\n\ndef wave(array):\n coeffs = pywt.wavedec(array, 'haar', level=2)\n coeffs[-1], coeffs[-2] = np.zeros_like(coeffs[-1]), np.zeros_like(coeffs[-2])\n ss = pywt.waverec(coeffs, 'haar')\n return ss[-1]\n\n\ndef on_data(context):\n data = get_reg_kdata(reg_idx=context.reg_kdata[0], length=context.barlength, fill_up=True, df=True) # 获取所有标的数据\n if data['close'].isna().any():\n return\n long_positions = context.account().positions['volume_long']\n short_positions = context.account().positions['volume_short']\n close = data.close\n s1 = close.rolling(102).apply(wave)\n dif, dea, macd = talib.MACD(s1, fastperiod=12, slowperiod=26, signalperiod=9)\n ma1 = talib.EMA(s1, context.n1)\n ma2 = talib.EMA(s1, context.n2)\n condi_long = macd.iloc[-1] > 0 and ma1.iloc[-1] > ma2.iloc[-1] # 开多平空条件\n condi_short = macd.iloc[-1] < 0 and ma1.iloc[-1] < ma2.iloc[-1] # 开空平多条件\n if condi_long and long_positions[0] == 0: # 开多仓\n order_target_value(account_idx=0, target_idx=0, target_value=context.initial, side=1, order_type=2)\n if condi_short and short_positions[0] == 0: # 开空仓\n order_target_value(account_idx=0, target_idx=0, target_value=context.initial, side=2, order_type=2)\n if condi_short and long_positions[0] > 0: # 平多仓\n order_target_volume(account_idx=0, target_idx=0, target_volume=0, side=1, order_type=2)\n if condi_long and short_positions[0] > 0: # 平空仓\n order_target_volume(account_idx=0, target_idx=0, target_volume=0, side=2, order_type=2)\n\n\nif __name__ == '__main__':\n target = ['cffex.if0000']\n run_backtest('小波降噪', '小波降噪.py', target_list=target, frequency='min', fre_num=30, begin_date='2017-06-01',\n end_date='2018-06-01', fq=1)\n","sub_path":"CTA/日间/小波降噪.py","file_name":"小波降噪.py","file_ext":"py","file_size_in_byte":2530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"138364113","text":"\"\"\"\n(quote ((section MIPI13.4)(groupe )\n (date \"Thu Sep 21 12:35:57 CEST 2017\")(time \"1505990157\")\n (id1 \"3704090\")(nom1 \"IBOBI\")(prenom1 \"OsÚe\")\n (mel1 \"osee_ibobi@yahoo.com\")\n (id2 \"3670485\")(nom2 \"rizqi\")(prenom2 \"Zaccharia\")\n (mel2 \"Alzack94550@gmail.com\")))\n\n\nfonctions bboleennes pas faites sauf ou qui est bien\nsablier pas fait\n\"\"\"\n\nimport sys\nsys.path.append(\"/home/agrospel/logiciel/MrPython/mrpython/\")\nfrom studentlib.gfx.image import *\nfrom studentlib.gfx.img_canvas import *\n\nprint(\"Interpretation:\")\n\n\"\"\" exercice 2.2\"\"\"\nimport math\n\ndef volume_tetraedre(a,b,c,d,e,f):\n \"\"\"number**6->float\n hypoth├Ęse:a,b,c,d,e,f sont des longueurs des six cot├ęs d'un tr├ętra├Ędre e\nt sont positif\n retourne le volume de ce tr├ętra├Ędre\"\"\"\n #p:number\n p=4*a**2*b**2*c**2\n #q:number\n q=a**2*(a**2+b**2-d**2)**2+b**2*(a**2+c**2-f**2)**2+c**2*(b**2+c**2-e**2)**2\n #r:number\n r=(a**2+b**2-d**2)*(b**2+c**2-e**2)*(a**2+c**2-f**2)\n return (1/12)*math.sqrt(p-q+r)\n\n#jeu de tests:\nassert volume_tetraedre(1,1,1,1,1,1)==0.11785113019775792\nassert volume_tetraedre(2,2,2,2,2,2)==0.9428090415820634\n\n\"\"\" quest 2\"\"\"\n\nimport math\ndef tetraedre_regulier(a):\n \"\"\"number**6->float\n hypoth├Ęse:t├ętraedre de cot├ę a\n\n retourne le volume de ce t├ętraedre r├ęgulier\"\"\"\n return (math.sqrt(2)*a**3)/12\n\n#jeu de tests:\nassert tetraedre_regulier(1)==math.sqrt(2)/12\nassert tetraedre_regulier(2)== math.sqrt(2)/12*(2*2*2)\n\n\"\"\" exercice 2.5\"\"\"\ndef ou(p,q):\n \"\"\"bool*bool->bool\n retourne la disjonction de p et q\"\"\"\n if p:\n return True\n else:\n return q\n\nassert ou(True,False)==True\nassert ou(True,True)==True\nassert ou(False,False)==False\nassert ou(False,True)==True\n\n \n# def et(p,q):\n# \"\"\"bool*bool->bool\n# retourne la disjonction\n","sub_path":"monitorat/1I001-2/13.4/rendu2/ibobi-rizqi-1505990157_pas_fait.py","file_name":"ibobi-rizqi-1505990157_pas_fait.py","file_ext":"py","file_size_in_byte":1820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"307503339","text":"#!/usr/bin/env python\n# -*- coding: UTF-8 -*-\n\nimport rospy\nfrom std_msgs.msg import Int8\n\nparam_task = '/voice/param/task'\n\ntopic_base_task_status = '/comm/voice/ctrl/task_status'\n\n\nclass TaskFeedback:\n def __init__(self):\n rospy.init_node('TaskFeedback', anonymous=True)\n rospy.Subscriber(topic_base_task_status, Int8, self.task_feedback_callback)\n\n @staticmethod\n def task_feedback_callback(msg):\n task = rospy.get_param(param_task)\n if msg.data == 1 and task == 'bottle':\n rospy.set_param(\"/comm/param/control/target/is_set\", True)\n rospy.set_param(\"/comm/param/control/target/label\", \"bottle\")\n rospy.delete_param(param_task)\n\n\nif __name__ == \"__main__\":\n try:\n TaskFeedback()\n rospy.spin()\n except rospy.ROSInterruptException:\n print(\"TaskFeedback is over!\")\n","sub_path":"scripts/TaskFeedback.py","file_name":"TaskFeedback.py","file_ext":"py","file_size_in_byte":862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"360758378","text":"#### NOTES:\n#### I have completely NO IDEA what does this thing do\n\nimport os\nimport cv2 as cv\nimport numpy as np\nfrom scipy import signal\n\ncategories = []\n\n\nbelief_root = '/usr/home/rez/ZM/CNN/Up_Proj/result_newmodel';\nout_root = '/usr/home/rez/ZM/CNN/Up_Proj/result_newmodel_post_03';\n# belief_root = '/media/dit/data/Datasets/cdnet2014_subsense_bg_model';\n# out_root = '/media/dit/data/Datasets/cdnet2014_subsense_bg_model_corrected';\nR = 0.3\n# Extract only those that are directories.\nsubFolders = [item for item in os.listdir(belief_root) if os.path.isdir(os.path.join(belief_root, item))]\n\npath_ = belief_root\n\nfor i in range(1, 10001):\n\tfile_path = path_ + '/' + 'bin{:06d}.png'.format(i)\n\tim = cv.imread(file_path) / 255.0\n\tim = signal.medfilt2d(im, kernel_size=9)\n\tim = (im > R)\n\n\tout_path = out_root + '/' + 'bin{:06d}.png'.format(i)\n\tif os.path.exists(out_path):\n\t\tbreak\n\tcv.imwrite(out_path, im)","sub_path":"CNN_Code/bg_cnn_code/linux/scripts/medianPP3.py","file_name":"medianPP3.py","file_ext":"py","file_size_in_byte":907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"544666480","text":"import multiprocessing\nfrom joblib import Parallel, delayed\nfrom statsmodels.tsa.ar_model import AutoReg\n\n\nrules = pd.read_csv('data/xfers_per_rule_2.csv')\nrules.nxfers = rules.nxfers.astype(int)\nrules.bytes = rules.bytes.astype(float)\nfor d in ['min_created', 'min_submitted',\n 'min_started', 'min_ended', 'max_created', 'max_submitted',\n 'max_started', 'max_ended']:\n rules[d] = pd.to_datetime(rules[d])\nrules['ttc'] = (rules.max_ended - rules.min_created).astype(int)/10**9\nrules['createdatonce'] = (rules.min_created == rules.max_created).values.astype(int)\n\nrules = rules[rules.createdatonce == 1]\n# Tell pandas to treat the infinite as NaN\npd.set_option('use_inf_as_na', True)\ndef re(y, yhat):\n return abs(y - yhat)/y\n\ndef fogp(y, yhat, thr):\n e = re(y, yhat)\n return sum((e < thr).astype(int))/len(y)\n\ndef get_observed_finished_rules_at(t0, rho, lags, lookback):\n cut = rules[(rules.min_created >= (t0 - dt.timedelta(seconds=rho*lookback+rho*lags))) & (rules.max_ended < t0)]\n return cut\n\ndef get_real_finished_rules_at(t0, rho, lags, lookback):\n cut = rules[(rules.min_created >= (t0 - dt.timedelta(seconds=rho*lookback+rho*lags))) & (rules.min_created < t0)]\n return cut\n\ndef get_timeseries_for_rules(r, cut, rho, lags, lookback):\n try:\n x = pd.date_range(r.min_created - dt.timedelta(seconds=rho*lookback+rho*lags), r.min_created, freq=str(rho)+'s')\n except ValueError as e:\n #print('Returning shit for rule %s cause of NaT in get_timeseries_for_timestamp'%cut.ruleid)\n return [ts, [], [], [], [], []]\n dates = []\n minttc = []\n medianttc = []\n meanttc = []\n maxttc = []\n for s, e in zip(x,x[1:]):\n cut2 = cut[(cut.min_created > s) & (cut.min_created < e)]\n dates.append(s)\n minttc.append(cut2.ttc.min())\n medianttc.append(cut2.ttc.median())\n meanttc.append(cut2.ttc.mean())\n maxttc.append(cut2.ttc.max())\n df = pd.DataFrame(np.array([dates, minttc, medianttc, meanttc, maxttc]).T, columns=['ts', 'minttc', 'medianttc', 'meanttc', 'maxttc']).fillna(method='ffill')\n return df\n\ndef predict_beta_hat_mu(r,df, lags, lookahead):\n rid = r.ruleid\n df = df.fillna(method='bfill')\n for mu in ['minttc', 'medianttc', 'meanttc', 'maxttc']:\n train = df[mu].values[:-(lookahead+1)]\n pred = df[mu].values[-(lookahead+1)] \n preds = [pred]*(lookahead+1)\n df['p'+mu] = np.concatenate((train, preds))\n return df\n\ndef real_beta_mu(r, df, lags, lookahead):\n rid = r.ruleid\n df = df.fillna(method='bfill')\n for mu in ['minttc', 'medianttc', 'meanttc', 'maxttc']:\n df['p'+mu] = [df[mu].values.mean()]*len(df) \n return df\n\n\n\ndef get_prediction_for_rule(rid, rho, lags, lookback):\n lookahead = 8 * 60 // rho\n r = rules[rules.ruleid == rid].iloc[0]\n cutobs = get_observed_finished_rules_at(r.min_created, rho, lags, lookback)\n cutreal = get_real_finished_rules_at(r.min_created, rho, lags, lookback)\n tsobs = get_timeseries_for_rules(r, cutobs, rho, lags, lookback)\n tsreal = get_timeseries_for_rules(r, cutreal, rho, lags, lookback)\n tsobs = predict_beta_hat_mu(r, tsobs, lags, lookahead)\n tsreal = real_beta_mu(r, tsreal, lags, lookahead)\n# tsobs.to_csv('data/timeseries/obs_log%s.csv.bz2'%r.ruleid, index=False, compression='bz2')\n# tsreal.to_csv('data/timeseries/real_log%s.csv.bz2'%r.ruleid, index=False, compression='bz2')\n obspmin = tsobs.pminttc.values[-1]\n obspmedian = tsobs.pmedianttc.values[-1]\n obspmean = tsobs.pmeanttc.values[-1]\n obspmax = tsobs.pmaxttc.values[-1]\n realpmin = tsreal.pminttc.values[-1]\n realpmedian = tsreal.pmedianttc.values[-1]\n realpmean = tsreal.pmeanttc.values[-1]\n realpmax = tsreal.pmaxttc.values[-1]\n realmin = tsreal.minttc.values[-1]\n realmedian = tsreal.medianttc.values[-1]\n realmean = tsreal.meanttc.values[-1]\n realmax = tsreal.maxttc.values[-1]\n return r.ruleid, r.ttc, obspmin, obspmedian, obspmean, obspmax, realpmin, realpmedian, realpmean, realpmax, realmin, realmedian, realmean, realmax\n\nrhos = [30, 60, 90]\nlags = [15, 20, 30, 45, 60] # lags de 30 segundos\nlookback = [120, 240, 480] # lookback de 6, 12 y 24 horas dividido 30 segundos\nfor run in range(100):\n print('RUN: %d'%run)\n indices = np.random.choice(rules[(rules.min_created > dt.datetime(2019,6,9)) & (rules.min_created < dt.datetime(2019,7,30))].index, 200)\n for rho in rhos:\n for lag in lags:\n for lb in lookback:\n print('Calculating predictions for ρ=%d lags=%d lookback=%d'%(rho, lag, lb), end='\\r')\n rids = Parallel(n_jobs=12, backend='multiprocessing')(delayed(get_prediction_for_rule)(r, rho, lag, lb) for r in rules.loc[indices].ruleid.values)\n rids = pd.DataFrame(rids, columns=['rid', 'ttc', 'obspmin', 'obspmedian', 'obspmean', 'obspmax', 'realpmin', 'realpmedian', 'realpmean', 'realpmax', 'realmin', 'realmedian', 'realmean', 'realmax'])\n rids.to_csv('data/tsa/nonTSA_predictions_rho_%d_lags_%d_lookback_%d_run_%d.csv'%(rho, lag, lb, run), index=False)\n\n","sub_path":"study14_TSA_beta_hat_mu.py","file_name":"study14_TSA_beta_hat_mu.py","file_ext":"py","file_size_in_byte":5114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"114320877","text":"# This class handles all the incoming traffic and messages\nimport os\nimport pickle\nimport struct\nimport threading\nfrom queue import Queue\nfrom socket import socket\nfrom datetime import datetime\nimport cv2\n\nfrom SocketServer.ByteStreamAdapter import bs_adapter\nfrom SocketServer.WebAppInterface import WebAppInterface\n\nlbl = \"Incoming Thread - \"\n\n\nclass IncomingThread(threading.Thread):\n\n def __init__(self,\n name: str,\n inc_queue: Queue,\n connection: socket):\n \"\"\"\n :param name: The name of the thread\n :param inc_queue: This queue will hold all of the incoming information, we should only be pushing to this\n :param connection: The socket we are listening on\n \"\"\"\n # Call the supers init function\n threading.Thread.__init__(self)\n self.name: str = name\n self.running: bool = False\n self.inc_queue: Queue = inc_queue\n self.connection: socket = connection\n # Create a byte stream adapter for easier use\n self.bsa = bs_adapter(self.connection)\n\n def run(self):\n print(\"Starting: \" + self.name)\n self.running = True\n while self.running:\n # Receive the message type\n received_bytes = self.bsa.get_bytes(4)\n if len(received_bytes) == 0:\n raise Exception(lbl, \"The other end must have closed\")\n # Identify the message type\n\n msg_type = struct.unpack('i', received_bytes)[0]\n print(msg_type)\n if msg_type == 1:\n print(lbl, \"Handling as test message\")\n self.handle_test_message()\n elif msg_type == 2:\n print(lbl, \"Handling as video send\")\n self.handle_video_send()\n else:\n print(lbl, \"Message type was not recognized\")\n\n self.break_down()\n\n def handle_test_message(self):\n # Receive the next four bytes\n received_bytes = self.bsa.get_bytes(4)\n # Calculate the length of bytes in the message\n msg_len = struct.unpack('i', received_bytes)[0]\n received_bytes = self.bsa.get_bytes(msg_len)\n text = received_bytes.decode('utf-8')\n print(lbl, \"Test command:\", text)\n\n def handle_video_send(self):\n path = self.generate_video_path()\n received_tags = []\n\n # Create local copy of bsa\n _bsa = self.bsa\n ### Receive file check ###\n file_check = _bsa.read_int()\n print(lbl, \"File check result: \", file_check)\n if file_check != 1:\n # Verify the node wants to continue the transaction, if not return early\n print(lbl, \"The node failed to open the file and aborted the transaction\")\n return\n else:\n print(lbl, \"The node opened the file successfully and will now continue\")\n\n ### Receive tag count ###\n tag_count = _bsa.read_int()\n print(lbl, \"Receiving\", tag_count, \"tags\")\n\n # Per tag #\n # Check to make sure there are actually tags to receive\n while tag_count > 0:\n ### Receive the length of the first tag ###\n tag_len = _bsa.read_int()\n\n if tag_len <= 0:\n # Check if we have received an end of tag message\n print(lbl, \"Done reading tags\")\n break\n\n ### Receive tag string ###\n tag_str = _bsa.read_string(tag_len)\n received_tags.append(tag_str)\n print(lbl, \"Received tag:\", tag_str, \"at\", tag_count)\n # Keep track of how many more tags we need to read\n tag_count -= 1\n\n if tag_count == 0:\n # If we successfully read all our tags\n # We need to consume the end of tags message\n ### Read tags done message ###\n tag_res = _bsa.read_int()\n print(lbl, \"Finished reading tags successfully:\", tag_res)\n\n ### Read frame count ###\n frame_count = _bsa.read_int()\n ### Read frame width ###\n frame_width = _bsa.read_int()\n ### Read frame Height ###\n frame_height = _bsa.read_int()\n print(lbl, \"Frame count:\", frame_count, \"| Width,Height:\", frame_width, \",\", frame_height)\n\n # Open up the video writer to write the file\n # out = cv2.VideoWriter(path, cv2.VideoWriter_fourcc('m', 'p', '4', 'a'), 10, (frame_width, frame_height))\n \t# cv2.VideoWriter_fourcc('a', 'v', 'c', '1')\n # While we still have frames to receive\n while frame_count > 0:\n\n ### Receive frame length ###\n frame_len = _bsa.read_int()\n\n # if we receive a negative value it means something went wrong\n if frame_len <= 0:\n print(lbl, \"Received frame length below 0, ending transaction\")\n break\n\n ### Receive frame data ###\n img = _bsa.read_image(frame_len)\n frame_count -= 1\n # Write the image to our video writer\n out.write(img)\n\n if frame_count == 0:\n # If we successfully read all the frames we needed to\n ### Receive end of transaction byte ###\n video_res = _bsa.read_int()\n print(lbl, \"Done receiving video successfully:\", video_res)\n\n # Release the video writer\n out.release()\n WebAppInterface.getInstance().add_video_data(path, received_tags)\n\n def set_running(self, option: bool):\n self.running = option\n\n def generate_video_path(self):\n # Replace all the spaces in the name with dashes to avoid upsetting linux\n node_name = self.name.replace(' ', '-')\n # The name of the counter file for this node\n cf_name = \"{node_name}.cnt\".format(node_name=node_name)\n # the actual path to our counter file\n cf_path = os.path.join(os.getcwd(), 'Videos', 'Counters', cf_name)\n # The video number\n cnt = 0\n # check if the file exists\n if os.path.isfile(cf_path):\n # if the file exists read the int stored in it\n with open(cf_path, 'rb') as file:\n cnt = struct.unpack('i', file.read(4))[0]\n # afterwards overwrite it with the new count\n with open(cf_path, 'wb') as file:\n file.write(struct.pack('i', cnt + 1))\n else:\n with open(cf_path, 'wb') as file:\n file.write(struct.pack(\"i\", 1))\n\n now = datetime.now()\n date_time = now.strftime(\"%m-%d-%Y-%H-%M-%S\")\n print(\"date and time:\", date_time)\n # The title of the video file\n video_title = \"{node_name}-{date_time}-Video-{cnt}.mp4\".\\\n format(node_name=node_name, date_time=date_time, cnt=cnt)\n\n video_path = os.path.join(os.getcwd(), 'Videos', video_title)\n return video_path\n\n def break_down(self):\n print(\"Breaking down thread: \" + self.name)\n","sub_path":"SocketServer/IncomingThread.py","file_name":"IncomingThread.py","file_ext":"py","file_size_in_byte":6941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"396701505","text":"#!/usr/bin/env python3\nimport os\nimport time\nimport cv2\nfrom frame import Frame, denormalize, match_frames, IRt\nimport numpy as np\nimport g2o\nfrom point_map import Map, Point\n\n# camera intrinsics\nW, H = 1920//2, 1080//2\nF = 800\nK = np.array([[F,0,W//2],[0,F,H//2],[0,0,1]])\nKinv = np.linalg.inv(K)\n\n# main classes\nmapp = Map()\n\ndef triangulate(pose1, pose2, pts1, pts2):\n ret = np.zeros((pts1.shape[0], 4))\n pose1 = np.linalg.inv(pose1)\n pose2 = np.linalg.inv(pose2)\n for i, (p1, p2) in enumerate(zip(pts1, pts2)):\n A = np.zeros((4, 4))\n A[0] = p1[0] * pose1[2] - pose1[0]\n A[1] = p1[1] * pose1[2] - pose1[1]\n A[2] = p2[0] * pose2[2] - pose2[0]\n A[3] = p2[1] * pose2[2] - pose2[1]\n _, _, vt = np.linalg.svd(A)\n ret[i] = vt[3]\n return ret\n\ndef process_frame(img):\n img = cv2.resize(img, (W,H))\n frame = Frame(mapp, img, K)\n if frame.id == 0:\n return\n\n f1 = mapp.frames[-1]\n f2 = mapp.frames[-2]\n idx1, idx2, Rt = match_frames(f1, f2)\n f1.pose = np.dot(Rt, f2.pose)\n\n for i,idx in enumerate(idx2):\n if f2.pts[idx] is not None:\n f2.pts[idx].add_observation(f1, idx1[i])\n # homogeneous 3-D coords\n pts4d = triangulate(f1.pose, f2.pose, f1.kps[idx1], f2.kps[idx2])\n pts4d /= pts4d[:, 3:]\n\n # reject pts without enough \"parallax\" (this right?)\n # reject points behind the camera\n unmatched_points = np.array([f1.pts[i] is None for i in idx1])\n print(\"Adding: {} points\".format(np.sum(unmatched_points)))\n good_pts4d = (np.abs(pts4d[:, 3]) > 0.005) & (pts4d[:, 2] > 0) & unmatched_points\n for i,p in enumerate(pts4d):\n if not good_pts4d[i]:\n continue\n # print(idx1[i])\n # print(f1.pts[idx1[i]])\n # print(f1.pts)\n u, v = int(round(f1.kpus[idx1[i], 0])), int(round(f1.kpus[idx1[i], 1]))\n pt = Point(mapp, p, img[v, u])\n pt.add_observation(f1, idx1[i])\n pt.add_observation(f2, idx2[i])\n\n for pt1, pt2 in zip(f1.kps[idx1], f2.kps[idx2]):\n u1, v1 = denormalize(K, pt1)\n u2, v2 = denormalize(K, pt2)\n cv2.circle(img, (u1, v1), color=(0,255,0), radius=3)\n cv2.line(img, (u1, v1), (u2, v2), color=(255,0,0))\n # cv2.imshow(\"result\", img)\n # cv2.waitKey(1)\n if frame.id >=4:\n mapp.optimize()\n # 3-D\n mapp.display()\n\nif __name__ == \"__main__\":\n cap = cv2.VideoCapture(\"drone.mp4\")\n mapp.create_viewer()\n while cap.isOpened():\n ret, frame = cap.read()\n if ret == True:\n process_frame(frame)\n else:\n break\n\n\n","sub_path":"slam.py","file_name":"slam.py","file_ext":"py","file_size_in_byte":2604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"532737988","text":"import openpyxl\r\nfrom collections import Counter\r\nfrom selenium import webdriver\r\n\r\ndef countItem(li):\r\n result = {}\r\n for i in set(li):\r\n result[i] = li.count(i)\r\n return result\r\n\r\nif __name__ == '__main__':\r\n wb = openpyxl.load_workbook(\"example.xlsx\")\r\n ws = wb.active\r\n\r\n colA = ws['D']\r\n rowRange = ws[1:20]\r\n ele = []\r\n subClassNumber = {}\r\n countNumber = 1\r\n for cell in colA:\r\n ele.append(cell.value)\r\n result = countItem(ele)\r\n print(result)\r\n\r\n\r\n","sub_path":"excelExecise.py","file_name":"excelExecise.py","file_ext":"py","file_size_in_byte":509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"124095105","text":"# -*- coding: utf-8 -*-\nimport os, utils, pyprind\nimport spold2_reader as spold2\n\nversion = '20180411'\nsystem_model = 'Undefined'\nfolder = utils.version_system_model_path(version, system_model)\ndataset_folder = os.path.join(folder, 'datasets')\nao = utils.pkl_load(os.path.join(folder, 'pkl'), 'ao')\nmft = set(ao[ao['mft'] == 'mft']['name'])\nMD = utils.pkl_load(os.path.join(folder, 'pkl'), 'MD')\nMD = MD['IntermediateExchanges'].set_index('name')\nfilelist = utils.build_file_list(dataset_folder, 'spold')\ndf = []\nfor filename in pyprind.prog_bar(filelist):\n f = spold2.Dataset(dataset_folder, filename)\n for exc in f.FromTechnosphere:\n if exc.name in mft:\n to_add = f.baseline()\n to_add.update(exc.baseline())\n df.append(to_add)\ndf = utils.list_to_df(df)\ndf = df.set_index('name').join(MD[['By-product classification']]).reset_index()\ncolumns = ['activityName', 'geography', 'name', 'By-product classification']\ndfs = [(df, 'Sheet1', columns)]\nfolder = os.path.join(folder, 'excel')\nfilename = 'specialty_production_detector_{}.xlsx'.format(version)\nutils.dataframe_to_excel(folder, filename, dfs, feedback = True)","sub_path":"projects/short_scripts/specialty_production_detector.py","file_name":"specialty_production_detector.py","file_ext":"py","file_size_in_byte":1160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"300507326","text":"from . import models\nfrom django.views import generic\nfrom django.views.generic.edit import FormView\nfrom .documents import ElasticSectionDocument, ElasticPersonDocument, ElasticOfficeDocument, ElasticFileDocument\nfrom django import forms\nimport json\nimport logging\nimport urllib\nfrom declarations.common import resolve_fullname, resolve_person_name_from_search_request\nfrom disclosures_site.declarations.statistics import TDisclosuresStatisticsHistory\n\nclass SectionView(generic.DetailView):\n model = models.Section\n template_name = 'section/detail.html'\n\n\nclass PersonView(generic.DetailView):\n model = models.Person\n template_name = 'person/detail.html'\n\n\nclass FileView(generic.DetailView):\n model = models.Source_Document\n template_name = 'file/detail.html'\n\n\nclass HomePageView(generic.TemplateView):\n template_name = 'morda/index.html'\n\n\nclass OfficeView(generic.DetailView):\n model = models.Office\n template_name = 'office/detail.html'\n\n\nclass AboutPageView(generic.TemplateView):\n template_name = 'morda/about.html'\n\n\nclass StatisticsView(generic.TemplateView):\n template_name = \"statistics/statistics.html\"\n history = TDisclosuresStatisticsHistory()\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n for key, value in StatisticsView.history.get_last().metrics.items():\n context[key] = value\n context[key+\"_name\"] = TDisclosuresStatisticsHistory.get_metric_name(key)\n return context\n\n\nclass CommonSearchForm(forms.Form):\n search_request = forms.CharField(\n widget=forms.TextInput(attrs={'size': 80}),\n strip=True,\n label=\"ФИО\")\n office_request = forms.CharField(\n widget=forms.TextInput(attrs={'size': 80}),\n required=False,\n empty_value=\"\",\n label=\"Ведомство\")\n\n\ndef check_Russiam_name(name1, name2):\n if name1 is None or name2 is None:\n return True\n if len(name1) == 0 or len(name2) == 0:\n return True\n name1 = name1.strip(\".\").lower()\n name2 = name2.strip(\".\").lower()\n return name1.startswith(name2) or name2.startswith(name1)\n\n\ndef compare_Russian_fio(search_query, person_name):\n if search_query.find(' ') == -1 and search_query.find('.') == -1:\n return True\n fio1 = resolve_person_name_from_search_request(search_query)\n fio2 = resolve_fullname(person_name)\n if fio1 is None or fio2 is None:\n return True\n if fio1['family_name'].lower() != fio2['family_name'].lower():\n return False\n return check_Russiam_name(fio1.get('name'), fio2.get('name')) \\\n and check_Russiam_name(fio1.get('patronymic'), fio2.get('patronymic'))\n\n\nclass CommonSearchView(FormView, generic.ListView):\n\n paginate_by = 20\n #paginate_by = 2 #temporal\n\n form_class = CommonSearchForm\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n if hasattr(self, \"hits_count\"):\n context['hits_count'] = self.hits_count\n context['query_fields'] = self.get_query_in_cgi()\n return context\n\n def get_initial(self):\n return {\n 'search_request': self.request.GET.get('search_request'),\n 'office_request': self.request.GET.get('office_request')\n }\n\n def query_elastic_search(self, match_operator=\"OR\"):\n query = self.get_initial().get('search_request')\n if query is None:\n return None\n if len(query) == 0:\n return None\n try:\n if query.startswith('{') and query.endswith('}'):\n query_dict = json.loads(query)\n else:\n query_dict = {\n #self.elastic_search_document.default_field_name: query,\n self.elastic_search_document.default_field_name : {\n 'query': query,\n 'operator': match_operator\n }\n }\n\n\n search_results = self.elastic_search_document.search().query('match', **query_dict)\n return search_results\n except Exception:\n return None\n\n def process_search_results(self, search_results, max_count, person_name_filtering=False):\n object_list = list()\n person_name_query = self.get_initial().get('search_request')\n for x in search_results[:max_count]:\n try:\n if not person_name_filtering or compare_Russian_fio(person_name_query, x.person_name):\n rec = self.model.objects.get(pk=x.id)\n object_list.append(rec)\n except Exception as exp:\n logging.getLogger('django').error(\"cannot get record, id={}\".format(x.id))\n raise\n self.hits_count = len(object_list)\n return object_list\n\n def process_query(self, max_count=100, match_operator=\"OR\"):\n search_results = self.query_elastic_search(match_operator)\n if search_results is None:\n return []\n return self.process_search_results(search_results, max_count)\n\n def get_query_in_cgi(self):\n query_fields = []\n for (k, v) in self.get_initial().items():\n if v is not None and len(v) > 0:\n query_fields.append((k, v))\n query_fields = urllib.parse.urlencode(query_fields)\n return query_fields\n\n\nclass OfficeSearchView(CommonSearchView):\n model = models.Office\n template_name = 'office/index.html'\n elastic_search_document = ElasticOfficeDocument\n\n def get_queryset(self):\n if self.get_initial().get('search_request') is None:\n object_list = list(models.Office.objects.all())\n return object_list\n else:\n object_list = self.process_query(500, match_operator=\"and\")\n object_list.sort(key=lambda x: x.source_document_count, reverse=True)\n return object_list\n\n\nclass PersonSearchView(CommonSearchView):\n model = models.Person\n template_name = 'person/index.html'\n elastic_search_document = ElasticPersonDocument\n\n def get_queryset(self):\n search_results = self.query_elastic_search()\n if search_results is None:\n return []\n object_list = self.process_search_results(search_results, 1000, person_name_filtering=True)\n\n object_list.sort(key=lambda x: x.section_count, reverse=True)\n return object_list\n\n\nclass SectionSearchView(CommonSearchView):\n model = models.Section\n template_name = 'section/index.html'\n elastic_search_document = ElasticSectionDocument\n\n def query_elastic_search(self):\n query = self.get_initial().get('search_request')\n if query is None or len(query) == 0:\n return None\n try:\n if query.startswith('{') and query.endswith('}'):\n query_dict = json.loads(query)\n return self.elastic_search_document.search().query('match', **query_dict)\n else:\n query_string = \"(person_name: {})\".format(query)\n office_query = self.get_initial().get('office_request')\n if office_query is not None and len(office_query) > 0:\n offices_search = ElasticOfficeDocument.search().query('match', name=office_query)\n total = offices_search.count()\n if total == 0:\n return None\n offices = list(str(o.id) for o in offices_search[0:total])\n office_query = \" AND (office_id: ({}))\".format(\" OR \".join(offices))\n query_string += office_query\n\n search_results = self.elastic_search_document.search().query('query_string',\n query=query_string\n )\n return search_results\n except Exception as e:\n return None\n\n def get_queryset(self):\n search_results = self.query_elastic_search()\n if search_results is None:\n return []\n object_list = self.process_search_results(search_results, max_count=1000, person_name_filtering=True)\n object_list.sort(key=lambda x: x.person_name)\n return object_list\n\n\nclass FileSearchView(CommonSearchView):\n model = models.Source_Document\n template_name = 'file/index.html'\n elastic_search_document = ElasticFileDocument\n\n def get_queryset(self):\n # using 300 here to allow search bots to crawl all file links going from one office\n object_list = self.process_query(max_count=300)\n\n object_list.sort(key=lambda x: x.file_path, reverse=True)\n return object_list\n","sub_path":"tools/disclosures_site/declarations/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"429294023","text":"#!/usr/bin/python\nimport sys\nimport BreedingSimulationUtils\nmax_chr_size=320000000\nsimilarities_file_name=sys.argv[1]\nvcf_file_for_sample_names=sys.argv[2]\nsimulations_num=int(sys.argv[3]) \noutput_filename=sys.argv[4]\nf=open(similarities_file_name,'r')\nline=f.readline().rstrip()\nlines_list=[]\npos_set=set()\npos_set.add(1)\npos_set.add(max_chr_size)\nline=f.readline().rstrip()\nwhile line:\n parts=line.split('\\t')\n assert len(parts)==4\n for i in range(2,4):\n parts[i]=int(parts[i])\n pos_set.add(parts[i])\n lines_list.append(parts)\n # a = sorted(a, key=lambda x: x.modified, reverse=True)\n line=f.readline().rstrip()\n #line.strsplit\nf.close()\nlines_list = sorted(lines_list, key=lambda x: x[3]-x[2], reverse=True)\npos_set=sorted(pos_set)\npositions_index={}\npositions_num=len(pos_set)\nfor i in range(positions_num):\n positions_index[pos_set[i]]=i\nsample_names=GenotyperUtils.extractSampleNamesFromVCF(vcf_file_for_sample_names,9)\ninitial_group_size=len(sample_names)\nsample_index={}\ndata_matrix = [[0 for x in range(positions_num-1)] for y in range(simulations_num+ initial_group_size)]\n\nfor i in range(initial_group_size):\n sample_index[sample_names[i]]=i+1\n data_matrix[i]=[i+1 for x in range(positions_num-1)]\n\nfor i in range(simulations_num):\n sample_names.append(\"sample_{}\".format(i+initial_group_size+1))\n\nsimilarity_lines_num=len(lines_list)\nfor i in range(similarity_lines_num):\n target_val=sample_index[lines_list[i][0]]\n assert lines_list[i][1][:7]=='sample_'\n curr_sample_index= int(lines_list[i][1][7:])-1\n assert curr_sample_index>=initial_group_size\n assert curr_sample_index/', views.topic, name='topic'),\n # 用于添加新主题的页面\n path('new_topic/', views.new_topic, name='new_topic'),\n # 用于添加新条目的页面。\n path('new_entry//', views.new_entry, name='new_entry'),\n # 用于编辑条目的页面。\n path('edit_entry//', views.edit_entry, name='edit_entry'),\n\n\n]","sub_path":"learning_logs/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"597235147","text":"import pandas as pd\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nfrom sklearn.cluster import KMeans, AgglomerativeClustering\r\n\r\n# contains count, median price for each quarter as cols, LGA in 2nd entry of \r\n# each row.\r\n\r\ndef preprocess_house(fname):\r\n # reorganises the house price csv files into a more standard format\r\n # columns: Quarter, LGA, Count, Median\r\n\r\n h = pd.read_csv(fname)\r\n\r\n # # creates a sorted list of LGAs \r\n LGAs = h[\"Unnamed: 1\"].to_list()\r\n LGAs = sorted(LGAs[2:-6])\r\n LGAs = LGAs[0:28] + LGAs[35:] # removing \"group total\" rows\r\n\r\n # creates a sorted list of quarters\r\n quarters = h.values.tolist()[0]\r\n quarters = quarters[2::2]\r\n\r\n # duplicates list values to store 1 row per quarter per LGA\r\n quarters_new = [\"\"] * (len(quarters)*len(LGAs))\r\n for i in range(len(quarters)):\r\n for j in range(len(LGAs)):\r\n quarters_new[i * len(LGAs) + j] = quarters[i]\r\n\r\n LGAs_new = [\"\"] * (len(quarters)*len(LGAs))\r\n for i in range(len(quarters)):\r\n for j in range(len(LGAs)):\r\n LGAs_new[i * len(LGAs) + j] = LGAs[j]\r\n\r\n\r\n\r\n dict = {} # stores counts and median house prices as list of tuples for each LGA\r\n row_count = len(h.index)\r\n for r in [i + 2 for i in range(row_count - 7)]:\r\n row = h.values.tolist()[r]\r\n if row[1] != \"Group Total\":\r\n dict[row[1]] = []\r\n for j in range(len(quarters)):\r\n dict[row[1]].append((row[2*j+2], row[2*j+3]))\r\n \r\n # uses dict to create columns for counts and median house prices\r\n counts = [\"\"] * len(quarters_new)\r\n prices = [\"\"] * len(quarters_new)\r\n for i in range(len(quarters)):\r\n j = 0\r\n for LGA in sorted(dict.keys()):\r\n if \"-\" not in dict[LGA][i][0]:\r\n counts[i * len(LGAs) + j] = int(dict[LGA][i][0].replace(\",\", \"\"))\r\n prices[i * len(LGAs) + j] = int(dict[LGA][i][1][1:].replace(\",\", \"\"))\r\n else:\r\n counts[i * len(LGAs) + j] = 0\r\n prices[i * len(LGAs) + j] = 0\r\n j += 1\r\n\r\n df = pd.DataFrame.from_dict({\"Quarter\": quarters_new, \"LGA\": LGAs_new, \"Count\": counts, \"Median House Price\": prices})\r\n\r\n\r\n\r\n # aggregating data per year\r\n years = df[\"Quarter\"].to_list()\r\n for i in range(len(years)):\r\n years[i] = years[i][4:]\r\n df.insert(1, \"Year\", years, True)\r\n df.drop(\"Quarter\", inplace=True, axis=1)\r\n df = df.reset_index()\r\n \r\n prices_new = [''] * (79 * 22)\r\n i = 0\r\n year_set = sorted(list(set(years)))\r\n LGA_set = sorted(list(set(df[\"LGA\"].to_list())))\r\n for year in year_set:\r\n for LGA in LGA_set:\r\n temp = df[df[\"Year\"] == year]\r\n temp = temp[temp[\"LGA\"] == LGA]\r\n temp = temp[temp[\"Median House Price\"] != 0]\r\n if len(temp):\r\n p = temp[\"Median House Price\"].to_list()\r\n else:\r\n p = [0]\r\n prices_new[i] = sum(p) / len(p)\r\n i += 1\r\n\r\n df1 = df.groupby(['Year', 'LGA']).sum()\r\n df1[\"Median House Price\"] = prices_new\r\n df1 = df1[-790::]\r\n df1 = df1.reset_index().drop(\"index\", axis=1)\r\n\r\n return df1\r\n\r\ndef preprocess_crime1(fname):\r\n # reorganises and cleans crime1 csv\r\n # columns: year, lga, incidents, rate per 100k\r\n\r\n df = pd.read_csv(fname, usecols=[\"Year\", \"Local Government Area\", \"Incidents Recorded\", 'Rate per 100,000 population']) # contains incidents and rate/100k\r\n\r\n # sorting years in ascending order\r\n df = df.sort_values(by=[\"Year\", \"Local Government Area\"])\r\n\r\n # removing misc rows\r\n df = df[df[\"Local Government Area\"] != \"Total\"]\r\n df = df[df[\"Local Government Area\"] != \" Unincorporated Vic\"]\r\n df = df[df[\"Local Government Area\"] != \" Justice Institutions and Immigration Facilities\"]\r\n df = df.reset_index()\r\n df.drop(\"index\", inplace=True, axis=1)\r\n\r\n\r\n # converting rate and incidents to int/float\r\n rates = df[\"Rate per 100,000 population\"].to_list()\r\n incidents = df[\"Incidents Recorded\"].to_list()\r\n for i in range(len(rates)):\r\n rates[i] = float(rates[i].replace(\",\", \"\"))\r\n incidents[i] = int(incidents[i].replace(\",\", \"\"))\r\n df[\"Rate per 100,000 population\"] = rates\r\n df[\"Incidents Recorded\"] = incidents\r\n\r\n\r\n return df\r\n\r\ndef preprocess_combined(df1, df2):\r\n # Combines two dataframes and removes rows with 0\r\n df1.insert(len(df1.columns), \"Incidents Recorded\", df2[\"Incidents Recorded\"])\r\n df1.insert(len(df1.columns), \"Rate per 100,000 population\", df2[\"Rate per 100,000 population\"])\r\n df1 = df1[df1[\"Median House Price\"] != 0]\r\n df1.reset_index(inplace=True)\r\n return df1\r\n\r\ndef cluster_kmeans(X, k, fname, htype):\r\n kmeans = KMeans(n_clusters=k, init='k-means++', max_iter=300, n_init=10, random_state=0)\r\n kmeans.fit_predict(X)\r\n plt.scatter(X[:,0], X[:,1])\r\n plt.scatter(kmeans.cluster_centers_[:, 0], kmeans.cluster_centers_[:, 1], s=300, c='red')\r\n plt.xlabel(\"Median Rent Price\")\r\n plt.ylabel(\"Incidents Recorded\")\r\n plt.title(f\"Median Rent Price vs Incidents Recorded per 100k population for {htype}\", fontsize=10)\r\n plt.savefig(fname)\r\n plt.clf()\r\n return 0\r\n\r\n\r\ndef cluster_agglomerative(X, k, fname, htype):\r\n clustering = AgglomerativeClustering(n_clusters=k).fit(X)\r\n plt.scatter(X[:,0],X[:,1], c=clustering.labels_, cmap='rainbow')\r\n plt.xlabel(\"Median Rent Price\")\r\n plt.ylabel(\"Incidents Recorded\")\r\n plt.title(f\"Median Rent Price vs Incidents Recorded per 100k population for {htype}\", fontsize=10)\r\n plt.savefig(fname)\r\n plt.clf()\r\n return 0\r\n\r\n\r\n\r\n\r\n# reading in csv files\r\nc1 = preprocess_crime1(\"crime1.csv\") # contains incidents and rate/100k\r\none_bf = preprocess_combined(preprocess_house(\"1bflat.csv\"), c1) # contains count and median price\r\none_bf_2020 = one_bf[one_bf[\"Year\"] == \"2020\"]\r\ntwo_bf = preprocess_combined(preprocess_house(\"2bflat.csv\"), c1) # contains count and median price\r\ntwo_bf_2020 = two_bf[two_bf[\"Year\"] == \"2020\"]\r\nthree_bf = preprocess_combined(preprocess_house(\"3bflat.csv\"), c1) # contains count and median price\r\nthree_bf_2020 = three_bf[three_bf[\"Year\"] == \"2020\"]\r\ntwo_bh = preprocess_combined(preprocess_house(\"2bhouse.csv\"), c1) # contains count and median price\r\ntwo_bh_2020 = two_bh[two_bh[\"Year\"] == \"2020\"]\r\nthree_bh = preprocess_combined(preprocess_house(\"3bhouse.csv\"), c1) # contains count and median price\r\nthree_bh_2020 = three_bh[three_bh[\"Year\"] == \"2020\"]\r\nfour_bh = preprocess_combined(preprocess_house(\"4bhouse.csv\"), c1) # contains count and median price\r\nfour_bh_2020 = four_bh[four_bh[\"Year\"] == \"2020\"]\r\nall = preprocess_combined(preprocess_house(\"all.csv\"), c1) # contains count and median price\r\nall_2020 = all[all[\"Year\"] == \"2020\"]\r\n\r\np = all[\"Median House Price\"].to_list()\r\nc = all[\"Rate per 100,000 population\"].to_list()\r\nl = []\r\nfor i in range(len(all)):\r\n l.append([p[i], c[i]])\r\nX = np.array(l)\r\nwcss = []\r\nfor i in range(1, 11):\r\n kmeans = KMeans(n_clusters=i, init='k-means++', max_iter=300, n_init=10, random_state=0)\r\n kmeans.fit(X)\r\n wcss.append(kmeans.inertia_)\r\nplt.plot(range(1, 11), wcss)\r\nplt.title('Elbow Method')\r\nplt.xlabel('Number of clusters')\r\nplt.ylabel('WCSS')\r\nplt.savefig(\"all-elbow.png\")\r\nplt.clf()\r\ncluster_kmeans(X, 4, \"plot-all-kmeans-4.png\", \"All House Types\")\r\ncluster_agglomerative(X, 4, \"plot-all-agglomerative-4.png\", \"All House types\")\r\n\r\np = two_bh[\"Median House Price\"].to_list()\r\nc = two_bh[\"Rate per 100,000 population\"].to_list()\r\nl = []\r\nfor i in range(len(two_bh)):\r\n l.append([p[i], c[i]])\r\nY = np.array(l)\r\ncluster_kmeans(Y, 4, \"plot-2bh-kmeans.png\", \"2 Bedroom Houses\")\r\ncluster_agglomerative(Y, 4, \"plot-2bh-agglomerative.png\", \"2 Bedroom Houses\")\r\n\r\n# print(h1)\r\n# print(h1)\r\n# print(c1)\r\n# h1.to_csv(\"h1.csv\")\r\n# c1.to_csv(\"c1.csv\")\r\n\r\n# 1 BEDROOM FLAT\r\nplt.scatter(one_bf[\"Median House Price\"], one_bf[\"Incidents Recorded\"])\r\nplt.xlabel(\"Median Rent Price\")\r\nplt.ylabel(\"Incidents Recorded\")\r\nplt.title(\"Median Rent Price vs Incidents Recorded for 1 Bedroom Flat\")\r\nplt.yticks(np.arange(0, 32000, 2000))\r\nplt.savefig(\"plot1bf.png\")\r\nplt.clf()\r\n\r\nplt.scatter(one_bf[\"Median House Price\"], one_bf[\"Rate per 100,000 population\"])\r\nplt.xlabel(\"Median Rent Price\")\r\nplt.ylabel(\"Rate per 100,000 population\")\r\nplt.title(\"Median Rent Price vs Rate per 100,000 population for 1 Bedroom Flat\")\r\nplt.savefig(\"plot1bf100k.png\")\r\nplt.clf()\r\n\r\n# 1 BEDROOM FLAT 2020\r\nplt.scatter(one_bf_2020[\"Median House Price\"], one_bf_2020[\"Incidents Recorded\"])\r\nplt.xlabel(\"Median Rent Price\")\r\nplt.ylabel(\"Incidents Recorded\")\r\nplt.title(\"Median Rent Price vs Incidents Recorded for 1 Bedroom Flat in 2020\")\r\nplt.yticks(np.arange(0, 32000, 2000))\r\nplt.savefig(\"plot1bf-2020.png\")\r\nplt.clf()\r\n\r\nplt.scatter(one_bf_2020[\"Median House Price\"], one_bf_2020[\"Rate per 100,000 population\"])\r\nplt.xlabel(\"Median Rent Price\")\r\nplt.ylabel(\"Rate per 100,000 population\")\r\nplt.title(\"Median Rent Price vs Rate per 100,000 population for 1 Bedroom Flat in 2020\")\r\nplt.savefig(\"plot1bf100k-2020.png\")\r\nplt.clf()\r\n\r\n# 2 BEDROOM FLAT\r\nplt.scatter(two_bf[\"Median House Price\"], two_bf[\"Incidents Recorded\"])\r\nplt.xlabel(\"Median Rent Price\")\r\nplt.ylabel(\"Incidents Recorded\")\r\nplt.title(\"Median Rent Price vs Incidents Recorded for 2 Bedroom Flat\")\r\nplt.yticks(np.arange(0, 32000, 2000))\r\nplt.savefig(\"plot2bf.png\")\r\nplt.clf()\r\n\r\nplt.scatter(two_bf[\"Median House Price\"], two_bf[\"Rate per 100,000 population\"])\r\nplt.xlabel(\"Median Rent Price\")\r\nplt.ylabel(\"Rate per 100,000 population\")\r\nplt.title(\"Median Rent Price vs Rate per 100,000 population for 2 Bedroom Flat\")\r\nplt.savefig(\"plot2bf100k.png\")\r\nplt.clf()\r\n\r\n# 2 BEDROOM FLAT 2020\r\nplt.scatter(two_bf_2020[\"Median House Price\"], two_bf_2020[\"Incidents Recorded\"])\r\nplt.xlabel(\"Median Rent Price\")\r\nplt.ylabel(\"Incidents Recorded\")\r\nplt.title(\"Median Rent Price vs Incidents Recorded for 2 Bedroom Flat in 2020\")\r\nplt.yticks(np.arange(0, 32000, 2000))\r\nplt.savefig(\"plot2bf-2020.png\")\r\nplt.clf()\r\n\r\nplt.scatter(two_bf_2020[\"Median House Price\"], two_bf_2020[\"Rate per 100,000 population\"])\r\nplt.xlabel(\"Median Rent Price\")\r\nplt.ylabel(\"Rate per 100,000 population\")\r\nplt.title(\"Median Rent Price vs Rate per 100,000 population for 2 Bedroom Flat in 2020\")\r\nplt.savefig(\"plot2bf100k-2020.png\")\r\nplt.clf()\r\n\r\n# 2 BEDROOM HOUSE\r\nplt.scatter(two_bh[\"Median House Price\"], two_bh[\"Incidents Recorded\"])\r\nplt.xlabel(\"Median Rent Price\")\r\nplt.ylabel(\"Incidents Recorded\")\r\nplt.title(\"Median Rent Price vs Incidents Recorded for 2 Bedroom House\")\r\nplt.yticks(np.arange(0, 32000, 2000))\r\nplt.savefig(\"plot2bh.png\")\r\nplt.clf()\r\n\r\nplt.scatter(two_bh[\"Median House Price\"], two_bh[\"Rate per 100,000 population\"])\r\nplt.xlabel(\"Median Rent Price\")\r\nplt.ylabel(\"Rate per 100,000 population\")\r\nplt.title(\"Median Rent Price vs Rate per 100,000 population for 2 Bedroom House\")\r\nplt.savefig(\"plot2bh100k.png\")\r\nplt.clf()\r\n\r\n# 2 BEDROOM HOUSE 2020\r\nplt.scatter(two_bh_2020[\"Median House Price\"], two_bh_2020[\"Incidents Recorded\"])\r\nplt.xlabel(\"Median Rent Price\")\r\nplt.ylabel(\"Incidents Recorded\")\r\nplt.title(\"Median Rent Price vs Incidents Recorded for 2 Bedroom House in 2020\")\r\nplt.yticks(np.arange(0, 32000, 2000))\r\nplt.savefig(\"plot2bh-2020.png\")\r\nplt.clf()\r\n\r\nplt.scatter(two_bh_2020[\"Median House Price\"], two_bh_2020[\"Rate per 100,000 population\"])\r\nplt.xlabel(\"Median Rent Price\")\r\nplt.ylabel(\"Rate per 100,000 population\")\r\nplt.title(\"Median Rent Price vs Rate per 100,000 population for 2 Bedroom House in 2020\")\r\nplt.savefig(\"plot2bh100k-2020.png\")\r\nplt.clf()\r\n\r\n# 3 BEDROOM FLAT\r\nplt.scatter(three_bf[\"Median House Price\"], three_bf[\"Incidents Recorded\"])\r\nplt.xlabel(\"Median Rent Price\")\r\nplt.ylabel(\"Incidents Recorded\")\r\nplt.title(\"Median Rent Price vs Incidents Recorded for 3 Bedroom Flat\")\r\nplt.yticks(np.arange(0, 32000, 2000))\r\nplt.savefig(\"plot3bf.png\")\r\nplt.clf()\r\n\r\nplt.scatter(three_bf[\"Median House Price\"], three_bf[\"Rate per 100,000 population\"])\r\nplt.xlabel(\"Median Rent Price\")\r\nplt.ylabel(\"Rate per 100,000 population\")\r\nplt.title(\"Median Rent Price vs Rate per 100,000 population for 3 Bedroom Flat\")\r\nplt.savefig(\"plot3bf100k.png\")\r\nplt.clf()\r\n\r\n# 3 BEDROOM FLAT 2020\r\nplt.scatter(three_bf_2020[\"Median House Price\"], three_bf_2020[\"Incidents Recorded\"])\r\nplt.xlabel(\"Median Rent Price\")\r\nplt.ylabel(\"Incidents Recorded\")\r\nplt.title(\"Median Rent Price vs Incidents Recorded for 3 Bedroom Flat in 2020\")\r\nplt.yticks(np.arange(0, 32000, 2000))\r\nplt.savefig(\"plot3bf-2020.png\")\r\nplt.clf()\r\n\r\nplt.scatter(three_bf_2020[\"Median House Price\"], three_bf_2020[\"Rate per 100,000 population\"])\r\nplt.xlabel(\"Median Rent Price\")\r\nplt.ylabel(\"Rate per 100,000 population\")\r\nplt.title(\"Median Rent Price vs Rate per 100,000 population for 3 Bedroom Flat in 2020\")\r\nplt.savefig(\"plot3bf100k-2020.png\")\r\nplt.clf()\r\n\r\n# 3 BEDROOM HOUSE\r\nplt.scatter(three_bh[\"Median House Price\"], three_bh[\"Incidents Recorded\"])\r\nplt.xlabel(\"Median Rent Price\")\r\nplt.ylabel(\"Incidents Recorded\")\r\nplt.title(\"Median Rent Price vs Incidents Recorded for 3 Bedroom House\")\r\nplt.yticks(np.arange(0, 32000, 2000))\r\nplt.savefig(\"plot3bh.png\")\r\nplt.clf()\r\n\r\nplt.scatter(three_bh[\"Median House Price\"], three_bh[\"Rate per 100,000 population\"])\r\nplt.xlabel(\"Median Rent Price\")\r\nplt.ylabel(\"Rate per 100,000 population\")\r\nplt.title(\"Median Rent Price vs Rate per 100,000 population for 3 Bedroom House\")\r\nplt.savefig(\"plot3bh100k.png\")\r\nplt.clf()\r\n\r\n# 3 BEDROOM HOUSE 2020\r\nplt.scatter(three_bh_2020[\"Median House Price\"], three_bh_2020[\"Incidents Recorded\"])\r\nplt.xlabel(\"Median Rent Price\")\r\nplt.ylabel(\"Incidents Recorded\")\r\nplt.title(\"Median Rent Price vs Incidents Recorded for 3 Bedroom House in 2020\")\r\nplt.yticks(np.arange(0, 32000, 2000))\r\nplt.savefig(\"plot3bh-2020.png\")\r\nplt.clf()\r\n\r\nplt.scatter(three_bh_2020[\"Median House Price\"], three_bh_2020[\"Rate per 100,000 population\"])\r\nplt.xlabel(\"Median Rent Price\")\r\nplt.ylabel(\"Rate per 100,000 population\")\r\nplt.title(\"Median Rent Price vs Rate per 100,000 population for 3 Bedroom House in 2020\")\r\nplt.savefig(\"plot3bh100k-2020.png\")\r\nplt.clf()\r\n\r\n# 4 BEDROOM HOUSE\r\nplt.scatter(four_bh[\"Median House Price\"], four_bh[\"Incidents Recorded\"])\r\nplt.xlabel(\"Median Rent Price\")\r\nplt.ylabel(\"Incidents Recorded\")\r\nplt.title(\"Median Rent Price vs Incidents Recorded for 4 Bedroom House\")\r\nplt.yticks(np.arange(0, 32000, 2000))\r\nplt.savefig(\"plot4bh.png\")\r\nplt.clf()\r\n\r\nplt.scatter(four_bh[\"Median House Price\"], four_bh[\"Rate per 100,000 population\"])\r\nplt.xlabel(\"Median Rent Price\")\r\nplt.ylabel(\"Rate per 100,000 population\")\r\nplt.title(\"Median Rent Price vs Rate per 100,000 population for 4 Bedroom House\")\r\nplt.savefig(\"plot4bh100k.png\")\r\nplt.clf()\r\n\r\n# 4 BEDROOM HOUSE 2020\r\nplt.scatter(four_bh_2020[\"Median House Price\"], four_bh_2020[\"Incidents Recorded\"])\r\nplt.xlabel(\"Median Rent Price\")\r\nplt.ylabel(\"Incidents Recorded\")\r\nplt.title(\"Median Rent Price vs Incidents Recorded for 4 Bedroom House in 2020\")\r\nplt.yticks(np.arange(0, 32000, 2000))\r\nplt.savefig(\"plot4bh-2020.png\")\r\nplt.clf()\r\n\r\nplt.scatter(four_bh_2020[\"Median House Price\"], four_bh_2020[\"Rate per 100,000 population\"])\r\nplt.xlabel(\"Median Rent Price\")\r\nplt.ylabel(\"Rate per 100,000 population\")\r\nplt.title(\"Median Rent Price vs Rate per 100,000 population for 4 Bedroom House in 2020\")\r\nplt.savefig(\"plot4bh100k-2020.png\")\r\nplt.clf()\r\n\r\n# ALL\r\nplt.scatter(all[\"Median House Price\"], all[\"Incidents Recorded\"])\r\nplt.xlabel(\"Median Rent Price\")\r\nplt.ylabel(\"Incidents Recorded\")\r\nplt.title(\"Median Rent Price vs Incidents Recorded for All Housing\")\r\nplt.yticks(np.arange(0, 32000, 2000))\r\nplt.savefig(\"plotall.png\")\r\nplt.clf()\r\n\r\nplt.scatter(all[\"Median House Price\"], all[\"Rate per 100,000 population\"])\r\nplt.xlabel(\"Median Rent Price\")\r\nplt.ylabel(\"Rate per 100,000 population\")\r\nplt.title(\"Median Rent Price vs Rate per 100,000 population for All Housing\")\r\nplt.savefig(\"plotall100k.png\")\r\nplt.clf()\r\n\r\n# ALL 2020\r\nplt.scatter(all_2020[\"Median House Price\"], all_2020[\"Incidents Recorded\"])\r\nplt.xlabel(\"Median Rent Price\")\r\nplt.ylabel(\"Incidents Recorded\")\r\nplt.title(\"Median Rent Price vs Incidents Recorded for All Housing in 2020\")\r\nplt.yticks(np.arange(0, 32000, 2000))\r\nplt.savefig(\"plotall-2020.png\")\r\nplt.clf()\r\n\r\nplt.scatter(all_2020[\"Median House Price\"], all_2020[\"Rate per 100,000 population\"])\r\nplt.xlabel(\"Median Rent Price\")\r\nplt.ylabel(\"Rate per 100,000 population\")\r\nplt.title(\"Median Rent Price vs Rate per 100,000 population for All Housing in 2020\")\r\nplt.savefig(\"plotall100k-2020.png\")\r\nplt.clf()\r\n\r\n# to add: plot more things, add calculations\r\n# # to add: plot more things, add calculations\r\n","sub_path":"scatter.py","file_name":"scatter.py","file_ext":"py","file_size_in_byte":16657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"528760159","text":"#!/usr/bin/env python\n\nimport os\nimport jwt\nimport logging\nimport requests\nfrom cryptography.x509 import load_pem_x509_certificate\nfrom cryptography.hazmat.backends import default_backend\n\n# OAuth token prefix passed in the REST header\nAUTHORIZATION_TYPE = 'Bearer '\n\nlogger = logging.getLogger(__name__)\n\n\ndef azure_public_certificate(user_token):\n token_header = jwt.get_unverified_header(user_token)\n token_kid = token_header.get('kid')\n token_x5t = token_header.get('x5t')\n\n azure_reply = requests.get(url='https://login.microsoftonline.com/common/discovery/keys', timeout=3.0)\n azure_data = azure_reply.json()\n for key in azure_data.get('keys'):\n if key.get('kid') == token_kid and key.get('x5t') == token_x5t:\n cert_body = key.get('x5c')[0]\n return '-----BEGIN CERTIFICATE-----\\n' + cert_body + '\\n-----END CERTIFICATE-----\\n'\n return None\n\n\ndef verify_and_decode(user_token):\n cert_str = azure_public_certificate(user_token)\n cert_obj = load_pem_x509_certificate(cert_str.encode('utf-8'), default_backend())\n public_key = cert_obj.public_key()\n\n tenant_id = os.getenv('AAD_TENANT_ID', '')\n\n # Ignore expiration date for now until we figure out how to either get refresh tokens\n # or make environment update them for us:\n verify_options = {'verify_exp': False}\n try:\n return jwt.decode(user_token, public_key, algorithms=['RS256'], audience=tenant_id, options=verify_options)\n except jwt.exceptions.InvalidTokenError as e:\n logger.error(repr(e))\n return None\n","sub_path":"callisto_nbimport/oauth_utils.py","file_name":"oauth_utils.py","file_ext":"py","file_size_in_byte":1559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"153841274","text":"\"\"\"\nThis script will be a simple test that verifies the gamepage\nfor the linked list game loads correctly.\nThere is nothing to test on the llist gameboard page currently \n\nTo run this test, make the below changes first:\n 1- Safari --> Allow Remote Automation\n 2- Change the remote url variable to local in LListGameboard.js\n 3- npm run build\n\nHow to run:\n 1) Run Django: python manage.py runserver\n 2) Run the test: python -m unittest test_llist_gameboard.py\n\"\"\"\n# BEFORE TESTING: for this iteration (4/29/21), \n# in LListGameboard.js : UNCOMMENT and COMMENT the appropriate lines in \n# renderChambers() (lines 250 & 251)\n\nimport unittest\nfrom selenium import webdriver \nfrom time import sleep\nfrom selenium.webdriver.support.ui import Select\nfrom selenium.webdriver.common.by import By\n\nclass TestStringMethods(unittest.TestCase):\n\n def setUp(self):\n \"\"\"setup the test\"\"\"\n # Web browser instance\n self.driver = webdriver.Safari()\n self.driver.get(\"http://127.0.0.1:8000/\")\n\n def test_homepage(self):\n \"\"\"setup the test\"\"\"\n \n # setup to start linked list game\n # setup player\n player_list = self.driver.find_element_by_name('playerList')\n player_list.click()\n player_list.send_keys(\"Test\")\n # choose difficulty\n difficulty_levels = Select(self.driver.find_element_by_name('level'))\n difficulty_levels.select_by_visible_text('Easy')\n #game mode\n dsGame = Select(self.driver.find_element_by_name('gameDS'))\n dsGame.select_by_visible_text('Linked List Standard')\n selected_dsGame = dsGame.first_selected_option\n\n self.assertEqual(selected_dsGame.text, 'Linked List Standard')\n sleep(5)\n # Start Game\n self.driver.find_element_by_name('start_game').click()\n sleep(1)\n\n\n # check llist gamepage is loaded: check state variables are correct\n #def test_llist_gamepage_loads(self) :\n #self.driver.assertEqual\n\n # checks that the chambers and tunnels render\n def test_chamber_rendering(self) :\n self.driver.find_element_by_id('chamberButton').click()\n self.driver.find_element_by_id('tunnelButton').click()\n self.driver.find_element_by_name('chamberFoodUI')\n\n\n def tearDown(self):\n self.driver.close()\n\nif __name__ == '__main__':\n unittest.main()\n ","sub_path":"src/Tests/test_llist_gameboard.py","file_name":"test_llist_gameboard.py","file_ext":"py","file_size_in_byte":2399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"428258926","text":"# a programme to import a csv file and save the contents to an SQLite database\n\nimport csv\nfrom sys import argv, exit\nfrom cs50 import SQL\n\n\n# check number of command line arguments\nif len(argv) != 2:\n print(\"missing command-line argument\")\n exit(1)\n \n# open the database\ndb = SQL(\"sqlite:///students.db\")\n\n# read contents of csv into variable student_list\nwith open(argv[1]) as csv_file:\n reader = csv.DictReader(csv_file)\n for row in reader:\n full_name = row[\"name\"]\n if len(full_name.split()) == 2:\n first_name = full_name.split(' ', 1)[0]\n last_name = full_name.split(' ', 1)[1]\n middle_name = None\n else:\n first_name = full_name.split(' ', 2)[0]\n middle_name = full_name.split(' ', 2)[1]\n last_name = full_name.split(' ', 2)[2]\n house = row[\"house\"]\n birth = row[\"birth\"]\n db.execute(\"INSERT INTO students (first, middle, last, house, birth) VALUES(?, ?, ?, ?, ?)\",\n first_name, middle_name, last_name, house, birth)\n","sub_path":"pset7/houses/import.py","file_name":"import.py","file_ext":"py","file_size_in_byte":1063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"414383255","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport logging\n# from datetime import datetime\nimport datetime\nimport time\nimport math\nimport when\n\n# from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage\n\nfrom common.models import BackstageHTTPResponse, PageInfo\nfrom common.views import BackstageBaseAPIView\n# from common.utils import gen_page_info\nfrom common.utils import log_exception\nfrom alert.models import Alert\n# from alert.serializers import AlertSerializer\n# from workers.calculation.lib.vo import FormulaEnv, DBPreProcess\n# from workers.calculation.lib import mathlib\n# from workers.calculation.lib.mathlib import *\nfrom ..view_lib import para_name_map, get_history_data\nfrom ..models import MainContract, DayKline\nfrom share.data import Ship\n\n\n\nlogger = logging.getLogger(\"use_info_ms\")\n\n\ndef get_cross_star(varieties, past_day, limit=3, offset=0):\n \"\"\"获取十字星数据\"\"\"\n m_con_objs = MainContract.objects.filter(varieties=varieties, settlement_date__gte=str(past_day)[:10]).order_by('-settlement_date').all()\n vals_len = len(m_con_objs)\n res = []\n data = []\n lmt = limit + 1\n if vals_len >= limit:\n m_con_objs = m_con_objs[offset:lmt]\n else:\n m_con_objs = m_con_objs[offset:]\n for obj in m_con_objs:\n daykline_obj_lst = DayKline.objects.filter(contract=obj.main_contract,\n date_time=obj.settlement_date).order_by('-date_time').all()\n # daykline_obj = DayKline.objects.filter(contract=obj.main_contract).order_by('-date_time')[0]\n daykline_obj = daykline_obj_lst and daykline_obj_lst[0] or None\n if not daykline_obj:\n continue\n price_open = daykline_obj.price_open\n price_high = daykline_obj.price_high\n price_low = daykline_obj.price_low\n pric_close = daykline_obj.price_close\n price_date = str(daykline_obj.date_time)[:10]\n dt = datetime.datetime.strptime(str(price_date)[:10] + ' 00:00:00', '%Y-%m-%d %H:%M:%S')\n res.append([int(time.mktime(dt.timetuple())) * 1000, price_open, price_high, price_low, pric_close])\n # res.reverse()\n return res[1:]\n\n\nclass AlertHistoryChartView(BackstageBaseAPIView):\n\n\n @log_exception\n def get(self, request):\n u\"\"\"\n 获取预警提示,主力合约,预警类别信息\n ---\n\n parameters:\n - name: alert_id\n description: 预警的id\n paramType: query\n required: true\n - name: limit\n description: 数据条数\n paramType: query\n required: false\n\n \"\"\"\n query_dict = request.query_params.dict().copy()\n alert_id = query_dict.get('alert_id', None)\n limit = int(query_dict.get('limit', 3))\n logger.info('查看预警历史数据, 预警id: %s, 查看数量: %s'%(alert_id, limit))\n leta = math.floor(limit / 30)\n if leta <1:\n leta = 1\n # now = datetime.datetime.strptime(str(datetime.datetime.now())[10] + ' 00:00:00', '%Y-%m-%d %H:%M:%S')\n past_day = datetime.datetime.strptime(str(when.past(months=leta))[:10] + ' 00:00:00', '%Y-%m-%d %H:%M:%S')\n today = datetime.datetime.today()\n if not alert_id:\n return BackstageHTTPResponse(\n code=BackstageHTTPResponse.API_HTTP_CODE_INVILID_PARAMS,\n message=u'预警id不存在').to_response()\n alert_obj = Alert.objects.get(pk=alert_id)\n variety = alert_obj.variety\n price = alert_obj.price\n # source = alert_obj.source\n # exchange = alert_obj.exchange\n contract = alert_obj.contract\n\n _y = []\n\n data, date_time = get_history_data(variety, 'CLOSE', limit=limit,\n contract=contract, start=past_day, end=today)\n y = list(zip(date_time, data))\n # for i in range(len(data)):\n # if datetime.datetime.fromtimestamp(date_time[i]/1000) < past_day:\n # break\n # y.append([date_time[i], data[i]])\n new_vals = Ship(variety, price, start=None, end=None, limit=None, offset=None, desc=True)\n para_unit = new_vals.unit or ''\n y.reverse()\n res = {\n 'y': y,\n 'y_max': max(data),\n 'y_min': min(data),\n 'y_name': '主力合约',\n 'y_unit': '元',\n '_y_name': para_name_map[price],\n '_y_unit': para_unit,\n 'para_type': price,\n 'date_end': str(datetime.datetime.now())[:10],\n 'date_start': str(past_day)[:10],\n }\n\n if price == 'CROSS_STAR':\n para_vals = get_cross_star(variety, past_day, limit)\n res.update({\n '_y': para_vals,\n '_y_max': None,\n '_y_min': None,\n })\n else:\n para_data, para_date_time = get_history_data(variety, price, limit=limit, start=past_day, end=today)\n # for i in range(len(para_data)-1):\n # # print(datetime.datetime.fromtimestamp(para_date_time[i] / 1000))\n # if datetime.datetime.fromtimestamp(para_date_time[i] / 1000) < past_day:\n # break\n # _y.append([para_date_time[i], para_data[i]])\n _y = list(zip(para_date_time, para_data))\n\n _y.reverse()\n res.update({\n '_y': _y,\n '_y_max': max(para_data),\n '_y_min': min(para_data),\n })\n\n\n logger.info('正常返回预警详细数据')\n return BackstageHTTPResponse(\n data=res,\n message=u'正常返回预警详细数据').to_response()\n\n\n\n","sub_path":"src/api/alert/views/chart.py","file_name":"chart.py","file_ext":"py","file_size_in_byte":5801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"627161786","text":"from contextlib import contextmanager\nimport sqlite3\n\nname = \"\"\n\n\n@contextmanager\ndef create_db(name):\n try:\n conn = sqlite3.connect(f'{name}.db')\n cursor = conn.cursor()\n yield cursor\n finally:\n conn.close()\n\n\ndef prompt_for_name():\n name = input(\"What would you like to name your test db file?: \")\n return name\n\n\ndef get_table_name():\n table_name = input(\"What would you liek to name your table?: \")\n table_name.replace(' ', '_')\n return table_name\n\n\nif __name__ == \"__main__\":\n name = prompt_for_name()\n table_name = get_table_name()\n with create_db(name) as cursor:\n cursor.execute(f\"\"\"CREATE TABLE {table_name}\n (col1 TEXT, col2 TEXT, col3 TEXT, col4 INT)\"\"\")\n print(f'{name}.db has been created')\n print(f'The table {table_name} has also been created')\n","sub_path":"days/79-81-sqlite3/code/generateddb.py","file_name":"generateddb.py","file_ext":"py","file_size_in_byte":833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"210273668","text":"import itertools\nimport numpy as np\nimport sys\n\nif \"./gym-botenv/\" not in sys.path:\n sys.path.append(\"./gym-botenv/\")\n\nfrom collections import defaultdict\nfrom gym_botenv.envs.botenv_env import BotenvEnv\nfrom utils import plotting\n\nenv = BotenvEnv(1000)\n\ndef make_epsilon_greedy_policy(Q, epsilon, nA):\n\n def policy_fn(observation):\n A = np.ones(nA, dtype=float) * epsilon / nA\n best_action = np.argmax(Q[observation])\n A[best_action] += (1.0 - epsilon)\n return A\n return policy_fn\n\n\ndef nstep_sarsa(env, num_episodes, discount_factor=1.0, alpha=0.5, epsilon=0.1, n=5):\n\n Q = defaultdict(lambda: np.zeros(env.nA))\n\n\n\n stats = plotting.EpisodeStats(\n episode_lengths=np.zeros(num_episodes),\n episode_rewards=np.zeros(num_episodes)\n )\n\n botstats = plotting.BotStats(\n blocked=np.zeros(num_episodes),\n not_blocked=np.zeros(num_episodes)\n )\n\n policy = make_epsilon_greedy_policy(Q, epsilon, env.nA)\n list_returns = [0]\n\n for i_episode in range(num_episodes):\n\n print(\"\\rEpisode {}/{}. Sum returns {}\".format(i_episode + 1, num_episodes, list_returns[-1]), end=\"\")\n sys.stdout.flush()\n\n state = env.reset()\n\n rewards = [0]\n states = [state]\n\n action_probs = policy(state)\n action = np.random.choice(np.arange(len(action_probs)), p=action_probs)\n\n actions = [action]\n n_steps = 10000000\n for t in itertools.count():\n\n if t < n_steps:\n next_state, reward, done, _ = env.step(action)\n\n states.append(next_state)\n rewards.append(reward)\n stats.episode_rewards[i_episode] += reward\n if reward <= -1:\n botstats.blocked[i_episode] += 1\n elif reward >= 5:\n botstats.not_blocked[i_episode] += 1\n\n if done:\n n_steps = t+1\n else:\n next_action_probs = policy(state)\n next_action = np.random.choice(np.arange(len(next_action_probs)), p=next_action_probs)\n actions.append(next_action)\n pi = t - n + 1\n\n if pi >= 0:\n returns = 0.\n\n for x in range(pi+1, min(pi+n, n_steps) + 1):\n returns += pow(discount_factor, x-pi-1) * rewards[x]\n\n if pi + n < n_steps:\n returns += (discount_factor**n) * Q[states[pi+n]][actions[pi+n]]\n\n Q[states[pi]][actions[pi]] += alpha * (returns - Q[states[pi]][actions[pi]])\n\n\n list_returns.append(returns)\n\n\n if pi == n_steps - 1:\n break\n\n state = next_state\n action = next_action\n\n return Q, stats, botstats\n\nif __name__ == '__main__':\n Q, stats, botstats = nstep_sarsa(env, 100)\n plotting.plot_episode_stats(stats, title=\"N-Step sarsa\")\n plotting.plot_bot_stats(botstats)","sub_path":"nstep_sarsa.py","file_name":"nstep_sarsa.py","file_ext":"py","file_size_in_byte":2978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"27980664","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\n__author__ = \"Maximus\"\n\nfrom xml.etree.ElementTree import ElementTree\nfrom datetime import datetime\nfrom zapretinfo import ZapretInfo\nimport time\nimport zipfile\nfrom base64 import b64decode\nimport argparse\nimport os.path\nimport logging\nimport hashlib\nfrom peewee import *\nimport smtplib\nfrom email.mime.text import MIMEText\nimport pymysql\nimport subprocess\nfrom config import Config\n\ndatabase_proxy = Proxy()\n\n\nclass Dump(Model):\n param = CharField(primary_key=True, max_length=255, null=False)\n value = TextField(null=False)\n\n class Meta(object):\n database = database_proxy\n\n\nclass Item(Model):\n content_id = IntegerField(null=False, index=True)\n includeTime = DateTimeField(null=False)\n urgencyType = IntegerField(null=False, default=0)\n entryType = IntegerField(null=False)\n blockType = TextField(null=False, default='default')\n hashRecord = TextField(null=False)\n decision_date = DateField(null=False)\n decision_num = TextField(null=False)\n decision_org = TextField(null=False)\n date_added = DateTimeField(null=False)\n\n class Meta(object):\n database = database_proxy\n\n\nclass IP(Model):\n item = IntegerField(null=False, index=True)\n ip = TextField(null=False)\n mask = IntegerField(null=False, default=32)\n date_added = DateTimeField(null=False)\n\n class Meta(object):\n database = database_proxy\n\n\nclass Domain(Model):\n item = IntegerField(null=False, index=True)\n domain = TextField(null=False)\n date_added = DateTimeField(null=False)\n\n class Meta(object):\n database = database_proxy\n\n\nclass URL(Model):\n item = IntegerField(null=False, index=True)\n url = TextField(null=False)\n date_added = DateTimeField(null=False)\n\n class Meta(object):\n database = database_proxy\n\n\nclass History(Model):\n requestCode = TextField(null=False)\n date = DateTimeField(null=False)\n\n class Meta(object):\n database = database_proxy\n\n\ndef date_time_xml_to_db(date_time_xml):\n date_time_db = date_time_xml.replace('T', ' ')\n return date_time_db\n\n\ndef init_dump_db(logger, cfg):\n if cfg.MySQL():\n login = cfg.MySQLUser()\n password = cfg.MySQLPassword()\n host = cfg.MySQLHost()\n port = cfg.MySQLPort()\n db = pymysql.connect(host=host, port=port, user=login, passwd=password)\n cursor = db.cursor()\n check_db = \"SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = 'blacklist'\"\n cursor.execute(check_db)\n if not cursor.fetchone():\n create_db = \"CREATE DATABASE IF NOT EXISTS `blacklist` CHARACTER SET utf8 COLLATE utf8_unicode_ci\"\n cursor.execute(create_db)\n blacklist_db = MySQLDatabase('blacklist', host=host, port=port, user=login, passwd=password)\n logger.info('Check database: MySQL Ok')\n else:\n blacklist_db = SqliteDatabase('blacklist.db', threadlocals=True)\n logger.info('Check database: SQLite Ok')\n\n database_proxy.initialize(blacklist_db)\n database_proxy.create_tables([Dump, Item, IP, Domain, URL, History], safe=True)\n\n try:\n Dump.create(param='lastDumpDate', value='1325376000')\n except IntegrityError:\n pass\n # logger.info('Parameter lastDumpDate already exists.')\n try:\n Dump.create(param='lastDumpDateUrgently', value='1325376000')\n except IntegrityError:\n pass\n # logger.info('Parameter lastDumpDateUrgently already exists.')\n try:\n Dump.create(param='lastAction', value='getLastDumpDate')\n except IntegrityError:\n pass\n # logger.info('Parameter lastAction already exists.')\n try:\n Dump.create(param='lastResult', value='default')\n except IntegrityError:\n pass\n # logger.info('Parameter lastResult already exists.')\n try:\n Dump.create(param='lastCode', value='default')\n except IntegrityError:\n pass\n # logger.info('Parameter lastCode already exists.')\n try:\n Dump.create(param='dumpFormatVersion', value='2.2')\n except IntegrityError:\n pass\n # logger.info('Parameter dumpFormatVersion already exists.')\n try:\n Dump.create(param='webServiceVersion', value='3')\n except IntegrityError:\n pass\n # logger.info('Parameter webServiceVersion already exists.')\n try:\n Dump.create(param='docVersion', value='4')\n except IntegrityError:\n pass\n # logger.info('Parameter docVersion already exists.')\n return True\n\n\ndef check_new_dump(logger, session):\n logger.info('Check if dump.xml has updates since last sync.')\n last_dump = session.getLastDumpDateEx()\n last_date_dump = max(last_dump.lastDumpDate // 1000, last_dump.lastDumpDateUrgently // 1000)\n current_date_dump = max(int(Dump.get(Dump.param == 'lastDumpDate').value),\n int(Dump.get(Dump.param == 'lastDumpDateUrgently').value))\n logger.info('Current versions: webservice: %s, dump: %s, doc: %s',\n Dump.get(Dump.param == 'webServiceVersion').value,\n Dump.get(Dump.param == 'dumpFormatVersion').value,\n Dump.get(Dump.param == 'docVersion').value)\n if last_dump.webServiceVersion != Dump.get(Dump.param == 'webServiceVersion').value:\n logger.warning('New webservice: %s', last_dump.webServiceVersion)\n Dump.update(value=last_dump.webServiceVersion).where(Dump.param == 'webServiceVersion').execute()\n if last_dump.dumpFormatVersion != Dump.get(Dump.param == 'dumpFormatVersion').value:\n logger.warning('New dumpFormatVersion: %s', last_dump.dumpFormatVersion)\n Dump.update(value=last_dump.dumpFormatVersion).where(Dump.param == 'dumpFormatVersion').execute()\n if last_dump.docVersion != Dump.get(Dump.param == 'docVersion').value:\n logger.warning('New docVersion: %s', last_dump.docVersion)\n Dump.update(value=last_dump.docVersion).where(Dump.param == 'docVersion').execute()\n logger.info('Current date: lastDumpDate: %s, lastDumpDateUrgently: %s',\n datetime.fromtimestamp(int(Dump.get(Dump.param == 'lastDumpDate').value))\n .strftime('%Y-%m-%d %H:%M:%S'),\n datetime.fromtimestamp(int(Dump.get(Dump.param == 'lastDumpDateUrgently').value))\n .strftime('%Y-%m-%d %H:%M:%S'))\n logger.info('Last date: lastDumpDate: %s, lastDumpDateUrgently: %s',\n datetime.fromtimestamp(int(last_dump.lastDumpDate // 1000)).strftime('%Y-%m-%d %H:%M:%S'),\n datetime.fromtimestamp(int(last_dump.lastDumpDateUrgently // 1000)).strftime('%Y-%m-%d %H:%M:%S'))\n if last_date_dump != current_date_dump:\n logger.info('New dump is available.')\n # Dump.update(value=last_dump.lastDumpDate // 1000).where(Dump.param == 'lastDumpDate').execute()\n # Dump.update(value=last_dump.lastDumpDateUrgently // 1000) \\\n # .where(Dump.param == 'lastDumpDateUrgently').execute()\n Dump.update(value='getLastDumpDate').where(Dump.param == 'lastAction').execute()\n Dump.update(value='NewDump').where(Dump.param == 'lastResult').execute()\n return True\n else:\n logger.info('Dump date without changes.')\n Dump.update(value='getLastDumpDate').where(Dump.param == 'lastAction').execute()\n Dump.update(value='lastDump').where(Dump.param == 'lastResult').execute()\n return False\n\n\ndef send_request(logger, session, xml_file, p7s_file, version='2.1'):\n logger.info('Sending request.')\n request = session.sendRequest(xml_file, p7s_file, version)\n logger.info('Checking request status.')\n if request['result']:\n code = request['code']\n logger.info('Got code %s', code)\n Dump.update(value=code).where(Dump.param == 'lastCode').execute()\n Dump.update(value='sendRequest').where(Dump.param == 'lastAction').execute()\n Dump.update(value='Code').where(Dump.param == 'lastResult').execute()\n logger.info('Save code in History')\n History.create(requestCode=code, date=datetime.now().strftime('%Y-%m-%d %H:%M:%S'))\n return code\n else:\n Dump.update(value='sendRequest').where(Dump.param == 'lastAction').execute()\n Dump.update(value='Error').where(Dump.param == 'lastResult').execute()\n logger.error(request['resultComment'])\n return False\n\n\ndef get_request(logger, session, code, cfg):\n logger.info('Waiting for a 90 sec.')\n time.sleep(90)\n logger.info('Trying to get result...')\n request = session.getResult(code)\n Dump.update(value='getRequest').where(Dump.param == 'lastAction').execute()\n max_count = cfg.GetResultMaxCount()\n for count in range(1, max_count + 1):\n if request['result']:\n logger.info('Got a dump ver. %s for the %s (INN %s)',\n request['dumpFormatVersion'],\n request['operatorName'],\n request['inn'])\n with open(os.path.dirname(os.path.abspath(__file__)) + '/result.zip', \"wb\") as f:\n f.write(b64decode(request['registerZipArchive']))\n logger.info('Downloaded dump %d bytes, MD5 hashsum: %s',\n os.path.getsize(os.path.dirname(os.path.abspath(__file__)) + '/result.zip'),\n hashlib.md5(open(os.path.dirname(os.path.abspath(__file__)) + '/result.zip', 'rb')\n .read()).hexdigest())\n try:\n logger.info('Unpacking.')\n zip_file = zipfile.ZipFile(os.path.dirname(os.path.abspath(__file__)) + '/result.zip', 'r')\n zip_file.extract('dump.xml', os.path.dirname(os.path.abspath(__file__)) + '/')\n if cfg.DumpFileSave():\n zip_file.extractall(os.path.dirname(os.path.abspath(__file__)) +\n '/dumps/%s' % datetime.now().strftime(\"%Y-%m-%d %H-%M-%S\"))\n zip_file.close()\n except zipfile.BadZipfile:\n logger.error('Wrong file format.')\n Dump.update(value='Error').where(Dump.param == 'lastResult').execute()\n return False\n Dump.update(value='Ok').where(Dump.param == 'lastResult').execute()\n return True\n else:\n if not request['resultCode']:\n logger.info('Not ready yet. Waiting for a minute. Attempt number %s', count)\n time.sleep(60)\n else:\n logger.error('Got an error, code %d: %s',\n request['resultCode'],\n request['resultComment'])\n Dump.update(value='Error').where(Dump.param == 'lastResult').execute()\n return False\n logger.info('Cant get result.')\n return False\n\n\ndef parse_dump(logger):\n if os.path.exists(os.path.dirname(os.path.abspath(__file__)) + '/dump.xml'):\n logger.info('dump.xml already exists.')\n tree_xml = ElementTree().parse(os.path.dirname(os.path.abspath(__file__)) + '/dump.xml')\n\n dt = datetime.strptime(tree_xml.attrib['updateTime'][:19], '%Y-%m-%dT%H:%M:%S')\n update_time = int(time.mktime(dt.timetuple()))\n Dump.update(value=update_time).where(Dump.param == 'lastDumpDate').execute()\n logger.info('Got updateTime: %s.', update_time)\n\n dt = datetime.strptime(tree_xml.attrib['updateTimeUrgently'][:19], '%Y-%m-%dT%H:%M:%S')\n update_time_urgently = int(time.mktime(dt.timetuple()))\n Dump.update(value=update_time_urgently).where(Dump.param == 'lastDumpDateUrgently').execute()\n logger.info('Got updateTimeUrgently: %s.', update_time_urgently)\n\n list_xml = tree_xml.findall(\".//*[@id]\")\n id_set_dump = set()\n id_set_db = set()\n for content_xml in list_xml:\n # print(content_xml.tag, content_xml.attrib, content_xml.text)\n id_set_dump.add(int(content_xml.attrib['id']))\n\n select_content_id_db = Item.select(Item.content_id)\n for content_db in select_content_id_db:\n id_set_db.add(content_db.content_id)\n\n common_id_set = id_set_dump.intersection(id_set_db)\n delete_id_set = id_set_db.difference(common_id_set)\n add_id_set = id_set_dump.difference(common_id_set)\n # print(delete_id_set)\n # print(add_id_set)\n\n url_inform_del_set = set()\n ip_inform_del_set = set()\n sub_ip_inform_del_set = set()\n domain_inform_del_set = set()\n id_inform_del_set = set()\n\n url_inform_add_set = set()\n ip_inform_add_set = set()\n sub_ip_inform_add_set = set()\n domain_inform_add_set = set()\n id_inform_add_set = set()\n\n if len(delete_id_set) > 0:\n for del_item in delete_id_set:\n logger.info('Full delete Item, IP, Domain, URL id: %s.', del_item)\n\n id_inform_del_set.add(del_item)\n url_del_sql = URL.select().where(URL.item == del_item)\n for url_del_txt in url_del_sql:\n url_inform_del_set.add(url_del_txt.url)\n ip_del_sql = IP.select().where(IP.item == del_item)\n for ip_del_txt in ip_del_sql:\n ip_inform_del_set.add(ip_del_txt.ip)\n for sub_ip_del_txt in ip_del_sql:\n if sub_ip_del_txt.mask < 32:\n sub_ip_inform_del_set.add(sub_ip_del_txt.ip + '/' + str(sub_ip_del_txt.mask))\n domain_del_sql = Domain.select().where(Domain.item == del_item)\n for domain_del_txt in domain_del_sql:\n domain_inform_del_set.add(domain_del_txt.domain)\n\n Domain.delete().where(Domain.item == del_item).execute()\n URL.delete().where(URL.item == del_item).execute()\n IP.delete().where(IP.item == del_item).execute()\n Item.delete().where(Item.content_id == del_item).execute()\n\n if len(add_id_set) > 0:\n include_time = str()\n urgency_type = int()\n entry_type = int()\n block_type = str()\n hash_value = str()\n for new_item in add_id_set:\n logger.info('Create Item, IP, Domain, URL id: %s.', new_item)\n id_inform_add_set.add(new_item)\n new_item_xml = tree_xml.find(\".//*[@id='\" + str(new_item) + \"']\")\n for data_xml in new_item_xml.iter():\n if data_xml.tag == 'content':\n content_id = int(data_xml.attrib['id'])\n try:\n urgency_type = int(data_xml.attrib['urgencyType'])\n except KeyError:\n urgency_type = 0\n include_time = date_time_xml_to_db(data_xml.attrib['includeTime'])\n try:\n block_type = data_xml.attrib['blockType']\n except KeyError:\n block_type = 'default'\n entry_type = int(data_xml.attrib['entryType'])\n hash_value = data_xml.attrib['hash']\n if data_xml.tag == 'decision':\n decision_date = data_xml.attrib['date']\n decision_number = data_xml.attrib['number']\n decision_org = data_xml.attrib['org']\n Item.create(content_id=content_id, includeTime=include_time, urgencyType=urgency_type,\n entryType=entry_type, blockType=block_type, hashRecord=hash_value,\n decision_date=decision_date, decision_num=decision_number,\n decision_org=decision_org, date_added=datetime.now().strftime(\"%Y-%m-%d %H-%M-%S\"))\n if data_xml.tag == 'url':\n url = data_xml.text\n url_inform_add_set.add(url)\n URL.create(item=content_id, url=url, date_added=datetime.now().strftime(\"%Y-%m-%d %H-%M-%S\"))\n if data_xml.tag == 'domain':\n domain = data_xml.text\n domain_inform_add_set.add(domain)\n Domain.create(item=content_id, domain=domain,\n date_added=datetime.now().strftime(\"%Y-%m-%d %H-%M-%S\"))\n if data_xml.tag == 'ip':\n ip = data_xml.text\n ip_inform_add_set.add(ip)\n IP.create(item=content_id, ip=ip, date_added=datetime.now().strftime(\"%Y-%m-%d %H-%M-%S\"))\n if data_xml.tag == 'ipSubnet':\n net = data_xml.text.split('/')\n sub_ip_inform_add_set.add(data_xml.text)\n ip = net[0]\n mask = net[1]\n IP.create(item=content_id, ip=ip, mask=mask,\n date_added=datetime.now().strftime(\"%Y-%m-%d %H-%M-%S\"))\n\n url_db_set = set()\n url_xml_set = set()\n ip_db_set = set()\n ip_xml_set = set()\n sub_ip_xml_set = set()\n sub_ip_db_set = set()\n domain_db_set = set()\n domain_xml_set = set()\n data_update = False\n for item_xml in list_xml:\n for data_xml in item_xml.iter():\n # print(data_xml.tag, data_xml.attrib, data_xml.text)\n if data_xml.tag == 'content':\n content_id = int(data_xml.attrib['id'])\n hash_value = data_xml.attrib['hash']\n item_db = Item.get(Item.content_id == content_id)\n\n if hash_value != item_db.hashRecord:\n logger.info('Hashes not equal, update data')\n try:\n urgency_type = int(data_xml.attrib['urgencyType'])\n except KeyError:\n urgency_type = 0\n include_time = date_time_xml_to_db(data_xml.attrib['includeTime'])\n try:\n block_type = data_xml.attrib['blockType']\n except KeyError:\n block_type = 'default'\n entry_type = int(data_xml.attrib['entryType'])\n\n Item.update(hashRecord=hash_value).where(Item.content_id == content_id).execute()\n data_update = True\n else:\n data_update = False\n break\n\n if data_xml.tag == 'decision':\n decision_date = data_xml.attrib['date']\n decision_number = data_xml.attrib['number']\n decision_org = data_xml.attrib['org']\n # print(item_db)\n if str(item_db.includeTime) != include_time:\n logger.info('content_id: %s.', content_id)\n logger.info('XML includeTime: %s.', include_time)\n logger.info('DB includeTime: %s.', item_db.includeTime)\n Item.update(includeTime=include_time).where(Item.content_id == content_id).execute()\n if item_db.urgencyType != urgency_type:\n logger.info('content_id: %s.', content_id)\n logger.info('XML urgencyType: %s.', urgency_type)\n logger.info('DB urgencyType: %s.', item_db.urgencyType)\n Item.update(urgencyType=urgency_type).where(Item.content_id == content_id).execute()\n if item_db.blockType != block_type:\n logger.info('content_id: %s.', content_id)\n logger.info('XML blockType: %s.', block_type)\n logger.info('DB blockType: %s.', item_db.blockType)\n Item.update(blockType=block_type).where(Item.content_id == content_id).execute()\n if item_db.entryType != entry_type:\n logger.info('content_id: %s.', content_id)\n logger.info('XML entryType: %s.', entry_type)\n logger.info('DB entryType: %s.', item_db.entryType)\n Item.update(entryType=entry_type).where(Item.content_id == content_id).execute()\n if str(item_db.decision_date) != decision_date:\n logger.info('content_id: %s.', content_id)\n logger.info('XML date: %s.', decision_date)\n logger.info('DB date: %s.', str(item_db.decision_date))\n Item.update(decision_date=decision_date).where(Item.content_id == content_id).execute()\n if item_db.decision_num != decision_number:\n logger.info('content_id: %s.', content_id)\n logger.info('XML number: %s.', decision_number)\n logger.info('DB number: %s.', item_db.decision_num)\n Item.update(decision_numbe=decision_number).where(Item.content_id == content_id).execute()\n if item_db.decision_org != decision_org:\n logger.info('content_id: %s.', content_id)\n logger.info('XML org: %s.', decision_org)\n logger.info('DB org: %s.', item_db.decision_org)\n Item.update(decision_org=decision_org).where(Item.content_id == content_id).execute()\n\n if data_xml.tag == 'url':\n url_xml_set.add(data_xml.text)\n\n if data_xml.tag == 'domain':\n domain_xml_set.add(data_xml.text)\n\n if data_xml.tag == 'ip':\n ip_xml_set.add(data_xml.text)\n\n if data_xml.tag == 'ipSubnet':\n sub_ip_xml_set.add(data_xml.text)\n\n if data_update:\n url_db = URL.select().where(URL.item == content_id)\n\n for url_item in url_db:\n url_db_set.add(url_item.url)\n if url_db_set != url_xml_set:\n common_url_set = url_xml_set.intersection(url_db_set)\n delete_url_set = url_db_set.difference(common_url_set)\n add_url_set = url_xml_set.difference(common_url_set)\n if len(delete_url_set) > 0:\n logger.info('Delete id %s URL: %s', content_id, delete_url_set)\n url_inform_del_set.update(delete_url_set)\n for delete_url in delete_url_set:\n URL.delete().where(URL.url == delete_url).execute()\n if len(add_url_set) > 0:\n logger.info('Add id %s URL: %s', content_id, add_url_set)\n url_inform_add_set.update(add_url_set)\n for add_url in add_url_set:\n URL.create(item=content_id, url=add_url,\n date_added=datetime.now().strftime(\"%Y-%m-%d %H-%M-%S\"))\n url_db_set.clear()\n url_xml_set.clear()\n\n domain_db = Domain.select().where(Domain.item == content_id)\n\n for domain_item in domain_db:\n domain_db_set.add(domain_item.domain)\n if domain_db_set != domain_xml_set:\n common_domain_set = domain_xml_set.intersection(domain_db_set)\n delete_domain_set = domain_db_set.difference(common_domain_set)\n add_domain_set = domain_xml_set.difference(common_domain_set)\n if len(delete_domain_set) > 0:\n logger.info('Delete id %s Domain: %s', content_id, delete_domain_set)\n domain_inform_del_set.update(delete_domain_set)\n for delete_domain in delete_domain_set:\n Domain.delete().where(Domain.domain == delete_domain).execute()\n if len(add_domain_set) > 0:\n logger.info('Add id %s Domain: %s', content_id, add_domain_set)\n domain_inform_add_set.update(add_domain_set)\n for add_domain in add_domain_set:\n Domain.create(item=content_id, domain=add_domain,\n date_added=datetime.now().strftime(\"%Y-%m-%d %H-%M-%S\"))\n domain_db_set.clear()\n domain_xml_set.clear()\n\n ip_db = IP.select().where(IP.item == content_id, IP.mask == 32)\n\n for ip_item in ip_db:\n ip_db_set.add(ip_item.ip)\n if ip_db_set != ip_xml_set:\n common_ip_set = ip_xml_set.intersection(ip_db_set)\n delete_ip_set = ip_db_set.difference(common_ip_set)\n add_ip_set = ip_xml_set.difference(common_ip_set)\n if len(delete_ip_set) > 0:\n logger.info('Delete id %s ip: %s', content_id, delete_ip_set)\n ip_inform_del_set.update(delete_ip_set)\n for delete_ip in delete_ip_set:\n IP.delete().where(IP.ip == delete_ip).execute()\n if len(add_ip_set) > 0:\n logger.info('Add id %s ip: %s', content_id, add_ip_set)\n ip_inform_add_set.update(add_ip_set)\n for add_ip in add_ip_set:\n IP.create(item=content_id, ip=add_ip,\n date_added=datetime.now().strftime(\"%Y-%m-%d %H-%M-%S\"))\n ip_db_set.clear()\n ip_xml_set.clear()\n\n sub_ip_db = IP.select().where(IP.item == content_id, IP.mask < 32)\n\n for sub_ip_item in sub_ip_db:\n sub_ip_db_set.add(str(sub_ip_item.ip) + '/' + str(sub_ip_item.mask))\n if sub_ip_db_set != sub_ip_xml_set:\n common_sub_ip_set = sub_ip_xml_set.intersection(sub_ip_db_set)\n delete_sub_ip_set = sub_ip_db_set.difference(common_sub_ip_set)\n add_sub_ip_set = sub_ip_xml_set.difference(common_sub_ip_set)\n if len(delete_sub_ip_set) > 0:\n logger.info('Delete id %s subnet: %s', content_id, delete_sub_ip_set)\n sub_ip_inform_del_set.update(delete_sub_ip_set)\n for delete_sub_ip in delete_sub_ip_set:\n del_subnet = str(delete_sub_ip).split('/')\n del_ip = del_subnet[0]\n del_mask = del_subnet[1]\n IP.delete().where(IP.ip == del_ip, IP.mask == del_mask).execute()\n if len(add_sub_ip_set) > 0:\n logger.info('Add id %s subnet: %s', content_id, add_sub_ip_set)\n sub_ip_inform_add_set.update(add_sub_ip_set)\n for add_sub_ip in add_sub_ip_set:\n add_subnet = str(add_sub_ip).split('/')\n add_ip = add_subnet[0]\n add_mask = add_subnet[1]\n IP.create(item=content_id, ip=add_ip, mask=add_mask,\n date_added=datetime.now().strftime(\"%Y-%m-%d %H-%M-%S\"))\n sub_ip_db_set.clear()\n sub_ip_xml_set.clear()\n\n if len(url_inform_del_set) == 0 and len(ip_inform_del_set) == 0 and len(domain_inform_del_set) == 0 and \\\n len(id_inform_del_set) == 0 and len(sub_ip_inform_del_set) == 0 and len(url_inform_add_set) == 0 and \\\n len(ip_inform_add_set) == 0 and len(domain_inform_add_set) == 0 and len(id_inform_add_set) == 0 and \\\n len(sub_ip_inform_add_set) == 0:\n return 2, str()\n\n msg = gen_report(url_inform_del_set, ip_inform_del_set, domain_inform_del_set, id_inform_del_set,\n sub_ip_inform_del_set, url_inform_add_set, ip_inform_add_set, domain_inform_add_set,\n id_inform_add_set, sub_ip_inform_add_set)\n # print(msg)\n return 1, msg\n else:\n return 0, str()\n\n\ndef gen_report(url_inform_del, ip_inform_del, domain_inform_del, id_inform_del, sub_ip_inform_del, url_inform_add,\n ip_inform_add, domain_inform_add, id_inform_add, sub_ip_inform_add):\n domain_count = Domain.select(fn.Count(fn.Distinct(Domain.domain))).scalar()\n url_count = URL.select(fn.Count(fn.Distinct(URL.url))).scalar()\n ip_count = IP.select(fn.Count(fn.Distinct(IP.ip))).scalar()\n id_count = Item.select(fn.Count(fn.Distinct(Item.content_id))).scalar()\n\n date_time = datetime.fromtimestamp(int(Dump.get(Dump.param == 'lastDumpDate')\n .value)).strftime('%Y-%m-%d %H:%M:%S')\n\n message = 'vigruzki.rkn.gov.ru update: ' + date_time + '\\n'\n\n if len(url_inform_add) > 0:\n message += '\\nURLs added: \\n\\n'\n for url_a in url_inform_add:\n message += url_a + '\\n'\n\n if len(ip_inform_add) > 0:\n message += '\\nIPs added: \\n\\n'\n for ip_a in ip_inform_add:\n message += ip_a + '\\n'\n\n if len(sub_ip_inform_add) > 0:\n message += '\\nSUBNETs added: \\n\\n'\n for sub_ip_a in sub_ip_inform_add:\n message += sub_ip_a + '\\n'\n\n if len(domain_inform_add) > 0:\n message += '\\nDOMAINs added: \\n\\n'\n for domain_a in domain_inform_add:\n message += domain_a + '\\n'\n\n if len(url_inform_del) > 0:\n message += '\\nURLs deleted: \\n\\n'\n for url_d in url_inform_del:\n message += url_d + '\\n'\n\n if len(ip_inform_del) > 0:\n message += '\\nIPs deleted: \\n\\n'\n for ip_d in ip_inform_del:\n message += ip_d + '\\n'\n\n if len(sub_ip_inform_del) > 0:\n message += '\\nSUBNETs deleted: \\n\\n'\n for sub_ip_d in sub_ip_inform_del:\n message += sub_ip_d + '\\n'\n\n if len(domain_inform_del) > 0:\n message += '\\nDOMAINs deleted: \\n\\n'\n for domain_d in domain_inform_del:\n message += domain_d + '\\n'\n\n message += '\\nURLs count: ' + str(url_count) + '\\n'\n message += 'IPs count: ' + str(ip_count) + '\\n'\n message += 'DOMAINs count: ' + str(domain_count) + '\\n'\n message += 'Item count: ' + str(id_count) + '\\n'\n\n if len(id_inform_add) > 0:\n message += 'Items added: ' + str(len(id_inform_add)) + '\\n'\n\n if len(id_inform_del) > 0:\n message += 'Items deleted: ' + str(len(id_inform_del)) + '\\n'\n\n return message\n\n\ndef gen_request(logger, cfg):\n logger.info('Generate request file %s', cfg.XMLPathFName())\n dt = datetime.now().strftime(\"%Y-%m-%dT%H:%M:%S\")\n request_xml = '\\n'\n request_xml += '\\n'\n request_xml += '' + dt + '.000+04:00\\n'\n request_xml += '' + cfg.OperatorName() + '\\n'\n request_xml += '' + str(cfg.inn()) + '\\n'\n request_xml += '' + str(cfg.ogrn()) + '\\n'\n request_xml += '' + cfg.email() + '\\n'\n request_xml += ''\n with open(cfg.XMLPathFName(), 'wb') as f:\n f.write(request_xml.encode(encoding='cp1251'))\n return True\n\n\ndef sign_request(logger, cfg):\n logger.info('Sign file %s', cfg.XMLPathFName())\n subprocess.call(\"sudo openssl smime -engine pkcs11_gost -sign -in \" + cfg.XMLPathFName() + \" -out \" +\n cfg.P7SPathFName() + \" -outform der -noverify -binary -signer \" + cfg.PEMPathFName() +\n \" -inkey \" + cfg.ID() + \" -keyform engine\", shell=True)\n return True\n\n\ndef notify(logger, message, cfg):\n from_address = cfg.FromMail()\n to_address = cfg.ToMail()\n msg = MIMEText(message)\n msg['Subject'] = 'vigruzki.rkn.gov.ru ver. 2.2 update'\n msg['From'] = from_address\n msg['To'] = to_address\n # Send the message via local SMTP server.\n logger.info('Send email from %s to %s', from_address, to_address)\n logger.info('%s', message)\n server = smtplib.SMTP()\n server.connect()\n server.sendmail(from_address, to_address, msg.as_string())\n server.quit()\n return True\n\n\ndef domain_show():\n domain_sql = Domain.select()\n for domain_row in domain_sql:\n print(domain_row.domain)\n return True\n\n\ndef ip_show():\n ip_sql = IP.select()\n for ip_row in ip_sql:\n if ip_row.mask < 32:\n print(ip_row.ip + '/' + str(ip_row.mask))\n else:\n print(ip_row.ip)\n return True\n\n\ndef url_show():\n url = []\n url_sql = URL.select()\n for url_row in url_sql:\n url.append(url_row.url)\n\n item_sql = Item.select()\n for item_row in item_sql:\n if item_row.blockType == 'domain':\n url.append('http://' + Domain.get(Domain.item == item_row.content_id).domain)\n\n for url_one in url:\n print(url_one)\n return True\n\n\ndef history_show():\n history_sql = History.select()\n for history_row in history_sql:\n print(history_row.date, history_row.requestCode)\n return True\n\n\ndef main():\n parser = argparse.ArgumentParser(add_help=True,\n description='Downloads list of restricted websites http://vigruzki.rkn.gov.ru/')\n parser.add_argument(\"--url\", action=\"store_true\", required=False, default=False, help=\"url show\")\n parser.add_argument(\"--ip\", action=\"store_true\", required=False, default=False, help=\"ip show\")\n parser.add_argument(\"--domain\", action=\"store_true\", required=False, default=False, help=\"domain show\")\n parser.add_argument(\"--history\", action=\"store_true\", required=False, default=False, help=\"history show\")\n\n args = parser.parse_args()\n\n ip_print = args.ip\n url_print = args.url\n domain_print = args.domain\n history_print = args.history\n\n cfg = Config()\n\n if cfg.LogRewrite():\n filemode = 'w'\n else:\n filemode = 'a'\n\n logging.basicConfig(filename=cfg.LogPathFName(), filemode=filemode,\n format=u'%(asctime)s %(message)s', level=logging.INFO)\n logger = logging.getLogger(__name__)\n\n logger.info('Starting script.')\n\n init_dump_db(logger, cfg)\n\n if ip_print:\n ip_show()\n elif url_print:\n url_show()\n elif domain_print:\n domain_show()\n elif history_print:\n history_show()\n else:\n session = ZapretInfo()\n if check_new_dump(logger, session):\n if cfg.GenRequest():\n gen_request(logger, cfg)\n sign_request(logger, cfg)\n code = send_request(logger, session, cfg.XMLPathFName(), cfg.P7SPathFName(), '2.2')\n if code:\n if get_request(logger, session, code, cfg):\n result_bool, message = parse_dump(logger)\n if result_bool == 1:\n if cfg.Notify():\n notify(logger, message, cfg)\n elif result_bool == 2:\n logger.info('No updates')\n elif result_bool == 0:\n if cfg.Notify():\n message = 'Houston, we have a problem'\n notify(logger, message, cfg)\n logger.info('parse_dump error')\n logger.info('Script stopped.')\n # todo parse_dump() добавить состояние\n # todo оповещение по почте при изменении dumpFormatVersion, webServiceVersion, docVersion\n # todo HistoryCount функционал\n # todo DumpFileSave = 1 добавить новую опцию путь хранения дампов\n # todo поиск в базе + аргументы командной строки\n # todo обработка исключений и прочих нестандартных ситуации\n # todo документация\n # todo больше объектов: ZapretInfo, Config, Dump\n # todo проверять blockType при выдаче url\n # todo не уведомлять, если в дампе не было измененеий ip, url, domain +\n # todo venv, requerements.txt\n # todo создать пакет pypi\n # todo openssl path добавить параметр\n # todo отправка почты с авторизацией и ssl, tls\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"bl-rkn.py","file_name":"bl-rkn.py","file_ext":"py","file_size_in_byte":36681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"418488684","text":"#!/usr/bin/env python\n\n\n\n\nimport rospy\nimport roslib\nimport socket\nimport sys\n\nfrom geometry_msgs.msg import Twist\nfrom std_msgs.msg import String\n\n\nglobalQueue=[]\nclass Server:\n\tmessage=\"\"\n\t\n\tdef __init__(self):\n\t\trospy.init_node('Server_Main')\n\t\tself.host = '149.125.86.221' \n\t\tself.portNo=8888\n\t\tself.s=None #socket\n\t\tself.queue=None\n\t\tself.queuePtr=0;\n\t\tself.pub = rospy.Publisher('chatter', String, queue_size=10)\n\t\tself.queue=list([])\n\t\tself.createServer()\n\n\tdef createServer(self):\n\t\tself.queue=list([])\n\t\tself.s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\t\tprint(\"Socket Created\")\n\t\ttry:\n\t\t\tself.s.bind((self.host, self.portNo))\n\t\texcept socket.error as err:\n\t\t\tprint('Bind Failed, Error Code: ' + str(err[0]) + ', Message: ' + err[1])\n\t\t\tsys.exit()\n\t\tprint('Socket Bind Success!')\n\n\t\tself.s.listen(10)\n\t\tprint('Socket is now listening')\n\n\t\twhile 1:\n\t\t\tconn, addr = self.s.accept()\n\t\t\tprint('Connect with ' + addr[0] + ':' + str(addr[1]))\n\t\t\tbuf = conn.recv(64)\n\t\t\tself.queue.append(str(buf.decode('utf-8')))\n\t\t\t#print(self.queue)\n\t\t\tprint(\"Queued\"+str(buf.decode('utf-8')))\n\t\t\tglobalQueue.append(str(buf.decode('utf-8')))\n\t\t\tself.pub.publish(str(buf.decode('utf-8')))\n\n\t\t\t#self.moveBase()\n\n\n\n\t\tself.s.close()\n\n\nif __name__ == '__main__':\n\tServer()\n\n\n","sub_path":"Autonomous WaiterBot/working with android integration/waiterbot/scripts/server_main.py","file_name":"server_main.py","file_ext":"py","file_size_in_byte":1267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"411989926","text":"from html.parser import HTMLParser\n\nclass Parser(HTMLParser):\n\tfolderList = []\n\tcurrentId = None\n\tcurrentName = 'Вне папки'\n\tcurrentFileLink = ''\n\tcurrentFileId = None\n\tcurrentFileName = ''\n\tcurrentFolderList = []\n\tinFileList = False\n\tinFile = False\n\tisWaitingForFolderName = False\n\tisWaitingForFileName = False\n\trootDocumentId = None\n\tdef handle_starttag(self, tag, attrs):\n\t\tif tag == 'ul':\n\t\t\tthisId = None\n\t\t\tisFolderList = False\n\t\t\tisFileList = False\n\t\t\tfor attr in attrs:\n\t\t\t\tif attr[0] == 'class' and attr[1] == 'folder':\n\t\t\t\t\tisFolderList = True\n\t\t\t\telif attr[0] == 'class' and attr[1] == 'file-list':\n\t\t\t\t\tisFileList = True\n\t\t\t\telif attr[0] == 'id':\n\t\t\t\t\tthisId = attr[1]\n\t\t\tif isFolderList:\n\t\t\t\tself.currentId = thisId\n\t\t\t\tself.isWaitingForFolderName = True\t\t\t\n\t\t\t\t#print(\"Working with folder, id {}\".format(self.currentId))\n\t\t\telif isFileList:\n\t\t\t\tself.inFileList = True\n\t\telif self.inFileList and tag == 'li':\n\t\t\tself.inFile = True\n\t\t\tself.isWaitingForFileName = True\n\t\telif self.inFile and tag == 'a':\n\t\t\tthisClass = None\n\t\t\tthisHref = ''\n\t\t\tthisID = None\n\t\t\tfor attr in attrs:\n\t\t\t\tif attr[0] == 'class':\n\t\t\t\t\tthisClass = attr[1]\n\t\t\t\telif attr[0] == 'href':\n\t\t\t\t\tthisHref = attr[1]\n\t\t\t\telif attr[0] == 'id':\n\t\t\t\t\tthisId = attr[1]\n\t\t\t#print(thisClass)\n\t\t\tif thisClass is None:\n\t\t\t\t#This is a file link\n\t\t\t\tself.currentFileLink = thisHref\n\t\t\telif thisClass == 'delete-file icon':\n\t\t\t\tself.currentFileId = thisId\n\t\telif self.rootDocumentId is None and tag == 'a':\n\t\t\tthisHref = None\n\t\t\tthisClass = None\n\t\t\tfor attr in attrs:\n\t\t\t\tif attr[0] == 'href':\n\t\t\t\t\tthisHref = attr[1]\n\t\t\t\telif attr[0] == 'class':\n\t\t\t\t\tthisClass = attr[1]\n\t\t\tif not thisHref is None and not thisClass is None and thisClass == 'add-file fancybox.ajax button button-colour-pink':\n\t\t\t\ttry:\n\t\t\t\t\ttail = thisHref[thisHref.index('editForm/')+len('editForm/'):]\n\t\t\t\t\tself.rootDocumentId = tail[:tail.index('/')]\n\t\t\t\texcept ValueError:\n\t\t\t\t\tpass\n\tdef handle_endtag(self, tag):\n\t\tif self.inFileList and tag=='ul':\n\t\t\tself.folderList.append( (self.currentId, self.currentName, self.currentFolderList ))\n\t\t\tself.currentFolderList = []\n\t\t\tself.inFileList = False\n\t\t\tself.currentName = 'Вне папки'\n\t\t\tself.currentId = None\n\t\telif self.inFile and tag=='li':\n\t\t\tself.currentFolderList.append( (self.currentFileId, self.currentFileName, self.currentFileLink) )\n\t\t\tself.currentFileId = None\n\t\t\tself.currentFileLink = ''\n\t\t\tself.inFile = False\n\tdef handle_data(self, data):\n\t\tif not data.isspace():\n\t\t\tif self.isWaitingForFolderName:\n\t\t\t\tself.currentName = data\n\t\t\t\tself.isWaitingForFolderName = False\n\t\t\telif self.isWaitingForFileName:\n\t\t\t\tself.currentFileName = data\n\t\t\t\tself.isWaitingForFileName = False\n\t\t","sub_path":"FolderSearcher.py","file_name":"FolderSearcher.py","file_ext":"py","file_size_in_byte":2690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"621232063","text":"import webapp2\nimport cgi\nfrom helpers import alphabet_position, rotate_character\n\n#html boilerplate for the top of every page\npage_header = \"\"\"\n\n\n\n ROT13\n \n\n\n\"\"\"\n\ntext_header = \"

Enter some text to encrypt:

\"\n\nform = \"\"\"\n
\n