diff --git "a/2928.jsonl" "b/2928.jsonl" new file mode 100644--- /dev/null +++ "b/2928.jsonl" @@ -0,0 +1,725 @@ +{"seq_id":"73391755","text":"from pip import call_subprocess\nfrom pip.vcs.git import Git as PipGit\nfrom pip.log import logger\n\nclass Git(PipGit):\n def unpack(self, location):\n \"\"\"Clone the Git repository at the url to the destination location\"\"\"\n url, rev = self.get_url_rev()\n\n logger.notify('Cloning Git repository %s to %s' % (url, location))\n logger.indent += 2\n try:\n\n if os.path.exists(location):\n os.rmdir(location)\n if not rev:\n rev = 'HEAD'\n call_subprocess(\n [self.cmd, 'clone', '-n', url, location],\n filter_stdout=self._filter, show_stdout=False)\n call_subprocess(\n [self.cmd, 'checkout', '-b', rev],\n filter_stdout=self._filter, show_stdout=False, cwd=location)\n finally:\n logger.indent -= 2\n\n def get_remote_refs(self, *ls_remote_args):\n \"\"\"\n Return an iterator over triples (pipversion, ref, SHA1) for\n each symbolic reference in the repository, where pipversion is\n a version number in pip format, ref is the symbolic name for\n that revision in the repository, and SHA1 is that revision's\n immutable revision number.\n \"\"\"\n url,rev = self.get_url_rev()\n remote_refs = call_subprocess(\n (self.cmd, 'ls-remote')+ ls_remote_args + (url,), show_stdout=False)\n\n return ((ref.rsplit('/',1)[-1], ref, sha) for (sha,ref) in \n (line.strip().split() for line in remote_refs.splitlines() ))\n \n \n","sub_path":"src/ryppl/vcs/git.py","file_name":"git.py","file_ext":"py","file_size_in_byte":1565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"120371005","text":"####################\n# Authour: Aleksa Zatezalo\n# Date: April 18, 2020\n# Title: Matrix Multiplication\n####################\n\n# Chapter 15.2 - CLRS\n\n\ndef matrixChainMultiply(a, s, i, j):\n \"\"\"Uses dynamic programing to multiply a matrixies a, and s, \n in optimal runtime.\n\n Arguments:\n a {array} -- a matrix\n s {array} -- a matrix\n i {int} -- an index\n j {int} -- an index\n \"\"\"\n\n # Return matrix if indicies are equal\n if (i == j):\n return a[i]\n\n # Multiply if indicies differ by one\n if (i == (j - 1)):\n return a[i] * a[j]\n\n result1 = matrixChainMultiply(a, s, i, s[i, j])\n result2 = matrixChainMultiply(a, s, s[i, j] + 1, j)\n return result1 * result2\n\n\ndef memoizedMatrixChainMultiply(p):\n \"\"\"Uses memoization to multiply a matrixies a, and s, \n in optimal runtime.\n\n Arguments:\n a {array} -- a matrix\n s {array} -- a matrix\n i {int} -- an index\n j {int} -- an index\n \"\"\"\n\n n = len(p) - 1\n subT = [None] * n\n m = [subT] * n\n for i in range(n):\n for j in range(i):\n m[i][j] = float('inf')\n return lookupChain(m, p, 1, n)\n\n\ndef lookupChain(m, p, i, j):\n if (m[i][j] < float('inf')):\n return m[i][j]\n if (i == j):\n m[i][j] = 0\n else:\n for x in range(i, j):\n q = lookupChain(m, p, i, x) + lookupChain(m, p,\n x + 1, j) + p[i - 1] * p[x] * p[j]\n if q < m[i][j]:\n m[i][j] = q\n return m[i][j]\n\n\nif __name__ == '__main__':\n a = [0, 1]\n s = [1, 0]\n i = 0\n j = 1\n print(matrixChainMultiply(a, s, i, j))\n","sub_path":"Dynamic Programming/matrixMultiplication.py","file_name":"matrixMultiplication.py","file_ext":"py","file_size_in_byte":1677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"112213388","text":"\nimport logging\nfrom .Defaults import *\n\n\nclass Gre(object):\n\t\n\n\tdef get_gre_tunnel_details(self):\n\n\t\turi = self.api_url + 'api/v1/orgProvisioning/ipGreTunnelInfo'\n\n\t\tres = self._perform_get_request(\n\t\t\turi,\n\t\t\tself._set_header(self.jsessionid)\n\t\t)\n\t\treturn res\n","sub_path":"zscaler_python_sdk/Gre.py","file_name":"Gre.py","file_ext":"py","file_size_in_byte":262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"229444958","text":"\"\"\"Player, Board, and TileBag classes for scrabble game\"\"\"\n\nimport os\nimport sys\nimport logging\nimport xml.etree.ElementTree as ET\nfrom random import randrange\n\nclass Game(object):\n \"\"\"Parent game class, set the rules\"\"\"\n\n def __init__(self, name='Untitled', max_rack_letters=7, letter_ratio_file=os.path.join(os.path.dirname(os.path.realpath(__file__)),'config','letter_ratios_en-us.xml'), board_setup_file=os.path.join(os.path.dirname(os.path.realpath(__file__)),'config','board_config.xml'),board_matrix=[],dims=[],letters=[]):\n \"\"\"Set up the board and tile bag, add the players\"\"\"\n self.name = name\n self.logger = logging.getLogger(type(self).__name__)\n self.logger.debug('Configuring game with name %s'%self.name)\n self.max_rack_letters = max_rack_letters\n self.players = {}\n self.board = Board(board_setup_file=board_setup_file, board_matrix=board_matrix, dims=dims)\n self.tilebag = TileBag(letter_ratio_file,letters)\n\n\n def add_players(self, num_players=2, player_names=[], max_players=4, scores=[], letter_racks=[]):\n if num_players > max_players:\n raise ValueError('Exceeded maximum number of players %d.'%max_players)\n if player_names and len(player_names) != num_players:\n raise ValueError('List of player names must be equal to number of players.')\n for i in range(num_players):\n if not player_names:\n pname='player%d'%(i)\n else:\n pname=player_names[i]\n if not scores:\n score = 0\n else:\n score = scores[pname]\n if not letter_racks:\n letter_rack = []\n else:\n letter_rack = letter_racks[pname]\n self.players[pname] = Player(self.tilebag, self.max_rack_letters, name=pname, letter_rack=letter_rack, score=score)\n\n\nclass Board(object):\n \"\"\"Scrabble board class\"\"\"\n\n def __init__(self, board_matrix=[],board_setup_file='',dims=[]):\n \"\"\"Setup scrabble board\"\"\"\n self.logger = logging.getLogger(type(self).__name__)\n if board_setup_file:\n self.logger.debug('Configuring board from setup file %s'%(board_setup_file))\n self._setup_board(board_setup_file)\n elif dims and board_matrix:\n self.board_matrix = board_matrix\n self.dims = dims\n else:\n self.logger.error('Specify config file or preexisting board setup.')\n\n def _setup_board(self,board_setup_file,default_color='#BBB89E'):\n \"\"\"Configure board\"\"\"\n self.logger.debug('Setting up board')\n tree = ET.parse(board_setup_file)\n root = tree.getroot()\n special_spaces = root.find('special')\n dims = root.find('dimensions')\n nrows,ncols = int(dims.attrib['rows']),int(dims.attrib['cols'])\n self.dims = [nrows,ncols]\n self.board_matrix = []\n self.logger.debug('Setting board dimensions to (%d,%d)'%(self.dims[0],self.dims[1]))\n for j in range(ncols):\n for i in range(nrows):\n self.board_matrix.append({'label':None, 'wmult':1, 'lmult':1, 'letter':None, 'x':j, 'y':i, 'color':default_color, 'points':0})\n for space in special_spaces:\n i_row,i_col = int(space.attrib['row']),int(space.attrib['col'])\n for square in self.board_matrix:\n if square['x'] == i_col and square['y'] == i_row:\n square['label'] = space.attrib['label']\n square['wmult'] = space.attrib['wmult']\n square['lmult'] = space.attrib['lmult']\n square['color'] = space.attrib['color']\n\n def place_tiles(self,tiles,tile_color='#E1BF9A'):\n \"\"\"Put tiles from play on board\"\"\"\n for t in tiles:\n for i in range(len(self.board_matrix)):\n if t['rpos'] == self.board_matrix[i]['y'] and t['cpos'] == self.board_matrix[i]['x']:\n self.board_matrix[i]['letter'] = t['letter']\n self.board_matrix[i]['points'] = t['points']\n self.board_matrix[i]['color'] = tile_color\n break\n\nclass TileBag(object):\n \"\"\"Scrabble TileBag class\"\"\"\n\n def __init__(self,letter_ratio_file='',letters=[]):\n \"\"\"Create the bag of letter tiles with appropriate ratios\"\"\"\n if not letter_ratio_file and not letters:\n raise ValueError('Specify existing letter bag or config file.')\n\n self.logger = logging.getLogger(type(self).__name__)\n self.letters = letters\n if not self.letters:\n self._make_bag(letter_ratio_file)\n\n def _make_bag(self,letter_ratio_file):\n \"\"\"Construct tilebag\"\"\"\n tree = ET.parse(letter_ratio_file)\n root = tree.getroot()\n for child in root:\n self.letters.extend(int(child.attrib['number'])*[{'letter':child.attrib['char'], 'points':int(child.attrib['points'])}])\n\n def draw_letters(self,player):\n \"\"\"Draw multiple letters from bag\"\"\"\n num_letters_needed = player.max_rack_letters - len(player.letter_rack)\n for _ in range(num_letters_needed):\n if len(self.letters) > 0:\n self._draw_letter(player)\n else:\n print('Tile bag is empty. No. of letters = %d'%len(self.letters))\n break\n\n def swap_letter(self,player,letter):\n \"\"\"Swap a letter from the players rack with one in the bag\"\"\"\n letter_rack_letters = [r['letter'] for r in player.letter_rack]\n try:\n i_swap = letter_rack_letters.index(letter.upper())\n self.letters.append(player.letter_rack[i_swap])\n player.letter_rack.pop(i_swap)\n self._draw_letter(player)\n except ValueError:\n print('Cannot swap %s. Not in letter rack.'%letter)\n\n def _draw_letter(self,player):\n \"\"\"Draw a letter from the bag, add it to the rack of a player instance\"\"\"\n i_draw = randrange(0,len(self.letters))\n player.letter_rack.append(self.letters[i_draw])\n self.letters.pop(i_draw)\n\n def display_letter_count(self):\n \"\"\"Display how many letters are left in the bag\"\"\"\n print('Number of letters left in tile bag: %d'%(len(self.letters)))\n\n def _display_bag(self):\n \"\"\"Show the contents of the tile bag. Should not be used in game\"\"\"\n print(self.letters)\n\n\nclass Player(object):\n \"\"\"Class to control player action and movement\"\"\"\n\n def __init__(self,tilebag,max_rack_letters,name='player',letter_rack=[],score=0):\n \"\"\"Create player\"\"\"\n self.logger = logging.getLogger(type(self).__name__)\n self.max_rack_letters=max_rack_letters\n self.name=name\n self.score = score\n self.letter_rack = letter_rack\n tilebag.draw_letters(self)\n\n def show_rack(self):\n \"\"\"Display letter rack\"\"\"\n for lr in self.letter_rack:\n print('%s, %d'%(lr['letter'],lr['points']))\n\n def play_word(self,word='',tile_pos=[]):\n \"\"\"Make a word\"\"\"\n word_letters = list(word.upper())\n rack_copy = list(self.letter_rack)\n word_play = []\n for wl,i in zip(word_letters,range(len(word_letters))):\n found_flag=False\n for lr,j in zip(rack_copy,range(len(rack_copy))):\n if wl == lr['letter']:\n word_play.append({'letter':wl, 'points':lr['points'], 'rpos':tile_pos[i][0], 'cpos':tile_pos[i][1]})\n found_flag=True\n rack_copy.pop(j)\n break\n if not found_flag:\n print('Letter %s not in letter rack. Try another word.'%wl)\n word_play = []\n break\n\n if found_flag:\n self.letter_rack = rack_copy\n\n return word_play\n","sub_path":"micro_scrabble/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":7854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"8673161","text":"import pandas as pd\nimport json\nimport urllib2\n\nxls = pd.ExcelFile('/Users/mcnamarp/Downloads/msg_append_sample_acxiom_fraday_comp.xlsx')\nnames = xls.parse('Gender Data').set_index('msg_id')\nnames['predicted_gender_acxiom'] = None\nnames['accuracy_acxiom'] = None\nmyKey = 'rXCcWNTUjHMyFUJmQp'\n\nfor i in names.dropna(subset = ['acxiom_person_first_name']).index:\n\ttemp_name = names.loc[i,'acxiom_person_first_name']\n\ttemp_results = json.load(urllib2.urlopen(\"https://gender-api.com/get?key=\" + myKey + \"&name=\" + temp_name))\n\tnames.loc[i,'predicted_gender_acxiom'] = temp_results['gender']\n\tnames.loc[i,'accuracy_acxiom'] = temp_results['accuracy']\n\t\nnames.to_csv('/Users/mcnamarp/Downloads/msg_append_sample_acxiom_fraday_comp_name_predictions.csv')","sub_path":"pmcnamara/acxiom_faraday_gender.py","file_name":"acxiom_faraday_gender.py","file_ext":"py","file_size_in_byte":748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"561175992","text":"# Program Name : Palindrome\r\n# Program Description : Takes a string and returns whether or not it is a\r\n# palindrome\r\n# Creation Date : September 05 2019\r\n# Author Name : Constantinos Soutos\r\n\r\nstring = input(\"Please enter a string: \")\r\n\r\nif (string == string[::-1]):\r\n print(string+\" is a palindrome\")\r\nelse:\r\n print(string+\" is not a palindrome\")\r\n","sub_path":"palindrome.py","file_name":"palindrome.py","file_ext":"py","file_size_in_byte":399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"332239806","text":"# Author: Vishakh Hegde\n# Requirements:\n#\t1. Given an image, produce the person key points\n#\t2. Option to save the image with key points.\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport argparse\nimport os\nimport pprint\n\nimport torch\nimport torch.nn.parallel\nimport torch.backends.cudnn as cudnn\nimport torch.optim\nimport torch.utils.data\nimport torch.utils.data.distributed\nimport torchvision.transforms as transforms\n\nimport _init_paths\nfrom config import cfg\nfrom config import update_config\nfrom core.loss import JointsMSELoss\nfrom core.function import validate\nfrom core.inference import get_max_preds\nfrom utils.utils import create_logger\nfrom utils.vis import save_batch_image_with_joints\n\nimport dataset\nimport models\n\nimport torchvision\nimport numpy as np\nimport cv2\n\nfrom dataset.mpiiSingleImage import MPIISingleImage\n\ndef parse_args():\n parser = argparse.ArgumentParser(description='Train keypoints network')\n # general\n parser.add_argument('--cfg',\n help='experiment configure file name',\n required=True,\n type=str)\n\n parser.add_argument('opts',\n help=\"Modify config options using the command-line\",\n default=None,\n nargs=argparse.REMAINDER)\n\n parser.add_argument('--modelDir',\n help='model directory',\n type=str,\n default='')\n parser.add_argument('--logDir',\n help='log directory',\n type=str,\n default='')\n parser.add_argument('--dataDir',\n help='data directory',\n type=str,\n default='')\n parser.add_argument('--prevModelDir',\n help='prev Model directory',\n type=str,\n default='')\n\n args = parser.parse_args()\n return args\n\ndef save_batch_image_with_joints_2(batch_image, batch_joints, file_name, batch_num):\n '''\n Custom code to save individual images instead of saving images as tiles.\n\n batch_image: [batch_size, channel, height, width]\n batch_joints: [batch_size, num_joints, 3],\n batch_joints_vis: [batch_size, num_joints, 1],\n }\n '''\n nmaps = batch_image.size(0)\n for k in range(nmaps):\n image = batch_image[k].mul(255).clamp(0, 255).byte().permute(1, 2, 0).cpu().numpy()\n image = image.copy()\n joints = batch_joints[k]\n for joint in joints:\n cv2.circle(image, (int(joint[0]), int(joint[1])), 2, [255, 0, 0], 2)\n\n save_file_name = '{}_{}_{}.jpg'.format(file_name, batch_num, k)\n cv2.imwrite(save_file_name, cv2.cvtColor(image, cv2.COLOR_RGB2BGR))\n\n\ndef main():\n args = parse_args()\n update_config(cfg, args)\n\n logger, final_output_dir, tb_log_dir = create_logger(\n cfg, args.cfg, 'valid')\n\n logger.info(pprint.pformat(args))\n logger.info(cfg)\n\n # cudnn related setting\n cudnn.benchmark = cfg.CUDNN.BENCHMARK\n torch.backends.cudnn.deterministic = cfg.CUDNN.DETERMINISTIC\n torch.backends.cudnn.enabled = cfg.CUDNN.ENABLED\n\n model = eval('models.'+cfg.MODEL.NAME+'.get_pose_net')(\n cfg, is_train=False\n )\n\n if cfg.TEST.MODEL_FILE:\n logger.info('=> loading model from {}'.format(cfg.TEST.MODEL_FILE))\n model.load_state_dict(torch.load(cfg.TEST.MODEL_FILE), strict=False)\n else:\n model_state_file = os.path.join(\n final_output_dir, 'final_state.pth'\n )\n logger.info('=> loading model from {}'.format(model_state_file))\n model.load_state_dict(torch.load(model_state_file))\n\n model = torch.nn.DataParallel(model, device_ids=cfg.GPUS).cuda()\n\n # define loss function (criterion) and optimizer\n criterion = JointsMSELoss(\n use_target_weight=cfg.LOSS.USE_TARGET_WEIGHT\n ).cuda()\n\n # Data loading code\n normalize = transforms.Normalize(\n mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]\n )\n\n # Loads the validation images and obtains metrics\n\n # valid_dataset = eval('dataset.'+cfg.DATASET.DATASET)(\n # cfg, cfg.DATASET.ROOT, cfg.DATASET.TEST_SET, False,\n # transforms.Compose([\n # transforms.ToTensor(),\n # normalize,\n # ])\n # )\n\n # valid_loader = torch.utils.data.DataLoader(\n # valid_dataset,\n # batch_size=cfg.TEST.BATCH_SIZE_PER_GPU*len(cfg.GPUS),\n # shuffle=False,\n # num_workers=cfg.WORKERS,\n # pin_memory=True\n # )\n\n # with torch.no_grad():\n # for i, (input, target, target_weight, meta) in enumerate(valid_loader):\n # # compute output\n # outputs = model(input)\n # if isinstance(outputs, list):\n # output = outputs[-1]\n # else:\n # output = outputs\n\n # # Inference: Obtain joints from model prediction\n # joints_pred, _ = get_max_preds(output.cpu().numpy())\n\n # prefix = '{}'.format(\n # os.path.join(final_output_dir, 'val'))\n\n # save_batch_image_with_joints_2(input, joints_pred*4, prefix, i)\n \n\n # Obtain joints predictions for a single test image\n image_path = '/home/vishakh/Projects/deep-high-resolution-net.pytorch/test_images/test_img7.jpg' \n with torch.no_grad():\n single_image_object = MPIISingleImage(cfg, image_path, transforms.Compose([\n transforms.ToTensor(),\n normalize,\n ]))\n input = single_image_object[0]\n\n outputs = model(input)\n if isinstance(outputs, list):\n output = outputs[-1]\n else:\n output = outputs\n\n joints_pred, _ = get_max_preds(output.cpu().numpy())\n prefix = '{}'.format(os.path.join(final_output_dir, 'val'))\n save_batch_image_with_joints_2(input, joints_pred*4, prefix, 999999)\n\nif __name__ == '__main__':\n main()","sub_path":"tools/estimate_pose.py","file_name":"estimate_pose.py","file_ext":"py","file_size_in_byte":6078,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"505852553","text":"import cv2\nimport os\nimport sys\nimport argparse\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='''\n This code will convert an input color JPG/PNG image to PPM format and convert depth PNG image to PGM format.\n ''')\n parser.add_argument('color_file', type=str, default='',\n help='input color image')\n parser.add_argument('depth_file', type=str, default='',\n help='input depth image')\n parser.add_argument(\"-d\", '--out_dir', type=str, default='',\n help='output image directory')\n args = parser.parse_args()\n\n color_image = cv2.imread(args.color_file, cv2.IMREAD_UNCHANGED)\n # Use 'try-except' to check if an image is read successfully or not\n try:\n color_image.shape\n print(color_image.shape, color_image.dtype)\n except:\n print('Cannot read color image file: ', args.color_file)\n sys.exit(1)\n\n depth_image = cv2.imread(args.depth_file, cv2.IMREAD_UNCHANGED)\n try:\n depth_image.shape\n print(depth_image.shape, depth_image.dtype)\n except:\n print('Cannot read depth image file: ', args.depth_file)\n sys.exit(1)\n\n # cv2.imshow('image', color_image)\n # cv2.waitKey(0)\n # cv2.destroyAllWindows()\n\n color_out_name = ''\n if args.out_dir:\n base = os.path.basename(args.color_file) # get 'name.jpg'\n name = os.path.splitext(base)[0] # get 'name' (while [1] is '.jpg')\n color_out_name = args.out_dir + '/' + name + '.ppm'\n else:\n color_name = os.path.splitext(args.color_file)[0] # get '.../dir/name'\n color_out_name = color_name + '.ppm'\n print(\"Save color image: \", color_out_name)\n cv2.imwrite(color_out_name, color_image)\n\n depth_out_name = ''\n if args.out_dir:\n base = os.path.basename(args.depth_file)\n name = os.path.splitext(base)[0]\n depth_out_name = args.out_dir + '/' + name + '.pgm'\n else:\n depth_name = os.path.splitext(args.depth_file)[0]\n depth_out_name = depth_name + '.pgm'\n print(\"Save depth image: \", depth_out_name)\n cv2.imwrite(depth_out_name, depth_image)\n","sub_path":"python_test/rgbd_jpg_png_to_ppm_pgm.py","file_name":"rgbd_jpg_png_to_ppm_pgm.py","file_ext":"py","file_size_in_byte":2171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"14150547","text":"# coding:utf8\nfrom django.conf.urls import url\nfrom rest_framework_jwt.views import obtain_jwt_token\nfrom . import views\n\n\nurlpatterns = [\n # /users/usernames/(?P\\w{5,20})/count/\n url(r'^usernames/(?P\\w{5,20})/count/$', views.RegisterUserNameView.as_view()),\n\n # /users/phones/(?P1[345789]\\d{9})/count/\n url(r'^phones/(?P1[345789]\\d{9})/count/$', views.RegisterMoblieView.as_view()),\n\n # 进行登陆认证,返回token\n #/users/auths/\n url(r'^auths/$', obtain_jwt_token, name='auths'),\n\n url(r'^infos/$', views.UserCenterInfoView.as_view()),\n\n url(r'^emails/$', views.UserEmailView.as_view()),\n\n url(r'^emails/verification/$', views.UserEmailActiveView.as_view()),\n\n url(r'^addresses/$', views.AddressView.as_view()),\n\n url(r'^browerhistories/$', views.UserHistoryView.as_view()),\n\n url(r'^$', views.RegisterCreateUserView.as_view()),\n\n\n]","sub_path":"mall/apps/users/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"490049403","text":"import random\nimport time\nprint(\"\")\nprint(\"Welcome to this ATM!!\")\nprint(\"Here, you're provided with 1000$ and a earner which can be upgraded by your balance.\")\nprint(\"There are several modes for this ATM.\")\nprint(\"Press S to see all your balances.\")\nprint(\"Press U to upgrade your earner level.\")\nprint(\"Press H to hack\")\nprint(\"Press W to withdraw your hacked balance\")\nprint(\"Press E to exit\")\nprint(\"\")\n\nstartTime= time.time()\n\nclass ATM (object):\n def __init__(self, balance, hackedMoney, earnerLevel, offlineEarnings):\n self.balance = balance\n self.hackedMoney = hackedMoney\n self.earnerLevel = earnerLevel\n self.offlineEarnings = offlineEarnings\n\n def inputMode(self):\n while(True):\n print(\"\")\n mode = input(\"Enter the mode you want = \")\n if(mode == \"S\" or mode == \"s\"):\n print(\"Your Balance : \" + str(self.balance))\n print(\"Hacked money : \" + str(self.hackedMoney))\n print(\"Earner Level : \" + str(self.earnerLevel) + ', Offline Earnings : + $'+ str(self.offlineEarnings) + '/10 sec')\n elif(mode == \"H\" or mode == \"h\"):\n hacking(self)\n elif(mode == \"W\" or mode == \"w\"):\n withdraw(self)\n elif(mode == \"E\" or mode == \"e\"):\n exit()\n elif(mode == \"U\" or mode == \"u\"):\n upgradeEarner(self)\n else:\n print(\"Wrong Mode!!\")\n\ndef hacking(self):\n print(self.hackedMoney)\n print(\"\")\n print(\"Entered Hacked Mode\")\n randomNumber = random.randint(10000, 99999)\n print(\"Your number : \" + str(randomNumber))\n inputedNumber = int(input(\"Enter the number : \"))\n if(inputedNumber == randomNumber and self.hackedMoney == 0):\n changeHackedMoney(self, 250, 'l')\n elif(inputedNumber == randomNumber and self.hackedMoney != 0):\n changeHackedMoney(self, self.hackedMoney + self.hackedMoney, 'l')\n else:\n print(\"Wrong Number\")\n atm.inputMode()\n\ndef withdraw(self):\n self.balance = self.balance + self.hackedMoney\n changeHackedMoney(self, 0, 'm')\n print(\"Withdrawn Successfully\")\n\ndef changeHackedMoney(self, hackedMoney, m):\n self.hackedMoney = hackedMoney\n if(m != 'm'):\n print('+' + str(self.hackedMoney) + '$')\n\ndef upgradeEarner(self):\n x = 0\n if(self.earnerLevel == 0 and self.balance >= 0):\n addOfflineEarnings(self, 50)\n x = x+100\n self.balance = self.balance-x\n self.earnerLevel = self.earnerLevel + 1\n elif(self.earnerLevel == 1 and self.balance >= 0):\n addOfflineEarnings(self, 100)\n x = x+200\n self.balance = self.balance-x\n self.earnerLevel = self.earnerLevel + 1\n elif(self.earnerLevel == 2 and self.balance >= 0):\n addOfflineEarnings(self, 200)\n x = x+500\n self.balance = self.balance-x\n self.earnerLevel = self.earnerLevel + 1\n elif(self.earnerLevel == 3 and self.balance >= 0):\n addOfflineEarnings(self, 500)\n x = x+1000\n self.balance = self.balance-x\n self.earnerLevel = self.earnerLevel + 1\n elif(self.earnerLevel > 3 and self.balance >= 0):\n addOfflineEarnings(self, self.offlineEarnings + self.offlineEarnings)\n x = x+x\n self.balance = self.balance-x\n self.earnerLevel = self.earnerLevel + 1\n elif(self.earnerLevel > 0 and self.balance == 0):\n print(\"You are not having enough money :(\")\n\ndef addOfflineEarnings(self, increaseBy):\n self.offlineEarnings = self.offlineEarnings + increaseBy\n self.balance = self.balance + self.offlineEarnings\n\natm = ATM(1000, 0, 0, 0)\natm.inputMode()\naddOfflineEarnings()","sub_path":"ATM.py","file_name":"ATM.py","file_ext":"py","file_size_in_byte":3703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"48432134","text":"import sys\n\nimport matplotlib.pyplot as plt\nimport networkx as nx\n# https://networkx.github.io/documentation/stable/reference/drawing.html\n# https://networkx.github.io/documentation/stable/reference/functions.html\n# https://matplotlib.org/examples/color/named_colors.html\n# H = nx.Graph(G) # convert G to undirected graph\n\n\nDG = nx.DiGraph()\n\ncolors=[\"silver\", \"red\", \"forestgreen\", \"oliva\", \"gold\", \"teal\"]\ngraphNodes=[\n\t[\"WA\", {\"size\":11, \"color\":colors[0]}], \n\t[\"NT\", {'color':colors[0]}],\n\t[\"SA\", {'color':colors[0]}],\n\t[\"Q\", {\"size\":11, \"color\":colors[0]}], \n\t[\"NSW\", {'color':colors[0]}],\n\t[\"V\", {'color':colors[0]}]\n]\n\ngraphEdges=[\n\t[\"WA\", \"NT\", {\"color\":colors[-1]}], \n\t[\"WA\", \"SA\", {\"color\":colors[-1]}],\n\t[\"NT\", \"Q\", {\"color\":colors[-1]}],\n\t[\"NT\", \"SA\", {\"color\":colors[-1]}],\n\t[\"SA\", \"Q\", {\"color\":colors[-1]}],\n\t[\"SA\", \"NSW\", {\"color\":colors[-1]}],\n\t[\"SA\", \"V\", {\"color\":colors[-1]}],\n\t[\"SA\", \"Q\", {\"color\":colors[-1]}],\n\t[\"Q\", \"NSW\", {\"color\":colors[-1]}],\n\t[\"Q\", \"SA\", {\"color\":colors[-2]}],\n\t[\"Q\", \"NT\", {\"color\":colors[-1]}],\n\t[\"NSW\", \"V\", {\"color\":colors[-1]}],\n]\n\n# graphEdges=[\n# \t(\"uno\", \"dos\", 3.0), \n# \t(\"dos\", \"tres\", 7.5)\n# ]\n\nG = nx.Graph()\nG.add_nodes_from(graphNodes)\nG.add_edges_from(graphEdges)\n\n#G.add_weighted_edges_from(graphEdges)\nnx.set_node_attributes(G, colors[1], 'color')\nG.node[\"NSW\"][\"color\"]=colors[2]\n\n\npos=nx.spring_layout(G)\nedge_labels = nx.get_edge_attributes(G,'weight')\nnode_colors=nx.get_node_attributes(G,'color')\nedge_colors=nx.get_edge_attributes(G,'color')\n\n#for i in nx.neighbors(G, \"WA\"):\n#\tprint(i)\n\nfor nodeI, listI in zip(sorted(G.nodes), nx.adjacency_matrix(G, nodelist=sorted(G.nodes())).todense()):\n\tprint(\"{}\\t{}\".format(nodeI, listI))\n\n#A^2\nprint(nx.adjacency_matrix(G, nodelist=sorted(G.nodes())).todense()**2)\n\n#print(nx.adjacency_matrix(G, nodelist=sorted(G.nodes())).todense()*)\n\n#for i in nx.adjacency_matrix(G, nodelist=sorted(G.nodes())).todense():\n#\tprint(i)\n# print(nx.adjacency_matrix(G, nodelist=sorted(G.nodes())).todense())\n\nnx.draw(G, pos, edge_color=edge_colors.values(), node_color=node_colors.values(),with_labels=True, font_weight='bold')\n\n# nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels, with_labels=True, font_weight='bold')\n\nplt.show()","sub_path":"classes/clase 01-06-2019/grafo matplot.py","file_name":"grafo matplot.py","file_ext":"py","file_size_in_byte":2235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"376124305","text":"#!/usr/bin/env python2\n\nimport Tkinter as tk\nimport ttk\nfrom interface import styler\nimport tkFileDialog\nfrom interface import test_case\nimport os, re\nimport threading\n\n\ncount = 0\nclass TestFrameView: \n def __init__(self, parent):\n self.parent = parent\n self.test_case_frame_list = []\n self.setup()\n\n def setup(self):\n self.create_test_header_frame()\n self.create_test_body_frame()\n self.test_frame_header()\n self.add_test()\n \n def create_test_header_frame(self):\n self.test_header_frame = tk.Frame(self.parent, **styler.test_header_properties[0])\n self.test_header_frame.grid(**styler.test_header_properties[1])\n\n for i,size in zip(range(5),(50,480,20,20,20)):\n self.test_header_frame.grid_columnconfigure(i, weight=1, minsize=size)\n self.test_header_frame.grid_rowconfigure(0, weight=1,minsize=1)\n\n def create_test_body_frame(self):\n self.test_body_frame = tk.Frame(self.parent, **styler.test_body_properties[0])\n self.test_body_frame.grid(row=1, column=0, sticky=styler.sticky_top_left)\n \n for _ in range(16):\n self.test_body_frame.grid_rowconfigure(_+1, weight=1,minsize=20)\n \n def test_frame_header(self):\n self.label1 = ttk.Label(self.test_header_frame, text='TC ID',)\n self.label1.grid(row=0, column=0,sticky='w')\n self.label2 = ttk.Label(self.test_header_frame, text='Text case XML Path')\n self.label2.grid(row=0, column=1, sticky='w')\n self.label3 = ttk.Label(self.test_header_frame, text='Runs')\n self.label3.grid(row=0, columnspan=3, column=2, sticky='w')\n\n def add_test(self):\n global count\n if count < 15:\n count += 1\n self.test = test_case.CreateTest(self.test_body_frame, count)\n self.test_case_frame_list.append(self.test)\n print((self.test_case_frame_list))\n else:\n pass\n\n def remove_test(self):\n global count\n if count > 1:\n count -= 1\n print('removed clicked')\n self.test_case_frame_list[count].test_case_frame.destroy()\n self.test_case_frame_list.pop()\n print(self.test_case_frame_list)\n else:\n pass\n\n # def search_all(self):\n # testcases_path = 'C:\\\\Pegasus_Pilot\\\\workspaceWCDMA_Pilot\\\\SCT_Workspace\\\\Testcases'\n # for tc in test_case_frame_list:\n # target = 'NEBSSCT_DSP_' + tc.test_case_id.get() + '.xml'\n # for path, sub_dirs, files in os.walk(testcases_path):\n # for f in files:\n # if f == target:\n # full_path = os.path.join(path, f)\n # m_path = re.search(r'\\\\Testcases.+$', full_path)\n # tc.test_case_path_value.set(m_path.group(0))\n\n\n","sub_path":"interface/test_interface.py","file_name":"test_interface.py","file_ext":"py","file_size_in_byte":2876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"640434942","text":"from celery import task\nfrom django.template.loader import render_to_string\nfrom django.core.mail import send_mail\nfrom .models import Service, service_dates\nimport os\n\n\n@task(name='send_reminders')\ndef send_reminders():\n sender_email = os.environ.get('EMAIL_HOST_USER')\n recipient_emails = os.environ.get('REMINDER_RECIPIENTS_EMAIL').split(',')\n\n this_week_service_date_str, following_service_date_str, _ = service_dates()\n this_week_services = Service.objects.filter(service_date=this_week_service_date_str)\n\n # send emails to all servants\n emails = ';'.join([servant.email for service in this_week_services.all() for servant in service.servants.all()])\n\n context = {'services': this_week_services,\n 'this_week_date': this_week_service_date_str,\n 'emails': emails}\n\n email_subject = render_to_string(\n 'catalog/reminder_email_subject.txt', context).replace('\\n', '')\n email_body = render_to_string('catalog/reminder_email_body.txt', context)\n\n\n send_mail(\n email_subject,\n email_body,\n sender_email,\n recipient_emails,\n fail_silently=False,\n )\n\n return \"Reminder email sent.\"\n","sub_path":"catalog/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":1184,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"256964566","text":"import numpy as np\n# 1.7 Write an algorithm such that if an element in an MxN matrix is 0,\n# its entire row and column are set to 0.\n\n# I would use numpy, since it is a matrix, but do as array since not\n# doing linear algebra.\n\ndef matrix_zero(matrix):\n \"\"\" (numpy.array) -> array\n Check matrix for zeros. Any column or row with a 0 in it, causes that row\n or column to become all zeros. Return new matrix. Converts whatever type\n is given to a numpy array.\n\n >>> matrix_zero(np.array([[1,2,3],[0,1,3],[1,3,4]]))\n array([[0, 2, 3],\n [0, 0, 0],\n [0, 3, 4]])\n >>> matrix_zero(np.array([[0,0,0],[0,9,0],[1,0,0]]))\n array([[0, 0, 0],\n [0, 0, 0],\n [0, 0, 0]])\n >>> matrix_zero(np.array([[1,2,3],[2,5,3],[1,3,4]]))\n ([1 2 3; 2 5 3; 1 3 4])\n \"\"\"\n # I want to use lists so I can get the index for the row\n # but I want to use arrays so I can change entire columns or rows\n # Argh! This would be easier in Matlab, I wouldn't even have to loop\n mtx = np.array(matrix)\n new_mtx = mtx.copy()\n # Need to make sure not 1-dim array, as you apparently cannot use\n # mtx[0,0] on a one dimentional array! Meh.\n if (mtx.ndim == 1):\n if ((mtx==0).any()):\n new_mtx[:] = 0\n return new_mtx\n # go through rows\n for i in range(0,len(mtx)):\n # go through each number in row, find zeros\n for j, yval in enumerate(mtx[i,:]):\n if (yval== 0):\n # if you find a zero,make that column and row all zeros\n new_mtx[:,j] = 0;\n new_mtx[i,:] = 0;\n return new_mtx\n\n","sub_path":"ch1.py","file_name":"ch1.py","file_ext":"py","file_size_in_byte":1611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"133477377","text":"from http import cookiejar\nfrom urllib import request\nfrom requests.cookies import RequestsCookieJar\nimport requests\nimport json\nfrom selenium import webdriver\nimport time\nfrom selenium.webdriver.chrome.options import Options\nimport os\nimport platform\n\n\ndef saveCookie():\n #职赢未来登录测试\n url = \"https://www.zhiyingwl.com/lcs/#/study/course\"\n header = {\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:64.0) Gecko/20100101 Firefox/64.0\",\n \"Accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\",\n \"Accept-Language\": \"zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2\",\n \"Accept-Encoding\": \"gzip, deflate, br\",\n \"Connection\": \"keep-alive\",\n }\n cookieFilename = \"cookie.txt\"\n cookie = cookiejar.LWPCookieJar(filename=cookieFilename)\n handler = request.HTTPCookieProcessor(cookie)\n opener = request.build_opener(handler)\n\n req = request.Request(url=url,headers=header)\n respone = opener.open(req)\n cookie.save(ignore_discard=True, ignore_expires=True)\n for item in cookie:\n print('Name = ' + item.name)\n print('Value = ' + item.value)\n\n\ndef seleniumCookieTest():\n #测试登录后获取页面\n url = \"https://www.zhiyingwl.com/lcs/#/study/homework\"\n header = {\n \"Host\": \"www.zhiyingwl.com\",\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:64.0) Gecko/20100101 Firefox/64.0\",\n \"Accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\",\n \"Accept-Language\": \"zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2\",\n \"Accept-Encoding\": \"gzip, deflate, br\",\n \"Referer\": \"https://www.zhiyingwl.com/lcs/\",\n \"Connection\": \"keep-alive\"\n }\n cookie = RequestsCookieJar\n cookieDict = dict()\n with open('seleniumCookie.txt','r') as f:\n cookies = json.load(f)\n for i in cookies:\n cookieDict[i[\"name\"]] = i[\"value\"]\n\n respone = requests.get(url,cookies = cookieDict,headers = header)\n respone.encoding='utf-8'\n print(respone.text)\n\ndef weiboLogin():\n #用selenium获取cookies保存到文件\n url = \"https://weibo.com/login\"\n url2 = \"https://weibo.com/6460703487/profile?topnav=1&wvr=6&is_all=1\"\n driver = webdriver.Firefox(executable_path=\"login/geckodriver\")\n driver.get(url)\n driver.find_element_by_xpath('//input[@id=\"loginname\"]').send_keys(\"whiskey0118@sina.com\")\n driver.find_element_by_xpath('//input[@type=\"password\"]').send_keys(\"Maozedong@123\")\n driver.find_element_by_xpath('//span[@node-type=\"submitStates\"]').click()\n time.sleep(10)\n driver.get(url=url2)\n cookie = driver.get_cookies()\n driver.close()\n with open(\"login/weiboCookie.txt\",'w+') as f:\n json.dump(cookie,f)\n return json.dumps(cookie)\n\n\ndef weiboLoginLinux():\n chrome_options = Options()\n chrome_options.add_argument('--headless')\n chrome_options.add_argument('--disable-gpu')\n chrome_options.add_argument('--no-sandbox')\n chrome_options.add_argument('window-size=1920x3000')\n chrome_options.add_argument('--hide-scrollbars')\n chrome_options.add_argument('blink-settings=imagesEnabled=false')\n chrome_options.binary_location = r\"/usr/bin/google-chrome\"\n driver = webdriver.Chrome(executable_path=\"login/chromedriver\", chrome_options=chrome_options)\n url = \"https://weibo.com/login\"\n url2 = \"https://weibo.com/6460703487/profile?topnav=1&wvr=6&is_all=1\"\n driver.get(url)\n driver.find_element_by_xpath('//input[@id=\"loginname\"]').send_keys(\"whiskey0118@sina.com\")\n driver.find_element_by_xpath('//input[@type=\"password\"]').send_keys(\"Maozedong@123\")\n driver.find_element_by_xpath('//span[@node-type=\"submitStates\"]').click()\n time.sleep(10)\n driver.get(url=url2)\n cookie = driver.get_cookies()\n driver.close()\n with open(\"login/weiboCookie.txt\", 'w+') as f:\n json.dump(cookie, f)\n return json.dumps(cookie)\n\n\n\n\ndef cookies():\n if os.path.getsize(\"login/weiboCookie.txt\"):\n with open(\"login/weiboCookie.txt\",'r+') as f:\n cookies=json.load(f)\n return cookies\n else:\n if platform.system() == \"linux\":\n weiboLoginLinux()\n else:\n weiboLogin()\n with open(\"login/weiboCookie.txt\",'r+') as f:\n cookies=json.load(f)\n return cookies\n\n# cookieList = ''\ncookieList = cookies()\n\n\n# weiboLogin()","sub_path":"login/cookie.py","file_name":"cookie.py","file_ext":"py","file_size_in_byte":4428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"585980907","text":"# https://leetcode.com/problems/search-in-rotated-sorted-array/description/\nclass Solution(object):\n def search(self, nums, target):\n \"\"\"\n :type nums: List[int]\n :type target: int\n :rtype: int\n \"\"\"\n if len(nums) is 0:\n return -1\n\n j = 0\n for i in range(len(nums) - 1):\n if nums[i] > nums[i + 1]:\n j = i\n break\n x = self.binsearch(nums, 0, j, target)\n y = self.binsearch(nums, j + 1, len(nums) - 1, target)\n if x is -1 and y is -1:\n return -1\n elif x != -1:\n return x\n return y\n\n def binsearch(self, nums, lo, hi, target):\n if lo <= hi:\n mid = (lo + hi) / 2\n if nums[mid] == target:\n return mid\n elif nums[mid] > target:\n return self.binsearch(nums, lo, mid - 1, target)\n else:\n return self.binsearch(nums, mid + 1, hi, target)\n return -1","sub_path":"Test/NotCSharp/Python/EASY-SearchEleInRotatedArray.py","file_name":"EASY-SearchEleInRotatedArray.py","file_ext":"py","file_size_in_byte":1011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"199040222","text":"from entities.Page.PageEntity import PageEntity\nfrom repositories.SQL.MySQL.Page.mappers.PageMapper import PageMapper\nfrom repositories.SQL.MySQL.Page.mappers.PageTextMapper import PageTextMapper\nfrom repositories.SQL.SQLRepository import SQLRepository\nfrom services.Page.PageRepositoryInterface import PageRepositoryInterface\n\n\nclass PageRepository(SQLRepository, PageRepositoryInterface):\n\n def find_by_code(self, code: str) -> PageEntity|None:\n query = f'''\n SELECT\n {PageMapper.fields},\n {PageTextMapper.fields}\n FROM {PageMapper.table}\n JOIN {PageTextMapper.table}\n ON {PageTextMapper.table_prefix}.page_id = {PageMapper.table_prefix}.id\n AND {PageTextMapper.table_prefix}.language_id = %s\n WHERE\n {PageMapper.table_prefix}.code = %s\n '''\n\n with self.connection as connection:\n with connection.cursor() as cursor:\n cursor.execute(query, (1, code))\n\n return PageMapper.create_entity(cursor.fetchone())","sub_path":"app/repositories/SQL/MySQL/Page/PageRepository.py","file_name":"PageRepository.py","file_ext":"py","file_size_in_byte":1081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"17791355","text":"# -*- coding: utf-8 -*-\n\"\"\"\n@author: longshuicui\n@date : 2021/5/13\n@function:\n1269. 停在原地的方案数 (Hard)\nhttps://leetcode-cn.com/problems/number-of-ways-to-stay-in-the-same-place-after-some-steps/\n有一个长度为arrLen的数组,开始有一个指针在索引0 处。\n每一步操作中,你可以将指针向左或向右移动 1 步,或者停在原地(指针不能被移动到数组范围外)。\n给你两个整数steps 和arrLen ,请你计算并返回:在恰好执行steps次操作以后,指针仍然指向索引 0 ���的方案数。\n由于答案可能会很大,请返回方案数 模10^9 + 7 后的结果。\n示例 1:\n 输入:steps = 3, arrLen = 2\n 输出:4\n 解释:3 步后,总共有 4 种不同的方法可以停在索引 0 处。\n 向右,向左,不动\n 不动,向右,向左\n 向右,不动,向左\n 不动,不动,不动\n示例 2:\n 输入:steps = 2, arrLen = 4\n 输出:2\n 解释:2 步后,总共有 2 种不同的方法可以停在索引 0 处。\n 向右,向左\n 不动,不动\n示例 3:\n 输入:steps = 4, arrLen = 2\n 输出:8\n题解:\n 对于计算方案数的题目,常用的方法就是动态规划\n dp[i][j]表示在第i步操作之后,指针位于下标j的方案,0<=i<=steps, 0<=j<=arrLen-1,指针下标不会大于steps,所以0<=j<=min(arrLen-1,steps)\n dp边界,dp[0][0]=1,没有操作且指针位于0的情况,当没有操作指针位于其他下标的情况 dp[0][j]=0 不可能有这种情况\n 每一步操作,指针可以向前、向后、不动三种操作,所以得到状态转移方程\n dp[i][j]=dp[i-1][j-1]+dp[i-1][j]+dp[i-1][j+1]\n 注意下标越界情况\n 最终答案为dp[steps][0]\n\n\"\"\"\n\n\ndef numWays(steps, arrLen):\n \"\"\"时间复杂度O(steps*min(arrLen-1, steps)),\n 空间复杂度O(min(arrLen-1, steps))\"\"\"\n dp = [0 for _ in range(min(arrLen, steps + 1))]\n dp[0] = 1\n for i in range(1, steps + 1):\n dpNext=[0 for _ in range(min(arrLen, steps + 1))]\n for j in range(min(arrLen, steps + 1)):\n if j == 0:\n dpNext[j] = dp[j] + dp[j + 1]\n elif j == min(arrLen - 1, steps):\n dpNext[j] = dp[j - 1] + dp[j]\n else:\n dpNext[j] = dp[j - 1] + dp[j] + dp[j + 1]\n dp=dpNext\n return dp[0] % (10 ** 9 + 7)\n\n\nsteps = 3\narrLen = 2\nres = numWays(steps, arrLen)\nprint(res)\n","sub_path":"06.动态规划/1269. 停在原地的方案数(Hard).py","file_name":"1269. 停在原地的方案数(Hard).py","file_ext":"py","file_size_in_byte":2455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"161316527","text":"import unittest\n\nfrom mock import Mock\nfrom nose.tools import assert_false, assert_equal\n\nfrom consumerism import Processor, AbstractMessage\n\n\nclass Message(AbstractMessage):\n def __init__(self, body_dict):\n self.body = body_dict\n\n def resource_name(self):\n return self.body['resource'].lower()\n\n def invoke_args(self):\n return (self.body['action'], self.body['params']), {}\n\n\nclass TestProcessor(unittest.TestCase):\n def setUp(self):\n self.mock_resource = Mock()\n self.mock_resource.invoke = Mock(return_value=True)\n self.factory = Mock()\n self.factory.new.return_value = self.mock_resource\n\n def test_process_malformed_messages(self):\n processor = Processor(self.factory, Message)\n\n assert_equal(processor.process({}), True)\n assert_equal(processor.process({'resource': 'name'}), True)\n assert_equal(\n processor.process({'resource': 'name', 'action': 'action'}),\n True\n )\n\n assert_false(self.factory.new.called)\n assert_false(self.mock_resource.called)\n\n def test_process_creates_and_invokes_named_resource(self):\n processor = Processor(self.factory, Message)\n\n params = {'param1': True}\n result = processor.process({\n 'resource': 'name',\n 'action': 'action',\n 'params': params,\n })\n\n assert_equal(result, True)\n self.factory.new.assert_called_once_with('name')\n self.mock_resource.invoke.assert_called_once_with('action', params)\n\n def test_process_returns_false_when_factory_fails(self):\n processor = Processor(self.factory, Message)\n self.factory.new.side_effect = Exception('Cannot build new resource')\n\n result = processor.process({\n 'resource': 'name',\n 'action': 'action',\n 'params': {},\n })\n\n assert_false(result)\n\n def test_process_returns_false_when_invoke_fails(self):\n self.mock_resource.invoke = Mock(side_effect=Exception('Unhandled'))\n processor = Processor(self.factory, Message)\n\n result = processor.process({\n 'resource': 'name',\n 'action': 'action',\n 'params': {},\n })\n\n assert_equal(result, False)\n","sub_path":"tests/test_processor.py","file_name":"test_processor.py","file_ext":"py","file_size_in_byte":2282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"180286067","text":"import random\nimport os\n\nalphabets = ['a', 'b', 'c', 'd', 'r', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']\n\ndef lower(char):\n return char.lower()\n\ndef get_random_target():\n global alphabets\n lower_limit = 0\n upper_limit = len(alphabets) - 1\n return alphabets[random.randint(lower_limit, upper_limit)]\n\ndef pos(letter):\n global alphabets\n return alphabets.index(letter.lower())\n\ndef valid_guess(target, value):\n '''\n Returns True if target and values are equal\n else an exception is raised, indicating position\n '''\n if lower(target) == lower(value):\n return True\n elif pos(value) < pos(target):\n raise Exception(\"{} is lesser than the target value. Please try again!!\".format(value))\n else:\n raise Exception(\"{} is greater than the target value. Please try again!!\".format(value))\n \n\ndef init_game():\n tries = 20\n target = get_random_target()\n return tries, target\n\ndef valid_input(value):\n global alphabets\n if len(value) > 1:\n return False\n if lower(value) not in alphabets:\n return False\n \n return True\n \n\ndef start_game():\n # Initialize Game, target is the random alphabet chosen\n tries, target = init_game()\n\n # Loop till tries are pending\n while tries:\n print(\"Tries Remainig: {}\".format(tries))\n guess = raw_input(\"Enter your guess: \")\n \n # Backdoor for exiting gmae\n if guess.lower() in ['exit','quit','end']:\n print(\"Quitting Game\")\n return\n\n # Check if input is a valid. ie alphabet\n # else it costs a try\n if not valid_input(lower(guess)):\n print(\"Invalid guess! you must guess a valid alphabet\")\n tries -= 1\n continue \n\n '''\n Following try catch block test if the guess match the taget\n if guessed alphabet doesnt match the target it raise greather than or lesser than\n exception, which in turn is catched by except block and a try is deducted\n '''\n try:\n result = valid_guess(target, guess)\n except Exception as e:\n print(str(e))\n tries -= 1\n continue\n\n #The guess was correct. Player wins here\n print(\"Corrrect guess. You Won!\")\n return\n \n # No peending tries, hence game over\n print(\"Game Over\")\n return\n\nif __name__ == '__main__':\n start_game()\n","sub_path":"week2/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":2483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"582926332","text":"from ctypes import CDLL, Structure, c_long, c_int, c_ubyte, POINTER, sizeof, cast\nfrom ctypes.wintypes import BYTE, WORD, DWORD\nfrom ipaddress import ip_address\nfrom time import sleep\nimport pickle\n\n\nclass LJV7IF_ETHERNET_CONFIG(Structure):\n _fields_ = [\n ('abyIpAddress', BYTE * 4),\n ('wPortNo', WORD),\n ('reserve', BYTE * 2),\n ]\n\n def __repr__(self):\n ip = cast(self.abyIpAddress, POINTER(c_ubyte))\n return f'{ip[0]}.{ip[1]}.{ip[2]}.{ip[3]}:{self.wPortNo}'\n\n\nclass LJV7IF_GET_BATCH_PROFILE_REQ(Structure):\n _fields_ = [\n ('byTargetBank', BYTE),\n ('byPosMode', BYTE),\n ('reserve', BYTE * 2),\n ('dwGetBatchNo', DWORD),\n ('dwGetProfNo', DWORD),\n ('byGetProfCnt', BYTE),\n ('byErase', BYTE),\n ('reserve2', BYTE * 2)\n ]\n\n\nclass LJV7IF_GET_BATCH_PROFILE_RSP(Structure):\n _fields_ = [\n ('dwCurrentBatchNo', DWORD),\n ('dwCurrentBatchProfCnt', DWORD),\n ('dwOldestBatchNo', DWORD),\n ('dwOldestBatchProfCnt', DWORD),\n ('dwGetBatchNo', DWORD),\n ('dwGetBatchProfCnt', DWORD),\n ('dwGetBatchTopProfNo', DWORD),\n ('byGetProfCnt', BYTE),\n ('byCurrentBatchCommited', BYTE),\n ('reserve', BYTE * 2)\n ]\n\n\nclass LJV7IF_PROFILE_INFO(Structure):\n _fields_ = [\n ('byProfileCnt', BYTE),\n ('byEnvelope', BYTE),\n ('reserve', BYTE * 2),\n ('wProfDataCnt', WORD),\n ('reserve2', BYTE * 2),\n ('lXStart', c_long),\n ('lXPitch', c_long)\n ]\n\n\nclass LJV7IF_PROFILE_HEADER(Structure):\n _fields_ = [\n ('reserve', DWORD),\n ('dwTriggerCnt', DWORD),\n ('dwEncoderCnt', DWORD),\n ('reserve2', DWORD * 3)\n ]\n\n\nclass LJV7IF_PROFILE_FOOTER(Structure):\n _fields_ = [\n ('reserve', DWORD)\n ]\n\n\nclass LJV7IF():\n errs = {\n 0x1000: 'Failed to open the communication path',\n 0x1001: 'The communication path was not established',\n 0x1002: 'Failed to send the command',\n 0x1003: 'Failed to receive a response',\n 0x1004: 'A timeout occurred while waiting for the response',\n 0x1005: 'Failed to allocate memory',\n 0x1006: 'An invalid parameter was passed',\n 0x1007: 'The received response data was invali',\n 0x1009: 'High-speed communication initialization could not be performed',\n 0x100A: 'High-speed communication was initialized',\n 0x100B: 'Error already occurred during high-speed communication (for high-speed communication)',\n 0x100C: 'The buffer size passed as an argument is insufficient.'\n }\n\n _maxProfileCnt = 5000\n\n def __init__(self, deviceId=0):\n self.deviceId = deviceId\n self.ret = 0\n self.loaded = False\n self.ethConnected = False\n\n self.dll = CDLL('./dll/LJV7_IF.dll')\n self.initf = self.wrap('LJV7IF_Initialize', c_long, None)\n self.deinitf = self.wrap('LJV7IF_Finalize', c_long, None)\n self.ethOpenf = self.wrap('LJV7IF_EthernetOpen', c_long, [c_long, POINTER(LJV7IF_ETHERNET_CONFIG)])\n self.closef = self.wrap('LJV7IF_CommClose', c_long, [c_long])\n self.clearMemoryf = self.wrap('LJV7IF_ClearMemory', c_long, [c_long])\n self.changeActiveProgramf = self.wrap('LJV7IF_ChangeActiveProgram', c_long, [c_long, BYTE])\n self.startMeasuref = self.wrap('LJV7IF_StartMeasure', c_long, [c_long])\n self.getBatchProfilef = self.wrap('LJV7IF_GetBatchProfile', c_long, [\n c_long,\n POINTER(LJV7IF_GET_BATCH_PROFILE_REQ),\n POINTER(LJV7IF_GET_BATCH_PROFILE_RSP),\n POINTER(LJV7IF_PROFILE_INFO),\n POINTER(DWORD),\n DWORD\n ]\n )\n\n def init(self):\n if self.loaded:\n self.ret = 0\n return 0\n\n self.ret = self.initf()\n if self.ret == 0:\n self.loaded = True\n return self.ret\n\n def deinit(self):\n if not self.loaded:\n self.ret = 0\n return 0\n\n self.ret = self.deinitf()\n if self.ret == 0:\n self.loaded = False\n return self.ret\n\n def ethOpen(self, ip='192.168.0.18', port=24691):\n if self.ethConnected:\n self.ret = 0\n return 0\n\n ip = ip_address(ip)\n eth = LJV7IF_ETHERNET_CONFIG(self.makeArray(BYTE, ip.packed), port, (BYTE*2)())\n print(eth)\n self.ret = self.ethOpenf(self.deviceId, eth)\n if self.ret == 0:\n self.ethConnected = True\n return self.ret\n\n def close(self):\n if not self.ethConnected:\n self.ret = 0\n return 0\n\n self.ret = self.closef(self.deviceId)\n if self.ret == 0:\n self.ethConnected = False\n return self.ret\n\n def clearMemory(self):\n self.ret = self.clearMemoryf(self.deviceId)\n return self.ret\n\n def changeActiveProgram(self, prg=1):\n self.ret = self.changeActiveProgramf(self.deviceId, prg)\n return self.ret\n\n def startmeasure(self):\n self.ret = self.startMeasuref(self.deviceId)\n return self.ret\n\n def getBatchProfileData(self, cont=True, secs=1):\n dat = self.getBatchProfileDataEx()\n while cont and len(dat) == 0:\n dat = self.getBatchProfileDataEx()\n sleep(secs)\n return dat\n\n def getBatchProfileDataEx(self):\n req = LJV7IF_GET_BATCH_PROFILE_REQ(0x00, 0x03, (BYTE*2)(), 0, 0, 0xff, 0)\n rsp = LJV7IF_GET_BATCH_PROFILE_RSP()\n inf = LJV7IF_PROFILE_INFO()\n\n print(req)\n dwOneDataSize = self._maxProfileCnt + (sizeof(LJV7IF_PROFILE_HEADER) + sizeof(LJV7IF_PROFILE_FOOTER)) / sizeof(DWORD)\n dwAllDataSize = dwOneDataSize * req.byGetProfCnt\n print(dwAllDataSize)\n dwAllDataSize = abs(int(dwAllDataSize))\n arr = (DWORD * dwAllDataSize)()\n print('size of array', sizeof(arr))\n print(arr)\n\n self.ret = self.getBatchProfilef(self.deviceId, req, rsp, inf, arr, sizeof(arr))\n self.checkReturnCode()\n if self.ret != 0:\n # No data or error\n # 0x80A0 is no data\n return []\n\n dat = []\n nDataUnitSize = (sizeof(LJV7IF_PROFILE_HEADER) + sizeof(c_int) * inf.wProfDataCnt * inf.byProfileCnt * (inf.byEnvelope + 1) + sizeof(LJV7IF_PROFILE_FOOTER)) / sizeof(c_int)\n # Calculate the length of data between each header/footer\n ll = inf.wProfDataCnt * inf.byProfileCnt * (inf.byEnvelope + 1)\n for ii in range(nDataUnitSize):\n # Find the index of the data\n # Need to take into account the header and the footer around each entry\n jj = nDataUnitSize * ii + (sizeof(LJV7IF_PROFILE_HEADER) / sizeof(DWORD))\n dat.append(arr[jj:jj+ll])\n\n req.byPosMode = 0x02 # Specify position\n req.dwGetBatchNo = rsp.dwGetBatchNo\n while True:\n req.dwGetProfNo = rsp.dwGetBatchTopProfNo + rsp.byGetProfCnt\n req.byGetProfCnt = min(0xff, rsp.dwCurrentBatchProfCnt - req.dwGetProfNo)\n self.ret = self.getBatchProfilef(self.deviceId, req, rsp, inf, arr, sizeof(arr))\n if self.ret != 0:\n return []\n for ii in range(rsp.byGetProfCnt):\n jj = nDataUnitSize * ii + (sizeof(LJV7IF_PROFILE_HEADER) / sizeof(DWORD))\n dat.append(arr[jj:jj+ll])\n print(f'Image got profile {rsp.dwGetBatchTopProfNo} of {rsp.dwGetBatchProfCnt}')\n if rsp.dwGetBatchProfCnt == (rsp.dwGetBatchTopProfNo + rsp.byGetProfCnt):\n break\n\n self.ret = self.clearMemory()\n return dat\n\n @staticmethod\n def makeArray(type, dat):\n return (type * len(dat)).from_buffer(bytearray(dat))\n\n def wrap(self, funcname, restype, argtypes):\n \"\"\"Simplify wrapping ctypes functions\"\"\"\n func = self.dll.__getattr__(funcname)\n func.restype = restype\n func.argtypes = argtypes\n return func\n\n def checkReturnCode(self, ret=None):\n if ret is None:\n ret = self.ret\n if ret == 0:\n return True\n print(self.errs.get(ret, 'Unknown error'))\n return False\n\n\nif __name__ == '__main__':\n print(f\"Starting\")\n laser = LJV7IF()\n laser.init()\n print(f\"Initialized\")\n laser.ethOpen()\n print(f\"Ethernet Connected\")\n laser.checkReturnCode()\n # laser.clearMemory()\n laser.checkReturnCode()\n laser.changeActiveProgram()\n laser.checkReturnCode()\n laser.startmeasure()\n dat = laser.getBatchProfileData()\n with open('scan.pickle', 'wb') as f:\n pickle.dump(dat, f)\n print(len(dat))\n print(len(dat[0]))\n","sub_path":"laser.py","file_name":"laser.py","file_ext":"py","file_size_in_byte":8715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"82573060","text":"from django.conf.urls import url\nfrom . import views\nfrom django.conf import settings\n# from django.conf.urls.static import static\n\n\nurlpatterns = [\nurl('^$', views.allprofiles, name = 'allprofiles'),\nurl('^profile', views.profile, name = 'profile'),\nurl(r'^search/', views.search_results, name='search_results'),\nurl(r'^photo/(\\d+)',views.photo,name ='photo'), \nurl(r'^auth/login',views.login,name ='login'),\nurl(r'^auth/register',views.register,name ='register'),\nurl(r'^comment/(\\d+)',views.new_comment,name ='comment'),\nurl(r'^like/(\\d+)',views.new_like,name ='like'),\nurl(r'^follow/(\\d+)',views.follow,name ='follow'),\nurl('^upload', views.upload, name = 'upload'),\nurl(r'^update/', views.update, name = 'update'),\nurl(r'^logout/', views.logout_me, name = 'logout_me'),\n\n]\n","sub_path":"people/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"459230611","text":"# -*- coding: utf-8 -*-\n\nimport MySQLdb\nimport pandas as pd\nfrom sqlalchemy import create_engine\nfrom src.db.File import File\nclass DB:\n db = None\n cursor = None\n connect_string = \"\"\n db_name = \"\"\n db_type = \"\"\n engine = None\n def __init__(self,db_type,host_name,user_name,password,db_name):\n self.db_name = db_name\n self.db_type = db_type\n if db_type == \"mysql\":\n # 打开数据库连接\n self.db = MySQLdb.connect(host_name,user_name,password,db_name)\n # 使用cursor()方法获取操作游标\n self.cursor = self.db.cursor()\n # 引擎字符串\n self.connect_string = \"mysql+mysqldb://\"+ user_name + \":\"+\\\n password + \"@\"+ host_name + \":3306\" +\"/\"+db_name+\"?charset=utf8\"\n self.engine = self.get_connect()\n\n def excut(self,query):\n try:\n self.cursor.execute(query)\n self.db.commit()\n return self.cursor.fetchall()\n except:\n self.db.rollback()\n print(self.db.error())\n return -1\n\n def get_connect(self):\n return create_engine(self.connect_string)\n\n def input_dateframe2sqldb(self,thedataframe,database_name,table_name):\n pd.io.sql.to_sql(thedataframe,table_name, self.engine, schema=database_name, if_exists='append')\n\n def __del__(self):\n # 关闭数据库连接\n self.db.close()\n\n # data_path :数据路径,路径内必须是csv文件,符合dataframe的格式要求,不能有其他文件\n # numOfcsv_in_one_table:一张表中存多少张csv文件数据\n # 每张表都会自动添加index字段,默认(default_fixed=True)会用来替换为csv的名字用于识别哪张csv\n # 也可以自定义规则 fixed_function(current_table,file_name,start_line,end_line)\n def store_csv2db(self,data_path,numOfcsv_in_one_table=1,data_type=\"csv\",\n default_fixed=True,fixed_function=None):\n f = File(data_path);i = 0;current_table = \"\"\n for file_name in f.get_file_names_without_suffix_in_current_dir():\n if file_name =='.DS_Store' or int(file_name) < 2627 or int(file_name) >= 2838 : continue\n if i % numOfcsv_in_one_table == 0:\n current_table = file_name\n start_line = 0\n df = pd.read_csv(data_path+\"/\"+file_name+\".\"+data_type)\n self.input_dateframe2sqldb(df, self.db_name, current_table)\n self.excut(\"alter table `\" + current_table+\"` add column `share_num` varchar(20)\")\n self.excut(\"alter table `\" + current_table+\"` ADD COLUMN `id` int(20) \")\n self.excut(\"alter table `\" + current_table+\"` CHANGE COLUMN `id` `id` int(20) NOT NULL AUTO_INCREMENT, ADD PRIMARY KEY (`id`)\")\n else:\n start_line = self.excut(\"select max(id) from `\"+ current_table+ \"`\")[0][0]\n df = pd.read_csv(data_path+\"/\"+file_name+\".\"+data_type)\n self.input_dateframe2sqldb(df, self.db_name, current_table)\n\n end_line = start_line + len(df)\n if default_fixed:\n self.fix_function(current_table,file_name,start_line,end_line)\n else:\n fixed_function(current_table,file_name,start_line,end_line)\n i += 1\n print (file_name)\n\n def fix_function(self,current_table,file_name,start_line,end_line):\n self.excut(\"UPDATE `\" + current_table\n + \"` SET `share_num` = '\" + file_name\n + \"' where `id` >\" + str(start_line)\n + \" and `id` <=\"+ str(end_line))\n\n# demo :\n\n# a = DB(\"mysql\",\"localhost\", \"root\", \"123456\", \"modeling\")\n# a.store_csv2db(\"../../data\",100)\n","sub_path":"backend/util/db/DB.py","file_name":"DB.py","file_ext":"py","file_size_in_byte":3805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"223651829","text":"from settings import *\nimport pygame as pg\n\nclass Map:\n # static variables\n height = 20\n width = 15\n config = 0\n\n non_obstacle_tile_width = 30 # with of the tile\n tile_length = 35 # tile_length - tile_width = the gap between tile gaps, alter here to adjust length\n tile_gap = tile_length - non_obstacle_tile_width\n arena_border_left = 5\n arena_border_up = 5\n arena_border_right = tile_length * 13\n arena_border_down = tile_length * 18\n\n tiles_group = pg.sprite.Group() # the tiles sprite group\n map_tiles = [] # a 20 * 15 list holding tile objects\n\n def __init__(self):\n pass\n\n def generate_map(self, map_config):\n\n with open(map_config_path + map_config, 'r') as map_config:\n tile_x = 5\n tile_y = 5\n for row in range(1, 21):\n line = map_config.readline()\n tile_row = []\n for col in range (0, 15):\n if line[col] == '0':\n tile = Tile(tile_x, tile_y)\n elif line[col] == '1':\n tile = Tile(tile_x, tile_y)\n tile.is_obstacle = True\n elif line[col] =='2':\n tile = Tile(tile_x, tile_y)\n tile.update_color((255, 255, 0))\n tile.is_start_goal_zone = True\n tile.row = row-1\n tile.col = col\n tile_row.append(tile)\n tile_x += tile.length + tile.gap\n self.map_tiles.append(tile_row)\n tile_x = 5\n tile_y = 5 + (tile.length + tile.gap) * row\n\n for tile in self.map_tiles:\n self.tiles_group.add(tile)\n\n def map_update(self):\n for tile_row in self.map_tiles:\n for tile in tile_row:\n if tile.is_obstacle == False and tile.discovered ==True and tile.is_start_goal_zone == False:\n self.tiles_group.remove(tile)\n\n\nclass Tile(pg.sprite.Sprite):\n def __init__(self, x, y):\n pg.sprite.Sprite.__init__(self)\n self.length = 30\n self.gap = 5\n self.color = (255, 255, 255)\n self.image = pg.Surface((self.length, self.length))\n self.rect = self.image.get_rect()\n pg.draw.rect(self.image, self.color, self.rect)\n self.rect.x = x\n self.rect.y = y\n self.row = None\n self.col = None\n self.is_start_goal_zone = False\n self.is_obstacle = False\n self.discovered = False\n\n def update_color(self, color):\n self.color = color\n pg.draw.rect(self.image, self.color, pg.Rect(0,0, 35, 35))\n\n","sub_path":"Simulator/map_generator.py","file_name":"map_generator.py","file_ext":"py","file_size_in_byte":2694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"117088160","text":"# scraper for importing protocols from the German Bundestag in TEI format into the django parliament app\n# uses TEI documents from the following source:\n# https://github.com/PolMine/GermaParlTEI\n\nimport os\nimport difflib\nimport zipfile\n# from xml.etree import ElementTree\nimport lxml.etree as etree\nimport random\nimport re\nimport sys\nimport datetime\n\nimport django\nimport platform\n\nif platform.node() == \"mcc-apsis\":\n sys.path.append('/home/muef/tmv/BasicBrowser/')\n tei_path = \"/home/muef/GermaParlTEI-master\"\n\nelse:\n # local paths\n # sys.path.append('/media/Data/MCC/tmv/BasicBrowser/')\n # tei_path = \"/media/Data/MCC/Parliament Germany/GermaParlTEI-master\"\n sys.path.append('/home/leey/Documents/Data/tmv/BasicBrowser/')\n tei_path = \"/home/leey/Documents/Data/GermaParlTEI-master\"\n\n\n#sys.path.append('/home/galm/software/django/tmv/BasicBrowser/')\nos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"BasicBrowser.settings\")\ndjango.setup()\n\n# import from appended path\nimport parliament.models as pm\nfrom parliament.tasks import do_search, run_tm\nimport cities.models as cmodels\nfrom django.contrib.auth.models import User\nimport tmv_app.models as tm\n\nfrom parsing_utils import find_person_in_db, POI, dehyphenate_with_space, clean_text\nfrom regular_expressions_global import POI_MARK\n\n# ============================================================\n# write output to file and terminal\n\nimport pprint\npretty_printer = pprint.PrettyPrinter(indent=4)\n\ntime_stamp = datetime.datetime.now().strftime(\"%y%m%d_%H%M%S\")\noutput_file = \"./parlsessions_tei_parser_output_\" + time_stamp + \".log\"\nprint(\"log file: {}\".format(output_file))\n\n\nclass Logger(object):\n def __init__(self):\n self.terminal = sys.stdout\n self.log = open(output_file, \"a\")\n\n def write(self, message):\n self.terminal.write(message)\n self.log.write(message)\n\n def flush(self):\n #this flush method is needed for python 3 compatibility.\n #this handles the flush command by doing nothing.\n #you might want to specify some extra behavior here.\n pass\n\n\nclass parse_tei_items(object):\n\n def __init__(self, xtree, v=1, period=None, session=None):\n self.v = v\n self.divs = xtree.findall(\"//body//div\")\n self.wp = int(xtree.xpath(\"//legislativePeriod//text()\")[0])\n self.session = int(re.findall(r'\\b\\d+\\b', xtree.xpath(\"//sessionNo//text()\")[0])[0])\n if period is not None:\n if period != self.wp:\n print(\"! Warning: period number not matching: {} {}\".format(period, self.wp))\n\n if session is not None:\n if session != self.session:\n print(\"! Warning: session number not matching: {} {}\".format(session, self.session))\n\n self.date = xtree.xpath(\"//date//text()\")[0]\n try:\n self.original_source = xtree.xpath(\"//sourceDesc//url//text()\")[0]\n except IndexError:\n self.original_source = \"NA\"\n if self.v > 0:\n print(\"xml with protocol {}/{} from {}\".format(self.wp, self.session, self.date))\n\n def get_or_create_objects(self):\n\n replace_old_documents = False\n\n parl, created = pm.Parl.objects.get_or_create(\n country=cmodels.Country.objects.get(name=\"Germany\"),\n level='N')\n if created and self.v > 0:\n print(\"created new object for parliament\")\n\n pp, created = pm.ParlPeriod.objects.get_or_create(\n parliament=parl,\n n=self.wp)\n if created and self.v > 0:\n print(\"created new object for legislative period\")\n\n if replace_old_documents == True:\n doc, created = pm.Document.objects.get_or_create(\n parlperiod=pp,\n doc_type=\"Plenarprotokoll\",\n date=self.date\n )\n if created:\n print(\"created new object for plenary session document\")\n else:\n doc = pm.Document(\n parlperiod=pp,\n doc_type=\"Plenarprotokoll\",\n date=self.date\n )\n\n doc.sitting = self.session\n doc.text_source = \"updated - GermaParlTEI from \" + self.original_source\n doc.save()\n\n # delete old utterances associated with the doc\n doc.utterance_set.all().delete()\n self.doc = doc\n return doc\n\n def create_paragraph(self, text, utterance):\n text = \"\\n\".join(text).replace(\"\\n\\n\", \"\\n\")\n text = clean_text(text)\n para = pm.Paragraph(\n utterance=utterance,\n text=text,\n word_count=len(text.split()),\n char_len=len(text)\n )\n para.save()\n return para\n\n def add_interjections(self, text, paragraph):\n poi_match = POI_MARK.match(text)\n if poi_match is not None:\n self.poi_content = poi_match.group(1)\n\n for poi_raw in re.split('\\s[-–]-?\\.?\\s', self.poi_content):\n # de-hyphenate:\n poi_raw = dehyphenate_with_space(poi_raw)\n poi_obj = POI(poi_raw)\n if self.v > 1:\n print(\"interjection: speakers: {}, party: {}, type: {},\"\n \"\\ninterjection text: {}\".format(poi_obj.speakers, poi_obj.parties,\n poi_obj.type, poi_obj.poitext))\n\n interjection = pm.Interjection(\n paragraph=paragraph,\n text=poi_obj.poitext,\n type=poi_obj.type\n )\n interjection.save()\n\n if poi_obj.parties:\n for party_name in poi_obj.parties.split(':'):\n party, created = pm.Party.objects.get_or_create(\n name=party_name\n )\n\n interjection.parties.add(party)\n if poi_obj.speakers:\n for person in poi_obj.speakers:\n per = find_person_in_db(person, add_info={'wp': self.wp, 'session': self.session,\n 'source_type': 'TEI/POI'}, verbosity=self.v)\n if per is not None:\n interjection.persons.add(per)\n else:\n print(\"! Warning: Speaker could not be identified\")\n\n def run(self):\n\n self.get_or_create_objects()\n\n ### start parsing of speeches\n for div in self.divs:\n if self.v > 1:\n print(\"TEI div type: {}\".format(div.get(\"type\")))\n\n agenda_item = div.get(\"desc\")\n tops, created = pm.AgendaItem.objects.get_or_create(\n title = agenda_item,\n document = self.doc\n )\n tops.save()\n\n for sp in div.getchildren():\n if self.v > 1:\n print(\"TEI current speaker: {}\".format(sp.get(\"who\")))\n # match speaker to database:\n info_dict = dict(sp.attrib)\n info_dict['wp'] = self.wp\n info_dict['session'] = self.session\n info_dict['source_type'] = 'TEI/SP'\n speaker = find_person_in_db(sp.get(\"who\"), add_info=info_dict, verbosity=self.v)\n\n if speaker is None:\n print(sp.get(\"who\"))\n\n speaker_role_set = pm.SpeakerRole.objects.filter(alt_names__contains=[sp.get(\"role\")])\n if len(speaker_role_set) < 1:\n speaker_role = pm.SpeakerRole(name=sp.get(\"role\"), alt_names=[sp.get(\"role\")])\n speaker_role.save()\n else:\n speaker_role = speaker_role_set.first()\n if len(speaker_role_set) > 1:\n print(\"Warning: several speaker roles matching\")\n\n text = []\n\n ut = pm.Utterance(\n document=self.doc,\n speaker=speaker,\n speaker_role=speaker_role,\n )\n try:\n ut.agenda_item = tops\n except UnboundLocalError:\n pass\n ut.save()\n\n for c in sp.getchildren():\n # tags: speaker (speaker), paragraph (p), interjection (stage)\n if self.v > 1:\n print(\"{}: {}\".format(c.tag, c.text))\n if c.tag == \"p\":\n if c.text:\n text.append(c.text.strip())\n elif c.tag == \"speaker\":\n if text:\n para = self.create_paragraph(text, ut)\n text = []\n elif c.tag == \"stage\":\n if text:\n para = self.create_paragraph(text, ut)\n text = []\n self.add_interjections(c.text, para)\n else:\n print(\"unknown tag\")\n if text:\n para = self.create_paragraph(text, ut)\n\n\n\n\n\n\n# =================================================================================================================\n\n# main execution script\nif __name__ == '__main__':\n\n sys.stdout = Logger()\n\n single_doc = True\n replace_docs = False\n delete_old = False\n\n delete_all = False\n delete_additional_persons = False\n\n if delete_all:\n print(\"Deleting all documents, utterances, paragraphs and interjections.\")\n pm.Interjection.objects.all().delete()\n pm.Paragraph.objects.all().delete()\n pm.Utterance.objects.all().delete()\n pm.Document.objects.all().delete()\n print(\"Deletion done.\")\n if delete_additional_persons:\n print(\"Deleting all persons added from protocol parsing.\")\n pm.Person.objects.filter(information_source__startswith=\"from protocol scraping\").delete()\n\n if single_doc:\n # single file\n wp = 13\n session = 86\n\n xml_file = os.path.join(tei_path, \"{wp:02d}/BT_{wp:02d}_{sn:03d}.xml\".format(wp=wp, sn=session))\n namespaces = {'tei': 'http://www.tei-c.org/ns/1.0'}\n\n print(\"reading from {}\".format(xml_file))\n\n xtree = etree.parse(xml_file)\n parser = parse_tei_items(xtree)\n\n # pm.Document.objects.filter(parlperiod__n=parser.wp, sitting=parser.session).delete()\n parser.run()\n print(\"Done.\")\n\n exit()\n\n # go through all scripts iteratively\n for pperiod in range(13, 12, -1):\n for session in range(86, 249):\n\n xml_file = os.path.join(tei_path, \"{wp:02d}/BT_{wp:02d}_{sn:03d}.xml\".format(wp=pperiod, sn=session))\n\n if os.path.isfile(xml_file):\n print(\"reading from {}\".format(xml_file))\n\n xtree = etree.parse(xml_file)\n if replace_docs:\n pm.Document.objects.filter(parlperiod__n=pperiod, sitting=session).delete()\n\n if delete_old:\n pm.Document.objects.filter(parlperiod__n=pperiod, sitting=session,\n text_source__startswith=\"GermaParlTEI from \").delete()\n\n parser = parse_tei_items(xtree, period=pperiod, session=session)\n parser.run()\n\n print(\"Done\")\n","sub_path":"scraper/TEI_parser.py","file_name":"TEI_parser.py","file_ext":"py","file_size_in_byte":11327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"17716854","text":"import argcurse\n\nimport pcap_to_hccapx\n\n\narg_handler = argcurse.Handler(\"-h\", \"--help\", using_modes=True)\n\narg_handler.add_mode(\"get-info\", \"Get information about the handshakes inside of the file\")\narg_handler.add_mode(\"make-file\", \"Make a hccapx file from a handshake in a file\")\n\narg_handler.add_flag(\"-o\", \"--output-file\", description=\"Output hccapx file path\", mode=\"make-file\",\n content_help=\"\", has_content=True, default=\"./results.hccapx\")\narg_handler.add_flag(\"-e\", \"--essid\", description=\"ESSID of the ap if it cannot be found\", mode=\"make-file\",\n content_help=\"\", has_content=True, default=\"Found Automatically\")\narg_handler.add_flag(\"-i\", \"--index\", description=\"The index of the handshake, found by using 'get-info'\",\n mode=\"make-file\", content_help=\"\", has_content=True)\n\narg_handler.add_file(file_required=True, mode=\"make-file\")\narg_handler.add_file(file_required=True, mode=\"get-info\")\n\narg_handler.generate_default_message(\"pcap_to_hccapx\")\narg_handler.generate_help_message(\"pcap_to_hccapx\")\n\narg_handler.compile()\n\n\nif arg_handler.results.mode_used == \"get-info\":\n print(f\"Handshake information from: '{arg_handler.results['file'].file_list[0]}'\")\n\n input_file = arg_handler.results[\"file\"].file_list[0]\n\n complete_handshakes, loose_messages = pcap_to_hccapx.get_handshakes(input_file)\n\n essids = pcap_to_hccapx.get_essids(input_file)\n\n if complete_handshakes:\n print(\"\\nComplete Handshakes Found: \")\n for index, complete_handshake in enumerate(complete_handshakes):\n print(f\" Handshake Index: {index}\\n{complete_handshake}\")\n if complete_handshake.ap_mac in essids:\n print(f\" ESSID : '{essids[complete_handshake.ap_mac]}'\\n\\n\")\n else:\n print(\" ESSID : Not Found\\n\\n\")\n\n else:\n print(\"\\nNo Valid Handshakes Found\")\n\n if loose_messages:\n print(f\"\\nEAPOL Messages (No Associated Handshake): \")\n for incomplete_handshake in loose_messages:\n print(f\" Message Number: {incomplete_handshake.message_number}\\n{incomplete_handshake}\\n\")\n\nelse:\n print(f\"Generating hccapx file from: '{arg_handler.results['file'].file_list[0]}'\")\n\n input_file = arg_handler.results[\"file\"].file_list[0]\n if arg_handler.results[\"-o\"].flag_used:\n output_file = arg_handler.results[\"-o\"].flag_content\n else:\n output_file = \"results.hccapx\"\n\n essid = arg_handler.results[\"-e\"].flag_content\n index = arg_handler.results[\"-i\"].flag_content\n\n complete_handshakes, loose_messages = pcap_to_hccapx.get_handshakes(input_file)\n essids = pcap_to_hccapx.get_essids(input_file)\n\n if len(complete_handshakes) == 0:\n print(\"\\nNo Valid Handshakes Found\")\n exit()\n\n elif len(complete_handshakes) > 1:\n if arg_handler.results[\"-i\"].flag_used:\n chosen_handshake = int(arg_handler.results[\"-i\"].flag_content)\n\n else:\n print(\"\\nMultiple Handshakes Found\")\n print(\"Please specify index by running get-info\")\n\n exit()\n\n else:\n chosen_handshake = 0\n\n if not arg_handler.results[\"-e\"].flag_used:\n if complete_handshakes[int(arg_handler.results[\"-i\"].flag_content)].ap_mac not in essids:\n print(\"\\nNo ESSID was found\")\n print(\"Please specify using -e\")\n else:\n essid = essids[complete_handshakes[chosen_handshake].ap_mac]\n\n hccapx_file_content = complete_handshakes[chosen_handshake].create_file(essid)\n\n print(f\"Writing file content to: '{output_file}'\")\n\n print()\n\n with open(output_file, \"wb\") as hccapx_file:\n hccapx_file.write(hccapx_file_content)\n","sub_path":"pcap_to_hccapx/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":3774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"641983745","text":"# -- coding = 'utf-8' -- \n# Author Kylin\n# Python Version 3.7.3\n# OS macOS\n\"\"\"\nNo.138 复制带随机指针的链表\n需求:\n · 给你一个长度为n的链表,每个节点包含一个额外增加的随机指针random,该指针可以指向链表中的任何节点或空节点。\n · 构造这个链表的深拷贝。 \n 深拷贝应该正好由n个全新节点组成,其中每个新节点的值都设为其对应的原节点的值。\n 新节点的next指针和random指针也都应指向复制链表中的新节点,并使原链表和复制链表中的这些指针能够表示相同的链表状态。\n 复制链表中的指针都不应指向原链表中的节点。\n · 返回复制链表的头节点。\n · 用一个由 n 个节点组成的链表来表示输入/输出中的链表。\n 每个节点用一个 [val, random_index] 表示\n (1)val:一个表示Node.val的整数。\n (2)random_index:随机指针指向的节点索引(范围从 0 到 n-1);如果不指向任何节点,则为null。\n注意:\n · 0 <= n <= 1000\n\"\"\"\n\n\ndef copyRandomList(head):\n \"\"\"\n 遍历链表节点,同时注意节点两个指针的链接~\n 可以考虑使用哈希表,存储新旧节点的地址{原节点:新节点}\n 时间复杂度:O(n)\n 空间复杂度:O(n)\n :type head: Node\n :rtype: Node\n \"\"\"\n if not head:\n return None\n\n # 用于存储拷贝前后地址的对应情况\n node_dict = dict()\n\n cur = head\n # 拷贝\n while cur:\n # 深拷贝,需要创建一个新节点\n new_node = Node(cur.val, None, None)\n node_dict[cur] = new_node\n cur = cur.next\n\n # 连接\n cur = head\n while cur:\n if cur.next:\n node_dict[cur].next = node_dict[cur.next]\n if cur.random:\n node_dict[cur].random = node_dict[cur.random]\n\n cur = cur.next\n\n # 返回新的head节点的地址\n return node_dict[head]\n\n","sub_path":"LeetCode/src/dataframe09/linkedList/copy_randomList.py","file_name":"copy_randomList.py","file_ext":"py","file_size_in_byte":2001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"399068220","text":"from django.http import HttpResponse\r\nfrom django.shortcuts import render\r\nfrom .models import Profile, Relationship\r\nfrom .forms import ProfileForm\r\nfrom django.shortcuts import render, get_object_or_404\r\n\r\n\r\n# Create your views here.\r\n\r\ndef profile_view(request):\r\n data = get_object_or_404(Profile, username=request.user)\r\n context = {\r\n 'username': data.username,\r\n 'fullname': data.full_name,\r\n }\r\n return render(request, 'profile.html', context)\r\n\r\n\r\ndef profile_view_by_id(request, usr_id):\r\n data = get_object_or_404(Profile, id=usr_id)\r\n context = {\r\n 'username': data.username,\r\n 'fullname': data.full_name,\r\n }\r\n return render(request, 'profile_id.html', context)\r\n # return HttpResponse(context['username']+context['fullname'])\r\n\r\n\r\ndef profile_edit(request):\r\n if request.method == 'POST':\r\n form = ProfileForm(request.POST)\r\n if form.is_valid():\r\n form.save()\r\n return HttpResponse('successful')\r\n else:\r\n context = {\r\n 'errors': form.errors\r\n }\r\n return render(request, 'profile_edit.html', context)\r\n else:\r\n form = ProfileForm()\r\n return render(request, 'profile_edit.html', {'form': form})\r\n","sub_path":"SocialNetworkBook/user/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"255449074","text":"import cv2\r\nimport numpy as np\r\n\r\nvideo_path = 'video/bts_video.mp4'\r\ncap = cv2.VideoCapture(video_path)\r\n\r\ndef setOutput(width, height):\r\n output_size = (width, height)\r\n return output_size\r\n\r\ndef writeVideo(output_size):\r\n fourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v')\r\n out = cv2.VideoWriter('%s_output.mp4' % (video_path.split('.')[0]), fourcc, cap.get(cv2.CAP_PROP_FPS), output_size)\r\n return out\r\n\r\n#set size (w, h)\r\n#output_size = (375, 667)\r\n#output_size = (185, 333)\r\n\r\n#write video initialize\r\n#fourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v')\r\n#out = cv2.VideoWriter('result/%s_output.mp4'%(video_path.split('.')[0]), fourcc, cap.get(cv2.CAP_PROP_FPS), output_size)\r\n\r\nif not cap.isOpened():\r\n exit()\r\n\r\ntracker = cv2.TrackerCSRT_create()\r\n\r\nret, img = cap.read()\r\n\r\ncv2.namedWindow('Selected Window')\r\ncv2.imshow('Selected Window', img)\r\n\r\n#ROI\r\nrect = cv2.selectROI('Selected Window', img, fromCenter=False, showCrosshair=True)\r\ncv2.destroyWindow('Selected Window')\r\n\r\n#initialize ROI\r\ntracker.init(img, rect)\r\n\r\nwhile True:\r\n ret, img = cap.read()\r\n\r\n #if not ret:\r\n # exit()\r\n\r\n success, box = tracker.update(img)\r\n l, r, w, h = [int(v) for v in box]\r\n\r\n center_x = l + w / 2\r\n center_y = r + h / 2\r\n\r\n\r\n #calculate result box's size\r\n res_t = int(center_y - output_size[1] / 2)\r\n res_b = int(center_y + output_size[1] / 2)\r\n res_l = int(center_x - output_size[0] / 2)\r\n res_r = int(center_x + output_size[0] / 2)\r\n\r\n res_img = img[res_t:res_b, res_l:res_r]#.copy()\r\n #out.write(res_img)\r\n\r\n cv2.rectangle(img, pt1=(l, r), pt2=(l+w, r+h), color=(255, 255, 255), thickness=3)\r\n\r\n\r\n cv2.imshow('res_img', res_img)\r\n cv2.imshow('img', img)\r\n if cv2.waitKey(60) == ord('q'):\r\n break","sub_path":"bts_project/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"622991223","text":"\"\"\" Tests for data_collection \"\"\"\nimport pytest\nfrom mock import MagicMock, patch\nfrom pathlib import Path\nimport pandas as pd\nfrom io import StringIO, BytesIO\n\nfrom wetterdienst.dwd.observations.access import (\n collect_climate_observations_data,\n _tidy_up_data,\n)\nfrom wetterdienst.dwd.metadata.parameter import Parameter\nfrom wetterdienst import TimeResolution\nfrom wetterdienst.dwd.metadata.period_type import PeriodType\n\nHERE = Path(__file__).parent\n\n# Set filename for mock\nfilename = \"tageswerte_KL_00001_19370101_19860630_hist.zip\"\n\n# Loading test data\nTEST_FILE = pd.read_json(HERE / \"FIXED_STATIONDATA.JSON\")\n\n# Prepare csv for regular \"downloading\" test\nCSV_FILE = StringIO()\nTEST_FILE.to_csv(CSV_FILE, sep=\";\")\nCSV_FILE.seek(0)\n\n\n@pytest.mark.xfail\n@patch(\n \"wetterdienst.dwd.observations.fileindex.create_file_list_for_climate_observations\",\n MagicMock(return_value=[filename]),\n)\n@patch(\n \"wetterdienst.dwd.observations.access.download_climate_observations_data_parallel\",\n MagicMock(return_value=[(filename, BytesIO(CSV_FILE.read().encode()))]),\n)\ndef test_collect_dwd_data_success():\n \"\"\" Test for data collection \"\"\"\n \"\"\"\n 1. Scenario\n This scenario makes sure we take fresh data and write it to the given folder, thus\n we can run just another test afterwards as no old data is used\n \"\"\"\n assert collect_climate_observations_data(\n station_ids=[1],\n parameter=Parameter.CLIMATE_SUMMARY,\n time_resolution=TimeResolution.DAILY,\n period_type=PeriodType.HISTORICAL,\n prefer_local=False,\n write_file=True,\n tidy_data=False,\n ).equals(TEST_FILE)\n\n \"\"\"\n 2. Scenario\n This scenario tries to get the data from the given folder. This data was placed by\n the first test and is now restored\n \"\"\"\n assert collect_climate_observations_data(\n station_ids=[1],\n parameter=Parameter.CLIMATE_SUMMARY,\n time_resolution=TimeResolution.DAILY,\n period_type=PeriodType.HISTORICAL,\n prefer_local=True,\n write_file=True,\n tidy_data=False,\n ).equals(TEST_FILE)\n\n # Have to place an assert afterwards to ensure that above function is executed.\n # WTF!!!\n # assert True\n\n\n@pytest.mark.xfail\n@patch(\n \"wetterdienst.dwd.observations.store.restore_climate_observations\",\n MagicMock(return_value=pd.DataFrame()),\n)\n@patch(\n \"wetterdienst.dwd.observations.fileindex.create_file_list_for_climate_observations\",\n MagicMock(return_value=[]),\n)\ndef test_collect_dwd_data_empty():\n \"\"\" Test for data collection with no available data \"\"\"\n\n \"\"\"\n 1. Scenario\n Test for request where no data is available\n \"\"\"\n\n assert collect_climate_observations_data(\n station_ids=[1048],\n parameter=Parameter.CLIMATE_SUMMARY,\n time_resolution=TimeResolution.DAILY,\n period_type=PeriodType.RECENT,\n prefer_local=True,\n write_file=False,\n tidy_data=False,\n ).empty\n\n\n@pytest.mark.remote\ndef test_collect_daily_vanilla():\n \"\"\" Test for data collection with real data \"\"\"\n\n data = collect_climate_observations_data(\n station_ids=[1048],\n parameter=Parameter.CLIMATE_SUMMARY,\n time_resolution=TimeResolution.DAILY,\n period_type=PeriodType.RECENT,\n tidy_data=False,\n )\n\n assert list(data.columns.values) == [\n \"STATION_ID\",\n \"DATE\",\n \"QN_3\",\n \"FX\",\n \"FM\",\n \"QN_4\",\n \"RSK\",\n \"RSKF\",\n \"SDK\",\n \"SHK_TAG\",\n \"NM\",\n \"VPM\",\n \"PM\",\n \"TMK\",\n \"UPM\",\n \"TXK\",\n \"TNK\",\n \"TGK\",\n ]\n\n\n@pytest.mark.remote\ndef test_collect_hourly_vanilla():\n \"\"\" Test for data collection with real data \"\"\"\n\n data = collect_climate_observations_data(\n station_ids=[1048],\n parameter=Parameter.TEMPERATURE_AIR,\n time_resolution=TimeResolution.HOURLY,\n period_type=PeriodType.RECENT,\n tidy_data=False,\n )\n\n assert list(data.columns.values) == [\n \"STATION_ID\",\n \"DATE\",\n \"QN_9\",\n \"TT_TU\",\n \"RF_TU\",\n ]\n\n\ndef test_tidy_up_data():\n \"\"\" Test for function to tidy data\"\"\"\n df = pd.DataFrame(\n {\n \"STATION_ID\": [1048],\n \"DATE\": [pd.Timestamp(\"2019-01-23 00:00:00\")],\n \"QN_3\": [10],\n \"FX\": [11.8],\n \"FM\": [5.8],\n \"QN_4\": [3],\n \"RSK\": [0.0],\n \"RSKF\": [0.0],\n \"SDK\": [7.1],\n \"SHK_TAG\": [0.0],\n \"NM\": [2.3],\n \"VPM\": [3.2],\n \"PM\": [975.4],\n \"TMK\": [-5.5],\n \"UPM\": [79.17],\n \"TXK\": [-1.7],\n \"TNK\": [-7.9],\n \"TGK\": [-11.4],\n }\n )\n\n df_tidy = pd.DataFrame(\n {\n \"STATION_ID\": [1048] * 14,\n \"PARAMETER\": [\"CLIMATE_SUMMARY\"] * 14,\n \"ELEMENT\": [\n \"FX\",\n \"FM\",\n \"RSK\",\n \"RSKF\",\n \"SDK\",\n \"SHK_TAG\",\n \"NM\",\n \"VPM\",\n \"PM\",\n \"TMK\",\n \"UPM\",\n \"TXK\",\n \"TNK\",\n \"TGK\",\n ],\n \"DATE\": [pd.Timestamp(\"2019-01-23 00:00:00\")] * 14,\n \"VALUE\": [\n 11.8,\n 5.8,\n 0.0,\n 0.0,\n 7.1,\n 0.0,\n 2.3,\n 3.2,\n 975.4,\n -5.5,\n 79.17,\n -1.7,\n -7.9,\n -11.4,\n ],\n \"QUALITY\": [10, 10, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3],\n }\n )\n\n assert _tidy_up_data(df, Parameter.CLIMATE_SUMMARY).equals(df_tidy)\n","sub_path":"tests/dwd/observations/test_access.py","file_name":"test_access.py","file_ext":"py","file_size_in_byte":5828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"147928092","text":"class TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\n\nclass Solution:\n def isBalanced(self, root: TreeNode) -> bool:\n if not root:\n return True\n\n left_depth = self.getDepth(root.left)\n right_depth = self.getDepth(root.right)\n\n return (\n abs(right_depth - left_depth) <= 1\n and self.isBalanced(root.left)\n and self.isBalanced(root.right)\n )\n\n def getDepth(self, node):\n if node:\n return max(self.getDepth(node.left), self.getDepth(node.right)) + 1\n else:\n return 0\n\n\n# [3,9,20,null,null,15,7]\nroot = TreeNode(3)\nroot.left = TreeNode(9)\nroot.right = TreeNode(20)\nroot.right.left = TreeNode(15)\nroot.right.right = TreeNode(7)\n\nis_balanced = Solution().isBalanced(root)\nprint(is_balanced)\n","sub_path":"Easy/110.py","file_name":"110.py","file_ext":"py","file_size_in_byte":899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"318505350","text":"# -*- coding: utf-8 -*-\n\nimport socket\nimport struct\nimport datetime\nimport ipaddress\nfrom luxtronik.lut import LUT as lut\n\nclass Luxtronik(object):\n\n def __init__(self, host, port):\n self._host = host\n self._port = port\n self._lut = lut\n self._data = {}\n self._socket = None\n\n def __connect(self):\n self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self._socket.connect((self._host,self._port))\n\n def __disconnect(self):\n self._socket.close()\n\n def get_data(self):\n self.__connect()\n self.__read_parameters()\n self.__read_calculations()\n self.__read_visibilities()\n self.__disconnect()\n return self._data\n\n def set_data(self, id, value):\n self.__connect()\n self.__write_parameter(id,value)\n self.__disconnect()\n\n def __read_parameters(self):\n data = []\n self._socket.sendall(struct.pack('>ii',3003,0))\n cmd = struct.unpack('>i',self._socket.recv(4))[0]\n len = struct.unpack('>i',self._socket.recv(4))[0]\n for i in range(0,len):\n data.append(struct.unpack('>i',self._socket.recv(4))[0])\n self.__parse(data, \"parameters\")\n\n def __write_parameter(self, id, value):\n (i, raw) = self.__compose(id, value, \"parameters\")\n self._socket.sendall(struct.pack('>iii',3002,i,raw))\n cmd = struct.unpack('>i',self._socket.recv(4))[0]\n ret = struct.unpack('>i',self._socket.recv(4))[0]\n assert(cmd == 3002 and ret == i)\n\n def __read_calculations(self):\n data = []\n self._socket.sendall(struct.pack('>ii',3004,0))\n cmd = struct.unpack('>i',self._socket.recv(4))[0]\n stat = struct.unpack('>i',self._socket.recv(4))[0]\n len = struct.unpack('>i',self._socket.recv(4))[0]\n for i in range(0,len):\n data.append(struct.unpack('>i',self._socket.recv(4))[0])\n self.__parse(data, \"calculations\")\n\n def __read_visibilities(self):\n data = []\n self._socket.sendall(struct.pack('>ii',3005,0))\n cmd = struct.unpack('>i',self._socket.recv(4))[0]\n len = struct.unpack('>i',self._socket.recv(4))[0]\n for i in range(0,len):\n data.append(struct.unpack('>b',self._socket.recv(1))[0])\n self.__parse(data, \"visibilities\")\n\n def __parse(self, data, target):\n if not target in self._data:\n self._data[target] = {}\n for i in range(0, len(data)):\n l = self._lut[target].get(i)\n raw = data[i]\n if not l:\n self._data[target][i] = {\"id\":None, \"unit\":\"unknown\", \"value\":raw}\n continue\n if isinstance(l[\"conversion\"], dict):\n self._data[target][i] = {\"id\":l[\"id\"], \"unit\":\"info\", \"value\":l[\"conversion\"].get(raw, raw)}\n else:\n if l[\"conversion\"] == \"celsius\":\n self._data[target][i] = {\"id\":l[\"id\"], \"unit\":\"celsius\", \"value\":raw/10}\n elif l[\"conversion\"] == \"bool\":\n self._data[target][i] = {\"id\":l[\"id\"], \"unit\":\"bool\", \"value\":bool(raw)}\n elif l[\"conversion\"] == \"seconds\":\n self._data[target][i] = {\"id\":l[\"id\"], \"unit\":\"seconds\", \"value\":raw}\n elif l[\"conversion\"] == \"pulses\":\n self._data[target][i] = {\"id\":l[\"id\"], \"unit\":\"pulses\", \"value\":raw}\n elif l[\"conversion\"] == \"ipaddress\":\n self._data[target][i] = {\"id\":l[\"id\"], \"unit\":\"ipaddress\", \"value\":f\"{raw >> 24 & 0xFF}.{raw >> 16 & 0xFF}.{raw >> 8 & 0xFF}.{raw & 0xFF}\"}\n elif l[\"conversion\"] == \"timestamp\":\n self._data[target][i] = {\"id\":l[\"id\"], \"unit\":\"datetime\", \"value\": datetime.datetime.fromtimestamp(raw)} \n elif l[\"conversion\"] == \"errorcode\":\n self._data[target][i] = {\"id\":l[\"id\"], \"unit\":\"errorcode\", \"value\":raw} \n elif l[\"conversion\"] == \"kelvin\":\n self._data[target][i] = {\"id\":l[\"id\"], \"unit\":\"kelvin\", \"value\":raw/10}\n elif l[\"conversion\"] == \"pressure\":\n self._data[target][i] = {\"id\":l[\"id\"], \"unit\":\"bar\", \"value\":raw/100}\n elif l[\"conversion\"] == \"percent\":\n self._data[target][i] = {\"id\":l[\"id\"], \"unit\":\"percent\", \"value\":raw/10}\n elif l[\"conversion\"] == \"speed\":\n self._data[target][i] = {\"id\":l[\"id\"], \"unit\":\"rpm\", \"value\":raw}\n elif l[\"conversion\"] == \"kwh\":\n self._data[target][i] = {\"id\":l[\"id\"], \"unit\":\"kWh\", \"value\":raw/10}\n elif l[\"conversion\"] == \"voltage\":\n self._data[target][i] = {\"id\":l[\"id\"], \"unit\":\"volt\", \"value\":raw/10}\n elif l[\"conversion\"] == \"version\":\n self._data[target][i] = {\"id\":l[\"id\"], \"unit\":\"version\", \"value\":\"\".join([chr(c) for c in data[i:i+9]]).strip('\\x00')}\n else:\n self._data[target][i] = {\"id\":l[\"id\"], \"unit\":\"unknown\", \"value\":raw}\n\n def __compose(self, id, value, target):\n for (i, item) in self._lut[target].items():\n if item[\"id\"] == id:\n if item[\"conversion\"] in [\"celsius\", \"kelvin\", \"percent\", \"kWh\", \"volt\"]:\n raw = int(value * 10)\n elif item[\"conversion\"] in [\"bar\"]:\n raw = int(value * 100)\n elif item[\"conversion\"] == \"ipaddress\":\n raw = struct.unpack('>i',ipaddress.ip_address(value).packed)[0]\n elif item[\"conversion\"] == \"datetime\":\n raw = int(datetime.datetime.timestamp(value))\n else:\n assert(item[\"conversion\"] not in [\"version\"])\n raw = int(value)\n if \"writable\" not in item:\n raise ValueError(\n \"Writing value for '%s' not not yet tested. If you are sure to write value %d for ID %d, \" % (id, raw, i) +\n \"please add 'writable':True to the corresponding dictionary in the lut.py file. \" +\n \"Please contribute to this project whether writing was successful or not by setting 'writable' explicitly to \" +\n \"True or False. Thanks!\")\n if not item[\"writable\"]:\n raise ValueError(\"Value not writable.\")\n return (i, raw)\n else:\n raise ValueError(\"Invalid id string.\")\n\n\n","sub_path":"luxtronik/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":6563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"535326206","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Nov 2 14:34:37 2017\n\n@author: yume\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport unittest\nimport factors\n\n\nclass TestAcceleration(unittest.TestCase):\n def setUp(self):\n self.factor = factors.Acceleration(a=0.45, b=1.00, c=0.0, d_t=0.1)\n\n def check_acceleration(self, prev_p, p, next_p, d_t, expected):\n prev_p = np.array(prev_p)\n p = np.array(p)\n next_p = np.array(next_p)\n actual = self.factor.acceleration(prev_p, p, next_p, d_t)\n np.testing.assert_allclose(expected, actual)\n\n def test_acceleration(self):\n# 正常系\n self.check_acceleration([1, 1], [2, 2], [4, 4], 0.1, np.sqrt(2)/0.1)\n# 異常系\n# 三点が同じとき\n self.check_acceleration([1, 1], [1, 1], [1, 1], 0.1, 0)\n# 一直線上に三点が並ぶとき\n self.check_acceleration([1, 1], [2, 1], [3, 1], 0.1, 0)\n self.check_acceleration([1, 1], [1, 2], [1, 3], 0.1, 0)\n\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"test_acceleration.py","file_name":"test_acceleration.py","file_ext":"py","file_size_in_byte":1055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"228478252","text":"import pytest\nimport glob\nimport logging\nimport os\nimport shutil\nimport signal\nimport subprocess\nimport sys\nimport tempfile\nimport time\n\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.common.by import By\nfrom selenium.common.exceptions import TimeoutException\nfrom selenium.webdriver.support.ui import WebDriverWait as Wait\nfrom selenium.webdriver.support import expected_conditions as EC\n\n\n@pytest.fixture(scope=\"module\")\ndef jupyter_root_dir(tmpdir_factory):\n return tmpdir_factory.mktemp('nbsg')\n\n\n@pytest.fixture(scope=\"module\")\ndef jupyter_config_dir(tmpdir_factory):\n return tmpdir_factory.mktemp('jupyter_config')\n\n\n@pytest.fixture(scope=\"module\")\ndef jupyter_data_dir(tmpdir_factory):\n return tmpdir_factory.mktemp('jupyter_data')\n\n\ndef stop_server(server):\n if sys.platform == 'win32':\n server.send_signal(signal.CTRL_BREAK_EVENT)\n time.sleep(1)\n else:\n server.terminate()\n\n\n@pytest.fixture(scope=\"module\")\ndef server(request, jupyter_root_dir, jupyter_config_dir, jupyter_data_dir):\n # create the test environment\n env = os.environ.copy()\n env['HOME'] = str(jupyter_root_dir)\n env['JUPYTER_CONFIG_DIR'] = str(jupyter_config_dir)\n env['JUPYTER_DATA_DIR'] = str(jupyter_data_dir)\n\n # store keyword arguments\n kwargs = dict(env=env, stderr=subprocess.DEVNULL)\n python = sys.executable\n\n # install and enable the extension\n project_root_dir = os.path.dirname(os.path.dirname(__file__))\n extension_dir = os.path.join(project_root_dir, 'nbsimplegrader')\n entry_point = 'nbsimplegrader/authoring_tools/main'\n subprocess.call([python, '-m', 'jupyter', 'nbextension', 'install', '--user', extension_dir], **kwargs)\n subprocess.call([python, '-m', 'jupyter', 'nbextension', 'enable', '--user', entry_point], **kwargs)\n\n # start the server\n if sys.platform == 'win32':\n kwargs['creationflags'] = subprocess.CREATE_NEW_PROCESS_GROUP\n\n server = subprocess.Popen([\n python, '-m', 'jupyter', 'notebook',\n '--no-browser',\n '--port=8888',\n '--NotebookApp.token=\"\"',\n '--log-level=DEBUG'],\n **kwargs)\n time.sleep(5)\n\n request.addfinalizer(lambda: stop_server(server))\n return server\n\n\n@pytest.fixture(scope=\"module\")\ndef browser(request, jupyter_root_dir, server):\n test_dir = os.path.dirname(__file__)\n\n # copy test notebooks to temp directory\n test_nb_pattern = os.path.join(test_dir, 'test_notebooks', '*.ipynb')\n for old_path in glob.glob(test_nb_pattern):\n new_path = jupyter_root_dir.join(os.path.basename(old_path))\n shutil.copy(old_path, str(new_path))\n\n # set logging options\n selenium_logger = logging.getLogger('selenium.webdriver.remote.remote_connection')\n selenium_logger.setLevel(logging.WARNING)\n\n # download the chrome driver from https://sites.google.com/a/chromium.org/chromedriver/downloads\n # put it in the current directory\n chrome_driver = os.path.join(os.path.dirname(__file__), 'chromedriver.exe')\n\n # set browser options\n chrome_options = Options()\n # chrome_options.add_argument('-headless')\n chrome_options.add_argument(\"--window-size=1920x1080\")\n\n # build and return the browser\n browser = webdriver.Chrome(\n executable_path=chrome_driver,\n options=chrome_options,\n service_log_path=os.path.devnull)\n browser.set_page_load_timeout(30)\n browser.set_script_timeout(30)\n\n request.addfinalizer(lambda: browser.quit())\n return browser\n\n\ndef load_notebook(browser, name):\n browser.get(f'http://localhost:8888/notebooks/test_notebooks/{name}.ipynb')\n\n # wait for the page to load\n def page_loaded(driver):\n return driver.execute_script(f'''\n return typeof Jupyter !== \"undefined\" \n && Jupyter.page !== undefined \n && Jupyter.notebook !== undefined \n && $(\"#notebook_name\").text() === \"{name}\" \n && Jupyter.notebook._fully_loaded;\n ''')\n\n return Wait(browser, 20).until(page_loaded)\n \n\n# def activate_tools(browser):\n# def tool_toggle_exists():\n# return browser.execute_script(f'''\n# return typeof $ !== \"undefined\" && $ !== undefined\n# && $('#view_menu #menu-cell-toolbar').find('[data-name=\"nbsimplegrader\"]').length == 1;\n# ''')\n#\n# Wait(browser, 20).until(tool_toggle_exists)\n# browser.execute_script(f'''\n# $('#view_menu #menu-cell-toolbar')\n# .find('[data-name=\"nbsimplegrader\"]')\n# .find('a')\n# .click();\n# ''')\n#\n# Wait(browser, 20).until(\n# EC.presence_of_all_elements_located(By.CSS_SELECTOR, \".celltoolbar select\")\n# )\n\n\ndef test_extension_loads(browser):\n load_notebook(browser, 'empty')\n Wait(browser, 20).until(EC.presence_of_element_located((By.ID, 'ipython_notebook')))\n assert EC.presence_of_element_located((By.ID, 'nbsg-logo-mini'))\n\n\ndef test_students_have_no_authoring_tools(browser):\n load_notebook(browser, 'empty')\n time.sleep(20)\n\n","sub_path":"tests/test_authoring.py","file_name":"test_authoring.py","file_ext":"py","file_size_in_byte":5100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"103176125","text":"# from bayes_opt import BayesianOptimization\n# from bayes_opt.observer import JSONLogger\n# from bayes_opt.event import Events\n# from bayes_opt.util import load_logs\n\nimport os,sys,csv,time,random,torch,threading,argparse\nfrom multiprocessing import Pool\nimport numpy as np\nimport torch.nn as nn\nfrom torchvision import datasets, transforms\nimport evaluate\n# from utils import *\nimport utils,ratio\nfrom train2 import parse_args,initialize_model,load_data,create_optimizer,train_model\nimport pandas as pd\nfrom PIL import Image\nfrom PIL import ImageFile\nImageFile.LOAD_TRUNCATED_IMAGES = True\n\ndef get_size(start_path):\n total_size = []\n for dirpath, dirnames, filenames in os.walk(start_path):\n for f in filenames:\n fp = os.path.join(dirpath, f)\n # skip if it is symbolic link\n if not os.path.islink(fp):\n total_size.append(os.path.getsize(fp))\n total_size = np.array(total_size)\n \n # return total_size.mean(),total_size.std()\n return total_size\n\n\ndata_t = transforms.Compose([transforms.Resize(256),transforms.CenterCrop(224)])\ndef to_bmp(in_root, in_dirs, file_list, out_dir, limit=300):\n pool = Pool(5)\n def xform(args):\n in_root,dir_in,file_in,file_out = args\n try:\n data_t(Image.open(\n os.path.join(in_root,dir_in,file_in)\n )).convert('RGB').save(file_out)\n except OSError as e:\n print(e)\n arg_list = []\n for dir_in in in_dirs:\n temp_path = os.path.join(out_dir,dir_in)\n if not os.path.exists(temp_path) and os.path.isdir(os.path.join(in_root,dir_in)):\n os.makedirs(temp_path)\n if dir_in in file_list:\n count = 0\n for file_in in file_list[dir_in]:\n count += 1\n if count>limit:\n break\n out_name = file_in.split('.')[0]+'.bmp'\n file_out = os.path.join(temp_path,out_name)\n if not os.path.isfile(file_out):\n # print(file_in, file_out)\n # xform(in_root,dir_in,file_in,file_out)\n arg_list.append((in_root,dir_in,file_in,file_out))\n # print(temp_path, count)\n pool.map(xform, arg_list)\n\n\n\ndef compress(dir_list,file_list,cmp_dir,uncmp_root,tmp_qtable,limit=10):\n for dir_in in dir_list:\n if dir_in not in file_list:\n continue\n create_dir(os.path.join(cmp_dir,dir_in))\n count = 0\n for file_in in file_list[dir_in]:\n count += 1\n if count>limit:\n break\n file_out = os.path.join(cmp_dir,dir_in,file_in.replace('bmp','jpg'))\n # print(file_in,file_out)\n if not os.path.isfile(file_out) or os.path.getsize(file_out)==0:\n execute = \"~/libjpeg/cjpeg -outfile \"+file_out+\" -quality 50 -qtable \"+tmp_qtable+\" -qslots 0 \"+os.path.join(uncmp_root,dir_in,file_in)\n os.system(execute)\n\n\ndef compress_quality(quality, dir_list, file_list, cmp_dir, uncmp_root,limit=10):\n for dir_in in dir_list:\n if dir_in not in file_list:\n continue\n create_dir(os.path.join(cmp_dir,dir_in))\n count = 0\n for file_in in file_list[dir_in]:\n count += 1\n if count>limit:\n break\n file_out = os.path.join(cmp_dir,dir_in,file_in.replace('bmp','jpg'))\n if not os.path.isfile(file_out) or os.path.getsize(file_out)==0:\n execute = \"~/libjpeg/cjpeg -outfile \"+file_out+\" -quality \"+quality+\" \"+os.path.join(uncmp_root,dir_in,file_in)\n os.system(execute)\n\ndef create_dir(n):\n if not os.path.exists(n):\n os.makedirs(n)\n\n\ndef run(args):\n ind,logs = args\n start = time.time()\n qtable_file=os.path.join(qtable_dir, 'qtable'+str(ind)+'.txt')\n\n ### compress train dataset\n if retrain:\n logs += 'Compressing train set...\\n'\n cmp_dir_train = os.path.join(optimize_root, 'train/qtable_'+str(ind))\n create_dir(cmp_dir_train)\n ts = []\n for j,k in enumerate(range(0,len(dir_list_train),partition)):\n ts.append(threading.Thread(target=compress,args=(dir_list_train[k:k+partition],file_list_train,cmp_dir_train,uncmp_root_train,qtable_file,img_per_cls_train)))\n ts[j].start()\n for t in ts:\n t.join()\n cmp_size = get_size(cmp_dir_train)\n cmp_mean,cmp_std = cmp_size.mean(), cmp_size.std()\n rate = uncmp_mean_train/cmp_mean\n logs += '--train cr: {}({}/{})'.format(rate, uncmp_mean_train, cmp_mean)\n\n ### compress val dataset\n logs += 'Compressing val set...\\n'\n cmp_dir = os.path.join(optimize_root, 'val/qtable_'+str(ind))\n create_dir(cmp_dir)\n # compress(dir_list,file_list,cmp_dir,uncmp_root,qtable_file)\n # raise Exception('fsfsfs')\n\n ts = []\n for j,k in enumerate(range(0,len(dir_list),partition)):\n ts.append(threading.Thread(target=compress,args=(dir_list[k:k+partition],file_list,cmp_dir,uncmp_root,qtable_file,img_per_cls))) \n ts[j].start()\n for t in ts:\n t.join()\n cmp_size = get_size(cmp_dir)\n cmp_mean,cmp_std = cmp_size.mean(), cmp_size.std()\n rate = uncmp_mean/cmp_mean\n logs += '--val cr: {}({}/{})'.format(rate, uncmp_mean, cmp_mean)\n\n ### retraining\n if retrain:\n train_args = [\n '--model_name','resnet',\n '--data_dir',cmp_dir_train,\n '--batch_size','64',\n '--num_classes','1000',\n '--val_name',cmp_dir,\n '--num_epochs','10',\n ]\n acc1,acc5 = run_train(train_args)\n else:\n ### evaluate model\n logs += 'Evaluating...\\n'\n sys.argv = ['skip','--dataset']\n acc1,acc5 = evaluate.run(sys.argv.append(cmp_dir))\n\n fitness = utils.diff_fit(acc1,rate)\n logs += '--acc1:{}, acc5:{}, fitness:{}\\n'.format(acc1,acc5,fitness)\n row = [ind, acc1,acc5,rate,qtable_file]\n utils.store_csv_check(row,csv_name,['ind','acc1','acc5','rate','qname'])\n _elapse = time.time() - start\n logs += 'Time: {:.1f}h\\n'.format(_elapse/3600)\n print(logs)\n\ndef run_standard(args):\n ind,logs = args\n start = time.time()\n \n ### compress train dataset\n if retrain:\n logs += 'Compressing train set...\\n'\n cmp_dir_train = os.path.join(optimize_root, 'train/qtable_'+str(ind))\n create_dir(cmp_dir_train)\n ts = []\n for j,k in enumerate(range(0,len(dir_list_train),partition)):\n ts.append(threading.Thread(target=compress_quality,args=(str(ind),dir_list_train[k:k+partition],file_list_train,cmp_dir_train,uncmp_root_train,img_per_cls_train)))\n ts[j].start()\n for t in ts:\n t.join()\n cmp_size = get_size(cmp_dir_train)\n cmp_mean,cmp_std = cmp_size.mean(), cmp_size.std()\n rate = uncmp_mean_train/cmp_mean\n logs += '--train cr: {}({}/{})'.format(rate, uncmp_mean_train, cmp_mean)\n\n ### compress val dataset\n logs += 'Compressing val set...\\n'\n cmp_dir = os.path.join(optimize_root, 'val/qtable_'+str(ind))\n create_dir(cmp_dir)\n ts = []\n for j,k in enumerate(range(0,len(dir_list),partition)):\n ts.append( threading.Thread(target=compress_quality,args=(str(ind),dir_list[k:k+partition],file_list,cmp_dir,uncmp_root,img_per_cls))) \n ts[j].start()\n for t in ts:\n t.join()\n cmp_size = get_size(cmp_dir)\n cmp_mean,cmp_std = cmp_size.mean(), cmp_size.std()\n rate = uncmp_mean/cmp_mean\n logs += '--val cr: {}({}/{})'.format(rate, uncmp_mean, cmp_mean)\n\n ### retraining\n if retrain:\n train_args = [\n '--model_name','resnet',\n '--data_dir',cmp_dir_train,\n '--batch_size','64',\n '--num_classes','1000',\n '--val_name',cmp_dir,\n '--num_epochs','10',\n ]\n acc1,acc5 = run_train(train_args)\n else:\n ### evaluate model\n logs += 'Evaluating...\\n'\n sys.argv = ['skip','--dataset']\n acc1,acc5 = evaluate.run(sys.argv.append(cmp_dir))\n\n fitness = utils.diff_fit(acc1,rate)\n logs += '--acc1:{}, acc5:{}, fitness:{}\\n'.format(acc1,acc5,fitness)\n row = [ind, acc1,acc5,rate,ind]\n utils.store_csv_check(row,csv_name,['ind','acc1','acc5','rate','quality'])\n _elapse = time.time() - start\n logs += 'Time: {:.1f}h\\n'.format(_elapse/3600)\n # break\n print(logs)\n\n\ndef identify_pareto(source=\"sorted.csv\", dest='pareto'):\n df = pd.read_csv(source)\n scores=np.array((df['rate'],df['acc1']))\n scores=np.swapaxes(scores,0,1)\n\n # Count number of items\n population_size = scores.shape[0]\n # Create a NumPy index for scores on the pareto front (zero indexed)\n population_ids = np.arange(population_size)\n # Create a starting list of items on the Pareto front\n # All items start off as being labelled as on the Parteo front\n pareto_front = np.ones(population_size, dtype=bool)\n # Loop through each item. This will then be compared with all other items\n for i in range(population_size):\n # Loop through all other items\n for j in range(population_size):\n # Check if our 'i' pint is dominated by out 'j' point\n if all(scores[j] >= scores[i]) and any(scores[j] > scores[i]):\n # j dominates i. Label 'i' point as not on Pareto front\n pareto_front[i] = 0\n # Stop further comparisons with 'i' (no more comparisons needed)\n break\n # Return ids of scenarios on pareto front\n np.save(dest,population_ids[pareto_front])\n return population_ids[pareto_front]\n\n\ndef run_train(args):\n args = parse_args(args)\n args.device = torch.device(\"cuda:{}\".format(gpu_id) if torch.cuda.is_available() else \"cpu\")\n model_ft, input_size = initialize_model(args,use_pretrained=True)\n image_datasets, dataloaders_dict = load_data(args, input_size) \n \n optimizer_ft = create_optimizer(args, model_ft)\n criterion = nn.CrossEntropyLoss()\n # Train and evaluate\n model_ft, hist = train_model( args=args, model=model_ft, dataloaders=dataloaders_dict, criterion=criterion, optimizer=optimizer_ft, is_inception=(args.model_name==\"inception\") )\n #torch.save(model_ft.state_dict(), os.path.join(args.dir,\"verification.final\"))\n best_acc = (0,0)\n for acc1,acc5 in hist:\n if acc1>best_acc[0]:\n best_acc = (acc1,acc5)\n return best_acc\n\n\n# ### convert jpeg images to bmp\n# dir_list = os.listdir('/data/ILSVRC2012/train_bmp300')\n# file_list = {}\n# for x in dir_list:\n# temp_dir = os.path.join('/data/ILSVRC2012/train_bmp300',x)\n# if os.path.isdir(temp_dir):\n# file_list[x] = os.listdir(temp_dir)\n# to_bmp('/data/ILSVRC2012/train_bmp300', dir_list, file_list, '/data/ILSVRC2012/train_bmp300_resize224')\n# raise Exception('to_bmp')\n\ngpu_id = 0\nretrain = True\nsuffix = 'standard' # standard,sorted,bayesian5,bound,mab\nimg_per_cls_train = 100\nimg_per_cls = 10\nsubproc,procs = 0,1 # 0,1,2,3\nuncmp_root = '/data/ILSVRC2012/val_bmp_resize224'\nuncmp_root_train = '/data/ILSVRC2012/train_bmp300_resize224'\n\n\n\ncsv_name = 'csv/crossval_imagenet_{}.csv'.format(suffix+'_retrain' if retrain else suffix)\noptimize_root = '/data/zh272/temp/{}/'.format(suffix)\nif suffix == 'mab':\n metrics_file = 'csv/mab_bounded.csv'\nelse:\n metrics_file = \"csv/{}.csv\".format(suffix)\n\nif suffix == 'sorted':\n qtable_dir = '/data/zh272/flickrImageNetV2/sorted_cache/qtables/'\n pareto_file = 'pareto1000'\nelif suffix == 'bayesian5':\n qtable_dir = '/data/zh272/flickrImageNetV2/bo_chace/qtables5/'\n pareto_file = 'pareto_bayesian'\nelif suffix == 'bound':\n qtable_dir = '/data/zh272/flickrImageNetV2/bound_cache/qtables/'\n pareto_file = 'pareto_bound'\nelif suffix == 'mab':\n qtable_dir = '/data/zh272/flickrImageNetV2/mab_cache/qtables/'\n pareto_file = 'pareto_mab'\n # df = pd.read_csv('csv/mab_bounded_qtable.csv')\n # for index in range(len(df)):\n # qtable = np.array([df['q'+str(i).zfill(2)][index] for i in range(64)]).reshape((8,8))\n # ratio.write_qtable(qtable,qname=os.path.join(qtable_dir, 'qtable'+str(index)+'.txt'))\nelif suffix == 'standard':\n pass\nelse:\n raise Exception('not finished')\n\nos.environ['CUDA_VISIBLE_DEVICES'] = str(gpu_id)\ncreate_dir(optimize_root)\nif suffix not in ['standard','mab']:\n create_dir(qtable_dir)\ndf = pd.read_csv(metrics_file)\n# uncmp_mean,uncmp_std = 687300.03404, 1118486.0851240403\n# uncmp_mean_train,uncmp_std_train = 662408.8940933333, 1233251.0965360408\nuncmp_mean,uncmp_std = 150582.0, 0.0\nuncmp_mean_train,uncmp_std_train = 150582.0, 0.0\n\n# uncmp_size = get_size(uncmp_root)\n# uncmp_mean,uncmp_std = uncmp_size.mean(), uncmp_size.std()\n# print('val',uncmp_mean,uncmp_std)\n# uncmp_size_train = get_size(uncmp_root_train)\n# uncmp_mean_train,uncmp_std_train = uncmp_size_train.mean(), uncmp_size_train.std()\n# print('train',uncmp_mean_train,uncmp_std_train)\n# raise Exception('umcmp_size')\n\ndir_list_train = os.listdir(uncmp_root_train)\nfile_list_train = {}\nfor x in dir_list_train:\n temp_dir = os.path.join(uncmp_root_train,x)\n if os.path.isdir(temp_dir):\n file_list_train[x] = os.listdir(temp_dir)\n\ndir_list = os.listdir(uncmp_root)\nfile_list = {}\nfor x in dir_list:\n temp_dir = os.path.join(uncmp_root,x)\n if os.path.isdir(temp_dir):\n file_list[x] = os.listdir(temp_dir)\n \nhist = set()\nif os.path.isfile(csv_name):\n with open(csv_name) as csvfile:\n reader = csv.reader(csvfile)\n for row in reader:\n if 'ind' in row:\n continue\n hist.add(int(row[0]))\n\n\npartition = int(len(dir_list)/20)#20\narg_list = []\n\nif suffix == 'standard':\n ### For standard JPEG table with different quality\n for ind,qua in enumerate(range(5,101,5)):\n if df['rate'][ind]>20 and df['rate'][ind]<24:\n logs = 'Cross-validating quality: {} (CR:{},acc1:{})\\n'.format(qua, df['rate'][ind], df['acc1'][ind])\n run_standard((qua,logs))\n\nelse:\n ### For customized JPEG tables\n if os.path.exists(pareto_file+'.npy'):\n indexs = np.load(pareto_file+'.npy')\n else:\n indexs = identify_pareto(source=metrics_file, dest=pareto_file)\n # pool = Pool(4)\n # indexs = np.random.choice(indexs,size=5,replace=False)\n\n st_rate = 22.107518218126575\n rates = np.abs(np.array(df['rate'][indexs]) - st_rate)\n ri = np.array([(rates[i], indexs[i]) for i in range(len(rates))], dtype=[('x', float), ('y', int)])\n ri.sort(order='x')\n # length = len(indexs)//procs\n # for ind in indexs[subproc*length:min((subproc+1)*length, len(indexs))]:\n for rate, ind in ri[:2]:\n # if df['rate'][ind] > 20 and df['rate'][ind] < 30 and ind not in hist:\n if ind not in hist:\n logs = 'Cross-validating q-table: {} (CR:{},acc1:{})\\n'.format(ind, df['rate'][ind], df['acc1'][ind])\n run((ind, logs))\n # arg_list.append((ind, logs))\n # pool.map(run, arg_list)","sub_path":"jpeg_eval/crossval_imagenet.py","file_name":"crossval_imagenet.py","file_ext":"py","file_size_in_byte":15008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"279924298","text":"## @file nn_prep.py\n# Helper routines for ANN integration\n# \n# Written by JP Janet for HJK Group\n# \n# Dpt of Chemical Engineering, MIT\n\nfrom molSimplify.Scripts.geometry import *\nfrom molSimplify.Scripts.io import *\nfrom molSimplify.Scripts.nn_prep import spin_classify\nfrom molSimplify.Informatics.decoration_manager import*\nfrom molSimplify.Classes.globalvars import *\nfrom molSimplify.Informatics.graph_analyze import *\nfrom molSimplify.Informatics.RACassemble import *\nfrom molSimplify.python_nn.tf_ANN import *\nimport time\nfrom sets import Set\n#import numpy\n#import openbabel\n\n## wrapper to get AN predictions from a known mol3D()\n## generally unsfae\ndef invoke_ANNs_from_mol3d(mol,oxidation_state,alpha=0.2):\n # check input\n if not oxidation_state == 2 and not oxidation_state == 3:\n print('Error, oxidation state must be 2 or 3')\n return False\n \n # find the metal from RACs \n metal = mol.getAtom(mol.findMetal()[0]).symbol()\n ox_modifier = {metal:oxidation_state}\n # get RACs\n descriptor_names, descriptors = get_descriptor_vector(mol,ox_modifier=ox_modifier)\n # get one-hot-encoding (OHE)\n descriptor_names,descriptors = create_OHE(descriptor_names,descriptors, metal,oxidation_state)\n # set exchange fraction\n descriptor_names += ['alpha']\n descriptors += [alpha]\n\n # call ANN for splitting\n split, latent_split = ANN_supervisor('split',descriptors,descriptor_names)\n\n # call ANN for bond lenghts\n if oxidation_state == 2:\n r_ls, latent_r_ls = ANN_supervisor('ls_ii',descriptors,descriptor_names)\n r_hs, latent_r_hs = ANN_supervisor('hs_ii',descriptors,descriptor_names)\n elif oxidation_state == 3:\n r_ls, latent_r_ls = ANN_supervisor('ls_iii',descriptors,descriptor_names)\n r_hs, latent_r_hs = ANN_supervisor('hs_iii',descriptors,descriptor_names)\n\n # ANN distance for splitting\n split_dist = find_true_min_eu_dist(\"split\",descriptors,descriptor_names)\n\n # compile results and return\n results_dictionary = {\"ls_bl\":r_ls,\n \"hs_bl\":r_hs,\n \"split\":split,\n \"distance\":split_dist }\n return(results_dictionary)\n \n\ndef tf_check_ligands(ligs,batlist,dents,tcats,occs,debug):\n ## tests if ligand combination\n ## is compatiable with the ANN\n # INPUT:\n # - ligs: list of mol3D class, ligands\n # - batlist: list of int, occupations \n # - dents: list of int, denticity\n # - tcats: list of int/bool\n # OUTPUT:\n # - valid: bool\n ## tcats controls\n ## manual overide\n ## of connection atoms\n\n n_ligs = len(ligs)\n if debug:\n print('nligs ' + str(n_ligs))\n print('ligs ' + str(ligs))\n print('occs in function ' + str(occs))\n print('tcats in function ' + str(tcats))\n unique_ligands = []\n axial_ind_list =[]\n equitorial_ind_list =[]\n axial_ligs = []\n equitorial_ligs = []\n ax_dent = 0 \n eq_dent =0\n eq_ligs = []\n eq_tcat = False\n ax_tcat = False\n triple_bidentate = False\n ax_occs = []\n eq_occs = []\n valid = True\n if (set(dents) == set([2])):\n print('triple bidentate case')\n triple_bidentate = True\n unique_ligs = []\n ucats = []\n unique_dict = {}\n if not(n_ligs) == 3:\n ## something unexpected happened!\n valid = False \n for i in range(0,n_ligs):\n this_bat = batlist[i]\n this_lig = ligs[i]\n this_dent = dents[i]\n this_occs = occs[i]\n ## mulitple points\n if not (this_lig in unique_ligs):\n unique_ligs.append(this_lig)\n ucats.append(tcats[i])\n unique_dict.update({this_lig: 1})\n elif (this_lig in unique_ligs):\n unique_dict.update({this_lig:unique_dict[this_lig]+1})\n \n if len(unique_ligs) == 1:\n axial_ligs.append(ligs[0])\n ax_dent = 2\n ax_tcat = tcats[0]\n ax_occs.append(1)\n equitorial_ligs.append(ligs[0])\n eq_dent = 2\n eq_tcat = tcats[0]\n eq_occs.append(2)\n elif len(unique_ligs) == 2:\n for key in unique_dict.keys():\n if unique_dict[key] == 1:\n axial_ligs.append(key)\n ax_dent = 2\n ax_occs.append(1)\n ax_tcat = tcats[ligs.index(key)]\n elif unique_dict[key] == 2:\n equitorial_ligs.append(key)\n eq_dent = 2\n eq_occs.append(2)\n eq_tcat = tcats[ligs.index(key)]\n else:\n valid = False\n else:\n for i in range(0,n_ligs):\n \n \n this_bat = batlist[i]\n if debug:\n print('iteration '+ str(i))\n print('this bat ' + str(this_bat) + ' from ' + str(batlist))\n this_lig = ligs[i]\n this_dent = dents[i]\n this_occ = occs[i]\n# print(this_bat,this_lig,this_dent)\n ## mulitple points\n if len(this_bat) == 1:\n if (5 in this_bat) or (6 in this_bat):\n \n if not (this_lig in axial_ligs):\n if debug:\n print('adding ' + str(this_lig) + ' to axial')\n axial_ligs.append(this_lig)\n ax_dent = this_dent\n if this_lig not in ['x','oxo','hydroxyl']:\n ax_tcat = tcats[i]\n ax_occs.append(occs[i])\n else:\n ax_occs[axial_ligs.index(this_lig)] += 1\n else: \n if not (this_lig in equitorial_ligs):\n equitorial_ligs.append(this_lig)\n eq_dent = this_dent\n eq_tcat = tcats[i]\n eq_occs.append(occs[i])\n else:\n eq_occs[equitorial_ligs.index(this_lig)] += 1\n \n else:\n if not (this_lig in equitorial_ligs):\n equitorial_ligs.append(this_lig)\n eq_dent = this_dent\n eq_tcat = tcats[i]\n eq_occs.append(occs[i])\n else:\n eq_occs[equitorial_ligs.index(this_lig)] += 1\n\n if (len(axial_ligs) > 2):\n print('axial lig error : ',axial_ligs,ax_dent,ax_tcat,ax_occs)\n valid = False\n if debug:\n print('eq occupations ' + str(eq_occs))\n print('eq dent ' + str(eq_dent))\n if not (4.0/(float(eq_dent)*sum(eq_occs)) == 1):\n print('equitorial ligs error: ',equitorial_ligs,eq_dent,eq_tcat)\n valid = False\n if valid: # get the index position in ligs\n axial_ind_list = [ligs.index(ax_lig) for ax_lig in axial_ligs]\n equitorial_ind_list = [ligs.index(eq_lig) for eq_lig in equitorial_ligs]\n \n return valid,axial_ligs,equitorial_ligs,ax_dent,eq_dent,ax_tcat,eq_tcat,axial_ind_list,equitorial_ind_list,ax_occs,eq_occs\n\ndef check_metal(metal,oxidation_state):\n supported_metal_dict = {\"fe\":[2,3],\"mn\":[2,3],\"cr\":[2,3],\n \"co\":[2,3],\"ni\":[2]}\n romans={'I':'1','II':'2','III':'3','IV':'4','V':'5','VI':'6'}\n if oxidation_state in romans.keys():\n oxidation_state= romans[oxidation_state]\n outcome = False\n if metal in supported_metal_dict.keys():\n# print('metal in',supported_metal_dict[metal])\n if int(oxidation_state) in supported_metal_dict[metal]:\n outcome = True\n return outcome,oxidation_state\n\n\n\n\ndef tf_ANN_preproc(args,ligs,occs,dents,batslist,tcats,licores):\n ### prepares and runs ANN calculation\n\n current_time = time.time()\n start_time = current_time\n last_time = current_time\n\n ######################\n ANN_reason = False # holder for reason to reject ANN call\n ANN_attributes = dict()\n ######################\n\n r = 0\n emsg = list()\n valid = True \n catalysis = False\n metal = args.core\n this_metal = metal.lower()\n if len(this_metal) >2 :\n this_metal = this_metal[0:2]\n newligs = []\n newcats = []\n newdents = []\n newoccs = []\n newdecs = [False]*6\n newdec_inds = [[]]*6\n ANN_trust = False\n count = -1\n for i,lig in enumerate(ligs):\n this_occ = occs[i]\n if args.debug:\n print('working on lig: ' + str(lig))\n print('occ is ' + str(this_occ)) \n for j in range(0,int(this_occ)):\n count += 1\n newligs.append(lig)\n newdents.append(dents[i])\n newcats.append(tcats[i])\n newoccs.append(1)\n if args.decoration: \n newdecs[count] = (args.decoration[i])\n newdec_inds[count] = (args.decoration_index[i])\n\n ligs = newligs \n dents = newdents\n tcats = newcats \n occs = newoccs\n print('FINISHED PREPPING LIGANDS') \n \n if not args.geometry == \"oct\":\n emsg.append(\"[ANN] Geometry is not supported at this time, MUST give -geometry = oct\")\n valid = False \n ANN_reason = 'geometry not oct'\n if not args.oxstate:\n emsg.append(\"\\n oxidation state must be given\")\n valid = False\n ANN_reason = 'oxstate not given'\n if valid:\n oxidation_state = args.oxstate\n valid, oxidation_state = check_metal(this_metal,oxidation_state)\n if int(oxidation_state) in [3, 4, 5]:\n catalytic_moieties = ['oxo','x','hydroxyl','[O--]','[OH-]']\n print('THE LIGANDS ARE',ligs)\n print(set(ligs).intersection(set(catalytic_moieties)))\n if len(set(ligs).intersection(set(catalytic_moieties))) > 0:\n catalysis = True\n ## generate key in descriptor space\n ox = int(oxidation_state)\n spin = args.spin\n if args.debug:\n print('metal is '+ str(this_metal))\n print('metal validity',valid)\n if not valid and not catalysis:\n emsg.append(\"\\n Oxidation state not available for this metal\")\n ANN_reason = 'ox state not avail for metal'\n if valid:\n high_spin,spin_ops = spin_classify(this_metal,spin,ox)\n if not valid and not catalysis:\n emsg.append(\"\\n this spin state not available for this metal\")\n ANN_reason = 'spin state not availble for metal'\n if emsg:\n print(str(\" \".join( [\"ANN messages:\"] + [str(i) for i in emsg] )))\n\n \n current_time = time.time()\n metal_check_time = current_time - last_time\n last_time = current_time\n print('checking metal/ox took ' + \"{0:.2f}\".format(metal_check_time) + ' seconds' )\n\n if valid or catalysis:\n valid,axial_ligs,equitorial_ligs,ax_dent,eq_dent,ax_tcat,eq_tcat,axial_ind_list,equitorial_ind_list,ax_occs,eq_occs = tf_check_ligands(ligs,batslist,dents,tcats,occs,args.debug)\n\n if args.debug:\n print(\"ligand validity is \"+str(valid))\n print('Occs',occs)\n print('Ligands',ligs)\n print('Dents',dents)\n print('Bats (backbone atoms)',batslist)\n print('lig validity',valid)\n print('ax ligs',axial_ligs)\n print('eq ligs',equitorial_ligs)\n print('spin is',spin)\n if catalysis:\n valid = False\n if (not valid) and (not catalysis):\n ANN_reason = 'found incorrect ligand symmetry'\n elif not valid and catalysis:\n print('THIS IS CATALYTIC!')\n ANN_reason = 'catalytic structure presented'\n\n \n ## placeholder for metal \n metal_mol = mol3D()\n metal_mol.addAtom(atom3D(metal)) \n\n if valid or catalysis:\n if args.debug:\n print('loading axial ligands')\n ax_ligands_list = list()\n eq_ligands_list = list()\n for ii, axl in enumerate(axial_ligs):\n ax_lig3D,r_emsg = lig_load(axl,licores) # load ligand\n if r_emsg:\n emsg += r_emsg\n if ax_tcat:\n ax_lig3D.cat = ax_tcat\n if args.debug:\n print('custom ax connect atom given (0-ind) '+str(ax_tcat))\n this_lig = ligand(mol3D(), [],ax_dent)\n this_lig.mol = ax_lig3D\n \n ## check decoration index\n if newdecs:\n if newdecs[axial_ind_list[ii]]:\n print('decorating ' + str(axl) + ' with ' +str(newdecs[axial_ind_list[ii]]) + ' at sites ' + str(newdec_inds[axial_ind_list[ii]]))\n ax_lig3D = decorate_ligand(args,axl,newdecs[axial_ind_list[ii]],newdec_inds[axial_ind_list[ii]])\n ax_lig3D.convert2mol3D() ## mol3D representation of ligand\n for jj in range(0,ax_occs[ii]):\n ax_ligands_list.append(this_lig)\n if args.debug:\n print('ax_ligands_list:')\n print(ax_ligands_list)\n print([h.mol.cat for h in ax_ligands_list])\n \n if args.debug:\n print('loading equitorial ligands')\n for ii, eql in enumerate(equitorial_ligs):\n eq_lig3D,r_emsg = lig_load(eql,licores) # load ligand\n if r_emsg:\n emsg += r_emsg\n if eq_tcat:\n eq_lig3D.cat = eq_tcat\n if args.debug:\n print('custom eq connect atom given (0-ind) '+str(eq_tcat))\n this_lig = ligand(mol3D(), [],eq_dent)\n this_lig.mol = eq_lig3D\n\n if newdecs:\n if newdecs[equitorial_ind_list[ii]]:\n print('decorating ' + str(eql) + ' with ' +str(newdecs[equitorial_ind_list[ii]]) + ' at sites ' + str(newdec_inds[equitorial_ind_list[ii]]))\n eq_lig3D = decorate_ligand(args,eql,newdecs[equitorial_ind_list[ii]],\n newdec_inds[equitorial_ind_list[ii]])\n \n eq_lig3D.convert2mol3D() ## mol3D representation of ligand\n for jj in range(0,eq_occs[ii]):\n eq_ligands_list.append(this_lig)\n if args.debug:\n print('eq_ligands_list:')\n print(eq_ligands_list)\n \n current_time = time.time()\n ligand_check_time = current_time - last_time\n last_time = current_time\n print('checking ligs took ' + \"{0:.2f}\".format(ligand_check_time) + ' seconds')\n \n \n ## make description of complex \n custom_ligand_dict = {\"eq_ligand_list\":eq_ligands_list,\n \"ax_ligand_list\":ax_ligands_list,\n \"eq_con_int_list\":[h.mol.cat for h in eq_ligands_list],\n \"ax_con_int_list\":[h.mol.cat for h in ax_ligands_list]}\n \n ox_modifier = {metal:ox}\n this_complex = assemble_connectivity_from_parts(metal_mol,custom_ligand_dict)\n \n \n if args.debug:\n print('custom_ligand_dict is : ') \n print(custom_ligand_dict) \n \n \n\n \n if args.debug:\n print('finished checking ligands, valid is '+str(valid))\n print('assembling RAC custom ligand configuration dictionary')\n \n if valid:\n ## build RACs without geo\n con_mat = this_complex.graph \n descriptor_names, descriptors = get_descriptor_vector(this_complex,custom_ligand_dict,ox_modifier)\n \n ## get one-hot-encoding (OHE)\n descriptor_names,descriptors = create_OHE(descriptor_names,descriptors, metal,oxidation_state)\n \n # get alpha\n alpha = 0.2 # default for B3LYP\n if args.exchange:\n try:\n if float(args.exchange) > 1:\n alpha = float(args.exchange)/100 # if given as %\n elif float(args.exchange) <= 1:\n alpha = float(args.exchange)\n except:\n print('cannot case exchange argument as a float, using 20%')\n descriptor_names += ['alpha']\n descriptors += [alpha]\n descriptor_names += ['ox']\n descriptors += [ox]\n descriptor_names += ['spin']\n descriptors += [spin]\n if args.debug:\n current_time = time.time()\n rac_check_time = current_time - last_time\n last_time = current_time\n print('getting RACs took ' + \"{0:.2f}\".format(rac_check_time) + ' seconds')\n\n\n ## get spin splitting:\n split, latent_split = ANN_supervisor('split',descriptors,descriptor_names)\n if args.debug:\n current_time = time.time()\n split_ANN_time = current_time - last_time\n last_time = current_time\n print('split ANN took ' + \"{0:.2f}\".format(split_ANN_time) + ' seconds')\n \n ## get bond lengths:\n if oxidation_state == '2':\n r_ls, latent_r_ls = ANN_supervisor('ls_ii',descriptors,descriptor_names)\n r_hs, latent_r_hs = ANN_supervisor('hs_ii',descriptors,descriptor_names)\n elif oxidation_state == '3':\n r_ls, latent_r_ls = ANN_supervisor('ls_iii',descriptors,descriptor_names)\n r_hs, latent_r_hs = ANN_supervisor('hs_iii',descriptors,descriptor_names)\n if not high_spin:\n r = r_ls[0]\n else:\n r = r_hs[0]\n \n if args.debug:\n current_time = time.time()\n GEO_ANN_time = current_time - last_time\n last_time = current_time\n print('GEO ANN took ' + \"{0:.2f}\".format(GEO_ANN_time)+ ' seconds')\n\n homo, latent_homo = ANN_supervisor('homo',descriptors,descriptor_names)\n if args.debug:\n current_time = time.time()\n homo_ANN_time = current_time - last_time\n last_time = current_time\n print('homo ANN took ' + \"{0:.2f}\".format(homo_ANN_time) + ' seconds')\n\n gap, latent_gap = ANN_supervisor('gap',descriptors,descriptor_names)\n if args.debug:\n current_time = time.time()\n gap_ANN_time = current_time - last_time\n last_time = current_time\n print('gap ANN took ' + \"{0:.2f}\".format(gap_ANN_time) + ' seconds')\n\n ## get minimum distance to train (for splitting)\n \n split_dist = find_true_min_eu_dist(\"split\",descriptors,descriptor_names)\n if args.debug:\n current_time = time.time()\n min_dist_time = current_time - last_time\n last_time = current_time\n print('min dist took ' + \"{0:.2f}\".format(min_dist_time)+ ' seconds')\n \n homo_dist = find_true_min_eu_dist(\"homo\",descriptors,descriptor_names)\n homo_dist = find_ANN_latent_dist(\"homo\",latent_homo)\n if args.debug:\n current_time = time.time()\n min_dist_time = current_time - last_time\n last_time = current_time\n print('min HOMO dist took ' + \"{0:.2f}\".format(min_dist_time)+ ' seconds')\n\n gap_dist = find_true_min_eu_dist(\"gap\",descriptors,descriptor_names)\n gap_dist = find_ANN_latent_dist(\"gap\",latent_gap)\n if args.debug:\n current_time = time.time()\n min_dist_time = current_time - last_time\n last_time = current_time\n print('min GAP dist took ' + \"{0:.2f}\".format(min_dist_time)+ ' seconds')\n\n ## save attributes for return\n ANN_attributes.update({'split':split[0][0]})\n ANN_attributes.update({'split_dist':split_dist} )\n ANN_attributes.update({'This spin':spin})\n if split[0][0] < 0 and (abs(split[0]) > 5):\n ANN_attributes.update({'ANN_ground_state':spin_ops[1]})\n elif split[0][0] > 0 and (abs(split[0]) > 5):\n ANN_attributes.update({'ANN_ground_state':spin_ops[0]})\n else:\n ANN_attributes.update({'ANN_ground_state':'dgen ' + str(spin_ops)})\n\n ANN_attributes.update({'homo':homo[0][0]})\n ANN_attributes.update({'gap':gap[0][0]})\n ANN_attributes.update({'homo_dist':homo_dist})\n ANN_attributes.update({'gap_dist':gap_dist}) \n \n ## now that we have bond predictions, we need to map these\n ## back to a length of equal size as the original ligand request\n ## in order for molSimplify to understand if\n ANN_bondl = len(ligs)*[False]\n added = 0\n for ii,eql in enumerate(equitorial_ind_list):\n for jj in range(0,eq_occs[ii]):\n ANN_bondl[added] = r[2]\n added += 1\n \n\n for ii,axl in enumerate(axial_ind_list):\n if args.debug:\n print(ii,axl,added,ax_occs)\n for jj in range(0,ax_occs[ii]):\n if args.debug:\n print(jj,axl,added,r[ii])\n ANN_bondl[added] = r[ii]\n added += 1\n\n ANN_attributes.update({'ANN_bondl':4*[r[2]]+[r[0],r[1]]})\n \n HOMO_ANN_trust = 'not set'\n HOMO_ANN_trust_message = \"\"\n if float(homo_dist)< 3: #Not quite sure if this should be divided by 3 or not, since RAC-155 descriptors\n HOMO_ANN_trust_message = 'ANN results should be trustworthy for this complex '\n HOMO_ANN_trust = 'high'\n elif float(homo_dist)< 5:\n HOMO_ANN_trust_message = 'ANN results are probably useful for this complex '\n HOMO_ANN_trust = 'medium'\n elif float(homo_dist)<= 10:\n HOMO_ANN_trust_message = 'ANN results are fairly far from training data, be cautious '\n HOMO_ANN_trust = 'low'\n elif float(homo_dist)> 10:\n HOMO_ANN_trust_message = 'ANN results are too far from training data, be cautious '\n HOMO_ANN_trust = 'very low'\n ANN_attributes.update({'homo_trust':HOMO_ANN_trust})\n ANN_attributes.update({'gap_trust':HOMO_ANN_trust})\n\n ANN_trust = 'not set'\n ANN_trust_message = \"\"\n if float(split_dist/3)< 0.25:\n ANN_trust_message = 'ANN results should be trustworthy for this complex '\n ANN_trust = 'high'\n elif float(split_dist/3)< 0.75:\n ANN_trust_message = 'ANN results are probably useful for this complex '\n ANN_trust = 'medium'\n elif float(split_dist/3)< 1.0:\n ANN_trust_message = 'ANN results are fairly far from training data, be cautious '\n ANN_trust = 'low'\n elif float(split_dist/3)> 1.0:\n ANN_trust_message = 'ANN results are too far from training data, be cautious '\n ANN_trust = 'very low'\n ANN_attributes.update({'split_trust':ANN_trust})\n \n ## print text to std out\n print(\"******************************************************************\")\n print(\"************** ANN is engaged and advising on spin ***************\")\n print(\"************** and metal-ligand bond distances ****************\")\n print(\"******************************************************************\")\n if high_spin:\n print('You have selected a high-spin state, s = ' + str(spin))\n else:\n print('You have selected a low-spin state, s = ' + str(spin))\n ## report to stdout\n if split[0] < 0 and not high_spin:\n if abs(split[0]) > 5:\n print('warning, ANN predicts a high spin ground state for this complex')\n else:\n print('warning, ANN predicts a near degenerate ground state for this complex')\n elif split[0] >= 0 and high_spin:\n if abs(split[0]) > 5:\n print('warning, ANN predicts a low spin ground state for this complex')\n else:\n print('warning, ANN predicts a near degenerate ground state for this complex')\n print('delta is' ,split[0],' spin is ',high_spin)\n print(\"ANN predicts a spin splitting (HS - LS) of \" + \"{0:.2f}\".format(float(split[0])) + ' kcal/mol at '+\"{0:.0f}\".format(100*alpha) + '% HFX')\n print('ANN low spin bond length (ax1/ax2/eq) is predicted to be: '+\" /\".join([\"{0:.2f}\".format(float(i)) for i in r_ls[0]]) + ' angstrom')\n print('ANN high spin bond length (ax1/ax2/eq) is predicted to be: '+\" /\".join([\"{0:.2f}\".format(float(i)) for i in r_hs[0]]) + ' angstrom')\n print('distance to training data is ' + \"{0:.2f}\".format(split_dist) )\n print(ANN_trust_message)\n print(\"ANN predicts a HOMO value of \" + \"{0:.2f}\".format(float(homo[0])) + ' eV at '+\"{0:.0f}\".format(100*alpha) + '% HFX')\n print(\"ANN predicts a LUMO-HOMO energetic gap value of \" + \"{0:.2f}\".format(float(gap[0])) + ' eV at '+\"{0:.0f}\".format(100*alpha) + '% HFX')\n print(HOMO_ANN_trust_message)\n print('distance to HOMO training data is ' + \"{0:.2f}\".format(homo_dist) )\n print('distance to GAP training data is ' + \"{0:.2f}\".format(gap_dist) )\n print(\"*******************************************************************\")\n print(\"************** ANN complete, saved in record file *****************\")\n print(\"*******************************************************************\")\n from keras import backend as K\n K.clear_session() #This is done to get rid of the attribute error that is a bug in tensorflow.\n \n if valid: \n current_time = time.time()\n total_ANN_time = current_time - start_time\n last_time = current_time\n print('Total ML functions took ' + \"{0:.2f}\".format(total_ANN_time) + ' seconds') \n\n if catalysis:\n ## build RACs without geo\n con_mat = this_complex.graph \n descriptor_names, descriptors = get_descriptor_vector(this_complex,custom_ligand_dict,ox_modifier)\n # get alpha\n alpha = 20 # default for B3LYP\n if args.exchange:\n try:\n if float(args.exchange) < 1:\n alpha = float(args.exchange)*100 # if given as %\n elif float(args.exchange) >= 1:\n alpha = float(args.exchange)\n except:\n print('cannot case exchange argument as a float, using 20%')\n descriptor_names += ['alpha']\n descriptors += [alpha]\n descriptor_names += ['ox']\n descriptors += [ox]\n descriptor_names += ['spin']\n descriptors += [spin]\n if args.debug:\n current_time = time.time()\n rac_check_time = current_time - last_time\n last_time = current_time\n print('getting RACs took ' + \"{0:.2f}\".format(rac_check_time) + ' seconds')\n oxo, latent_oxo = ANN_supervisor('oxo',descriptors,descriptor_names)\n if args.debug:\n current_time = time.time()\n split_ANN_time = current_time - last_time\n last_time = current_time\n print('oxo ANN took ' + \"{0:.2f}\".format(split_ANN_time) + ' seconds')\n oxo_dist = find_ANN_latent_dist(\"oxo\",latent_oxo)\n if args.debug:\n current_time = time.time()\n min_dist_time = current_time - last_time\n last_time = current_time\n print('min oxo dist took ' + \"{0:.2f}\".format(min_dist_time)+ ' seconds')\n ANN_attributes.update({'oxo':oxo[0][0]})\n ANN_attributes.update({'oxo_dist':oxo_dist})\n\n hat, latent_hat = ANN_supervisor('hat',descriptors,descriptor_names)\n if args.debug:\n current_time = time.time()\n split_ANN_time = current_time - last_time\n last_time = current_time\n print('HAT ANN took ' + \"{0:.2f}\".format(split_ANN_time) + ' seconds')\n\n hat_dist = find_ANN_latent_dist(\"hat\",latent_hat)\n if args.debug:\n current_time = time.time()\n min_dist_time = current_time - last_time\n last_time = current_time\n print('min hat dist took ' + \"{0:.2f}\".format(min_dist_time)+ ' seconds')\n\n ANN_attributes.update({'hat':hat[0][0]})\n ANN_attributes.update({'hat_dist':hat_dist})\n\n Oxo_ANN_trust = 'not set'\n Oxo_ANN_trust_message = \"\"\n if float(oxo_dist)< 3: #Not quite sure if this should be divided by 3 or not, since RAC-155 descriptors\n Oxo_ANN_trust_message = 'Oxo ANN results should be trustworthy for this complex '\n Oxo_ANN_trust = 'high'\n elif float(oxo_dist)< 5:\n Oxo_ANN_trust_message = 'Oxo ANN results are probably useful for this complex '\n Oxo_ANN_trust = 'medium'\n elif float(oxo_dist)<= 10:\n Oxo_ANN_trust_message = 'Oxo ANN results are fairly far from training data, be cautious '\n Oxo_ANN_trust = 'low'\n elif float(oxo_dist)> 10:\n Oxo_ANN_trust_message = 'Oxo ANN results are too far from training data, be cautious '\n Oxo_ANN_trust = 'very low'\n ANN_attributes.update({'oxo_trust':Oxo_ANN_trust})\n\n\n HAT_ANN_trust = 'not set'\n HAT_ANN_trust_message = \"\"\n if float(hat_dist)< 3: #Not quite sure if this should be divided by 3 or not, since RAC-155 descriptors\n HAT_ANN_trust_message = 'HAT ANN results should be trustworthy for this complex '\n HAT_ANN_trust = 'high'\n elif float(hat_dist)< 5:\n HAT_ANN_trust_message = 'HAT ANN results are probably useful for this complex '\n HAT_ANN_trust = 'medium'\n elif float(hat_dist)<= 10:\n HAT_ANN_trust_message = 'HAT ANN results are fairly far from training data, be cautious '\n HAT_ANN_trust = 'low'\n elif float(hat_dist)> 10:\n HAT_ANN_trust_message = 'HAT ANN results are too far from training data, be cautious '\n HAT_ANN_trust = 'very low'\n ANN_attributes.update({'hat_trust':HAT_ANN_trust})\n print(\"*******************************************************************\")\n print(\"************** CATALYTIC ANN ACTIVATED! ****************\")\n print(\"*********** Currently advising on Oxo and HAT energies ************\")\n print(\"*******************************************************************\")\n print(\"ANN predicts a oxo formation energy of \" + \"{0:.2f}\".format(float(oxo[0])) + ' kcal/mol at '+\"{0:.2f}\".format(alpha) + '% HFX')\n print(Oxo_ANN_trust_message)\n print('Distance to oxo training data in the latent space is ' + \"{0:.2f}\".format(oxo_dist) )\n print(\"ANN predicts a HAT energy of \" + \"{0:.2f}\".format(float(hat[0])) + ' kcal/mol at '+\"{0:.2f}\".format(alpha) + '% HFX')\n print(HAT_ANN_trust_message)\n print('Distance to HAT training data in the latent space is ' + \"{0:.2f}\".format(hat_dist) )\n print(\"*******************************************************************\")\n print(\"************** ANN complete, saved in record file *****************\")\n print(\"*******************************************************************\")\n from keras import backend as K\n K.clear_session() #This is done to get rid of the attribute error that is a bug in tensorflow.\n\n if catalysis: \n current_time = time.time()\n total_ANN_time = current_time - start_time\n last_time = current_time\n print('Total Catalysis ML functions took ' + \"{0:.2f}\".format(total_ANN_time) + ' seconds')\n\n if not valid and not ANN_reason and not catalysis:\n ANN_reason = ' uncaught rejection (see sdout/stderr)'\n\n return valid,ANN_reason,ANN_attributes, catalysis\n\n \n \n\n\n if False:\n ## test Euclidean norm to training data distance\n train_dist,best_row = find_eu_dist(nn_excitation)\n ANN_trust = max(0.01,1.0-train_dist)\n \n ANN_attributes.update({'ANN_closest_train':best_row} )\n\n print(' with closest training row ' + best_row[:-2] + ' at ' + str(best_row[-2:]) + '% HFX')\n\n \n \n ### use ANN to predict fucntional sensitivty\n HFX_slope = 0 \n HFX_slope = get_slope(slope_excitation)\n print('Predicted HFX exchange sensitivity is : '+\"{0:.2f}\".format(float(HFX_slope)) + ' kcal/HFX')\n ANN_attributes.update({'ANN_slope':HFX_slope})\n","sub_path":"molSimplify/Scripts/tf_nn_prep.py","file_name":"tf_nn_prep.py","file_ext":"py","file_size_in_byte":32724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"376557600","text":"#!/usr/bin/env python\n\n# Copyright (C) 2015-2016 Hewlett Packard Enterprise Development LP\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport pytest\nfrom pytest import mark\nimport re\nfrom opstestfw import *\nfrom opstestfw.switch.CLI import *\nfrom opstestfw.switch import *\n\n# Topology definition\ntopoDict = {\"topoExecution\": 1000,\n \"topoTarget\": \"dut01\",\n \"topoDevices\": \"dut01\",\n \"topoFilters\": \"dut01:system-category:switch\"}\n\n\ndef enterConfigShell(dut01):\n retStruct = dut01.VtyshShell(enter=True)\n retCode = retStruct.returnCode()\n assert retCode == 0, \"Failed to enter vtysh prompt\"\n\n return True\n\n\ndef sftpserverfeature(dut01):\n sftpserver_enable = True\n SSHD_CONFIG = \"/etc/ssh/sshd_config\"\n\n devIntReturn = dut01.DeviceInteract(command=\"start-shell\")\n retCode = devIntReturn.get('returnCode')\n assert retCode == 0, \"Failed to enter bash shell\"\n\n out = dut01.DeviceInteract(command=\"cat /etc/ssh/sshd_config | grep sftp\")\n\n if \"#Subsystem\tsftp\t/usr/lib/openssh/sftp-server\" in out.get('buffer'):\n sftpserver_enable = False\n\n assert sftpserver_enable is False, \"SFTP server is not disabled by default\"\n\n dut01.DeviceInteract(command=\"exit\")\n\n #enable the sftp server\n dut01.DeviceInteract(command=\"configure terminal\")\n devIntReturn = dut01.DeviceInteract(command=\"sftp server enable\")\n retCode = devIntReturn.get('returnCode')\n assert retCode == 0, \"Enable SFTP server failed\"\n dut01.DeviceInteract(command=\"exit\")\n\n devIntReturn = dut01.DeviceInteract(command=\"start-shell\")\n retCode = devIntReturn.get('returnCode')\n assert retCode == 0, \"Failed to enter bash shell\"\n\n out = dut01.DeviceInteract(command=\"cat /etc/ssh/sshd_config | grep sftp\")\n\n if \"Subsystem\tsftp\t/usr/lib/openssh/sftp-server\" in out.get('buffer'):\n sftpserver_enable = True\n\n assert sftpserver_enable is True, \"Failed to enable SFTP server in \" \\\n \"sshd_config file\"\n\n dut01.DeviceInteract(command=\"exit\")\n\n #disable the sftp server\n dut01.DeviceInteract(command=\"configure terminal\")\n devIntReturn = dut01.DeviceInteract(command=\"no sftp server enable\")\n retCode = devIntReturn.get('returnCode')\n assert retCode == 0, \"Disable SFTP server failed\"\n dut01.DeviceInteract(command=\"exit\")\n\n devIntReturn = dut01.DeviceInteract(command=\"start-shell\")\n retCode = devIntReturn.get('returnCode')\n assert retCode == 0, \"Failed to enter bash shell\"\n\n out = dut01.DeviceInteract(command=\"cat /etc/ssh/sshd_config | grep sftp\")\n\n if \"#Subsystem\tsftp\t/usr/lib/openssh/sftp-server\" in out.get('buffer'):\n sftpserver_enable = False\n\n assert sftpserver_enable is False, \"Failed to disable SFTP server \" \\\n \"in sshd_config file\"\n dut01.DeviceInteract(command=\"exit\")\n\n return True\n\n@mark.skipif(True, reason=\"Disabling as AAA feature revamp in progress\")\nclass Test_sftpserver_feature:\n def setup_class(cls):\n # Test object will parse command line and formulate the env\n Test_sftpserver_feature.testObj =\\\n testEnviron(topoDict=topoDict, defSwitchContext=\"vtyShell\")\n # Get topology object\n Test_sftpserver_feature.topoObj = \\\n Test_sftpserver_feature.testObj.topoObjGet()\n\n def teardown_class(cls):\n Test_sftpserver_feature.topoObj.terminate_nodes()\n\n def test_feature(self):\n dut01Obj = self.topoObj.deviceObjGet(device=\"dut01\")\n retValue = sftpserverfeature(dut01Obj)\n if(retValue):\n LogOutput('info', \"SFTP server feature - passed\")\n else:\n LogOutput('error', \"SFTP server feature - failed\")\n","sub_path":"tests/test_sftp_ct_aaautils.py","file_name":"test_sftp_ct_aaautils.py","file_ext":"py","file_size_in_byte":4252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"222097348","text":"from django.contrib.auth import get_user_model\nfrom django.contrib.auth.models import Group\nfrom django.test import TestCase\n\nfrom advanced_filters.models import AdvancedFilter\n\n\nclass AdvancedFilterPermissions(TestCase):\n def setUp(self):\n User = get_user_model()\n self.user = User.objects.create(email='test1@example.com')\n\n self.group = Group.objects.create(name='test')\n\n self.user.set_password('test')\n self.user.groups.add(self.group)\n self.user.save()\n\n self.advancedfilter = AdvancedFilter.objects.create(\n title='test', url='test', created_by=self.user,\n b64_query='MQ=='\n )\n\n def test_filter_by_user_empty(self):\n qs = AdvancedFilter.objects.filter_by_user(user=self.user)\n\n self.assertEquals(qs.count(), 0)\n\n def test_filter_by_user_users(self):\n self.advancedfilter.users.add(self.user)\n\n qs = AdvancedFilter.objects.filter_by_user(user=self.user)\n\n self.assertEquals(qs.count(), 1)\n\n def test_filter_by_user_groups(self):\n self.advancedfilter.groups.add(self.group)\n\n qs = AdvancedFilter.objects.filter_by_user(user=self.user)\n\n self.assertEquals(qs.count(), 1)\n","sub_path":"advanced_filters/tests/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":1221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"332523147","text":"import cv2\nimport numpy as np\n\n# Grayscale\ndef BGR2GRAY(img):\n # Grayscale\n gray = 0.2126 * img[..., 2] + 0.7152 * img[..., 1] + 0.0722 * img[..., 0]\n return gray\n\n\ngabor_0 = cv2.getGaborKernel((11, 11), 1.5, np.radians(0), 3, 1.2 ,0 ,cv2.CV_64F)\ngabor_45 = cv2.getGaborKernel((11, 11), 1.5, np.radians(45), 3, 1.2 ,0 ,cv2.CV_64F)\ngabor_90 = cv2.getGaborKernel((11, 11), 1.5, np.radians(90), 3, 1.2 ,0 ,cv2.CV_64F)\ngabor_135 = cv2.getGaborKernel((11, 11), 1.5, np.radians(135), 3, 1.2 ,0 ,cv2.CV_64F)\n\nimg = cv2.imread(\"./image_71_80/imori.jpg\").astype(np.float)\n\nH, W, C = img.shape\nimg_gray = BGR2GRAY(img)\nimg_gray = np.pad(img_gray, (11//2, 11//2), 'edge')\n\nout0 = np.zeros((H, W), dtype=np.float32)\nout45 = np.zeros((H, W), dtype=np.float32)\nout90 = np.zeros((H, W), dtype=np.float32)\nout135 = np.zeros((H, W), dtype=np.float32)\n\nfor y in range(H):\n for x in range(W):\n out0[y,x] = np.sum(img_gray[y:y+11, x:x+11] * gabor_0) #out[0,0]はimg_grayまわりに11//2、0パディングされた画像の[0,0]~[10,10]までの画素(つまり、実際にはimg_gray[-5,-5]~img_gray[5,5]までってこと。img_gray[0,0]が中心)に、ガボールフィルタされたものの合計値が入る。\n out45[y,x] = np.sum(img_gray[y:y+11, x:x+11] * gabor_45)\n out90[y,x] = np.sum(img_gray[y:y+11, x:x+11] * gabor_90)\n out135[y,x] = np.sum(img_gray[y:y+11, x:x+11] * gabor_135)\n\nout0 = out0.clip(0,255)\nout45 = out45.clip(0,255)\nout90 = out90.clip(0,255)\nout135 = out135.clip(0,255)\n\nout = np.zeros((H, W), dtype=np.float32)\n\nout = out0 + out45 + out90 + out135\n\nprint(np.max(out))\nprint(out)\n\nout = out/np.max(out) * 255\n\nout = out.astype(np.uint8)\nprint(out)\n\ncv2.imwrite(\"./image_71_80/answer_80.jpg\",out)\ncv2.imshow(\"result\", out)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n","sub_path":"Question_71_80/q80.py","file_name":"q80.py","file_ext":"py","file_size_in_byte":1822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"13579678","text":"# -*- coding: utf-8 -*-\n# @Author: ywb\n# @Date: 2019-05-03 21:21:47\n# @Last Modified by: ywb\n# @Last Modified time: 2019-05-03 22:07:32\ndef greet_user(username):\n\tprint(\"Hello, \" + username.title()+'!')\n\ngreet_user('jesse') \n\ndef describe_pet(pet_name, animal_type='hamster'):\n\tprint('I have a '+animal_type)\n\tprint('My ' + animal_type + \"'s name is \" + pet_name)\ndescribe_pet('harry')\n\ndef get_formatted_name(first_name, last_name, middle_name=''):\n\tif middle_name:\n\t\tfull_name = first_name + ' ' + middle_name + ' ' + last_name\n\telse:\n\t\tfull_name = first_name + ' ' + last_name\n\treturn full_name.title()\nmusician = get_formatted_name('jimi', 'hendrix')\nprint(musician)\nmusician = get_formatted_name('john', 'hooker', 'lee')\nprint(musician)\n\ndef greet_users(names):\n\tfor name in names:\n\t\tprint(\"Hello, \" + name.title() + '!')\nusernames = ['hannah', 'ty', 'margot']\ngreet_users(usernames)\n\ndef make_pizza(*toppings):\n\tprint(\"\\nMaking a pizza with the following toppings\")\n\tfor topping in toppings:\n\t\tprint('-' + topping)\nmake_pizza('mushrooms', 'green peppers', 'extra cheese')\n\ndef build_profile(first, last, **user_info):\n\tprofile = {}\n\tprofile['first_name'] = first\n\tprofile['last_name'] = last\n\tfor key,value in user_info.items():\n\t\tprofile[key] = value\n\treturn profile\nuser_profile = build_profile('yang','paul',location='princeton', field='physics')\nprint(user_profile)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"第一部分 基础知识/第八章 函数/greeter2.py","file_name":"greeter2.py","file_ext":"py","file_size_in_byte":1402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"502532621","text":"\n# coding: utf-8\n\n# In[99]:\n\n\n# Import all the required libraries\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom gensim.models import Word2Vec, KeyedVectors\nimport nltk\nfrom nltk.tokenize import word_tokenize, sent_tokenize\nnltk.download('stopwords')\nnltk.download('wordnet')\nfrom nltk.corpus import stopwords\nfrom nltk.stem import WordNetLemmatizer \nimport numpy as np\n\n\n# In[100]:\n\n\n#### \n\ndef initialize_all_variables(path1, path2=None, data=None):\n \n wines = pd.read_csv(path1)\n\n food = pd.read_csv(path2)\n \n\n lemmatizer = WordNetLemmatizer()\n\n synonyms = {'Savagnin Noir':'Pinot Noir', 'Bourguignon':'Pinot Noir', 'Pinot Nero':'Pinot Noir', \n 'Pignola':'Pinot Noir', 'Spätburgunder':'Pinot Noir', 'Blauburgunder':'Pinot Noir', \n 'Klevner':'Pinot Noir', 'Nagyburgundi':'Pinot Noir', 'Modri Pinot':'Pinot Noir', \n 'Bourgogne':'Pinot Noir', 'Côte de Nuits':'Pinot Noir', 'Gevrey-Chambertin':'Pinot Noir', \n 'Morey-St-Denis':'Pinot Noir', 'Chambolle-Musigny':'Pinot Noir', 'Vougeot':'Pinot Noir', \n 'Flagney-Echezeaux':'Pinot Noir', 'Nuits-St-Georges':'Pinot Noir', 'Vosne-Romanee':'Pinot Noir', \n 'Aloxe-Corton':'Pinot Noir', 'Côte Challonaise':'Pinot Noir',\"Cannonau\":\"Grenache\", \n \"Garnacha\":\"Grenache\", \"Garnatxa\":\"Grenache\", \"Grenache Noir\":\"Grenache\", \"Alicante\":\"Grenache\",\n \"St. Emilion\":\"Merlot\", \"Pomerol\":\"Merlot\", \"Fronsac\":\"Merlot\", \"Côtes de Bourg\":\"Merlot\", \n \"Blaye\":\"Merlot\",\"Vino Nobile di Montepulciano\":\"Sangiovese\", \"Prugnolo Gentile\":\"Sangiovese\", \n \"Sangiovese Grosso\":\"Sangiovese\", \"Brunello di Montalcino\":\"Sangiovese\", \"Nielluccio\":\"Sangiovese\", \n \"Rosso di Montepulciano\":\"Sangiovese\", \"Morellino\":\"Sangiovese\", \"Rosso di Montalcino\":\"Sangiovese\", \n \"Montefalco Rosso\":\"Sangiovese\", \"Chianti\":\"Sangiovese\", \"Morellino di Scansano\":\"Sangiovese\",\n 'Tinto del Toro':\"Tempranillo\", 'Tinta Fina':\"Tempranillo\", 'Tinto del Pais':\"Tempranillo\", \n 'Tinta Roriz':\"Tempranillo\", 'Aragonez':\"Tempranillo\", 'Rioja':\"Tempranillo\", \n 'Valdepeñas':\"Tempranillo\", 'Ribera del Duero':\"Tempranillo\",'Shiraz':\"Syrah\", 'Sirac':\"Syrah\", \n 'Marsanne Noir':\"Syrah\", 'Entournerein':\"Syrah\", 'Serène':\"Syrah\", 'Hermitage':\"Syrah\", \n 'Crozes-Hermitage':\"Syrah\", 'Cornas':\"Syrah\", 'Côte-Rôtie':\"Syrah\", 'St. Joseph':\"Syrah\",\n 'Pinot Gris':'Pinot Grigio','Ruländer':'Pinot Grigio','Johannisberg Riesling':'Riesling',\n 'Fumé Blanc':\"Sauvignon Blanc\", 'Muskat-Silvaner':\"Sauvignon Blanc\", 'Feigentraube':\"Sauvignon Blanc\", \n 'Sauvignon':\"Sauvignon Blanc\", 'White Riesling':'Riesling', 'Gamay Noir':'Gamay', 'Durif':'Petite Sirah',\n 'Veltliner':'Grüner Veltliner', 'Primitivo':'Zinfandel'}\n\n final_varieties = {'Pinot Noir', 'Grenache', 'Merlot', 'Sangiovese', 'Nebbiolo', \n 'Tempranillo', 'Cabernet Sauvignon', 'Syrah', 'Malbec', 'Pinot Grigio', \n 'Riesling', 'Sauvignon Blanc', 'Chenin Blanc', 'Moscato', 'Gewürztraminer',\n 'Sémillon', 'Viognier', 'Chardonnay', 'Zinfandel', 'Cabernet Franc', \n 'Grüner Veltliner', 'Gamay', 'Petite Sirah', 'Barbera', 'Glera', 'Port', \n 'Chenin Blanc', 'Carmenère'}\n \n allowed_countries = {'US', 'France', 'Italy', 'Chile', 'Argentina', 'Austria', 'Spain', 'Germany', \n 'Australia', 'New Zealand', 'South Africa', 'Portugal', 'Israel', 'Canada'}\n \n\n all_varieties = wines.variety.unique().tolist()\n all_countries = wines.country.unique().tolist()\n all_winery = wines.winery.unique().tolist()\n all_region_1 = wines.region_1.unique().tolist()\n all_region_2 = wines.region_2.unique().tolist()\n all_province = wines.province.unique().tolist()\n stop_set = [all_varieties, all_countries, all_winery, all_region_1, all_region_2, all_province]\n \n if data:\n wines = data\n \n return wines, food, lemmatizer, synonyms, final_varieties, allowed_countries, stop_set\n\n\n# In[101]:\n\n\n#############replace\ndef clean_dataset(df, synonyms, final_varieties, allowed_countries):\n df_rep = df.replace(synonyms)\n df_rep = df_rep[df_rep.variety.isin(final_varieties)]\n df_rep = df_rep[df_rep.country.isin(allowed_countries)]\n return df_rep\n \n\n\n# In[102]:\n\n\ndef set_stop_words(stop_set):\n \n stop_words_nltk = stopwords.words('english')\n for i in stop_set:\n stop_words_nltk.extend(i)\n \n stop_words_nltk.extend(['wine', 'wines', 'vineyard', 'blanc', 'flavor', 'flavors', 'aroma', \n 'aromas', 'Pinot', 'Reisling', \"Merlot\", 'Cabernet'])\n stop_words_nltk = [str(x) for x in stop_words_nltk]\n stop_words_nltk = [x.lower() for x in stop_words_nltk]\n stop_words_nltk = set(stop_words_nltk)\n \n return stop_words_nltk\n\n\n# In[103]:\n\n\n## Text Data\ndef get_corpus(wines, food):\n corpus = ''\n for index, row in wines.iterrows():\n corpus += row['description']\n \n for index, row in food.iterrows():\n corpus += row['Text']\n \n sentences = corpus.split('.')\n corpus_words = []\n \n for i in sentences:\n corpus_words.append(word_tokenize(i))\n \n return corpus_words\n \n\n\n# In[104]:\n\n\ndef train_embedding_model(corpus_words, save_path):\n model = Word2Vec(corpus_words, min_count=3)\n #model.save('/Users/qu318sq/w2v_model.bin')\n model.wv.save(save_path)\n return model.wv\n\n\n# In[105]:\n\n\ndef load_model(save_path):\n model = KeyedVectors.load(save_path, mmap='r')\n return model\n\n\n# In[106]:\n\n\ndef lemmatize_text(text, lemmatizer):\n return [lemmatizer.lemmatize(w) for w in text]\n\n\n\n# In[107]:\n\n\ndef get_primary(model, text, lim=5):\n result = []\n for i in text:\n if i in model.vocab:\n if model.similarity('fruit', i) >= 0.4:\n result.append([i, model.similarity('fruit', i), model[i]])\n \n elif model.similarity('flower', i) >= 0.4:\n result.append([i, model.similarity('flower', i), model[i]])\n elif model.similarity('herbal', i) >= 0.4:\n result.append([i, model.similarity('herbal', i), model[i]])\n else:\n continue\n \n result.sort(key=lambda tup: tup[1], reverse=True)\n #final_result = [(item[0],item[2]) for item in result]\n final_shape = lim * 100\n final_result = np.zeros(final_shape)\n int_result = [item[2] for item in result]\n if len(int_result) >= lim:\n int_result = int_result[:lim]\n \n else:\n padding_size = lim - len(int_result)\n padding = [model['nothing']]*padding_size\n int_result.extend(padding)\n i = 0\n j = 0\n for item in int_result:\n j += item.shape[0]\n final_result[i:j] = item[:]\n i += item.shape[0]\n final_result = final_result.tolist()\n \n return final_result\n\n \n\n\n# In[108]:\n\n\ndef get_acidity(model, text, lim=3):\n result = []\n for i in text:\n if i in model.vocab:\n if model.similarity('acid', i) >= 0.4:\n result.append([i, model.similarity('acid', i), model[i]])\n elif model.similarity('tart', i) >= 0.4:\n result.append([i, model.similarity('tart', i), model[i]])\n elif model.similarity('fresh', i) >= 0.4:\n result.append([i, model.similarity('fresh', i), model[i]])\n elif model.similarity('rich', i) >= 0.4:\n result.append([i, model.similarity('rich', i), model[i]])\n elif model.similarity('round', i) >= 0.4:\n result.append([i, model.similarity('round', i), model[i]])\n else:\n continue\n \n result.sort(key=lambda tup: tup[1], reverse=True)\n final_shape = lim * 100\n final_result = np.zeros(final_shape)\n int_result = [item[2] for item in result]\n if len(int_result) >= lim:\n int_result = int_result[:lim]\n \n else:\n padding_size = lim - len(int_result)\n padding = [model['nothing']]*padding_size\n int_result.extend(padding)\n i = 0\n j = 0\n for item in int_result:\n j += item.shape[0]\n final_result[i:j] = item[:]\n i += item.shape[0]\n final_result = final_result.tolist() \n return final_result\n\n\n# In[109]:\n\n\ndef get_tannicity(model, text, lim=3):\n result = []\n for i in text:\n if i in model.vocab:\n if model.similarity('astringent', i) >= 0.5:\n result.append([i, model.similarity('astringent', i), model[i]])\n elif model.similarity('balance', i) >= 0.5:\n result.append([i, model.similarity('balance', i), model[i]])\n elif model.similarity('complex', i) >= 0.5:\n result.append([i, model.similarity('complex', i), model[i]])\n elif model.similarity('smooth', i) >= 0.5:\n result.append([i, model.similarity('smooth', i), model[i]])\n elif model.similarity('soft', i) >= 0.5:\n result.append([i, model.similarity('soft', i), model[i]])\n elif model.similarity('bitter', i) >= 0.5:\n result.append([i, model.similarity('bitter', i), model[i]])\n elif model.similarity('herb', i) >= 0.5:\n result.append([i, model.similarity('herb', i), model[i]])\n else:\n continue\n \n result.sort(key=lambda tup: tup[1], reverse=True)\n final_shape = lim * 100\n final_result = np.zeros(final_shape)\n int_result = [item[2] for item in result]\n if len(int_result) >= lim:\n int_result = int_result[:lim]\n \n else:\n padding_size = lim - len(int_result)\n padding = [model['nothing']]*padding_size\n int_result.extend(padding)\n i = 0\n j = 0\n for item in int_result:\n j += item.shape[0]\n final_result[i:j] = item[:]\n i += item.shape[0]\n final_result = final_result.tolist() \n return final_result\n\n\n# In[110]:\n\n\ndef get_dryness(model, text, lim=3):\n result = []\n for i in text:\n if i in model.vocab:\n if model.similarity('sweet', i) >= 0.5:\n result.append([i,model.similarity('sweet', i), model[i]])\n elif model.similarity('dry', i) >= 0.5:\n result.append([i, model.similarity('dry', i), model[i]])\n else:\n continue\n \n result.sort(key=lambda tup: tup[1], reverse=True)\n final_shape = lim * 100\n final_result = np.zeros(final_shape)\n int_result = [item[2] for item in result]\n if len(int_result) >= lim:\n int_result = int_result[:lim]\n \n else:\n padding_size = lim - len(int_result)\n padding = [model['nothing']]*padding_size\n int_result.extend(padding)\n i = 0\n j = 0\n for item in int_result:\n j += item.shape[0]\n final_result[i:j] = item[:]\n i += item.shape[0]\n final_result = final_result.tolist() \n return final_result\n\n\n# In[111]:\n\n\ndef get_aging(model, text, lim=3):\n result = []\n for i in text:\n if i in model.vocab:\n if model.similarity('wood', i) >= 0.4:\n result.append([i, model.similarity('wood', i), model[i]])\n elif model.similarity('nut', i) >= 0.4:\n result.append([i, model.similarity('nut', i), model[i]])\n elif model.similarity('smoke', i) >= 0.4:\n result.append([i, model.similarity('smoke', i), model[i]])\n elif model.similarity('spice', i) >= 0.4:\n result.append([i, model.similarity('spice', i), model[i]])\n else:\n continue\n result.sort(key=lambda tup: tup[1], reverse=True)\n final_shape = lim * 100\n final_result = np.zeros(final_shape)\n int_result = [item[2] for item in result]\n if len(int_result) >= lim:\n int_result = int_result[:lim]\n \n else:\n padding_size = lim - len(int_result)\n padding = [model['nothing']]*padding_size\n int_result.extend(padding)\n i = 0\n j = 0\n for item in int_result:\n j += item.shape[0]\n final_result[i:j] = item[:]\n i += item.shape[0]\n final_result = final_result.tolist() \n return final_result\n\n \n\n\n# In[112]:\n\n\ndef get_wine_characteristic_features(wines_rep, model): \n \n wines_rep['primary'] = wines_rep['lemmatized_text'].apply(lambda x: get_primary(model, x))\n wines_rep['aging'] = wines_rep['lemmatized_text'].apply(lambda x: get_aging(model, x))\n wines_rep['acidity'] = wines_rep['lemmatized_text'].apply(lambda x: get_acidity(model, x))\n wines_rep['tannicity'] = wines_rep['lemmatized_text'].apply(lambda x: get_tannicity(model, x))\n wines_rep['dryness'] = wines_rep['lemmatized_text'].apply(lambda x: get_dryness(model, x))\n \n return wines_rep\n\n\n# In[113]:\n\n\ndef prep_dataset(wines_rep, stop_words, lemma):\n wines_rep['description_nostopwords'] = wines_rep['description'].apply(lambda x: ' '.join([word for word in x.split() if word.lower() not in stop_words]))\n wines_rep['tokenized_text'] = wines_rep['description_nostopwords'].apply(word_tokenize)\n wines_rep['lemmatized_text'] = wines_rep['tokenized_text'].apply(lambda x: lemmatize_text(x, lemma))\n return wines_rep\n\n\n# In[114]:\n\n\ndef get_processed_data(path_1, path_2, model_path, train=False, data=None):\n \n wines_, food_, lemmatizer_, synonyms_, final_varieties_, allowed_countries_, stop_set_ = initialize_all_variables(path_1, path_2, data)\n wines_clean = clean_dataset(wines_, synonyms_, final_varieties_, allowed_countries_)\n stop_words_ = set_stop_words(stop_set_)\n \n if train:\n training_corpus = get_corpus(wines_, food_)\n model_ = train_embedding_model(training_corpus, model_path)\n else:\n if model_path:\n model_ = load_model(model_path)\n else:\n return 'Provide a path to a saved model'\n \n wines_prepped = prep_dataset(wines_clean, stop_words_, lemmatizer_)\n wines_features = get_wine_characteristic_features(wines_prepped, model_)\n \n # shuffle\n \n wines_selected = wines_features.loc[:, ['primary', 'aging', 'acidity', 'tannicity', 'dryness', 'country', 'variety', 'price']]\n # Train\n \n return wines_selected\n \n \n\n\n# In[115]:\n\n\ndef get_train_test_data(path1, path2, model_p, train):\n wines_data = get_processed_data(path1, path2, model_p, train)\n wines_data = wines_data.sample(frac=1).reset_index(drop=True)\n wines_train = wines_data.iloc[:-15000,:].reset_index(drop=True)\n wines_test = wines_data.iloc[-15000:,:].reset_index(drop=True)\n return wines_train, wines_test\n\n\n# In[116]:\n\n\n#p1 = '/Users/qu318sq/wine-reviews/winemag-data-130k-v2.csv'\n#p2 = '/Users/qu318sq/Downloads/amazon-fine-food-reviews/reviews.csv'\n#p3 = '/Users/qu318sq/wordvectors.kv'\n#w_train, w_test = get_train_test_data(p1, p2, p3, train=False)\n\n\n# In[117]:\n\n\n#w_train.to_csv('/Users/qu318sq/wine_train.csv')\n#w_test.to_csv('/Users/qu318sq/wine_test.csv')\n\n","sub_path":"wines_feature_engineering.py","file_name":"wines_feature_engineering.py","file_ext":"py","file_size_in_byte":15162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"600424786","text":"# -*- coding: utf-8 -*-\n# python 3.x\nimport datetime\nfrom src.util.db.DBExecutor import DbUtils\n# 常量存储器\nclass _const_holder(object):\n\n def __init__(self):\n self.UTC_FORMAT = \"%Y-%m-%dT%H:%M:%S.%fZ\"\n self.host_url = 'http://gitlab.iduoku.cn'\n self.private_token = '6Fwz2xJpffNzD3PE8AGu'\n # projects (page)\n self.url_project_list = self.host_url + \"/api/v4/projects?per_page=100&page=%d\"\n # tags info by project id\n self.url_tags_info = self.host_url + '/api/v4/projects/%s/repository/tags?per_page=100&page=%d'\n # commits\n self.url_commits_info = self.host_url + '/api/v4/projects/%s/repository/commits'\n self.url_commits_detail = self.host_url + '/api/v4/projects/%s/repository/commits/%s'\n # db info\n self.dbut = DbUtils(\"172.16.4.220\", \"duoku\", \"123456\", \"bi_test\", 3306)\n\n # http info\n self.http_header = {\n 'PRIVATE-TOKEN': self.private_token\n }\n self.time_dif = datetime.timedelta(hours=8)\n\n def date_refine(self, date_str):\n if str is None:\n return ''\n return datetime.datetime.strptime(date_str, self.UTC_FORMAT) + self.time_dif\n\n\n def str_refine(self, istr):\n if istr is None:\n return ''\n return str(istr).strip().replace('\\'', '\"')\n\n class ConstError(PermissionError):\n pass\n\n def __setattr__(self, key, value):\n if key in self.__dict__.keys():\n raise self.ConstError(\"have not const: %s\" % key)\n self.__dict__[key] = value\n\n def __delattr__(self, item):\n if item in self.__dict__:\n raise self.ConstError(\"unbind fail:%s\" % item)\n raise NameError(item)\n\nimport sys\nsys.modules[__name__] = _const_holder()\n","sub_path":"src/hw1/catch/const_holder.py","file_name":"const_holder.py","file_ext":"py","file_size_in_byte":1772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"304353658","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue May 8 17:38:43 2018\r\n\r\n@author: wyh\r\n\"\"\"\r\n\r\n\"\"\"\r\nGiven an array of integers, return indices of the two numbers \r\nsuch that they add up to a specific target.\r\nYou may assume that each input would have exactly one solution, \r\nand you may not use the same element twice. \r\n\"\"\"\r\n\r\nclass Solution:\r\n def twoSum1(self, nums, target):\r\n \"\"\"\r\n :type nums: List[int]\r\n :type target: int\r\n :rtype: List[int]\r\n \"\"\"\r\n dic = {}\r\n for index, num in enumerate(nums):\r\n if num in dic:\r\n return [dic[num], index]\r\n else:\r\n dic[target - num] = index\r\n\r\n def twoSum2(self, nums, target):\r\n \"\"\"\r\n :type nums: List[int]\r\n :type target: int\r\n :rtype: List[int]\r\n \"\"\"\r\n for i in range(len(nums)):\r\n for j in range(i+1, len(nums)):\r\n if nums[i] + nums[j] == target:\r\n return [i, j]","sub_path":"1. Two Sum.py","file_name":"1. Two Sum.py","file_ext":"py","file_size_in_byte":997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"118954243","text":"import board\nimport neopixel\nimport time\nimport datetime\nimport logging\nfrom datetime import timezone\nimport numpy\nimport json\nfrom skyfield.api import N, W, wgs84, load, utc\nfrom skyfield.almanac import find_discrete, risings_and_settings\n\n#initialize log\nlogging.basicConfig(filename='main.log', format='%(asctime)s %(levelname)-8s %(message)s',\ndatefmt='%Y-%m-%d %H:%M:%S', level=logging.DEBUG)\nlogging.logProcesses = 0\nlogging.logThreads = 0\n\ndef read_config():\n with open('config.json') as json_file:\n config_data = json.load(json_file)\n return config_data\n\ndef planet_timestamp(name, action, ts, planets, city, eph, names):\n print(name, action)\n logging.info('%s %s' % (name, action))\n # this function returns the next rise or set time from now\n t0 = datetime.datetime.now(timezone.utc)\n print('t0:', t0)\n logging.info('t0: %s' % t0)\n # make hours 24+1 because during spring, next sunset will be more than 24h later than current\n t1 = t0 + datetime.timedelta(hours=28)\n print('t1:', t1)\n logging.info('t1: %s' % t1)\n\n # t0 = t0.replace(tzinfo=utc)\n t0 = ts.utc(t0)\n # t1 = t1.replace(tzinfo=utc)\n t1 = ts.utc(t1)\n\n f = risings_and_settings(eph, planets[names.index(name)], city)\n #This returns a function taking a Time argument returning True if the body’s altazimuth altitude angle plus radius_degrees is greater than horizon_degrees, else False\n t, values = find_discrete(t0, t1, f)\n #Find the times at which a discrete function of time changes value. in this case, find the set (0) and rise (1) times, t.\n\n if action == 'rise':\n #values array is 1 for the rise. we look up the index of the rise in the time array, t, to get the time of the rise event.\n timestamp = t[numpy.where(values == 1)].utc_datetime()\n print('timestamp:', timestamp)\n logging.info('timestamp: %s' % timestamp)\n else:\n #values array is 0 for the set. we look up the index of the set in the time array, t, to get the time of the set event.\n timestamp = t[numpy.where(values == 0)].utc_datetime()\n print('timestamp:', timestamp)\n logging.info('timestamp: %s' % timestamp)\n\n timestamp = timestamp[0].timestamp()\n return int(timestamp)\n\ndef make_planet_list(ts, planets, city, eph, names):\n rise = [[0 for i in range(3)] for j in range(len(names))]\n sett = [[0 for i in range(3)] for j in range(len(names))]\n for i, name in enumerate(names):\n # obtain the next rise time\n rise[i][0] = planet_timestamp(name, 'rise', ts, planets, city, eph, names)\n rise[i][1] = name\n rise[i][2] = 'rise'\n\n print('acquired:', rise[i][0], name, 'rise')\n logging.info('acquired: %s, %s, rise' % (rise[i][0], name))\n\n # obtain the next set time\n sett[i][0] = planet_timestamp(name, 'sett', ts, planets, city, eph, names)\n sett[i][1] = name\n sett[i][2] = 'sett'\n\n print('acquired:', sett[i][0], name, 'sett')\n logging.info('acquired: %s, %s, sett' % (sett[i][0], name))\n\n rise = [tuple(l) for l in rise]\n sett = [tuple(l) for l in sett]\n planet_list = rise + sett\n return planet_list\n\ndef run_clock():\n #initialize skyfield stuff\n eph = load('de421.bsp')\n sun = eph['sun']\n moon = eph['moon']\n mercury = eph['mercury']\n venus = eph['venus']\n earth = eph['earth']\n mars = eph['mars']\n jupiter = eph['JUPITER BARYCENTER']\n saturn = eph['SATURN BARYCENTER']\n uranus = eph['URANUS BARYCENTER']\n neptune = eph['NEPTUNE BARYCENTER']\n planets = [sun,\n moon,\n mercury,\n venus,\n mars,\n jupiter,\n saturn,\n uranus,\n neptune]\n ts = load.timescale()\n\n # define variables\n # lat = 38.9072\n # lon = 77.0369\n config_data = read_config()\n #define city just by lat/lon for almanac lookup\n city = wgs84.latlon(float(config_data['lat']), float(config_data['lon']))\n names = ['sun', 'moon', 'mercury', 'venus', 'mars', 'jupiter', 'saturn', 'uranus', 'neptune']\n\n #initialize neopixel\n pixel_pin = board.D18\n n = 81\n ORDER = neopixel.RGBW\n pixels = neopixel.NeoPixel(pixel_pin, n, brightness=1, pixel_order=ORDER)\n # LED list for each light\n LED = [(0, 0, 0, 25),\n (0, 0, 0, 25),\n (0, 0, 0, 25),\n (0, 0, 0, 25),\n (0, 0, 0, 25),\n (0, 0, 0, 25),\n (0, 0, 0, 25),\n (0, 0, 0, 25),\n (0, 0, 0, 25)]\n\n now = int(time.time()) # return time since the Epoch\n print('current unix timestamp:', now)\n logging.info('current unix timestamp: %s' % now)\n now_local = time.localtime(now)\n now_local_str = \" \".join(map(str, now_local))\n\n print('local time string:', now_local_str)\n logging.info('local time string: %s' % now_local_str)\n\n planet_list = make_planet_list(ts, planets, city, eph, names)\n\n for i in range(len(names)):\n\n #clear LEDs at boot\n pixels[i * 9] = (0, 0, 0, 0)\n pixels[i * 9 + 1] = (0, 0, 0, 0)\n pixels[i * 9 + 2] = (0, 0, 0, 0)\n pixels[i * 9 + 3] = (0, 0, 0, 0)\n pixels[i * 9 + 4] = (0, 0, 0, 0)\n pixels[i * 9 + 5] = (0, 0, 0, 0)\n pixels[i * 9 + 6] = (0, 0, 0, 0)\n pixels[i * 9 + 7] = (0, 0, 0, 0)\n pixels[i * 9 + 8] = (0, 0, 0, 0)\n pixels.show()\n time.sleep(0.5)\n\n #turn on LEDs for planets already above horizon\n if planet_list[i][0] > planet_list[i + 9][0]: # if rise time is later than set time, it's above the horizon\n print('above horizon:', planet_list[i][1])\n\n dur_rem = planet_list[i + 9][0] - now #find time remaining until set\n dur = (24 * 3600) - (planet_list[i][0] - planet_list[i + 9][0]) #find approximate total time above horizon\n dur_int = int(dur / (2 * (n / len(names)) - 1)) #find duration of a single timestemp interval\n int_rem = int(dur_rem / dur_int) # number of intervals remaining is the duration remaining divided by duration interval\n if int_rem > 17:\n int_rem = 17\n\n dur_int_rem = dur % dur_int #remainder of time in final interval\n print('duration remaining:', dur_rem)\n print('intervals remaining:', int_rem)\n\n timestamp, planetname, action = planet_list[i + 9]\n\n #if the planet is setting:\n if int_rem < (n / len(names)) and not int_rem == 0:\n # 1. find a_set timestamps\n for j in range(int_rem - 1):\n above_set_timestamp = int(timestamp - ((dur_int * (j + 1)) + dur_int_rem))\n above_set_tuple = (above_set_timestamp, planetname, 'a_set')\n planet_list.append(above_set_tuple)\n\n # 2. light up last int_rem LEDs for setting\n if i % 2 == 1:\n for j in range(int_rem):\n pixels[i * 9 + 9 - (j + 1)] = LED[j]\n pixels.show()\n elif i % 2 == 0:\n for j in range(int_rem):\n pixels[i * 9 + j] = LED[j]\n pixels.show()\n elif int_rem == 0: #if the planet is about to set, light up last LED only\n if i % 2 == 1:\n pixels[i * 9 + 9 - 1] = LED[0]\n pixels.show()\n elif i % 2 == 0:\n pixels[i * 9] = LED[0]\n pixels.show()\n\n # if the planet is rising:\n else:\n #1. find a_rise timestamps\n for j in range(int_rem - int(n / len(names))):\n above_rise_timestamp = int(timestamp - (int((n / len(names)) - 1) * dur_int + dur_int * (j + 1) + dur_int_rem))\n above_rise_tuple = (above_rise_timestamp, planetname, 'a_rise')\n planet_list.append(above_rise_tuple)\n #2. find a_set timestamps\n for j in range(int(n / len(names) - 1)):\n above_set_timestamp = int(timestamp - (dur_int * (j + 1) + dur_int_rem))\n above_set_tuple = (above_set_timestamp, planetname, 'a_set')\n planet_list.append(above_set_tuple)\n #3. light up LEDs\n for j in range(2 * int(n / len(names)) - int_rem):\n if i % 2 == 1:\n pixels[i * 9 + j] = LED[j]\n pixels.show()\n elif i % 2 == 0:\n pixels[i * 9 + 9 - (j + 1)] = LED[j]\n pixels.show()\n\n list.sort(planet_list) #sort list of rise and set chronologically\n print('planet list:')\n print(planet_list)\n logging.info('planet_list: %s' % planet_list)\n\n while True:\n timestamp, planetname, action = planet_list.pop(0)\n timestamp_local = time.localtime(timestamp)\n timestamp_local_str = \" \".join(map(str, timestamp_local))\n print('next up:',\n 'planet:', planetname,\n 'action:', action,\n 'unix timestamp:', timestamp,\n 'local event time:', timestamp_local_str)\n logging.info('next up: planet: %s, action: %s, unix timestamp: %s, local event time: %s' % (planetname, action, timestamp,timestamp_local_str))\n\n planet_num = names.index(planetname)\n\n #sleep until the action\n delay = timestamp - now\n print('delay is:', delay)\n logging.info('delay is: %s' % delay)\n\n if delay > 0:\n # sleep until timestamp\n time.sleep(delay)\n\n if action == 'rise':\n print('action is:', action)\n logging.info('action is: %s' % action)\n\n #part 1: create list of above horizon intervals to adjust LEDs\n dur = [item for item in planet_list if planetname in item][0][0] - timestamp\n #find duration above horizon in seconds by looking up the timstamp of that planet's set time in planet_list (the rise time has been popped out)\n dur_int = int(dur / (2 * (n / len(names)) - 1)) #find duration of a single timestemp interval\n #dur_rem = dur % dur_int #find duration leftover (might not need this)\n print('total time above horizon:', dur)\n logging.info('total time above horizon: %s' % dur)\n\n #add action timestamps for above_rise and above_set intervals between rise and set\n for j in range(int((n / len(names)) - 1)):\n above_rise_timestamp = int((timestamp + dur_int * (j + 1)))\n above_rise_tuple = (above_rise_timestamp, planetname, 'a_rise')\n planet_list.append(above_rise_tuple)\n for j in range(int((n / len(names)) - 1)):\n above_set_timestamp = int((timestamp + int((n / len(names)) - 1) * dur_int + dur_int * (j + 1)))\n above_set_tuple = (above_set_timestamp, planetname, 'a_set')\n planet_list.append(above_set_tuple)\n\n #turn on first LED at rise action timestamp\n if planet_num % 2 == 1:\n pixels[planet_num * 9] = LED[0]\n pixels.show()\n if planet_num % 2 == 0:\n pixels[planet_num * 9 + 9 - 1] = LED[0]\n pixels.show()\n\n print(planetname, 'rise')\n logging.info('%s, rise' % planetname)\n\n elif action == \"a_rise\":\n print('action is:', action)\n logging.info('action is: %s' % action)\n\n #count remaining instances of a_rise\n count = 0\n for i in range(len(planet_list)):\n if planet_list[i][1] == planetname and planet_list[i][2] == action:\n count += 1\n LED_count = int(n / len(names)) - count\n print('count is:', count)\n logging.info('count is: %s' % count)\n\n for i in range(LED_count):\n if planet_num % 2 == 1:\n pixels[planet_num * 9 + i] = LED[i]\n pixels.show()\n elif planet_num % 2 == 0:\n pixels[planet_num * 9 + 9 - (i + 1)] = LED[i]\n pixels.show()\n\n elif action == \"a_set\":\n print('action is:', action)\n logging.info('action is: %s' % action)\n\n count = 0\n for i in range(len(planet_list)):\n if planet_list[i][1] == planetname and planet_list[i][2] == action:\n count += 1\n LED_count = count + 1\n print('count is:', count)\n logging.info('count is: %s' % count)\n\n pixels[planet_num * 9] = (0, 0, 0, 0)\n pixels[planet_num * 9 + 1] = (0, 0, 0, 0)\n pixels[planet_num * 9 + 2] = (0, 0, 0, 0)\n pixels[planet_num * 9 + 3] = (0, 0, 0, 0)\n pixels[planet_num * 9 + 4] = (0, 0, 0, 0)\n pixels[planet_num * 9 + 5] = (0, 0, 0, 0)\n pixels[planet_num * 9 + 6] = (0, 0, 0, 0)\n pixels[planet_num * 9 + 7] = (0, 0, 0, 0)\n pixels[planet_num * 9 + 8] = (0, 0, 0, 0)\n\n for i in range(LED_count):\n if planet_num % 2 == 1:\n pixels[planet_num * 9 + 9 - (i + 1)] = LED[i]\n pixels.show()\n if planet_num % 2 == 0:\n pixels[planet_num * 9 + i] = LED[i]\n pixels.show()\n\n elif action == \"sett\":\n print('action is:', action)\n logging.info('action is: %s' % action)\n\n pixels[planet_num * 9] = (0, 0, 0, 0)\n pixels[planet_num * 9 + 1] = (0, 0, 0, 0)\n pixels[planet_num * 9 + 2] = (0, 0, 0, 0)\n pixels[planet_num * 9 + 3] = (0, 0, 0, 0)\n pixels[planet_num * 9 + 4] = (0, 0, 0, 0)\n pixels[planet_num * 9 + 5] = (0, 0, 0, 0)\n pixels[planet_num * 9 + 6] = (0, 0, 0, 0)\n pixels[planet_num * 9 + 7] = (0, 0, 0, 0)\n pixels[planet_num * 9 + 8] = (0, 0, 0, 0)\n pixels.show()\n\n time.sleep(5)\n\n if [item for item in planet_list if item[1] == planetname and item[2] == 'rise']:\n #get next set timestamp only and add to list if there's already a 'rise' timestamp\n next_set_timestamp = planet_timestamp(planetname, 'sett', ts, planets, city, eph, names)\n next_set_tuple = (next_set_timestamp, planetname, 'sett')\n planet_list.append(next_set_tuple)\n print('rise found in planet_list')\n print('next set:', next_set_timestamp)\n logging.info('rise found in planet_list')\n logging.info('next set: %s' % next_set_timestamp)\n\n\n else:\n print('no rise found in planet_list')\n logging.info('no rise found in planet_list')\n #get next rise timestamp and add to tuple if there isn't a rise\n next_rise_timestamp = planet_timestamp(planetname, 'rise', ts, planets, city, eph, names)\n next_rise_tuple = (next_rise_timestamp, planetname, 'rise')\n planet_list.append(next_rise_tuple)\n print('next rise:', next_rise_timestamp)\n logging.info('next rise: %s' % next_rise_timestamp)\n\n\n #get next set timestamp and add to list\n next_set_timestamp = planet_timestamp(planetname, 'sett', ts, planets, city, eph, names)\n next_set_tuple = (next_set_timestamp, planetname, 'sett')\n planet_list.append(next_set_tuple)\n print('next set:', next_set_timestamp)\n logging.info('next set: %s' % next_set_timestamp)\n\n\n now = int(time.time()) # return time since the Epoch (embedded)\n print('current unix timestamp:', now)\n logging.info('current unix timestamp: %s' % now)\n\n now_local = time.localtime(now)\n now_local_str = \" \".join(map(str, now_local))\n print('current local time:', now_local_str)\n logging.info('current local time: %s' % now_local_str)\n\n list.sort(planet_list)\n print('planet list:')\n print(planet_list)\n logging.info('planet list: %s' % planet_list)\n\nif __name__ == \"__main__\":\n try:\n run_clock()\n\n except Exception as e:\n logging.exception(e)\n raise\n","sub_path":"embedded/RpiPico/main_zero.py","file_name":"main_zero.py","file_ext":"py","file_size_in_byte":16437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"579267835","text":"# Python imports\nimport os\nimport ipaddress\nimport requests\nimport json\nimport logging\nfrom time import sleep\nfrom jinja2 import Template\nfrom pprint import pprint\n\nfrom django.conf import settings\n\n\n# Netmiko imports\nfrom netmiko import ConnectHandler\nfrom netmiko.ssh_exception import NetMikoTimeoutException, NetMikoAuthenticationException\nfrom requests.exceptions import HTTPError\n\n# Pyez imports\nfrom jnpr.junos import Device\nfrom jnpr.junos.utils.config import Config\nfrom jnpr.junos.exception import CommitError, RpcTimeoutError, ConnectError, ConnectAuthError, ConfigLoadError\n\n\n# ONSA imports\nfrom worker.lib.nsx.nsx_rest import *\nfrom worker.lib.common.render import render\nfrom worker.constants import *\nfrom worker.exceptions import *\n\n\ndef get_edge_id_by_name(name, **kwargs):\n rheaders = {'Accept': 'application/json'}\n\n r = requests.get(kwargs['manager'] + \"/api/4.0/edges\",\n auth=(USER, PASS), verify=False, headers=rheaders)\n r.raise_for_status()\n\n r_dict = json.loads(r.text)\n allEdges = r_dict['edgePage']['data']\n\n for edge in allEdges:\n if edge['name'] == name:\n return edge['id']\n\n return \"\"\n\n\nclass ConfigHandler:\n\n def pyez(template_path, parameters):\n\n pprint(render(template_path, parameters))\n\n logging.basicConfig(level=logging.INFO)\n dev = Device(host=parameters['mgmt_ip'],\n user=os.getenv('AUTOMATION_USER'), password=os.getenv('AUTOMATION_PASSWORD'), port=443)\n dev.bind(cu=Config)\n\n try:\n logging.info(\"Openning NETCONF connection to device\")\n dev.open()\n except (ConnectError) as err:\n logging.error(\"Cannot connect to device:%s\", err)\n return ERR532\n except (ConnectAuthError) as err:\n logging.error('Cannot connect to device: %s', err)\n return ERR533\n\n logging.info(\"Locking the configuration\")\n try:\n dev.cu.lock()\n except LockError:\n logging.error(\"Error: Unable to lock configuration\")\n dev.close()\n return ERR531\n try:\n dev.cu.load(template_path=template_path, merge=True,\n template_vars=parameters, format=\"set\")\n dev.cu.pdiff()\n except ValueError as err:\n logging.error(\"Error: %s\", err.message)\n return ERR531\n except ConfigLoadError as err:\n logging.error(\"Unable to load configuration changes: %s\", err)\n\n logging.info(\"Unlocking the configuration\")\n try:\n dev.cu.unlock()\n except UnlockError:\n logging.error(\"Error: Unable to unlock configuration\")\n return ERR531\n\n dev.close()\n return ERR531\n\n logging.info(\"Committing the configuration\")\n try:\n dev.timeout = 120\n commit_result = dev.cu.commit()\n # Show that the commit worked True means it worked, false means it failed\n logging.debug(\"Commit result: %s\", commit_result)\n except (CommitError, RpcTimeoutError) as e:\n logging.error(\"Error: Unable to commit configuration\")\n logging.error(e)\n dev.cu.unlock()\n dev.close()\n return ERR531\n\n logging.info(\"Unlocking the configuration\")\n try:\n dev.cu.unlock()\n except UnlockError:\n logging.error(\"Error: Unable to unlock configuration\")\n return ERR531\n\n try:\n logging.info(\"Closing NETCONF session\")\n dev.close()\n except ConnectClosedError as err:\n logging.info(\"Error: Unable to close connection. %s\", err)\n return ERR531\n\n return ERR0\n\n def ssh(template_path, params):\n\n my_device = {\n 'host': params['mgmt_ip'],\n 'username': os.getenv('AUTOMATION_USER'),\n 'password': os.getenv('AUTOMATION_PASSWORD'),\n 'device_type': 'cisco_ios',\n 'global_delay_factor': 1,\n 'timeout': TIMEOUT_TIME\n }\n\n config = render(template_path, params).splitlines()\n logging.info(\"config\")\n logging.info(config)\n\n try:\n net_connect = ConnectHandler(**my_device)\n output = net_connect.send_config_set(config)\n net_connect.disconnect()\n return CONFIG_OK\n except (NetMikoTimeoutException) as e:\n logging.error(e)\n return CONFIG_TIMEOUT_ERROR\n except (NetMikoAuthenticationException) as e:\n logging.error(e)\n return CONFIG_AUTH_ERROR\n\n def nsx(template_path, params):\n\n MANAGER = 'https://' + params['mgmt_ip']\n params['trigger'] = False\n data = render(template_path, params)\n\n try:\n rheaders = {'Content-Type': 'application/xml'}\n r = requests.post(MANAGER + \"/api/4.0/edges\", data=data,\n auth=(USER, PASS), verify=False, headers=rheaders)\n r.raise_for_status()\n\n sleep(45)\n\n edge_id = get_edge_id_by_name(params['edge_name'], manager=MANAGER)\n\n params['trigger'] = True\n data = render(template_path, params)\n\n rheaders = {'Content-Type': 'application/json'}\n r = requests.put(MANAGER + \"/api/4.0/edges/%s/routing/config/static\" %\n edge_id, data=data, auth=(USER, PASS), verify=False, headers=rheaders)\n r.raise_for_status()\n\n return ERR0\n\n except (HTTPError) as err:\n return ERR531\n","sub_path":"worker/worker/lib/ConfigHandler.py","file_name":"ConfigHandler.py","file_ext":"py","file_size_in_byte":5640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"75939779","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nfrom django.conf import settings\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ]\n\n operations = [\n migrations.CreateModel(\n name='BlogItem',\n fields=[\n ('id', models.AutoField(serialize=False, verbose_name='ID', primary_key=True, auto_created=True)),\n ('caption', models.CharField(max_length=100)),\n ('contents', models.TextField()),\n ('creationDate', models.DateTimeField(auto_now=True)),\n ('author', models.ForeignKey(to=settings.AUTH_USER_MODEL)),\n ],\n ),\n migrations.CreateModel(\n name='CommonReview',\n fields=[\n ('id', models.AutoField(serialize=False, verbose_name='ID', primary_key=True, auto_created=True)),\n ('creationDate', models.DateTimeField(auto_now=True)),\n ('caption', models.CharField(max_length=50)),\n ('contents', models.TextField()),\n ('rating', models.FloatField()),\n ],\n ),\n migrations.CreateModel(\n name='SellItem',\n fields=[\n ('id', models.AutoField(serialize=False, verbose_name='ID', primary_key=True, auto_created=True)),\n ('caption', models.CharField(max_length=50)),\n ('desc', models.TextField()),\n ('creationDate', models.DateTimeField(auto_now=True)),\n ('price', models.DecimalField(max_digits=16, decimal_places=2)),\n ('seller', models.ForeignKey(to=settings.AUTH_USER_MODEL)),\n ],\n ),\n migrations.CreateModel(\n name='SellItemImage',\n fields=[\n ('id', models.AutoField(serialize=False, verbose_name='ID', primary_key=True, auto_created=True)),\n ('image', models.ImageField(upload_to='')),\n ('isMain', models.BooleanField()),\n ('sellItem', models.ForeignKey(to='RMarket.SellItem')),\n ],\n ),\n migrations.CreateModel(\n name='BlogItemReview',\n fields=[\n ('commonreview_ptr', models.OneToOneField(primary_key=True, serialize=False, to='RMarket.CommonReview', parent_link=True, auto_created=True)),\n ('blogItem', models.ForeignKey(to='RMarket.BlogItem')),\n ],\n bases=('RMarket.commonreview',),\n ),\n migrations.CreateModel(\n name='SellItemReview',\n fields=[\n ('commonreview_ptr', models.OneToOneField(primary_key=True, serialize=False, to='RMarket.CommonReview', parent_link=True, auto_created=True)),\n ('sellItem', models.ForeignKey(to='RMarket.SellItem')),\n ],\n bases=('RMarket.commonreview',),\n ),\n migrations.CreateModel(\n name='UserReview',\n fields=[\n ('commonreview_ptr', models.OneToOneField(primary_key=True, serialize=False, to='RMarket.CommonReview', parent_link=True, auto_created=True)),\n ('user', models.ForeignKey(to=settings.AUTH_USER_MODEL)),\n ],\n bases=('RMarket.commonreview',),\n ),\n migrations.AddField(\n model_name='commonreview',\n name='author',\n field=models.ForeignKey(to=settings.AUTH_USER_MODEL),\n ),\n ]\n","sub_path":"RMarket/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":3553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"236080660","text":"#!/usr/bin/env python3\n\nimport numpy as np\nimport sys\nnp.set_printoptions(precision=10)\nsystem2_x, system2_y = np.loadtxt(sys.argv[2], unpack=True,usecols=(1,2))\nsystem1_x, system1_y = np.loadtxt(sys.argv[1], unpack=True,usecols=(1,2))\npoint_number = np.genfromtxt('system_1.txt',unpack=True,usecols=0,dtype='str')\nA=np.arange(len(system2_x)*8,dtype=np.float64).reshape(len(system2_x)*2,4)\nL=np.arange(len(system2_x)*2,dtype=np.float64).reshape(len(system2_x)*2,1)\npoint_n = len(system1_x)-len(system2_x)\ntransformed = np.arange(point_n*2,dtype=np.float64).reshape(point_n,2)\nfull_matrix = np.arange(len(system1_x)*3,dtype=np.float64).reshape(len(system1_x),3)\n\nkatsayi_2=[]\nkatsayi_1=[i for i in range(len(system2_x)*2)]\nfor i in range(len(system2_x)):\n katsayi_2.append(i)\n katsayi_2.append(i)\n\nfor i in range(1,len(katsayi_1),2):\n A[katsayi_1[i-1],:] = [1,0,system1_x[katsayi_2[i-1]],-system1_y[katsayi_2[i-1]]]\n A[katsayi_1[i],:] = [0,1,system1_y[katsayi_2[i]],system1_x[katsayi_2[i]]]\n\nfor i in range(1,len(katsayi_1),2):\n L[katsayi_1[i-1],:] = system2_x[katsayi_2[i]]\n L[katsayi_1[i],:] = system2_y[katsayi_2[i]]\n \nN = np.dot(np.transpose(A),A)\nn = np.dot(np.transpose(A),L)\n\nx = np.dot(np.linalg.inv(N),n)\nv = np.dot(A,x)-L\n\nscale = np.sqrt(x[2]**2+x[3]**2)\nrotation = np.arctan2(x[3],x[2])\n\nprint(\"X Shifting: %8.5f\" % x[0])\nprint(\"Y Shifting: %8.5f\" % x[1])\nprint(\" Scale: %13.10f\" % scale)\nprint(\" Rotation: %13.10f\" % rotation)\n\nfor i in range(point_n):\n transformed[i,:] = [x[2]*system1_x[point_n+i+1]-x[3]*system1_y[point_n+i+1]+x[0],\n x[3]*system1_x[point_n+i+1]+x[2]*system1_y[point_n+i+1]+x[1]]\n\nfor i in range(len(system2_x)):\n full_matrix[i,:] = [point_number[i],system2_x[i], system2_y[i]]\n\nfor i in range(point_n+1,len(system1_x)):\n full_matrix[i,:] = [point_number[i],transformed[i-len(system2_x)][0],transformed[i-len(system2_x)][1]]\n \nfilename = \"Transformed_\" + sys.argv[2] \nwith open(filename,'w') as file:\n file.write(\" Point ID X Y\\n\")\n for i in range(len(full_matrix)):\n file.write('%10s %20.5f %15.5f\\n' % (full_matrix[i][0],full_matrix[i][1],full_matrix[i][2]))\n","sub_path":"2D_Helmert_transformation.py","file_name":"2D_Helmert_transformation.py","file_ext":"py","file_size_in_byte":2184,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"328375802","text":"from selenium import webdriver\n\n# 페이지 스크롤링을 위한 모듈\nfrom selenium.webdriver.common.keys import Keys\n\n# 다운로드 받은 드라이버 주소\nDRIVER_DIR = 'driver2/chromedriver'\n\ndriver = webdriver.Chrome(DRIVER_DIR)\n\n# 목표 웹페이지를 가져옴\nurl = \"https://www.us.kohler.com/us/browse/kitchen-kitchen-sinks/_/N-25b4\"\ndriver.get(url)\n\n\n# 상품명 가져오기\nitem_list = driver.find_elements_by_css_selector('.product-panel__summary.product-panel__summary-new')\nitem = []\nfor i in item_list:\n item.append(i.text)\n\nlen(item)\n\n# 가격 가져오기\nprice_list = driver.find_elements_by_css_selector('.product-panel__price.product-panel__price-new.light-gray--sku--price.promo-price-discountprice-nk')\nprice = []\nfor p in price_list:\n price.append(p.text)\n\nlen(price)\n\n\n\n# 데이터프레임으로 만들기\nimport pandas as pd\n\ndata_tuples = list(zip(item, price))\n\ndf = pd.DataFrame(data_tuples, columns=['item', 'price'])\n\n# 엑셀로 저장하기\n#df.to_csv(\"test.csv\", mode = 'w')\ndf.to_csv(\"test.csv\", mode = 'a', header=False)\n\n# 드라이버 종료하기\ndriver.quit()\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"333396251","text":"import argparse\n\nparser = argparse.ArgumentParser()\nparser.add_argument('dataset_name')\nparser.add_argument('--gpus')\nargs = parser.parse_args()\nprint(args)\n\nimport os\nif args.gpus:\n os.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\"\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = args.gpus\n print('CUDA_VISIBLE_DEVICES:', os.environ[\"CUDA_VISIBLE_DEVICES\"])\n\n\nimport keras.backend as K\nimport tensorflow as tf\nimport Net\nimport numpy as np\nimport StyleFeature\nimport scipy.io as sio\nimport cv2\nfrom DMB_fragment import rebuild_AMaps_by_img\nimport pickle\nimport random\nimport yaml\n\nfrom Opts import save_images, matTonpy\n# =============================== path set =============================================== #\nout_dir = args.dataset_name + '_Reconstruct'\nload_model = args.dataset_name\ndb_dataset = args.dataset_name\nreal_img_dataset = args.dataset_name # 'DRIVE'\nreal_img_test_dataset = args.dataset_name # 'DRIVE'\n\nresult_dir = 'Test' + '/' + out_dir + ''\nmodel_directory = 'Model_and_Result' + '/' + load_model + '/models' # Directory to restore trained model from.\n\nif tf.gfile.Exists(result_dir):\n print('Result dir exists! Press Enter to OVERRIDE...', end='')\n input()\n tf.gfile.DeleteRecursively(result_dir)\nif not os.path.exists(result_dir):\n os.makedirs(result_dir)\n\nos.system('cp {} {}'.format(__file__, result_dir))\n\n# ============================== parameters set ========================================== #\nmax_epoch = 1\n\n\nimg_channel = 3\nimg_size = 512\nimg_x = 512\nimg_y = 512\ngt_channel = 1\n\nz_size = 400\n\n\n\n# =============================== model and data definition ================================ #\ngenerator = Net.generator\n\ntf.reset_default_graph()\n\ngt = tf.placeholder(shape=[None, img_size, img_size, gt_channel], dtype=tf.float32)\nimg = tf.placeholder(shape=[None, img_size, img_size, img_channel], dtype=tf.float32)\nmask = tf.placeholder(shape=[None, img_size, img_size, 1], dtype=tf.float32)\nz = tf.placeholder(shape=[None, z_size], dtype=tf.float32)\n\n# gt_mask = tf.concat([gt, mask], 3)\n\nimg_detector = StyleFeature.get_style_model(img, mask, with_feature_mask_from=('dense_2', []))\nact_input = {\n size: tf.image.resize_images((img_detector.get_layer(layer_name).related_projection.output - mean)/std, [size,size])\n for layer_name, size, mean, std in zip(StyleFeature.STYLE_LAYERS,\n StyleFeature.STYLE_LAYERS_SIZE,\n StyleFeature.STYLE_LAYERS_MEAN,\n StyleFeature.STYLE_LAYERS_STD)\n}\n\nsyn = generator(gt, act_input, z)\n\n\n# =============================== init ============================================= #\nt_vars = tf.trainable_variables()\ng_vars = list(set(t_vars) & set(tf.global_variables('generator')))\n\ninit = tf.variables_initializer(g_vars)\nsess = K.get_session()\nsaver = tf.train.Saver(g_vars, max_to_keep=None)\n\nsess.run(init)\n#writer = tf.train.SummaryWriter(model_directory, sess.graph)\n\n# ==================================== restore weights ================================ #\nckpt = tf.train.get_checkpoint_state(model_directory)\nrestore_path = ckpt.model_checkpoint_path.replace('-9000', '-9000')\nprint(restore_path)\nsaver.restore(sess, restore_path)\n\n\n\n# ==================================== start training ===================================== #\n\nif real_img_test_dataset in ['FGADR', 'retinal-lesions', 'IDRiD']:\n # img_sample = np.load('data/{}_test_image.npy'.format(real_img_test_dataset))\n gt_sample = np.load('data/{}_test_gt.npy'.format(real_img_test_dataset))[..., [0]]\n mask_sample = np.load('data/{}_test_mask.npy'.format(real_img_test_dataset))\nelif real_img_test_dataset == 'DRIVE':\n img_sample, gt_sample, mask_sample = Net.matTonpy_35()\n\n\n# img_sample = (np.reshape(img_sample, [-1, img_x, img_y, img_channel]) - 0.5) * 2.0\ngt_sample = (np.reshape(gt_sample, [-1, img_x, img_y, gt_channel]) - 0.5) * 2.0\nmask_sample = (np.reshape(mask_sample, [-1, img_x, img_y, 1]) - 0.5) * 2.0\n\nper_part = 250\npart_id = -1\n\nwith open('data/'+real_img_test_dataset+'_test.list', 'r') as f:\n fname_list = yaml.safe_load(f)\n\n# amaps = rebuild_AMaps_by_img(0, fragments_DB)\n\n# generate images with fragmentDB\nfor epoch in range(max_epoch):\n print('epoch:', epoch)\n batchNum = 1\n\n for i, (gt_array, mask_array) in enumerate(zip(gt_sample, mask_sample)):\n print('img:', batchNum)\n\n if i//per_part != part_id:\n part_id = i//per_part\n with open('DMB/{}.by_img.{}'.format(db_dataset, part_id), 'rb') as file:\n fragments_DB = pickle.load(file)\n\n zs = np.random.normal(0, 0.001, size=[1, z_size]).astype(np.float32)\n\n amaps = rebuild_AMaps_by_img(i % per_part, fragments_DB)\n syn_array = sess.run(syn, feed_dict={gt: [gt_array], z:zs, mask: [mask_array],\n act_input[256]: [amaps[256]],\n act_input[64]: [amaps[64]]})\n syn_array = (syn_array + 1) / 2\n syn_sample_m = syn_array * ((mask_array + 1) / 2)\n\n syn_sample_m = np.reshape(syn_sample_m, [img_x, img_y, img_channel])\n save_images(np.reshape(syn_sample_m, [1, img_x, img_y, img_channel]),\n [1, 1],\n result_dir + '/{}_{}.jpg'.format(fname_list[i], epoch))\n\n batchNum += 1\n\nsess.close()\n","sub_path":"Test_reconstruct_DMB_FGADR.py","file_name":"Test_reconstruct_DMB_FGADR.py","file_ext":"py","file_size_in_byte":5373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"379087794","text":"from django.apps import apps\n\nfrom django_airavata.app_config import AiravataAppConfig\n\n\ndef airavata_app_registry(request):\n \"\"\"Put airavata django apps into the context.\"\"\"\n airavata_apps = [app for app in apps.get_app_configs()\n if isinstance(app, AiravataAppConfig)]\n # Sort by app_order then by verbose_name (case-insensitive)\n airavata_apps.sort(\n key=lambda app: \"{:09}-{}\".format(app.app_order,\n app.verbose_name.lower()))\n current_airavata_app = [\n app for app in airavata_apps\n if request.resolver_match and\n app.url_app_name == request.resolver_match.app_name]\n current_airavata_app = current_airavata_app[0]\\\n if len(current_airavata_app) > 0 else None\n return {\n 'airavata_apps': airavata_apps,\n 'current_airavata_app': current_airavata_app,\n }\n\n\ndef resolver_match(request):\n \"\"\"Put resolver_match (ResolverMatch instance) into the context.\"\"\"\n return {'resolver_match': request.resolver_match}\n","sub_path":"django_airavata/context_processors.py","file_name":"context_processors.py","file_ext":"py","file_size_in_byte":1049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"257313588","text":"from django.conf.urls import url\nfrom . import views\n\napp_name = 'music'\n\nurlpatterns = [\n # /music/\n url(r'^$', views.IndexView.as_view(),name= 'index'),\n\nurl(r'^register/$', views.UserFormView.as_view(),name= 'register'),\n\n # music/45/\n url(r'^(?P[0-9]+)/$', views.DetailView.as_view(), name='detail'),\n\n #/music/album/add/\n url(r'album/add/$', views.AddCreate.as_view(), name='add-album'),\n\n #/music/album/45/\n url(r'album/(?P[0-9]+)/$', views.AlbumUpdate.as_view(), name='album-update'),\n\n #/music/45/delete\n url(r'album/(?P[0-9]+)/delete/$', views.AlbumDelete.as_view(), name='album-delte'),\n]","sub_path":"music/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"557800976","text":"import mimetypes\n\nfrom email import encoders as Encoders\nfrom email.message import Message\nfrom email.mime.text import MIMEText\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.nonmultipart import MIMENonMultipart\nfrom smtplib import SMTP\n\n\nclass StartMessage:\n def __init__(self, fromAdd, toAdd, subject, body):\n self.msg = Message()\n self.msg.set_payload(body)\n self[\"Subject\"] = subject\n self.setFrom(fromAdd)\n self.setTo(toAdd)\n self.hasAttachments = False\n\n def setFrom(self, fromAdd):\n if not fromAdd or not type(fromAdd) == type(\"\"):\n raise Exception(\"a message must have one and only one sender\")\n self[\"From\"] = fromAdd\n\n def setTo(self, to):\n if not to:\n raise Exception(\"a message must have at least one recipient\")\n self._addresses(to, \"To\")\n self.to = to\n\n def setCc(self, cc):\n self._addresses(cc, \"Cc\")\n\n def addAttachment(self, attachment, filename, mimetype=None):\n if not mimetype:\n mimetype = mimetypes.guess_type(filename)[0]\n if not mimetype:\n raise Exception(\"could not determine MIME type for \", filename)\n if \"/\" in mimetype:\n major, minor = mimetype.split(\"/\")\n else:\n major = mimetype\n minor = None\n if not self.hasAttachments:\n body = self.msg.set_payload()\n newMsg = MIMEMultipart()\n newMsg.attach(MIMEText(body))\n\n for header, value in self.msg.items():\n newMsg[header] = value\n\n self.msg = newMsg\n self.hasAttachments = True\n subMessage = MIMENonMultipart(major, minor, name=filename)\n subMessage.set_payload(attachment)\n\n if major == \"text\":\n encoder = Encoders.encode_quopri\n else:\n encoder = Encoders.encode_base64\n encoder(subMessage)\n self.msg.attach(subMessage)\n\n def _addresses(self, addresses, key):\n if hasattr(addresses, \"__iter__\"):\n addresses = ''.join(addresses)\n self[key] = addresses\n\n def __getitem__(self, key):\n return self.msg[key]\n\n def __setitem__(self, key, value):\n self.msg[key] = value\n\n def __getattr__(self, key):\n return getattr(self.msg, key)\n\n def __str__(self):\n return self.msg.as_string()\n\n\n\nclass MailServer(SMTP):\n def __init__(self, server, serverUser=None, serverPassword=None, port=25):\n SMTP.__init__(self, server, port)\n self.user = serverUser\n self.password = serverPassword\n # self.set_debuglevel(True)\n\n def sendMessage(self, message):\n if self.user:\n self.login(self.user, self.password)\n\n destinations = message.to\n if hasattr(destinations, \"__iter__\"):\n destinations = map(self._cleanAddress, destinations)\n else:\n destinations = self._cleanAddress(destinations)\n self.sendmail(message[\"From\"], destinations, str(message))\n\n def _cleanAddress(self, address):\n parts = address.split(\"<\", 1)\n if len(parts) > 1:\n newAddress = parts[1]\n endAddress = newAddress.find(\">\")\n if endAddress != -1:\n address = newAddress[:endAddress]\n return address\n\n\nmsg = StartMessage(\"Me \", \"You \", \"your picture\", \"pic of you\")\n# print(msg)\n\nmsg.addAttachment(open(\"/home/mahedi/ok.jpg\").read(), 'ok.jpg')\n# print(str(msg))","sub_path":"chapter_16_Network_Programming/SendMail.py","file_name":"SendMail.py","file_ext":"py","file_size_in_byte":3523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"502067290","text":"def https(s):\n if(s[0:8]==\"https://\"):\n return '1'\n else:\n return '0'\ndef url(s):\n if (\".com\" in s or \".net\" in s or \".org\" in s or \".in\" in s):\n return \"1\"\n else :\n return '0'\ns = input(\"Enter the string to check if it is an URL\")\nc = https(s)\nif c =='1':\n u = url(s)\n if u =='1':\n print(f\"{s} is an URL\")\n else:\n print(f\"{s} is not an URL\")\nelse:\n print(f\"{s} is not an URL\")\n","sub_path":"December-09/url.py","file_name":"url.py","file_ext":"py","file_size_in_byte":444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"124730278","text":"from django.contrib import admin\nfrom django.contrib.auth.admin import UserAdmin as DefaultUserAdmin\nfrom django.contrib.auth.models import User, Permission\nfrom redcross.api import models\nfrom django.contrib.auth import get_permission_codename\nfrom django.utils.translation import gettext as _\nfrom django.http import HttpResponse\nfrom django.utils.html import mark_safe\nimport csv\nfrom django_summernote.admin import SummernoteModelAdmin\n\n\nclass ProfileInline(admin.StackedInline):\n model = models.Profiles\n can_delete = False\n verbose_name_plural = _('Profile')\n fk_name = 'user'\n readonly_fields = [ 'mobile', 'mobile_verify_code', 'activation_key' ,'fb_user_id','gg_user_id']\n\n\nclass UserAdmin(DefaultUserAdmin):\n inlines = (ProfileInline,)\n \n def get_inline_instances(self, request, obj=None):\n if not obj:\n return list()\n return super(UserAdmin, self).get_inline_instances(request, obj)\n\n\nclass CategoriesProjectsInline(admin.TabularInline):\n model = models.Projects.category.through\n\nclass CategoriesAdmin(admin.ModelAdmin):\n list_display = ('name', 'sort', 'status', 'updated_at')\n list_filter = ('created_at', 'updated_at', 'status', )\n search_fields = ('id', 'name_en_US', 'name_km_KH', 'name_zh_CN')\n date_hierarchy = ('updated_at')\n ordering = ('id', 'created_at', 'updated_at')\n actions = ['make_disabled', 'make_enabled']\n inlines=(CategoriesProjectsInline,)\n\n def name(self, obj):\n return ', '.join([\n obj.name_en_US, obj.name_km_KH, obj.name_zh_CN\n ])\n name.short_description = _('name')\n\n def make_disabled(self, request, queryset):\n rows_updated = queryset.update(status=0)\n if rows_updated == 1:\n message_bit = _('1 category was')\n else:\n message_bit = _('%s categories were') % rows_updated\n self.message_user(request,\n _('%s successfully marked as disabled.') % message_bit)\n make_disabled.allowed_permissions = ('disable',)\n\n def has_disable_permission(self, request):\n \"\"\"Does the user have the disable permission?\"\"\"\n opts = self.opts\n codename = get_permission_codename('can_make_disabled', opts)\n return request.user.has_perm('%s.%s' % (opts.app_label, codename))\n\n def make_enabled(self, request, queryset):\n rows_updated = queryset.update(status=1)\n if rows_updated == 1:\n message_bit = _('1 category was')\n else:\n message_bit = _('%s categories were') % rows_updated\n self.message_user(request, _(\n '%s successfully marked as enabled.') % message_bit)\n make_enabled.allowed_permissions = ('enable',)\n\n def has_enable_permission(self, request):\n \"\"\"Does the user have the enable permission?\"\"\"\n opts = self.opts\n codename = get_permission_codename('can_make_enabled', opts)\n return request.user.has_perm('%s.%s' % (opts.app_label, codename))\n\n\nclass ProjectStuffsInline(admin.StackedInline):\n model = models.ProjectStuffs\n verbose_name_plural = 'Project Stuff'\n fk_name = 'project'\n\n\nclass ProjectsAdmin(SummernoteModelAdmin):\n list_display = (\n 'title','main_image','goal_money','status', 'deal_status',\n 'created_at', 'updated_at'\n )\n\n list_filter = ('created_at', 'updated_at', 'status', 'deal_status',)\n search_fields = ('id', 'title_km_KH', 'title_en_US', 'title_zh_CN')\n date_hierarchy = ('updated_at')\n ordering = ('id', 'created_at', 'updated_at')\n inlines = (ProjectStuffsInline, CategoriesProjectsInline)\n actions= ['export_as_csv']\n summernote_fields=('introduction_zh_CN','introduction_en_US','introduction_km_KH')\n readonly_fields = ['user','current_money','donate_people_total','reads_total']\n\n def save_model(self, request, obj, form, change):\n\n if not obj.pk:\n obj.user = request.user\n super().save_model(request, obj, form, change)\n\n def export_as_csv(self, request, queryset):\n meta = self.model._meta\n field_names = [field.name for field in meta.fields]\n\n response = HttpResponse(content_type='text/csv')\n response['Content-Disposition'] = 'attachment; filename={}.csv'.format(meta)\n writer = csv.writer(response)\n\n writer.writerow(field_names)\n for obj in queryset:\n row = writer.writerow([getattr(obj, field) for field in field_names])\n\n return response\n export_as_csv.short_description = \"Export Selected\"\n\n def title(self, obj):\n return ', '.join([\n obj.title_en_US if obj.title_en_US is not None else '', \n obj.title_km_KH if obj.title_km_KH is not None else '', \n obj.title_zh_CN if obj.title_zh_CN is not None else '', \n ])\n title.short_description = _('title')\n\nclass DonatesAdmin(admin.ModelAdmin):\n list_display = (\n 'id', 'user', 'project', 'donate_money', 'pay_type',\n 'is_noname', 'status', 'order_id', 'created_at', 'updated_at'\n )\n list_filter = ('id', 'is_noname', 'status', 'created_at', 'updated_at',)\n search_fields = ('id', 'pay_type', 'is_noname', 'status', 'order_id')\n date_hierarchy = ('updated_at')\n ordering = ('id', 'created_at', 'updated_at')\n\n readonly_fields=['user','project','donate_money','pay_type','is_noname','pay_type','order_id','status']\n\n\nclass NewsAdmin(SummernoteModelAdmin):\n list_display = (\n 'title','main_image','status','sort', 'updated_at'\n )\n list_filter = ('status', 'is_video', 'news_type',\n 'deal_status', 'created_at', 'updated_at',)\n search_fields = (\n 'id', 'title_km_KH', 'title_en_US',\n 'title_zh_CN', 'status', 'is_video'\n )\n date_hierarchy = ('updated_at')\n ordering = ('id', 'sort','created_at', 'updated_at')\n readonly_fields=['reads_total','user']\n summernote_fields = ('content_zh_CN','content_en_US','content_km_KH')\n\n def save_model(self, request, obj, form, change):\n\n if not obj.pk:\n obj.user = request.user\n super().save_model(request, obj, form, change)\n \n def title(self, obj):\n return ', '.join([\n obj.title_en_US if obj.title_en_US is not None else '', \n obj.title_km_KH if obj.title_km_KH is not None else '', \n obj.title_zh_CN if obj.title_zh_CN is not None else '', \n ])\n title.short_description = _('title')\n\nclass SlideshowsAdmin(admin.ModelAdmin):\n list_display = (\n 'id', 'news_id', 'image', 'status',\n 'sort', 'created_at', 'updated_at')\n list_filter = ('id', 'status', 'sort', 'image_type', 'created_at', 'updated_at', )\n search_fields = (\n 'id', 'title_km_KH', 'title_en_US', 'title_zh_CN',\n 'status', 'is_video', 'news_type', 'deal_status'\n )\n date_hierarchy = ('updated_at')\n ordering = ('id', 'created_at', 'updated_at')\n readonly_fields = ('user',)\n\n def save_model(self, request, obj, form, change):\n\n if not obj.pk:\n obj.user = request.user\n super().save_model(request, obj, form, change)\n\nclass HonorsAdmin(admin.ModelAdmin):\n list_display = (\n 'id','name', 'remark', 'icon',\n 'status', 'created_at', 'updated_at'\n )\n list_filter = ('id', 'status', 'created_at', 'updated_at',)\n search_fields = (\n 'id', 'name_zh_CN', 'name_en_US', 'name_km_KH','status'\n )\n date_hierarchy = ('updated_at')\n ordering = ('id', 'created_at', 'updated_at')\n def name(self, obj):\n return ', '.join([\n obj.name_en_US if obj.name_en_US is not None else '', \n obj.name_km_KH if obj.name_km_KH is not None else '', \n obj.name_zh_CN if obj.name_zh_CN is not None else '', \n ])\n name.short_description = _('name')\n\nclass NoticesInline(admin.TabularInline):\n # raw_id_fields = ('user'),)\n model = models.NoticesStatus\n can_delete = True\n verbose_name_plural = 'relations'\n fk_name = 'notices'\n\n\nclass NoticesAdmin(SummernoteModelAdmin):\n inlines = [NoticesInline]\n list_display = (\n 'title', 'created_at', 'status', 'user_type'\n )\n list_filter = ('id', 'status', 'created_at')\n search_fields = (\n 'id', 'title_km_KH', 'title_en_US', 'title_zh_CN'\n )\n ordering = ('id', 'created_at')\n summernote_fields = ('content_en_US','content_km_KH','content_zh_CN')\n \n def save_related(self, request, form, formsets, change):\n\n instance = formsets[0].instance\n \n if instance.user_type == 2:\n \n users = User.objects.all()\n for user in users:\n models.NoticesStatus.objects.get_or_create(\n user=user,\n notices=instance,\n defaults={\n 'status':0,\n }\n )\n change=False\n super().save_related(request, form, formsets, change)\n\n def title(self, obj):\n return ', '.join([\n obj.title_en_US if obj.title_en_US is not None else '', \n obj.title_km_KH if obj.title_km_KH is not None else '', \n obj.title_zh_CN if obj.title_zh_CN is not None else '', \n ])\n title.short_description = _('title')\n\n\nclass FeedbackStuffsInline(admin.StackedInline):\n model = models.FeedbackStuffs\n verbose_name_plural = 'Feedback Stuff'\n fk_name = 'feedback'\n readonly_fields=['image']\n\nclass FeedbacksAdmin(SummernoteModelAdmin):\n list_display = (\n 'content','contact','user', 'status', 'created_at', 'updated_at'\n )\n list_filter = ('id', 'status','created_at', 'updated_at',)\n search_fields = ('id', 'contact', 'status')\n date_hierarchy = ('updated_at')\n ordering = ('id', 'created_at', 'updated_at')\n summernote_fields=('content')\n readonly_fields=['user','contact','content']\n inlines = (FeedbackStuffsInline,)\n\n\nclass PrizesAdmin(SummernoteModelAdmin):\n list_display = (\n 'title', 'created_at', 'prize_image', 'status', 'updated_at'\n )\n list_filter = ('id', 'status','created_at', 'updated_at',)\n search_fields = ('id', 'title_en_US', 'title_km_KH','title_zh_CN')\n date_hierarchy = ('updated_at')\n ordering = ('id', 'created_at', 'updated_at')\n summernote_fields=('content_km_KH','content_en_US','content_zh_CN')\n def title(self, obj):\n return ', '.join([\n obj.title_en_US if obj.title_en_US is not None else '', \n obj.title_km_KH if obj.title_km_KH is not None else '', \n obj.title_zh_CN if obj.title_zh_CN is not None else '', \n ])\n title.short_description = _('title')\n\nclass NoticesStatusAdmin(admin.ModelAdmin):\n list_display = (\n 'id', 'user', 'notices', 'status', 'created_at', 'updated_at'\n )\n list_filter = ('id', 'created_at', 'updated_at',)\n search_fields = ('id', 'status',)\n date_hierarchy = ('updated_at')\n ordering = ('id', 'created_at', 'updated_at')\n\n\nclass TextConfigAdmin(SummernoteModelAdmin):\n list_display = (\n 'title', 'info_type', 'main_image', 'created_at', 'updated_at'\n )\n list_filter = ('id', 'created_at', 'updated_at',)\n search_fields = ('id', 'title_en_US', 'title_km_KH','title_zh_CN')\n date_hierarchy = ('updated_at')\n ordering = ('id', 'created_at', 'updated_at')\n summernote_fields=('content_km_KH','content_en_US','content_zh_CN')\n def title(self, obj):\n return ', '.join([\n obj.title_en_US if obj.title_en_US is not None else '', \n obj.title_km_KH if obj.title_km_KH is not None else '', \n obj.title_zh_CN if obj.title_zh_CN is not None else '', \n ])\n title.short_description = _('title')\n\n\nclass AddressesAdmin(admin.ModelAdmin):\n list_display = (\n 'id', 'user', 'receiver_name', 'phone', 'zone', 'address',\n 'post_code', 'created_at', 'updated_at'\n )\n list_filter = ('id', 'created_at', 'updated_at',)\n search_fields = ('id', 'receiver_name')\n date_hierarchy = ('updated_at')\n ordering = ('id', 'created_at', 'updated_at')\n\n readonly_fields=('user',)\n\n def save_model(self, request, obj, form, change):\n\n if not obj.pk:\n obj.user = request.user\n super().save_model(request, obj, form, change)\n\nadmin.site.unregister(User)\nadmin.site.register(User, UserAdmin)\nadmin.site.register(Permission)\nadmin.site.register(models.Categories, CategoriesAdmin)\nadmin.site.register(models.Projects, ProjectsAdmin)\nadmin.site.register(models.Donates, DonatesAdmin)\nadmin.site.register(models.News, NewsAdmin)\nadmin.site.register(models.Slideshows, SlideshowsAdmin)\nadmin.site.register(models.Honors, HonorsAdmin)\nadmin.site.register(models.Notices, NoticesAdmin)\nadmin.site.register(models.Feedbacks, FeedbacksAdmin)\nadmin.site.register(models.Prize, PrizesAdmin)\nadmin.site.register(models.TextConfig, TextConfigAdmin)\nadmin.site.register(models.Address,AddressesAdmin)\n\nadmin.site.site_header = _('RedCross Administration')\nadmin.site.site_url = None\nadmin.site.site_title = _('RedCross Administration')\nadmin.site.index_title = _('Welcome to RedCross Administration')\n","sub_path":"redcross_frontend_api/redcross/api/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":13181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"570555650","text":"#!/usr/bin/env python3\n# lectureDL.py by Larry Hudson\n# Python script to download all lecture files, either video or audio\n# What it does:\n# Logs in to Unimelb LMS system\n# Builds list of subjects\n# For each subject, navigate through to echo system\n# Builds list of lectures\n# For each lecture, builds filename based on subject number and date and downloads\n# Features:\n# Assigns week numbers based on date - formatted eg. \"LING30001 Week 1 Lecture 2.m4a\"\n# Support for subjects with single or multiple lectures per week\n# Skips if file already exists\n# Can download either video files or audio files\n# Allows user to choose specific subjects and to only download lectures newer than a specific date\n# To do list:\n# Allow user to choose download folder\n# Replace list system (eg. to_download) with class and attributes?\n# Change Week numbering from Week 1 to Week 01 (yeah yeah) - best boy Astrid xox\n\n# READ ME (Update as of 2017-07-29):\n# If you're modifying this in the future, know first off that the code was\n# not designed with easy future use, nor abstraction in general, in mind.\n# I've made it a bit better but it's still messy. Assuming you've got the\n# required directory structure in place (check out the uni_folder variable),\n# you'll have to:\n# 1. Change the current year and semester if necessary.\n# 2. Change the variables representing the start of the semester (such as\n# start_week0 and current_date) for this semester.\n# 3. Manually download the latest ChromeDriver and change the driver variable\n# accordingly.\n# 4. Perhaps change settings.py.\n# While it might be worth it, I feel like it'd be a fair bit of work to\n# refactor this project to be \"Good TM\", after which you could start adding\n# extra features. Like imagine trying to catch a selenium error and closing\n# chrome if one is encountered, it'd be like a million try/excepts.\n# So yeah, maybe one day. Still it wasn't too hard to get it working again.\n\n# UPDATE (As of 2017-10-07) - David Stern\n# Updates:\n# (1) Lecture Class Created & Implemented\n# (2) Scrolling Bug Fixed (Long lists of lectures weren't clickable)\n# (3) Fixed some constants\n# (4) Simplified getSubjectList()\n# (5) Require user to re-input choice of subjects, if invalid.\n# As a part of this, broke determine_subjects_to_download() down to\n# include:\n# - getValidUserChoice() Requests input until valid selection obtained\n# - getSubjects() Takes the list of subjects, returns only those\n# selected by the user.\n# (6) Switched to f-strings to improve clarity.\n# (7) Created and implemented Subject() Class.\n# (8) Other unlisted changes.\n#\n# TODO:\n# Implement Graphical Folder Selection\n# Implement full GUI\n# Fix Dates (Think of a better way to select dates)\n# Save file sizes in a .pickle file\n# Shorten Scrolling Function (Line 561 in download_lectures_for_subject())\n\n\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.common.exceptions import (\n NoSuchElementException,\n ElementNotVisibleException,\n StaleElementReferenceException,\n WebDriverException,\n)\n\nimport datetime\nimport functools\nimport getpass\nimport os\nimport os.path\nimport random\nimport re\nimport sys\nimport time\nimport urllib\n\nfrom collections import defaultdict\nfrom contextlib import suppress\nfrom queue import Queue\nfrom threading import Thread\nfrom util import (\n retry_until_result,\n show_progress,\n)\n\n# Try to read in a settings file.\ntry:\n from settings import (\n settings,\n getLectureName,\n )\nexcept ImportError as e:\n print(f'Couldn\\'t import a settings file: {str(e)}')\n settings = defaultdict(lambda: None, {\n # These are the defaults for when settings isn't defined.\n 'uni_location': os.path.join(os.path.expanduser('~'), 'Downloads'),\n 'lecture_subfolder_name': 'Lectures',\n 'auto_create_subfolders': True,\n 'default_auto_create_format': '{code} - {name}',\n 'driver_relative_path': 'chromedriver',\n })\n getLectureName = lambda lec: f'{lec.subjCode} Week {lec.week:02} Lecture {lec.lecOfWeek}'\n print('Will download to ' + str(settings['uni_location']))\n print('Will automatically create the subject folders.')\n print('Default folder and lecture names will be used.')\n\n# These are partial matches, so the best matches should appear first:\nLECTURE_TAB_STRINGS = [\"Lecture Recordings\", \"Lecture Capture\", \"Lectures\",\n \"lectures\", \"Lecture capture\", \"Recordings\",\n \"recordings\", \"Capture\", \"capture\"]\n# These must be exact matches:\nINTERMEDIATE_LECTURE_CAPTURE_NAMES = [\n 'Lecture Capture', 'Lecture-Capture', 'Lecture Recordings',\n]\nLECTURE_FOLDER_NAME = settings['lecture_subfolder_name']\nSUBJ_NAMES = settings['subject_names']\nFOLDER_ERROR = (\" doesn\\'t exist.\\nWould you like to use the Downloads\" +\n \" folder instead? \")\nFOLDER_NAME_ERROR = (\"There is a name mismatch between the subjects list and\" +\n \" the folder names.\\nYou might want to try the \" +\n \"'auto_create_subfolders' option in the settings.\")\nGET_ECHO = 'Getting past intermediate page / waiting for Echocenter to load...'\nNO_DL_FOLDER = 'The downloads folder doesn\\'t exist either, shutting down.'\n\nclass Subject(object):\n def __init__(self, code, name, link, num, path=None, downloaded=0):\n self.code = code\n self.name = name\n self.link = link\n self.num = num\n self.path = path\n self.downloaded = downloaded\n\n def __str__(self):\n return f\"{self.code} - {self.name}\"\n\n\nclass Lecture(object):\n def __init__(self, link, subjCode, week, lecOfWeek, date, subjName,\n recNum, fName=None, fPath=None, dl_status=None):\n self.link = link\n self.subjCode = subjCode\n self.week = week\n self.lecOfWeek = lecOfWeek\n self.date = date\n self.subjName = subjName\n self.recNum = recNum\n self.fName = fName\n self.fPath = fPath\n self.dl_status = dl_status\n\n def __str__(self):\n strFormat = f\"{self.subjCode} {self.subjName} - Week {self.week}\"\n return strFormat + f\" Lecture {self.lecOfWeek}\"\n\n\ndef check_uni_folder(uni_folder, home_dir):\n '''\n @param: uni_folder - pathname generated using os.path\n '''\n if not os.path.exists(uni_folder):\n conf = input(f\"{uni_folder}{FOLDER_ERROR}\")[0].lower()\n if conf != 'y':\n print('Ok, shutting down.')\n sys.exit(1)\n uni_folder = os.path.join(home_dir, \"Downloads\")\n if not os.path.exists(uni_folder):\n print(NO_DL_FOLDER, file=sys.stderr)\n sys.exit(1)\n return uni_folder\n\n\ndef getSubjectFolder(subject_code, uni_folder):\n ''' Enables any subject_code in which the subject code is included to be\n identified as the appropriate folder for the subject.\n '''\n print(f\"Retrieving folder with name that includes: {subject_code}\")\n # Using the subject code to find the appropriate folder.\n for fold in os.listdir(uni_folder):\n if subject_code.lower() in fold.lower():\n subjectFolder = fold\n break\n try:\n return subjectFolder\n except NameError as e:\n print(f\"No folder including the code '{subject_code}' found.\",\n \"Either create such a folder manually, or retry with\",\n \"'auto_create_subfolders' setting set to True.\")\n raise e\n\n\n# define function to find a link and return the one it finds\n# works by making a list of the elements and sorts by descending list length,\n# so it returns the one with length 1, avoiding the empty lists.\n# if it can't find anything, it will return none\ndef search_link_text(browser, query_terms):\n link_elements = []\n for term in query_terms:\n link_elements.append(browser.find_elements_by_partial_link_text(term))\n sorted_links = sorted(link_elements, key=len, reverse=True)\n sorted_links_flat = []\n for i in sorted_links:\n for j in i:\n sorted_links_flat.append(j)\n return sorted_links_flat[0]\n\n\n# Determine download mode.\ndef get_download_mode():\n valid_options = {'a': 'audio', 'v': 'video'}\n # Using the media_type specified in settings it was set.\n if settings['media_type']:\n return settings['media_type']\n valid = False\n while not valid:\n valid = True\n print(\"Enter 'v' to download videos or 'a' to download audio.\")\n user_choice = input(\"> \")[0].lower()\n if user_choice in valid_options:\n return valid_options[user_choice]\n else:\n print('That wasn\\'t an option.')\n valid = False\n\n\n# MUCH simpler selection of weeks.\n# def select_lectures()\n\n\n# if user enters comma-separated weeks, make a list for each and then\n# concatenate\ndef get_weeks_to_download(current_year, week_day):\n # TODO break up this god awful huge function.\n # build week number dictionary\n current_date = datetime.datetime(current_year, 7, 24)\n today = datetime.datetime.today()\n today_midnight = datetime.datetime(today.year, today.month, today.day)\n # This is O-Week, so the start of week 1 should be 7 days after this.\n start_week0 = datetime.datetime(current_year, 7, 17)\n end_week0 = datetime.datetime(current_year, 7, 23)\n day_delta = datetime.timedelta(days=1)\n week_delta = datetime.timedelta(days=7)\n week_counter = 1\n day_counter = 1\n midsemBreakWeek = 9 # Mid sem break occurs after this week.\n\n # assigns a week number to each date.\n while week_counter <= 12:\n while day_counter <= 7:\n week_day[current_date] = week_counter\n day_counter += 1\n current_date = current_date + day_delta\n week_counter += 1\n # If we enter the week of the midsem break, skip a week.\n if week_counter == midsemBreakWeek + 1:\n current_date = current_date + week_delta\n day_counter = 1\n\n current_week_no_offset = (datetime.datetime.today() - start_week0).days // 7\n midsem_offset = (current_week_no_offset+1) // midsemBreakWeek\n current_week = current_week_no_offset - midsem_offset\n\n # The user input stage.\n user_dates_input = \"default\"\n print(\"Would you like to download lectures from specific weeks or since a particular date?\")\n while user_dates_input == \"default\":\n\n # Automatically set the week range if specified in the settings.\n if settings['update_lower_week']:\n settings['date_range'] = f\"{current_week}-12\"\n\n # Read in the date range if none was given in the settings.\n if settings['date_range'] is None:\n print(\"Enter a range of weeks (eg. 1-5 or 1,3,4) or a date (DD/MM/2016) to download videos that have since been released.\")\n user_dates_input = input(\"> \")\n else:\n if len(settings['date_range']) > 0:\n print(\"Using\", settings['date_range'])\n else:\n print(\"Downloading lectures from every week.\")\n settings['date_range'] = '1-12' # TODO This is a hack.\n user_dates_input = settings['date_range']\n dates_list = []\n\n # if user enters comma-separated weeks, or just one, make a list for each and then concatenate\n if \",\" in user_dates_input or user_dates_input.isdigit():\n # TODO I think this might be a bit broken with the midsem thing.\n # This whole part needs to be reworked anyway.\n print(\"Lectures will be downloaded for: \")\n chosen_weeks = user_dates_input.replace(\" \", \"\").split(\",\")\n for item in chosen_weeks:\n start_date = start_week0 + (int(item) * week_delta)\n end_date = end_week0 + (int(item) * week_delta)\n dates_in_week = [start_date + datetime.timedelta(n) for n in range(int((end_date - start_date).days))]\n dates_list += dates_in_week\n print(\"Week \", item)\n dates_list.append(today_midnight)\n\n # create a table of dates between start date and end date\n elif \"-\" in user_dates_input or \"/\" in user_dates_input:\n\n if \"-\" in user_dates_input:\n # splits the start and the end weeks\n chosen_weeks = user_dates_input.split(\"-\")\n start_week = int(chosen_weeks[0])\n if start_week > midsemBreakWeek:\n start_week += 1\n start_date = start_week0 + (start_week * week_delta)\n end_week = int(chosen_weeks[1])\n if end_week > midsemBreakWeek:\n end_week += 1\n end_date = end_week0 + (end_week * week_delta)\n\n # create a range between start_date and today\n elif \"/\" in user_dates_input:\n\n start_date = datetime.datetime.strptime(user_dates_input, \"%d/%m/%Y\")\n end_date = datetime.datetime.today()\n # ???\n dates_list = [start_date + datetime.timedelta(n) for n in range((end_date - start_date).days)]\n dates_list.append(today_midnight)\n print(\"Lectures will be downloaded for the dates between \" + datetime.datetime.strftime(start_date, \"%d %B\")\n + \" and \" + datetime.datetime.strftime(end_date, \"%d %B\") + \", inclusive.\")\n # Go back to top of while loop.\n else:\n print(\"That wasn't a valid option\")\n user_dates_input = \"default\"\n return dates_list\n\n\ndef sign_in(driver):\n user_field = driver.find_element_by_css_selector(\"input[name=user_id]\")\n if settings['username'] is None:\n settings['username'] = input(\"Enter your username: \")\n user_field.send_keys(settings['username'])\n pass_field = driver.find_element_by_css_selector(\"input[name=password]\")\n if settings['password'] is None:\n settings['password'] = getpass.getpass(\"Enter your password: \")\n pass_field.send_keys(settings['password'])\n print()\n pass_field.send_keys(Keys.RETURN)\n\n\n# TODO think of a better way to select the lecture stuff and not the community stuff on the right.\n@retry_until_result('Waiting for course list to load...')\ndef get_course_links(driver):\n # NOTE: Because of the decorator, use this function as if it were a regular\n # function that returns, not yields.\n course_links = None\n try:\n time.sleep(1)\n # list items in list class \"courseListing\"\n course_list_candidates = driver.find_elements_by_css_selector(\"ul.courseListing\")\n course_list = None\n # Sometimes there is an invisible dummy subject list that of course\n # lists no subjects. If the style property 'display' is 'none', we\n # know it is the invisble one and we ignore it.\n for c in course_list_candidates:\n if c.value_of_css_property('display') == 'none':\n continue\n course_list = c\n if course_list is None:\n yield None\n # only get links with target=\"_top\" to single out subject headings\n course_links = course_list.find_elements_by_css_selector('a[target=_top]')\n # list to be appended with [subj_code, subj_name, subj_link]\n yield course_links\n yield None\n except NoSuchElementException:\n # This section must not have loaded yet.\n yield None\n\n\ndef getSubjectList(course_links):\n '''Takes the links found on the LMS page belonging to subjects,\n Returns the subject list (with all the information for each)\n '''\n subject_list = []\n for subj_num, link in enumerate(course_links):\n # Turn link text into usable information.\n # E.g. 'POLS20025_2017_SM2: International Relations: Key Questions'\n try:\n subj_code, _, _, subj_name = re.split(r\"[_:]\", link.text, 3)\n except ValueError:\n raise RuntimeError('Wrong box, communities probably')\n subj_name = subj_name.lstrip()\n subj_link = link.get_attribute(\"href\")\n\n subject_list.append(Subject(subj_code, subj_name, subj_link,\n subj_num+1))\n\n # They loaded! Don't recurse, return the list instead :)\n return subject_list\n\n\ndef getValidUserChoice():\n while True:\n # Either get the user's choice\n if settings['subject_choices'] is None:\n print(\"Please enter subjects you would like to download\",\n \"(E.g. 1,2,3) or leave blank to download all.\")\n user_choice = input(\"> \")\n # Or use pre-loaded subject choices\n else:\n print(f\"Using preloaded setting: {settings['subject_choices']}\")\n user_choice = settings['subject_choices']\n # Return the choice if it's valid\n if user_choice == \"\" or all([x.isdigit()\n for x in user_choice.split(\",\")]):\n print(\"User choice valid!\")\n return user_choice\n # If user choice invalid, continue loop.\n else:\n continue\n\n\ndef getSubjects(subject_list):\n '''\n Takes a list of subjects, retrieves a valid selection of subjects from\n the user, and returns just those subjects selected.\n '''\n # Get a user choice\n user_choice = getValidUserChoice()\n # Select specific choices, if they were made\n if user_choice != \"\":\n # Allows for more flexible input\n selection = [int(x) for x in re.findall(r\"\\d\", user_choice)]\n return list(filter(lambda sub: any(sel in sub.num\n for sel in selection),\n subject_list))\n # If not, just return all of the subjects\n return subject_list\n\n\ndef determine_subjects_to_download(subject_list):\n '''\n Prints candidate subjects for download, before clarifying which subjects\n the user chooses to download.\n '''\n print(\"Subject list:\")\n for subject in subject_list:\n print(f\"{subject.num}. {subject.code}: {subject.name}\")\n return getSubjects(subject_list)\n\n\ndef download_lecture(dl_link, output_name, pretty_name, sizeLocal):\n partial = bool(sizeLocal)\n req = urllib.request.Request(dl_link)\n if not partial:\n # Full download.\n mode = 'wb'\n else:\n # Resuming a partially completed download.\n req.headers['Range'] = 'bytes=%s-' % sizeLocal\n mode = 'ab'\n f = urllib.request.urlopen(req)\n # We do + sizeLocal because if we are doing a partial download, the length\n # is only for what we requested to download, not the whole thing.\n sizeWeb = int(f.headers[\"Content-Length\"]) + sizeLocal\n\n if not partial:\n print(f\"Downloading {pretty_name} to {output_name}.\")\n else:\n print(f\"Resuming partial download of {pretty_name} ({sizeLocal/1000:0.1f}/{sizeWeb/1000:0.1f}).\")\n\n # The ab is the append write mode.\n with open(output_name, mode) as output:\n for chunk in show_progress(f, pretty_name, sizeLocal, sizeWeb):\n # Process the chunk\n output.write(chunk)\n f.close()\n\n\ndef getToRecordingsFirstPage(driver):\n recs_first_page = search_link_text(driver, LECTURE_TAB_STRINGS)\n if recs_first_page:\n with suppress(WebDriverException):\n recs_first_page.click()\n return\n # Try to move down the page (only once).\n actions = webdriver.ActionChains(driver)\n actions.send_keys(Keys.SPACE)\n actions.perform()\n recs_first_page = search_link_text(driver, LECTURE_TAB_STRINGS)\n recs_first_page.click()\n\n\n# @retry_until_result('Waiting for the echocenter to load... ')\ndef getLectureList(driver):\n try:\n with suppress(Exception):\n iframe = driver.find_elements_by_tag_name('iframe')[1]\n driver.switch_to_frame(iframe)\n iframe = driver.find_elements_by_tag_name('iframe')[0]\n driver.switch_to_frame(iframe)\n iframe = driver.find_elements_by_tag_name('iframe')[0]\n driver.switch_to_frame(iframe)\n recs_ul = driver.find_element_by_css_selector(\"ul#echoes-list\")\n recs_list = recs_ul.find_elements_by_css_selector(\"li.li-echoes\")\n except NoSuchElementException:\n return None\n return (recs_ul, recs_list)\n\n\ndef getPastIntermediateRecordingsPage(driver):\n # Try to get past an intermediate page if there is one.\n for i in INTERMEDIATE_LECTURE_CAPTURE_NAMES:\n with suppress(IndexError, StaleElementReferenceException):\n # You'd be surprised at how effective this is, it can break some\n # pretty nasty loops that happen because of same-name links.\n # The only potentialy problem is the chance of timing out after\n # a string of bad / unlucky choices.\n # TODO: There is probably a better way to do this with generators\n # or static vars or something.\n w = random.choice(driver.find_elements_by_link_text(i))\n w.click()\n\n\n@retry_until_result(GET_ECHO, max_retries=40)\ndef getToEchoCenter(driver):\n getPastIntermediateRecordingsPage(driver)\n return getLectureList(driver)\n\n\ndef download_lectures_for_subject(driver, subject, current_year, week_day,\n dates_list, download_mode, uni_folder, q):\n downloaded = []\n skipped = []\n print(f\"\\nNow working on {subject.code}: {subject.name}\")\n\n # Go to subject page and find Lecture Recordings page.\n driver.get(subject.link)\n main_window = driver.current_window_handle\n\n # Get to the list of lectures.\n getToRecordingsFirstPage(driver)\n recs_ul, recs_list = getToEchoCenter(driver)\n\n # setup for recordings\n multiple_lectures = False\n lectures_list = []\n to_download = []\n\n # print status\n print(\"Building list of lectures...\")\n # for each li element, build up filename info and add to download list\n for rec_num, recording in enumerate(recs_list):\n # click on each recording to get different download links\n date_div = recording.find_element_by_css_selector(\"div.echo-date\")\n\n # Deals with error where the next element can't be selected if it isn't\n # literally visible. Limitation of selenium. Scrolls down to adjust.\n scroll_point = 10\n while True:\n scroll_point += 5\n try:\n recording.click()\n break\n except ElementNotVisibleException:\n actions = webdriver.ActionChains(driver)\n actions.move_to_element(recording)\n actions.click()\n actions.send_keys(Keys.SPACE)\n actions.perform()\n except:\n driver.execute_script(f\"arguments[0].focus();\", recs_ul)\n driver.execute_script(f\"window.scrollTo(0, {scroll_point});\")\n\n\n # convert string into datetime.datetime object\n # date is formatted like \"August 02 3:20 PM\" but I want \"August 02 2016\"\n # so I need to get rid of time and add year\n date_string = \" \".join(date_div.text.split(\" \")[:-2]) + f\" {current_year}\"\n try:\n date = datetime.datetime.strptime(date_string, \"%d %B %Y\")\n except ValueError:\n # Sometimes the date is presented in different format.\n date = datetime.datetime.strptime(date_string, \"%B %d %Y\")\n\n # Checking if we can terminate early.\n if date < dates_list[0]:\n print(\"The lectures further down are outside the date range, no need to check them.\")\n break\n\n # lookup week number and set default lecture number\n week_num = week_day[date]\n lec_num = 1\n\n # get link to initial download page for either audio or video\n while True:\n try:\n if download_mode == \"audio\":\n first_link = driver.find_element_by_partial_link_text(\"Audio File\").get_attribute(\"href\")\n else:\n first_link = driver.find_element_by_partial_link_text(\"Video File\").get_attribute(\"href\")\n break\n except NoSuchElementException:\n time.sleep(0.5)\n\n # check if week_num is already in to_download\n for lecture in lectures_list:\n if lecture.week == week_num:\n # set multiple_lectures to true so filenames include lec nums\n multiple_lectures = True\n # add 1 to lec_num of earlier video\n lecture.lecOfWeek += 1\n\n # Create Lecture\n lectures_list.append(Lecture(first_link, subject.code, week_num, lec_num,\n date, subject.name, rec_num))\n\n # TODO: Get the length of the
    ...
, use it when creating the\n # lectures instead\n # Fixing Lecture Nums (lecs are downloaded & created in reverse order)\n num_lectures = len(lectures_list)\n for lec in lectures_list:\n lec.recNum = num_lectures - lec.recNum\n\n # # Getting the subject folder in which to put the lecture.\n # preset_subject_folders = settings['subject_folders']\n # if preset_subject_folders != '':\n # subjectFolder =\n try:\n subjectFolder = getSubjectFolder(subject.code, uni_folder)\n except NameError:\n # If the user wants to automatically create the folders, do so.\n if settings['auto_create_subfolders']:\n subjectFolder = settings['default_auto_create_format'].format(\n code=subject.code, name=subject.name)\n os.mkdir(os.path.join(uni_folder, subjectFolder))\n print('Made folder: ' + subjectFolder)\n else:\n print(FOLDER_NAME_ERROR, file=sys.stderr)\n sys.exit(1)\n\n # assign filenames\n # made it a separate loop because in the loop above it's constantly\n # updating earlier values etc\n for lec in lectures_list:\n\n filename = getLectureName(lec)\n\n if download_mode == \"audio\":\n filename_with_ext = filename + \".mp3\"\n folder = audio_folder # TODO this audio folder thing is a bit dumb.\n else:\n filename_with_ext = filename + \".m4v\"\n folder = uni_folder\n\n file_path = os.path.join(folder, subjectFolder, LECTURE_FOLDER_NAME,\n filename_with_ext)\n\n if not os.path.isdir(os.path.join(folder, subjectFolder,\n LECTURE_FOLDER_NAME)):\n print(\"Making {} folder for {}\".format(LECTURE_FOLDER_NAME, folder))\n os.makedirs(os.path.join(folder, subjectFolder, LECTURE_FOLDER_NAME))\n\n lec.fName = filename\n lec.fPath = file_path\n\n # TODO - This is going into each link even if we don't need the lecture.\n # This slows the program down massively.\n # Perhaps filter out those with invalid dates & non-existent files?\n # A part of this is caused by having to check file sizes every\n # single time. Get the file sizes once, save into a document, so we\n # don't have to do this every time.\n # only add lectures to be downloaded if they are inside date range. else,\n # skip them\n for lec in lectures_list:\n\n # Append to download list if the file in date range and doesn't exist yet.\n if lec.date in dates_list and not os.path.isfile(lec.fPath):\n print(f\"Will download {lec.fName}\")\n to_download.append((lec, False)) # False means not downloaded at all.\n\n # If the file is in the range but does exist, check that the file is completely\n # downloaded. If not, we will add it to the download list and overwrite the\n # local incomplete version.\n\n # DAVETODO: SAVE FILE SIZES AND COMPLETED DOWNLOADS IN PICKLE FILE\n # DAVETODO: CREATE SETTING 're-download' WHICH MAKES THE PROGRAM CHECK\n # WHETHER OR NOT OLD FILES STILL EXIST, AND REDOWNLOAD IF\n # NECESSARY.\n\n elif lec.date in dates_list and os.path.isfile(lec.fPath):\n while True:\n try:\n driver.get(lec.link)\n dl_link = driver.find_element_by_partial_link_text(\"Download media file.\").get_attribute(\"href\")\n # send javascript to stop download redirect\n driver.execute_script('stopCounting=true')\n break\n except:\n time.sleep(0.5)\n # Check size of file on server. If the server version is larger than the local version,\n # we notify the user of an incomplete file (perhaps the connection dropped or the user\n # cancelled the download). We tell them we're going to download it again.\n # Using wget we could resume the download, but python urllib doesn't have such functionality.\n try:\n # TODO: This whole thing is weird, we shouldn't have to open the\n # web link twice. This should all probably be handled in the\n # download function, or at least more elegantly than this.\n f = urllib.request.urlopen(dl_link)\n # This is the size of the file on the server in bytes.\n sizeWeb = int(f.headers[\"Content-Length\"])\n except:\n # Catching the situation where the server doesn't advertise the file length.\n sizeWeb = 0\n\n # Get size of file on disk.\n statinfo = os.stat(lec.fPath)\n sizeLocal = statinfo.st_size\n\n # Add to download list with note that it was incomplete.\n # TODO Unify the two bits of code to do with downloading / progress.\n # BUG: Fully downloaded lectures are re-downloading?\n if sizeWeb > sizeLocal:\n lec.dl_status = \"Incomplete file (%0.1f/%0.1f MiB).\" % (\n sizeLocal / 1024 / 1024,\n sizeWeb / 1024 / 1024,\n )\n # Include (sizeLocal, sizeWeb) if partially downloaded.\n to_download.append((lec, (sizeLocal, sizeWeb)))\n print(\"Resuming \" + lec.fName + \": \" + lec.dl_status)\n # Otherwise the file must be fully downloaded.\n else:\n lec.dl_status = \"File already exists on disk (fully downloaded).\"\n skipped.append(lec)\n print(\"Skipping \" + lec.fName + \": \" + lec.dl_status)\n\n # Dealing with other cases.\n else:\n # if both outside date range and already exists\n if not lec.date in dates_list and os.path.isfile(lec.fPath):\n lec.dl_status = \"Outside date range and file already exists\"\n # if just outside date range\n elif not lec.date in dates_list:\n lec.dl_status = \"Outside date range\"\n # If file already exists and is fully completed.\n # Shouldn't really get to this case (caught above).\n elif os.path.isfile(lec.fPath):\n lec.dl_status = \"File already exists\"\n skipped.append(lec)\n print(f\"Skipping {lec.fName}: {lec.dl_status}\")\n\n # print list of lectures to be downloaded\n if len(to_download) > 0:\n print(\"Lectures to be downloaded:\")\n for lec, partial in to_download:\n # Print with additional note if it's there.\n # DAVE_HERE\n if lec.dl_status is not None:\n print(lec.fName, \"-\", lec.dl_status)\n else:\n print(lec.fName)\n else:\n print(\"No lectures to be downloaded for \" + subject.name)\n\n # for each lecture, set filename and download\n for lec, partial in to_download:\n\n # build up filename\n print(\"Now working on\", lec.fName)\n # go to initial download page and find actual download link\n while True:\n try:\n driver.get(lec.link)\n dl_link = driver.find_element_by_partial_link_text(\"Download media file.\").get_attribute(\"href\")\n # send javascript to stop download redirect\n driver.execute_script('stopCounting=true')\n break\n except:\n time.sleep(0.5)\n\n # This handles a full download. Report the local size as 0.\n if not partial:\n dl_func = functools.partial(download_lecture, dl_link, lec.fPath, lec.fName, 0)\n # This handles a partially downloaded file.\n else:\n sizeLocal, sizeWeb = partial\n dl_func = functools.partial(download_lecture, dl_link, lec.fPath, lec.fName, sizeLocal)\n\n q.put(dl_func)\n downloaded.append(lec)\n\n # when finished with subject\n print(f\"Queued downloads for {subject.code}! Going to next file!\")\n return downloaded, skipped\n\n# Check dates_list\n# The lectures further down are outside the date range, no need to check them.\n\ndef consume_dl_queue(q):\n # This will just keep consuming an item from the queue and downloading it\n # until the program ends. get() blocks if there isn't an item in the queue.\n while True:\n dl_func = q.get()\n res = dl_func()\n if res is False:\n break\n\n\ndef main():\n # Setup download folders\n home_dir = os.path.expanduser(\"~\")\n uni_folder = check_uni_folder(settings['uni_location'], home_dir)\n\n print(\"Welcome to\", sys.argv[0])\n\n # Date Junk\n current_year = datetime.datetime.now().year\n week_day = {}\n dates_list = get_weeks_to_download(current_year, week_day)\n # DATE ERROR\n # print(dates_list)\n\n download_mode = get_download_mode()\n\n # Start Chrome instance\n print(\"Starting up Chrome instance\")\n chrome_options = Options()\n window_size = settings.get('window_size', '1600,900')\n chrome_options.add_argument('--window-size=' + window_size)\n if settings['hide_window']:\n print('Running in headless (hidden window) mode.')\n chrome_options.add_argument('--headless')\n chrome_options.add_argument('--disable-gpu') # TODO: Remove this\n try:\n # We build an absolute path to avoid the \"Message: 'chromedriver'\n # executable needs to be in PATH\" error.\n path = os.path.abspath(settings['driver_relative_path'])\n driver = webdriver.Chrome(path, chrome_options=chrome_options)\n except:\n try:\n path = path + '.exe' # We're on Windows.\n driver = webdriver.Chrome(path, chrome_options=chrome_options)\n except Exception as e:\n print('Couldn\\'t start Chrome!', file=sys.stderr)\n print(str(e), file=sys.stderr)\n sys.exit(1)\n\n # Login\n print(\"Starting login process\")\n driver.get(\"https://app.lms.unimelb.edu.au\")\n sign_in(driver)\n driver.refresh()\n print(\"Building list of subjects\")\n\n # This yucky looking control structure makes sure we get the right\n # box (subjects and not communities).\n subjectsFoundSuccess = False\n while not subjectsFoundSuccess:\n course_listing = get_course_links(driver)\n try:\n subject_list = getSubjectList(course_listing)\n except RuntimeError:\n continue\n subjectsFoundSuccess = True\n\n numSubjects = len(subject_list)\n\n subjects_to_download = determine_subjects_to_download(subject_list)\n print(\"Subjects to be downloaded:\")\n for subject in subjects_to_download:\n print(f\"{subject.code}: {subject.name}\")\n\n # Track which lectures we downloaded and which we skipped.\n all_downloaded = []\n all_skipped = []\n\n q = Queue()\n t = Thread(target=consume_dl_queue, args=(q,), daemon=True)\n t.start()\n for subject in subjects_to_download:\n res = download_lectures_for_subject(driver, subject, current_year,\n week_day, dates_list,\n download_mode, uni_folder, q)\n if res:\n downloaded, skipped = res\n all_downloaded += downloaded\n all_skipped += skipped\n # Done , close the browser.\n print(\"All links have been collected, waiting for downloads to complete...\")\n driver.quit()\n # Let the thread know that we're done collecting download links.\n q.put(lambda: False)\n # Wait for all the downloads to complete.\n t.join()\n\n # List the lectures that we downloaded and those we skipped.\n if len(all_downloaded) > 0:\n print(f\"Downloaded {len(all_downloaded)} lecture(s):\")\n for lecture in all_downloaded:\n print(lecture.fName)\n\n if len(all_skipped) > 0:\n print(f\"Skipped {len(all_skipped)} lecture(s):\")\n for lecture in all_skipped:\n print(lecture.fName + \": \" + lecture.dl_status)\n\n print(\"\\nDone!\\n\")\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"lectureDL.py","file_name":"lectureDL.py","file_ext":"py","file_size_in_byte":36856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"208561518","text":"# (c) Crown copyright Met Office. All rights reserved.\n# For further details please refer to the file COPYRIGHT\n# which you should have received as part of this distribution\n\nimport os.path\nimport setuptools # type: ignore\n\n_here = os.path.dirname(__file__)\n\nwith open(os.path.join(_here, 'README.md'), 'r', encoding='utf-8') as handle:\n _long_description = handle.read()\n\nwith open(os.path.join(_here, 'source', 'fab', '__init__.py'),\n encoding='utf-8') as handle:\n for line in handle:\n bits = line.split('=', 1)\n if bits[0].strip().lower() == '__version__':\n _version = bits[1].strip().strip('\"\\'')\n break\n else:\n raise RuntimeError('Cannot determine package version.')\n\nsetuptools.setup(\n name='sci-fab',\n version=_version,\n author='SciFab Developers',\n author_email='metomi@metoffice.gov.uk',\n description='Build system for scientific software',\n long_description=_long_description,\n long_description_content_type='text/markdown',\n url='https://github.com/Metomi/fab',\n project_urls={\n 'Bug reports': 'https://github.com/metomi/fab/issues',\n 'Source': 'https://github.com/metomi/fab/'\n },\n classifiers=[\n 'Development Status :: 1 - Planning',\n 'Environment :: Console',\n 'License :: OSI Approved :: BSD License',\n 'Operating System :: POSIX',\n 'Programming Language :: Python :: 3',\n 'Topic :: Scientific/Engineering',\n 'Topic :: Software Development :: Build Tools'\n ],\n package_dir={'': 'source'},\n packages=setuptools.find_packages(where='source'),\n entry_points={'console_scripts': ['fab=fab.builder:entry', # Alias\n 'fab-build=fab.builder:entry',\n 'fab-grab=fab.grabber:entry',\n 'fab-dump=fab.dumper:entry'],\n 'gui_scripts': ['fab-explorer=fab.explorer:entry']},\n python_requires='>=3.6, <4',\n install_requires=[],\n extras_require={\n 'dev': ['flake8', 'mypy'],\n 'unit-test': ['pytest', 'pytest-cov', 'pytest-mock'],\n 'system-test': ['pytest']\n }\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"372944022","text":"#!/usr/bin/env python3\n\nimport sys\nimport math\nimport random\nimport copy\n\nfrom common import print_tour, read_input\n\n\ndef distance(city1, city2):\n return math.sqrt((city1[0] - city2[0]) ** 2 + (city1[1] - city2[1]) ** 2)\n\n\n# make distance list\ndef dist_list(cities,dist):\n N = len(cities)\n for i in range(N):\n for j in range(i, N):\n dist[i][j] = dist[j][i] = distance(cities[i], cities[j])\n return dist\n\n\n# greedy\ndef greedy(cities,current_city,dist):\n N = len(cities)\n unvisited_cities = set(range(0, N))\n tour = [current_city]\n unvisited_cities.remove(current_city)\n\n while unvisited_cities:\n next_city = min(unvisited_cities,\n key=lambda city: dist[current_city][city])\n unvisited_cities.remove(next_city)\n tour.append(next_city)\n current_city = next_city\n return tour,dist\n\n\n# greedy 確率0.7で1番目か2番目に近いノードをnextnodeとする\n# (N=4の場合初手に2番目に近いノードへ行った時が最小値だから)\ndef greedy2(cities,current_city,dist):\n N = len(cities)\n unvisited_cities = set(range(0, N))\n tour = [current_city]\n unvisited_cities.remove(current_city)\n\n while unvisited_cities:\n ra = random.random()\n\n if ra<0.8 or len(unvisited_cities)<=1:\n # 1番近いノードに行く場合\n next_city = min(unvisited_cities,\n key=lambda city: dist[current_city][city])\n unvisited_cities.remove(next_city)\n tour.append(next_city)\n current_city = next_city\n\n else:\n # 2番目に近い場合\n # 一度一番近いノードnearestを取り除いて、2番目に近いノードをnextcityに代入してまたnearestを戻す\n nearest = min(unvisited_cities,\n key=lambda city: dist[current_city][city])\n unvisited_cities.remove(nearest)\n next_city = min(unvisited_cities,\n key=lambda city: dist[current_city][city])\n unvisited_cities.remove(next_city)\n tour.append(next_city)\n current_city = next_city\n unvisited_cities.add(nearest)\n return tour,dist\n\n\n# 総距離を計算\ndef total_distance(tour,dist):\n length = 0\n for i in range(len(tour)):\n length += dist[tour[i-1]][tour[i % len(tour)]]\n return length\n\n\n# 全てのノードの組み合わせについて、入れ替えると短くなる場合は交換\n# 改善できる限り繰り返す\ndef change_two(tour,dist):\n N=len(tour)\n improved = True\n # print(tour)\n while improved:\n improved=False\n for i in range(1,N):\n A, B = tour[i-1],tour[i]\n dist_max = 1*10**6 # とりあえず大きな値で初期化\n for j in range(i+2,N+1):\n C,D = tour[j-1],tour[j%N]\n # print(A,B,C,D)\n # print(tour,'\\n')\n ch_C,ch_D =0,0 # changeするノード\n d = dist[A][B]+dist[C][D] - dist[A][C]+dist[B][D]\n if d>0 and dist_max swapに使いました ##########\n############### このプログラムでは今回は使ってないです ##############\n\n# 点p1,p2を通る直線の方程式にp3を代入\ndef f(p1,p2,p3):\n return (p2[0]-p1[0]) * (p3[1]-p1[1]) - (p2[1]-p1[1]) * (p3[0]-p1[0])\n\n\n# p1-p2とp3-p4がクロスしているかの判定\ndef isCross(p1,p2,p3,p4):\n return f(p1,p2,p3)*f(p1,p2,p4)<0 and f(p3,p4,p1)*f(p3,p4,p2)<0\n\n################## ここまで ###################\n\n\n\ndef search_best_route(cities):\n N = len(cities)\n sum_dis = 10**9 # とりあえず大きい値で初期化\n dist = [[0] * N for i in range(N)]\n for _ in range(min(50,N)): # スタート地点を全ノードで試す\n current_city = _\n dist = dist_list(cities,dist)\n\n tour, dist = greedy(cities,current_city,dist) # greedy\n tour,dist = change_two(tour,dist)\n # print(_,tour)\n # 最も距離の短いものを選択\n if sum_dis>total_distance(tour,dist):\n ans=tour\n sum_dis=total_distance(tour,dist)\n \n tour, dist = greedy2(cities,current_city,dist) # greedy\n tour,dist = change_two(tour,dist)\n # print(_,tour,total_distance(tour,dist))\n # 最も距離の短いものを選択\n if sum_dis>total_distance(tour,dist):\n ans=tour\n sum_dis=total_distance(tour,dist)\n return ans\n\n\nif __name__ == '__main__':\n assert len(sys.argv) > 1\n cities=read_input(sys.argv[1])\n print_tour(search_best_route(cities))","sub_path":"sample/solver.py","file_name":"solver.py","file_ext":"py","file_size_in_byte":5207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"598530064","text":"print(\"hello world\")\nimport re\n\ndef time_clean(t):\n \"\"\"Clean a string from the survey data to a consistent string format ('%H:%M').\n This function should handle the string cases found in Exercise 02.\"\"\"\n if isinstance(t, str): # NaN values will be of type float\n # re.sub replaces the parts of a string matching a pattern with a desired replacement\n t = re.sub(' +', '', t) # Remove spaces in the middle of the string\n t = re.sub('\\.', ':', t) # Remove spaces in the middle of the string\n t = re.sub(':', ':', t) # Replace \"fullwidth colon\" (Unicode character U+FF1A) with standard colon\n t = re.sub('^(\\d\\d)(\\d\\d)', '\\\\1:\\\\2', t) # 1700 -> 17:00\n t = re.sub('^(\\d+)[Aa][Mm]', '\\\\1:00', t) # 10am -> 10:00\n t = re.sub('^(\\d\\d)$', '\\\\1:00', t) # 10 -> 10:00\n if re.match('^([^:]+)[Pp][Mm]', t): # 5pm -> 17:00\n hour = re.sub('^([^:]+)[Pp][Mm]', '\\\\1', t)\n t = str((int(hour) + 12)) + \":00\"\n t = re.sub('[Aa][Mm]', '', t) # 10:00am -> 10:00\n t = re.sub('(\\d\\d):(\\d\\d).*', '\\\\1:\\\\2', t) # 10:00 plus a long comment -> 10:00\n return(t)","sub_path":"solutions.py","file_name":"solutions.py","file_ext":"py","file_size_in_byte":1138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"414105765","text":"import os\nimport pandas as pd\nimport numpy as np\nfrom sklearn import preprocessing, model_selection\nfrom sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier\n\n# Class for numerically encoding categeroical data\n# Ref: https://stackoverflow.com/questions/24458645/label-encoding-across-multiple-columns-in-scikit-learn\nclass MultiColumnLabelEncoder:\n def __init__(self,columns = None):\n self.columns = columns # array of column names to encode\n\n def fit(self,X,y=None):\n return self # not relevant here\n\n def transform(self,X):\n '''\n Transforms columns of X specified in self.columns using\n LabelEncoder(). If no columns specified, transforms all\n columns in X.\n '''\n output = X.copy()\n if self.columns is not None:\n for col in self.columns:\n output[col] = preprocessing.LabelEncoder().fit_transform(output[col])\n else:\n for colname,col in output.iteritems():\n output[colname] = preprocessing.LabelEncoder().fit_transform(col)\n return output\n\n def fit_transform(self,X,y=None):\n return self.fit(X,y).transform(X)\n\ndef initialise_data(file):\n # Read data csv into pandas dataframe\n print('Read following data file: ' + file)\n data = pd.read_csv(file, sep='\\t', parse_dates=True)\n print('Data input complete')\n print(data.columns)\n\n # Convert datetime columns to datetime format for easy manipulation\n datetime_cols = ['session_start', 'session_end', 'original_broadcast_start',\n 'original_broadcast_end', 'dob']\n for col in datetime_cols:\n data[col] = pd.to_datetime(data[col], infer_datetime_format=True)\n\n # drop columns that are missing dob information\n data.drop(data.loc[data['dob'] == pd.Timestamp(1900, 1, 1, 0)].index, inplace=True)\n data.fillna(value={'episode_title': 'Unspecified',\n 'series_title': 'Unspecified'},inplace=True)\n\n # drop samples which are incomplete\n data.dropna(inplace=True)\n\n # Extract and covert infromation from relevant datetime variables\n # and generate new features to store this information\n for col in datetime_cols:\n if col == 'dob':\n continue\n data[col + '_hour'] = data[col].dt.hour\n data[col + '_day'] = data[col].dt.dayofweek\n data[col + '_week'] = data[col].dt.weekofyear \n\n # Categorise viewers into age range class\n now = pd.Timestamp.now()\n data['age_band'] = -1\n data.loc[(now - data['dob']).dt.days < 26*365, 'age_band'] = 0\n data.loc[((now - data['dob']).dt.days > 26*365) &\n ((now - data['dob']).dt.days < 36*365), 'age_band'] = 1\n data.loc[((now - data['dob']).dt.days > 36*365) &\n ((now - data['dob']).dt.days < 46*365), 'age_band'] = 2\n data.loc[((now - data['dob']).dt.days > 46*365) &\n ((now - data['dob']).dt.days < 56*365), 'age_band'] = 3\n data.loc[((now - data['dob']).dt.days > 56*365) &\n ((now - data['dob']).dt.days < 66*365), 'age_band'] = 4\n data.loc[(now - data['dob']).dt.days > 66*365, 'age_band'] = 4\n\n # Transform categorical features\n features = ['channel_name', 'title', 'session_type',\n 'session_sub_type', 'genre', 'sub_genre', 'playback_speed',\n 'episode_title', 'series_title', 'session_start_hour',\n 'session_start_day', 'session_start_week', 'session_end_hour',\n 'session_end_day', 'session_end_week', 'original_broadcast_start_hour',\n 'original_broadcast_start_day', 'original_broadcast_start_week',\n 'original_broadcast_end_hour', 'original_broadcast_end_day',\n 'original_broadcast_end_week']\n categorical_features = ['channel_name', 'title', 'session_type', 'session_sub_type',\n 'genre', 'sub_genre','episode_title', 'series_title']\n label = 'age_band'\n feature_data = data[features]\n label_data = data[label]\n feature_data = (MultiColumnLabelEncoder(columns=categorical_features)\n .fit_transform(feature_data))\n\n # Generate numpy arrays for sklearn compatibility \n X = np.array(feature_data)\n y = np.array(label_data)\n\n return data, X, y\n\ndef develop_evaluate_model(X, y):\n X_train, X_test, y_train, y_test = model_selection.train_test_split(X, y, test_size=0.2)\n clf = RandomForestClassifier(criterion = 'entropy', random_state = 42)\n clf.fit(X_train, y_train)\n confidence = clf.score(X_test, y_test)\n print(confidence)\n\n \nif __name__ == '__main__':\n\n PROJECT_DIR = os.getcwd()\n DATA_FILENAME = 'viewership_data.csv'\n file_path = os.path.join(PROJECT_DIR, DATA_FILENAME)\n data, X, y = initialise_data(file_path)\n develop_evaluate_model(X,y)\n","sub_path":"analysis.py","file_name":"analysis.py","file_ext":"py","file_size_in_byte":4761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"377796367","text":"import textwrap\nfrom item import Item\nfrom room import Room\nfrom player import Player\n\n# Declare all the rooms\n\nroom = {\n 'outside': Room(\"Outside Cave Entrance\",\n \"North of you, the cave mount beckons\"),\n\n 'foyer': Room(\"Foyer\", \"\"\"Dim light filters in from the south. Dusty\npassages run north and east.\"\"\"),\n\n 'overlook': Room(\"Grand Overlook\", \"\"\"A steep cliff appears before you, falling\ninto the darkness. Ahead to the north, a light flickers in\nthe distance, but there is no way across the chasm.\"\"\"),\n\n 'narrow': Room(\"Narrow Passage\", \"\"\"The narrow passage bends here from west\nto north. The smell of gold permeates the air.\"\"\"),\n\n 'treasure': Room(\"Treasure Chamber\", \"\"\"You've found the long-lost treasure\nchamber! Sadly, it has already been completely emptied by\nearlier adventurers. The only exit is to the south.\"\"\"),\n}\n\n\n# Link rooms together\n\nroom['outside'].n_to = room['foyer']\nroom['foyer'].s_to = room['outside']\nroom['foyer'].n_to = room['overlook']\nroom['foyer'].e_to = room['narrow']\nroom['overlook'].s_to = room['foyer']\nroom['narrow'].w_to = room['foyer']\nroom['narrow'].n_to = room['treasure']\nroom['treasure'].s_to = room['narrow']\n\n# Items\n\nitem = {\n 'sword': Item(\"sword\",\n \"A sharp sword you can use to protect yourself\"),\n\n 'stone': Item(\"stone\", \"\"\"A large stone you can use to \nprotect yourself against your enemies.\"\"\"),\n\n 'book': Item(\"book\", \"\"\"A book with all the maps and\ninformation you need to get around in the forest and find your way\nto the enchanted castle.\"\"\"),\n\n 'coin': Item(\"coin\", \"\"\"A coin you can use to buy your\nway into the next village.\"\"\"),\n\n 'mirror': Item(\"mirror\", \"\"\"Ask for guidance using\nthe mirror with magical powers.\"\"\"),\n\n 'backpack': Item(\"backpack\",\n \"A red backpack for carrying all your items\"),\n\n 'water': Item(\"water\", \"\"\"A pint of water to get you\nthrough your journey.\"\"\"),\n\n 'knife': Item(\"knife\", \"\"\"A handy pocket knife to help you\nthrough the forest.\"\"\"),\n\n 'chain': Item(\"chain\", \"\"\"A chain for anything you see \nfit along your journey.\"\"\"),\n\n 'pen': Item(\"pen\", \"\"\"A pen for writing or scribbling notes\nfor sending messages.\"\"\"),\n}\n\n# Assigning items to rooms\n\nroom['outside'].items = [item['sword'], item['stone']]\nroom['foyer'].items = [item['book'], item['coin']]\nroom['overlook'].items = [item['mirror'], item['backpack']]\nroom['narrow'].items = [item['water'], item['knife']]\nroom['treasure'].items = [item['chain'], item['pen']]\n\n#\n# Main\n#\n\n# Make a new player object that is currently in the 'outside' room.\n\nmy_player = Player(\"Nayomi\", room[\"outside\"])\n\n# Write a loop that:\n#\n# * Prints the current room name\n# * Prints the current description (the textwrap module might be useful here).\n# * Waits for user input and decides what to do.\n# If the user enters a cardinal direction, attempt to move to the room there.\n# Print an error message if the movement isn't allowed.\ndir = \"\"\nwhile dir != \"q\":\n print(my_player.current_room)\n # print(textwrap.fill(my_player.current_room.description, 50))\n print(\"\\n[n] Enter n to go north.\")\n print(\"[s] Enter s to go south.\")\n print(\"[w] Enter w to go west.\")\n print(\"[e] Enter e to go east.\")\n print(\"[get item] Enter 'get' followed by an item name.\")\n print(\"[drop item] Enter 'drop' followed by an item name.\")\n print(\"[i] Enter i to see your list of items.\")\n print(\"[q] Enter q to quit.\")\n\n dir = input(\"\\nWhat would you like to do? \").lower()\n if len(dir.split()) == 1:\n if dir == \"n\":\n if my_player.current_room.n_to is not None:\n my_player.current_room = my_player.current_room.n_to\n else:\n print(\"You can't move north. Choose another direction.\")\n elif dir == \"s\":\n if my_player.current_room.s_to is not None:\n my_player.current_room = my_player.current_room.s_to\n else:\n print(\"You can't move south. Choose another direction.\")\n elif dir == \"e\":\n if my_player.current_room.e_to is not None:\n my_player.current_room = my_player.current_room.e_to\n else:\n print(\"You can't move east. Choose another direction.\")\n elif dir == \"w\":\n if my_player.current_room.w_to is not None:\n my_player.current_room = my_player.current_room.w_to\n else:\n print(\"You can't move west. Choose another direction.\")\n elif dir == \"i\":\n print(my_player)\n elif dir == \"q\":\n print(\"\\nThanks for playing. See you later.\\n\")\n exit()\n else:\n print(\"Please type 'n', 's', 'w', 'e', 'get item' or 'drop item'.\")\n elif len(dir.split()) == 2:\n room_items = [i.name for i in my_player.current_room.items]\n player_items = [i.name for i in my_player.items]\n if dir.split()[0] == 'get':\n if dir.split()[1] in room_items:\n my_player.items.append(item[dir.split()[1]])\n my_player.current_room.items.remove(item[dir.split()[1]])\n item[dir.split()[1]].on_take()\n else:\n print(\"Sorry, this item is not in the room.\")\n else:\n if dir.split()[1] in player_items:\n my_player.items.remove(item[dir.split()[1]])\n my_player.current_room.items.append(item[dir.split()[1]])\n item[dir.split()[1]].on_drop()\n else:\n print(\"Sorry, you do not have this item.\")\n else:\n print(\"Please type 'n', 's', 'w', 'e', 'get item' or 'drop item'.\")\n","sub_path":"src/adv.py","file_name":"adv.py","file_ext":"py","file_size_in_byte":5675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"271704384","text":"#!/usr/bin/env python\n# Copyright (c) Microsoft Corporation.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport inspect\nimport re\nfrom types import FunctionType\nfrom typing import Any\n\nfrom scripts.documentation_provider import DocumentationProvider\nfrom scripts.generate_api import (\n all_types,\n api_globals,\n arguments,\n get_type_hints,\n header,\n process_type,\n return_type,\n return_value,\n short_name,\n signature,\n)\n\ndocumentation_provider = DocumentationProvider(True)\n\n\ndef generate(t: Any) -> None:\n print(\"\")\n class_name = short_name(t)\n base_class = t.__bases__[0].__name__\n if class_name in [\"Page\", \"BrowserContext\", \"Browser\"]:\n base_sync_class = \"AsyncContextManager\"\n elif base_class in [\"ChannelOwner\", \"object\", \"AssertionsBase\"]:\n base_sync_class = \"AsyncBase\"\n else:\n base_sync_class = base_class\n print(f\"class {class_name}({base_sync_class}):\")\n print(\"\")\n documentation_provider.print_events(class_name)\n for [name, type] in get_type_hints(t, api_globals).items():\n print(\"\")\n print(\" @property\")\n print(f\" def {name}(self) -> {process_type(type)}:\")\n documentation_provider.print_entry(class_name, name, {\"return\": type}, True)\n [prefix, suffix] = return_value(type)\n prefix = \" return \" + prefix + f\"self._impl_obj.{name}\"\n print(f\"{prefix}{suffix}\")\n for [name, value] in t.__dict__.items():\n if name.startswith(\"_\"):\n continue\n if str(value).startswith(\" {return_type(value)}:\"\n )\n documentation_provider.print_entry(\n class_name, name, get_type_hints(value, api_globals), True\n )\n [prefix, suffix] = return_value(\n get_type_hints(value, api_globals)[\"return\"]\n )\n prefix = \" return \" + prefix + f\"self._impl_obj.{name}\"\n print(f\"{prefix}{arguments(value, len(prefix))}{suffix}\")\n for [name, value] in t.__dict__.items():\n if isinstance(value, FunctionType) and \"remove_listener\" != name:\n # List of dunder methods to allow without docs\n allow_without_docs_methods = [\n \"__getitem__\",\n ]\n if name.startswith(\"_\") and name not in allow_without_docs_methods:\n continue\n is_async = inspect.iscoroutinefunction(value)\n return_type_value = return_type(value)\n return_type_value = re.sub(r\"\\\"([^\\\"]+)Impl\\\"\", r\"\\1\", return_type_value)\n return_type_value = return_type_value.replace(\n \"EventContextManager\", \"AsyncEventContextManager\"\n )\n print(\"\")\n async_prefix = \"async \" if is_async else \"\"\n print(\n f\" {async_prefix}def {name}({signature(value, len(name) + 9)}) -> {return_type_value}:\"\n )\n # Allow dunder methods without docs\n if name not in allow_without_docs_methods:\n documentation_provider.print_entry(\n class_name, name, get_type_hints(value, api_globals)\n )\n if class_name in [\n \"LocatorAssertions\",\n \"PageAssertions\",\n \"APIResponseAssertions\",\n ]:\n print(\" __tracebackhide__ = True\")\n if \"expect_\" in name:\n print(\"\")\n print(\n f\" return AsyncEventContextManager(self._impl_obj.{name}({arguments(value, 12)}).future)\"\n )\n else:\n [prefix, suffix] = return_value(\n get_type_hints(value, api_globals)[\"return\"]\n )\n if is_async:\n prefix += \"await \"\n prefix = prefix + f\"self._impl_obj.{name}(\"\n suffix = \")\" + suffix\n print(\n f\"\"\"\n return {prefix}{arguments(value, len(prefix))}{suffix}\"\"\"\n )\n print(\"\")\n print(f\"mapping.register({class_name}Impl, {class_name})\")\n\n\ndef main() -> None:\n print(header)\n print(\n \"from playwright._impl._async_base import AsyncEventContextManager, AsyncBase, AsyncContextManager, mapping\"\n )\n\n for t in all_types:\n generate(t)\n documentation_provider.print_remainder()\n\n\nif __name__ == \"__main__\": # pragma: no cover\n main()\n","sub_path":"scripts/generate_async_api.py","file_name":"generate_async_api.py","file_ext":"py","file_size_in_byte":5131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"182407469","text":"# Program can read and output matrices, do operations on them - addition, multiplying by a constant, multiplying 2 matrices,\n# compute the determinant of a square matrix, transpose and inverse them.\n# example test input: [\"6\", \"3 3\", \"2 -1 0\", \"0 1 2\", \"1 1 0\"]\n\nclass Matrix:\n def __init__(self, rows, columns):\n self.matrix = []\n self.rows = int(rows)\n self.columns = int(columns)\n\n def __add__(self, other):\n addition = Matrix(self.rows, self.columns)\n for i in range(self.rows):\n row = list(map(lambda x, y: x + y, self.matrix[i], other.matrix[i]))\n addition.append(row)\n return addition\n\n def __mul__(self, multiplier):\n mul = multiply(multiplier)\n multi = Matrix(self.rows, self.columns)\n for i in range(self.rows):\n row = list(map(lambda x: mul(x), self.matrix[i]))\n multi.append(row)\n return multi\n\n def entry(self):\n for _i in range(self.rows):\n row = [float(x) for x in input().split()]\n self.append(row)\n\n def multiply_matrices(self, other):\n multi = Matrix(self.rows, other.columns)\n for i in range(self.rows):\n row = []\n for j in range(other.columns):\n total = 0\n for k in range(other.rows):\n total += self.matrix[i][k] * other.matrix[k][j]\n row.append(total)\n multi.append(row)\n return multi\n\n def transpose(self, diagonal):\n if diagonal == 1:\n transposed = Matrix(self.columns, self.rows)\n for i in range(self.rows):\n row = []\n for j in range(self.columns):\n row.append(self.matrix[j][i])\n transposed.append(row)\n return transposed\n elif diagonal == 2:\n transposed = Matrix(self.columns, self.rows)\n self.matrix.reverse()\n for i in range(self.rows):\n row = []\n for j in range(self.columns):\n row.append(self.matrix[j][i])\n transposed.append(row)\n transposed.matrix.reverse()\n return transposed\n elif diagonal == 3:\n transposed = Matrix(self.rows, self.columns)\n for i in range(self.rows):\n row = self.matrix[i][::-1]\n transposed.append(row)\n return transposed\n elif diagonal == 4:\n transposed = Matrix(self.rows, self.columns)\n transposed_assist_1 = Matrix(self.columns, self.rows)\n for i in range(self.rows):\n row = []\n for j in range(self.columns):\n row.append(self.matrix[j][i])\n transposed_assist_1.append(row)\n transposed_assist_2 = Matrix(self.columns, self.rows)\n for i in range(transposed_assist_1.rows):\n row = transposed_assist_1.matrix[i][::-1]\n transposed_assist_2.append(row)\n for i in range(transposed_assist_2.rows):\n row = []\n for j in range(transposed_assist_2.columns):\n row.append(transposed_assist_2.matrix[j][i])\n transposed.append(row)\n return transposed\n\n def get_minor(self, i, j):\n return [row[:j] + row[j+1:] for row in (self.matrix[:i] + self.matrix[i+1:])]\n\n def determinant(self):\n if len(self.matrix) == 2:\n return self.matrix[0][0] * self.matrix[1][1] - self.matrix[0][1] * self.matrix[1][0]\n elif len(self.matrix) == 1:\n return self.matrix[0][0]\n\n determinant = 0\n for c in range(len(self.matrix)):\n minor = Matrix(self.rows - (c + 1), self.columns - (c + 1))\n minor.matrix = self.get_minor(0,c)\n determinant += ((-1) ** c) * self.matrix[0][c] * minor.determinant()\n return determinant\n\n def get_cofactors(self):\n cofactors = Matrix(self.rows, self.columns)\n for i in range(self.rows):\n cofactors_row = []\n for j in range(self.columns):\n minor = Matrix(self.rows - (i + 1), self.columns - (i + 1))\n minor.matrix = self.get_minor(i, j)\n cofactors_row.append(((-1) ** (i+j)) * minor.determinant())\n cofactors.matrix.append(cofactors_row)\n return cofactors\n\n def inverse(self):\n inverted = Matrix(self.rows, self.columns)\n det = self.determinant()\n if det != 0:\n cofactors = self.get_cofactors()\n adj = cofactors.transpose(1)\n multiplier = round(1 / det, 2)\n inverted = adj * multiplier\n else:\n print(\"This matrix doesn't have an inverse.\")\n return inverted\n\n def print_matrix(self):\n print('\\n'.join([' '.join(['{}'.format(item) for item in row]) for row in self.matrix]))\n\n def append(self, row):\n self.matrix.append(row)\n\n\ndef multiply(multiplier):\n return lambda x: multiplier * x\n\n\ndef add():\n rows_1, columns_1 = input(\"Enter size of first matrix:\").split()\n print(\"Enter first matrix:\")\n matrix_1 = Matrix(rows_1, columns_1)\n matrix_1.entry()\n\n rows_2, columns_2 = input(\"Enter size of second matrix:\").split()\n print(\"Enter second matrix:\")\n matrix_2 = Matrix(rows_2, columns_2)\n matrix_2.entry()\n\n if rows_1 == rows_2 and columns_1 == columns_2:\n addition = matrix_1 + matrix_2\n print(\"The result is:\")\n addition.print_matrix()\n else:\n print(\"The operation cannot be performed.\")\n\n\ndef constant():\n rows, columns = input(\"Enter size of matrix:\").split()\n print(\"Enter matrix:\")\n matrix = Matrix(rows, columns)\n matrix.entry()\n\n multiplier = float(input(\"Enter constant:\"))\n multi = matrix * multiplier\n print(\"The result is:\")\n multi.print_matrix()\n\n\ndef multiply_matrices():\n rows_1, columns_1 = input(\"Enter size of first matrix:\").split()\n print(\"Enter first matrix:\")\n matrix_1 = Matrix(rows_1, columns_1)\n matrix_1.entry()\n\n rows_2, columns_2 = input(\"Enter size of second matrix:\").split()\n print(\"Enter second matrix:\")\n matrix_2 = Matrix(rows_2, columns_2)\n matrix_2.entry()\n\n if rows_2 == columns_1:\n multi = matrix_1.multiply_matrices(matrix_2)\n print(\"The result is:\")\n multi.print_matrix()\n else:\n print(\"The operation cannot be performed.\")\n\n\ndef transpose():\n print(\"\"\"1. Main diagonal\n2. Side diagonal\n3. Vertical line\n4. Horizontal line\"\"\")\n diagonal = int(input(\"Your choice:\"))\n rows, columns = input(\"Enter matrix size:\").split()\n print(\"Enter matrix:\")\n matrix = Matrix(rows, columns)\n matrix.entry()\n transposed = matrix.transpose(diagonal)\n transposed.print_matrix()\n\n\ndef calc_determinant():\n rows, columns = input(\"Enter matrix size:\").split()\n print(\"Enter matrix:\")\n matrix = Matrix(rows, columns)\n matrix.entry()\n print(matrix.determinant())\n\n\ndef inverse():\n rows, columns = input(\"Enter matrix size:\").split()\n print(\"Enter matrix:\")\n matrix = Matrix(rows, columns)\n matrix.entry()\n inverted = matrix.inverse()\n inverted.print_matrix()\n\n\nwhile 1:\n print(\"\"\"1. Add matrices\n2. Multiply matrix by a constant\n3. Multiply matrices\n4. Transpose matrix\n5. Calculate a determinant\n6. Inverse matrix\n0. Exit\"\"\")\n action = int(input(\"Your choice:\"))\n if action == 1:\n add()\n elif action == 2:\n constant()\n elif action == 3:\n multiply_matrices()\n elif action == 4:\n transpose()\n elif action == 5:\n calc_determinant()\n elif action == 6:\n inverse()\n elif action == 0:\n break\n","sub_path":"final projects/numeric_matrix_processor.py","file_name":"numeric_matrix_processor.py","file_ext":"py","file_size_in_byte":7760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"419298706","text":"import datetime\n\nfrom django.core.urlresolvers import reverse\n\nfrom ..models import Event, Task, Role\nfrom .base import TestBase\n\n\nclass TestInstructorsByDate(TestBase):\n def setUp(self):\n super().setUp()\n self._setUpUsersAndLogin()\n\n self.today = datetime.date.today()\n self.tomorrow = self.today + datetime.timedelta(days=1)\n self.yesterday = self.today - datetime.timedelta(days=1)\n self.after_tomorrow = self.today + datetime.timedelta(days=2)\n\n # set up some testing Events\n self.e1 = Event.objects.create(\n host=self.org_alpha,\n slug=\"in-range\",\n start=self.today,\n end=self.tomorrow,\n )\n\n self.e2 = Event.objects.create(\n host=self.org_alpha,\n slug=\"out-of-range1\",\n start=self.yesterday,\n end=self.tomorrow,\n )\n\n self.e3 = Event.objects.create(\n host=self.org_alpha,\n slug=\"out-of-range2\",\n start=self.today,\n end=self.after_tomorrow,\n )\n\n self.role = Role.objects.create(name='instructor')\n Task.objects.create(event=self.e1, person=self.hermione,\n role=self.role)\n Task.objects.create(event=self.e2, person=self.hermione,\n role=self.role)\n Task.objects.create(event=self.e3, person=self.hermione,\n role=self.role)\n\n def test_debrief(self):\n \"Make sure proper events are returned withing specific date ranges.\"\n data = {\n 'begin_date': self.today,\n 'end_date': self.tomorrow,\n 'url': reverse('instructors_by_date'),\n }\n FMT = '{url}?begin_date={begin_date}&end_date={end_date}'\n\n rv = self.client.get(FMT.format_map(data))\n assert rv.status_code == 200\n content = rv.content.decode('utf-8')\n assert self.e1.slug in content\n assert self.e2.slug not in content\n assert self.e3.slug not in content\n\n data['begin_date'] = self.yesterday\n rv = self.client.get(FMT.format_map(data))\n assert rv.status_code == 200\n content = rv.content.decode('utf-8')\n assert self.e1.slug in content\n assert self.e2.slug in content\n assert self.e3.slug not in content\n\n data['end_date'] = self.after_tomorrow\n rv = self.client.get(FMT.format_map(data))\n assert rv.status_code == 200\n content = rv.content.decode('utf-8')\n assert self.e1.slug in content\n assert self.e2.slug in content\n assert self.e3.slug in content\n\n data['begin_date'] = self.today\n rv = self.client.get(FMT.format_map(data))\n assert rv.status_code == 200\n content = rv.content.decode('utf-8')\n assert self.e1.slug in content\n assert self.e2.slug not in content\n assert self.e3.slug in content\n","sub_path":"workshops/test/test_instructors_by_date.py","file_name":"test_instructors_by_date.py","file_ext":"py","file_size_in_byte":2937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"12156921","text":"class Solution:\n def intervalIntersection(self, A, B): # AB are lists\n\n output = []\n ai,bi = 0, 0\n\n while ai < len(A) and bi < len(B):\n start_A, end_A = A[ai]\n start_B, end_B = B[bi]\n\n start = max(start_A, start_B)\n end = min(end_A, end_B)\n\n if start <= end: output.append([start, end])\n\n if end_A < end_B: ai+=1\n else: bi+=1\n\n return output\n\n #\nA = [[8, 15]]\nB = [[2, 6], [8, 10], [12, 20]]\n\nA = [[0,2],[5,10],[13,23],[24,25]]\nB = [[1,5],[8,12],[15,24],[25,26]]","sub_path":"leetcode/IntervalList Intersection.py","file_name":"IntervalList Intersection.py","file_ext":"py","file_size_in_byte":573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"313363336","text":"# Residual Gas Analysis at Asdex Upgrade\n# Michael Seibt\n\nfrom __future__ import division\n\nfrom itertools import cycle\nfrom time import strftime\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nimport settings\n\n\nclass CrackingPattern(object):\n faculty = [1, 1, 2, 6, 24]\n\n def __init__(self, base_mass, appendices, ratios, plot_header=''):\n if appendices + 1 != len(ratios):\n raise ValueError('Appendices must be the length of the '\n 'ratio + 1 list: {0}+1 != {1}'.format(appendices, len(ratios))\n )\n if appendices not in [2, 3, 4]:\n raise NotImplementedError('Only the crackingpattern matrices for '\n '2, 3, 4 appendices have been worked out')\n\n self.base_mass = base_mass\n self.appendices = appendices\n self.ratios = np.asarray(ratios)\n self.plot_header = plot_header\n\n # Transform the ratios to a probability for partials\n # self.probabilities = np.asarray(\n # list(map(lambda x: x / self.ratios.sum(), ratios))\n # )\n # print(self.probabilities)\n\n def calculate_probabilities(self, r):\n \"\"\" Calculates the probabilities for the base molecules at given r\n e.g. Methan @ 0.5:\n w(CH4) = (1/2)^4 * (1/2)^0 * (4+0)! / 4!*0!\n w(CH2D2) = (1/2)^2 * (1/2)^2 * (2+2)! / 2!*2!\n\n return: w[], W[0]:W[-1] -> HmaxD0:H0Dmax\n \"\"\"\n w = [\n r ** i * (1 - r) ** (self.appendices - i) *\n (self.faculty[self.appendices] / (self.faculty[i] * self.faculty[self.appendices - i]))\n for i in range(self.appendices, -1, -1)\n ]\n return w\n\n def matrix_at_r(self, r):\n w = self.calculate_probabilities(r)\n if self.appendices == 2:\n cp = np.array([\n [0, 0, 1], # 16\n [0, 1 * w[0] + (1 / 2) * w[1], 0], # 17\n [1 * w[0], (1 / 2) * w[1] + 1 * w[2], 0], # 18\n [1 * w[1], 0, 0], # 19\n [1 * w[2], 0, 0], # 20\n ])\n elif self.appendices == 3:\n cp = np.array([\n [0, 0, 0, 1], # 14\n [0, 0, 1 * w[0] + (2 / 3) * w[1] + (1 / 3) * w[2], 0], # 15\n [0, 1 * w[0] + (1 / 3) * w[1], (1 / 3) * w[1] + (2 / 3) * w[2] + 1 * w[3], 0], # 16\n [1 * w[0], (2 / 3) * w[1] + (2 / 3) * w[2], 0, 0], # 17\n [1 * w[1], (1 / 3) * w[2] + 1 * w[3], 0, 0], # 18\n [1 * w[2], 0, 0, 0], # 19\n [1 * w[3], 0, 0, 0], # 20\n ])\n elif self.appendices == 4:\n cp = np.array([\n [0, 0, 0, 0, 1], # 12\n [0, 0, 0, 1 * w[0] + (3 / 4) * w[1] + (1 / 2) * w[2] + (1 / 4) * w[3], 0], # 13\n [0, 0, 1 * w[0] + (1 / 2) * w[1] + (1 / 6) * w[2],\n (1 / 4) * w[1] + (1 / 2) * w[2] + (3 / 4) * w[3] + 1 * w[4], 0], # 14\n [0, 1 * w[0] + (1 / 4) * w[1], (1 / 2) * w[1] + (2 / 3) * w[2] + (1 / 2) * w[3], 0, 0], # 15\n [1 * w[0], (3 / 4) * w[1] + (1 / 2) * w[2], (1 / 6) * w[2] + (1 / 2) * w[3] + 1 * w[4], 0, 0], # 16\n [1 * w[1], (1 / 2) * w[2] + (3 / 4) * w[3], 0, 0, 0], # 17\n [1 * w[2], (1 / 4) * w[3] + 1 * w[4], 0, 0, 0], # 18\n [1 * w[3], 0, 0, 0, 0], # 19\n [1 * w[4], 0, 0, 0, 0], # 20\n ])\n return cp\n\n \n\n def ratios_at_r(self, r):\n \"\"\" Calculates the partial ratios at given r\n Cofficient determined by combinatorics\n \"\"\"\n return self.matrix_at_r(r).dot(self.ratios)\n\n def generate_cracking_pattern(self, n):\n \"\"\" Generates the complete Crackingpattern, with n steps in [0, 1]\n returns the r values as an array, the mass line as a dictionary\n \"\"\"\n x = np.linspace(0, 1, n)\n y = []\n for r in x:\n y.append(self.ratios_at_r(r))\n return x, {i + self.base_mass: line for i, line in enumerate(np.asarray(y).transpose())}\n\n def plot_cracking_pattern(self, n=100, save_to_file=False):\n x, m = self.generate_cracking_pattern(n)\n fig = plt.figure(figsize=(10, 6))\n ax = fig.add_subplot(111)\n\n for key, value in m.iteritems():\n # ax.plot(x, value, linewidth=2, markevery=10, label=str(key))\n ax.plot(x, value, marker=settings.markers.next(), markevery=10, label=str(key))\n\n # ax.set_xticks([])\n # ax.set_yticks([])\n # fig.tight_layout()\n ax.set_xlabel('R')\n ax.set_ylabel(u'Relative Intensit\\xe4t')\n # ax.set_title('Crackingpattern {0}'.format(self.plot_header))\n box = ax.get_position()\n ax.set_position([box.x0, box.y0, box.width*0.8, box.height])\n ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))\n\n if save_to_file:\n n = settings.TAB_SIZE\n filepathname = '{0}/{1}_{2}'.format(\n settings.CP_DATA_PATH,\n self.plot_header, \n strftime('%Y%m%d%H%M%S')\n )\n out = \"Molecule: {0} - Ratios: {1} - Steps: {2}\\n\\n\".format(self.plot_header, self.ratios, n)\n \n out += \"HD\".ljust(n) + ''.join([str(hd).ljust(n) for hd in x])\n for key in m:\n out += \"\\n\" + str(key).ljust(n) + ''.join([str(round(value, 5)).ljust(n) for value in m[key]])\n with open(filepathname+'.txt', 'w') as f:\n f.write(out)\n fig.savefig(filepathname+'.png', bbox_inches='tight')\n plt.savefig('cp_ammonia.pdf')\n plt.show()\n \n @classmethod\n def crackingpattern_factory(cls, molecule, ratios):\n return cls(molecule.base_mass, molecule.appendices, ratios, molecule.name)\n","sub_path":"lvl2/crackingpattern.py","file_name":"crackingpattern.py","file_ext":"py","file_size_in_byte":5819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"455372046","text":"from block import Block\nfrom transactions import Transaction\n\n\ndef main():\n\n genesis_transaction = Transaction(\"Logan\", \"Dorian\", 3)\n\n # initialize genesis\n genesis_block = Block(\"wow you're cool if you find this message...\", genesis_transaction)\n\n second_transaction = Transaction(\"Terry\", \"Bob\", 42)\n second_block = Block(genesis_block.hash, second_transaction)\n\n print(genesis_block.hash)\n print(second_block.hash)\n\n\n# by default run main method\nif __name__ == \"__main__\":\n main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"611109135","text":"# 4 GUEST BOOK\n# write a while loop that prompts\n# the users for their name\n# add the user input to a text file\n\n# text file where user input will be stored\nfilename='text_files/guest_book.txt'\n\nprint(\"\\nPlease enter all the guest that arrived today\")\n\nprompt=\"\\nEnter their first and last name:\"\nprompt+=\"\\nEnter 'quit' to exit the program: \"\n\n# create a loop and ask the user to enter guest names\nwhile True:\n guest_name=input(prompt)\n # exit the loop if user enters 'quit'\n if guest_name == 'quit':\n break\n # if user enters a name store it in file 'guest_book.txt'\n else:\n with open(filename,'a') as file_object:\n file_object.write(guest_name+\"\\n\")\n\n","sub_path":"guest_name.py","file_name":"guest_name.py","file_ext":"py","file_size_in_byte":693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"8387744","text":"# Copyright 2012 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS-IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Courses module.\"\"\"\n\n__author__ = 'Pavel Simakov (psimakov@google.com)'\n\nfrom controllers import assessments\nfrom controllers import lessons\nfrom controllers import utils\nfrom models import content\nfrom models import custom_modules\nfrom tools import verify\n\n\ncustom_module = None\n\n\ndef register_module():\n \"\"\"Registers this module in the registry.\"\"\"\n\n # provide parser to verify\n verify.parse_content = content.parse_string_in_scope\n\n # setup routes\n courses_routes = [\n ('/', lessons.CourseHandler),\n ('/activity', lessons.ActivityHandler),\n ('/answer', assessments.AnswerHandler),\n ('/assessment', lessons.AssessmentHandler),\n ('/course', lessons.CourseHandler),\n ('/forum', utils.ForumHandler),\n ('/preview', utils.PreviewHandler),\n ('/register', utils.RegisterHandler),\n ('/review', lessons.ReviewHandler),\n ('/reviewdashboard', lessons.ReviewDashboardHandler),\n ('/student/editstudent', utils.StudentEditStudentHandler),\n ('/student/home', utils.StudentProfileHandler),\n ('/student/unenroll', utils.StudentUnenrollHandler),\n ('/unit', lessons.UnitHandler)]\n\n global custom_module\n custom_module = custom_modules.Module(\n 'Course',\n 'A set of pages for delivering an online course.',\n [], courses_routes)\n return custom_module\n","sub_path":"coursebuilder/modules/courses/courses.py","file_name":"courses.py","file_ext":"py","file_size_in_byte":1975,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"214080763","text":"import numpy as np\nfrom sklearn.svm import SVC\nimport matplotlib.pyplot as plt\n\nx_train = np.random.randn(300, 2) # randn与rand不同,包含负数\ny_train = np.logical_xor(x_train[:,0]>0, x_train[:,1]>0)\n\"\"\"\ndisplay(x_train.shape, y_train.shape) --> (300, 2) (300,)\n以简单的小例子理解上述数据生成的具体过程:\na = np.array([[1, 2], [1, -2], [-1, -2], [-1,2]])\nb = np.logical_xor(a[:,0]>0, a[:,1]>0) --> [False, True, False, True]\n即array b 在第一、三象限为False,第二、四象限为True.\n\"\"\"\nx = np.arange(-3, 3, 0.01) # 600*600 600个点\ny = np.arange(-3, 3, 0.01) # 600*600 600个点\nxx, yy = np.meshgrid(x, y) # 生成网格\nxy = np.c_[xx.ravel(), yy.ravel()] # 降维打击后串联\n# xy.shape --> (360000, 2)\n\nsvc = SVC(kernel=\"rbf\") # 半径内核划分\nsvc.fit(x_train, y_train)\nplt.figure(figsize=(5, 5))\nplt.scatter(x_train[:,0], x_train[:,1], c=y_train, cmap=plt.cm.Paired, edgecolors=\"k\")\n# 定义几个界限\n# 样本X到分离超平面的距离\ndd = svc.decision_function(xy)\nd = dd.reshape(xx.shape)\nplt.imshow(d, extent=(-5, 5, -5, 5), cmap=plt.cm.PuOr_r)\nplt.contour(xx, yy, d) # 绘制轮廓\nplt.show()","sub_path":"Resources/SVM&K-Means/RadiusRegression-SVM.py","file_name":"RadiusRegression-SVM.py","file_ext":"py","file_size_in_byte":1168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"576128947","text":"#! /usr/bin/env python3.4\n#\n# $Author: ee364e04 $\n# $Date: 2015-02-11 11:04:24 -0500 (Wed, 11 Feb 2015) $\n# $HeadURL: svn+ssh://ece364sv@ecegrid-thin1/home/ecegrid/a/ece364sv/svn/S15/students/ee364e04/Lab04/processReports.py $\n# $Revision: 75467 $\n\nimport glob\nimport re\nfrom pprint import pprint as pp\n\n\ndef getUsers():\n users = {}\n usr_regex = re.compile(r\"^(\\w+)\\,\\s?(\\w+).*(\\d{5}\\-\\d{5})\", re.MULTILINE)\n\n with open('users.txt', \"r\") as fh:\n fContent = fh.read()\n fRegex = usr_regex.findall(fContent)\n\n for group in fRegex:\n name = group[1] + \" \" + group[0]\n id = group[2]\n users[id] = name\n\n return users\n\n\ndef getTotalSpending():\n reports = generateReportForAllViruses()\n sum = 0\n\n for group in reports.values():\n sum += group[1]\n return float(\"{0:.2f}\".format(sum))\n\n\ndef getUsersWithoutReports():\n users = getUsers()\n reports = generateReportForAllUsers()\n\n withoutReport = []\n\n for user in users.values():\n if user not in reports:\n withoutReport.append(user)\n\n return set(withoutReport)\n\n\ndef generateReportForAllViruses():\n report = {}\n virus_regex = re.compile(r\"^\\d{3}\\s+([\\w\\-]+)\\s+(\\d{3})\\s+\\$([\\d\\.]+)\", re.MULTILINE)\n files = glob.glob('./reports/report*.txt')\n\n for f in files:\n with open(f, \"r\") as fh:\n fContent = fh.read()\n fRegex = virus_regex.findall(fContent)\n\n for virus, vUnits, vCost in fRegex:\n if virus in report.keys():\n units, cost = report[virus]\n else:\n units, cost = [0, 0]\n\n units += int(vUnits)\n cost += float(vCost)\n report[virus] = units, float(\"{0:.2f}\".format(cost))\n\n return report\n\n\ndef generateReportForAllUsers():\n users = getUsers()\n files = glob.glob('./reports/report*.txt')\n user_regex = re.compile(r\"^[A-Za-z]+\\s+[A-Za-z:]+\\s+(\\d{5}-\\d{5})\", re.MULTILINE)\n virus_regex = re.compile(r\"^\\d{3}\\s+[\\w\\-]+\\s+(\\d{3})\\s+\\$([\\d\\.]+)\", re.MULTILINE)\n\n report = {}\n\n for f in files:\n with open(f, \"r\") as fh:\n fContent = fh.read()\n id = user_regex.findall(fContent)[0]\n virus = virus_regex.findall(fContent)\n\n for vUnits, vCost in virus:\n #print(line)\n if users[id] in report.keys():\n units, cost = report[users[id]]\n else:\n units = 0\n cost = 0\n\n units += int(vUnits)\n cost += float(vCost)\n\n report[users[id]] = units, float(\"{0:.2f}\".format(cost))\n\n return report\n\n\ndef main():\n pp(generateReportForAllUsers())\n #pp(generateReportForAllViruses())\n #pp(getUsersWithoutReports())\n #pp(getTotalSpending())\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"Lab04/redo.py","file_name":"redo.py","file_ext":"py","file_size_in_byte":2882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"233410540","text":"# credit to: https://leetcode.com/problems/campus-bikes-ii/discuss/307544/dfs-with-memorization\n\nclass Solution(object):\n def assignBikes(self, workers, bikes):\n def dist(i, j):\n return abs(workers[i][0] - bikes[j][0]) + abs(workers[i][1] - bikes[j][1])\n\n w = len(workers)\n b = len(bikes)\n memo = {}\n visited = [False] * b\n\n def dfs(i):\n if i == w:\n return 0\n res = float('inf')\n for j in range(b):\n if not visited[j]:\n visited[j] = True\n tmp = tuple(visited)\n if tmp not in memo:\n memo[tmp] = dfs(i+1)\n res = min(res, dist(i,j) + memo[tmp])\n visited[j] = False\n return res\n return dfs(0)\n \"\"\"\n :type workers: List[List[int]]\n :type bikes: List[List[int]]\n :rtype: int\n \"\"\"\n","sub_path":"python/1066 Campus Bikes II.py","file_name":"1066 Campus Bikes II.py","file_ext":"py","file_size_in_byte":964,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"316347545","text":"class DeansEmp(object):\n id_emp = 0\n\n @staticmethod\n def set_idx(id_emp):\n \"\"\"function set var id_emp\n\n Args:\n id_emp (int): new idx for class\n \"\"\"\n DeansEmp.id_emp = id_emp\n\n @staticmethod\n def status_id():\n \"\"\"func return variable id_emp\n\n Returns:\n int: [description]\n \"\"\"\n return DeansEmp.id_emp\n\n @staticmethod\n def select_all(db):\n \"\"\"func return all deans office employees\n data from db\n\n Args:\n db (TableDatabase): database that you want to search\n\n Returns:\n List: list of tuples of data\n \"\"\"\n cur = db.cursor_conn()\n cur.execute(\"SELECT * FROM deans_office_employee\")\n\n return cur.fetchall()\n\n @staticmethod\n def get_lastrowid(db):\n \"\"\"function return last row id\n\n Args:\n db (TableDatabase): database that you want to search\n\n Returns:\n [int]: last row id\n \"\"\"\n cur = db.cursor_conn()\n cur.execute(\"SELECT * FROM deans_office_employee\")\n\n return cur.lastrowid\n\n @staticmethod\n def create_tab(db):\n \"\"\"\n ***function must be execute after create\n department table***\\n\n function create table deans_office_employee\n \"\"\"\n\n sql = \"\"\"CREATE TABLE IF NOT EXISTS deans_office_employee (\n id_deans_office_employee INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,\n name TEXT NOT NULL,\n second_name TEXT,\n lastname TEXT NOT NULL,\n pesel INTEGER NOT NULL,\n email TEXT,\n id_department INTEGER NOT NULL,\n FOREIGN KEY (id_department) REFERENCES department(id_department)\n ON UPDATE CASCADE\n ON DELETE CASCADE\n );\n \"\"\"\n\n if db.get_conn() is not None:\n db.create_tab(sql)\n else:\n print(\"Error! Cant create deans_office_employee table\")\n\n def __init__(self, id_emp=0, name='', sec_name='', lastname='', ssn=1000, email='', department=None):\n \"\"\"Init Deans Office Employee\n\n Args:\n id_emp (int, optional): if of deans emp. Defaults to 0.\n name (str, optional): deans emp name. Defaults to ''.\n sec_name (str, optional): deans emp second name. Defaults to ''.\n lastname (str, optional): deans emp lastname. Defaults to ''.\n ssn (int, optional): deans emp ssn. Defaults to 1000.\n email (str, optional): deans emp email. Defaults to ''.\n department ([Department], optional): deans emp department.\n Defaults to None.\n \"\"\"\n DeansEmp.id_emp += 1\n # set id_student automatically or manual\n if id_emp == 0:\n self.__id_emp = DeansEmp.id_emp\n else:\n self.__id_emp = id_emp\n\n self.__name = name\n self.__sec_name = sec_name\n self.__lastname = lastname\n self.__ssn = ssn\n self.__email = email\n self.__department = department\n\n def insert(self, db):\n \"\"\"function insert data to db\n\n Args:\n db (TableDatabase): database that you want to fill\n \"\"\"\n sql = \"\"\"INSERT INTO deans_office_employee(\n name,\n second_name,\n lastname,\n pesel,\n email,\n id_department\n ) VALUES (?,?,?,?,?,?)\n \"\"\"\n\n try:\n department_id = self.__department.get_id()\n except AttributeError:\n department_id = \"NULL\"\n\n values = (\n self.__name,\n self.__sec_name,\n self.__lastname,\n self.__ssn,\n self.__email,\n department_id\n )\n\n if db.get_conn() is not None:\n cur = db.cursor_conn()\n cur.execute(sql, values)\n else:\n print(\"Error! Cant insert in deans_office_employee table\")\n\n def update(self, db):\n \"\"\"function update data to db\n\n Args:\n db (TableDatabase): database that you want to update\n \"\"\"\n sql = \"\"\"UPDATE deans_office_employee SET\n name = ?,\n second_name = ?,\n lastname = ?,\n pesel = ?,\n email = ?,\n id_department = ?\n WHERE id_deans_office_employee = ?\n \"\"\"\n\n try:\n department_id = self.__department.get_id()\n except AttributeError:\n department_id = \"NULL\"\n\n values = (\n self.__name,\n self.__sec_name,\n self.__lastname,\n self.__ssn,\n self.__email,\n department_id,\n self.__id_emp\n )\n\n if db.get_conn() is not None:\n cur = db.cursor_conn()\n cur.execute(sql, values)\n else:\n print(\"Error! Cant update in deans_office_employee table\")\n\n def delete(self, db):\n \"\"\"function delete data to db\n\n Args:\n db (TableDatabase): database that you want to update\n \"\"\"\n sql = \"\"\"\n DELETE FROM deans_office_employee WHERE\n id_deans_office_employee = ?\"\"\"\n\n if db.get_conn() is not None:\n cur = db.cursor_conn()\n cur.execute(sql, (self.__id_emp,))\n else:\n print(\"Error! Cant delete in deans_office_employee table\")\n\n def get_id(self):\n return self.__id_emp\n\n def get_name(self):\n return self.__name\n\n def get_sec_name(self):\n return self.__sec_name\n\n def get_lastname(self):\n return self.__lastname\n\n def get_ssn(self):\n return self.__ssn\n\n def get_email(self):\n return self.__email\n\n def get_department(self):\n return self.__department\n\n def set_id(self, id_emp):\n self.__id_emp = id_emp\n\n def set_name(self, name):\n self.__name = name\n\n def set_sec_name(self, sec_name):\n self.__sec_name = sec_name\n\n def set_lastname(self, lastname):\n self.__lastname = lastname\n\n def set_ssn(self, ssn):\n self.__ssn = ssn\n\n def set_email(self, email):\n self.__email = email\n\n def set_department(self, department):\n self.__department = department\n","sub_path":"Tables/DeansEmp.py","file_name":"DeansEmp.py","file_ext":"py","file_size_in_byte":6229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"162091947","text":"from django.http import HttpResponse\nfrom django.shortcuts import render\nfrom django.core.files.storage import FileSystemStorage\nimport sys\nfrom subprocess import run,PIPE\nfrom .models import card\nfrom .main_ import test\nfrom card_OCR.settings import MEDIA_ROOT,MEDIA_URL\n\ndef index(request):\n return render(request,'home.html')\ndef demo(request):\n image=request.FILES['image']\n fs=FileSystemStorage()\n filename=fs.save(image.name,image)\n fileurl=fs.open(filename)\n templateurl=fs.url(filename)\n url = MEDIA_ROOT+MEDIA_URL+filename\n print(url)\n print(\"raw url\",filename)\n print(\"file url\",fileurl)\n print(\"template url\",templateurl)\n contacts,pincode,email,website,city,state,address,name = test(filename)\n\n # image= run([sys.executable,'F://Visual Studio Code//djangoproject//main.py',str(fileurl),str(filename)],shell=False,stdout=PIPE)\n # print(\"final text\",image.stdout)\n sep=\" \"\n def converttostr(input_seq, seperator):\n final_str = seperator.join(input_seq)\n return final_str\n def remove(string):\n return string.replace(\" \",\"\")\n name=converttostr(name,sep)\n name=remove(name)\n company_name=\"xyz\"\n email=converttostr(email,sep)\n website=converttostr(website,sep)\n contact1,contact2=\"\",\"\"\n if(len(contacts)):\n contact1=contacts[0]\n if(len(contacts)>1):\n contact2=contacts[1]\n else:\n contact1,contact2=\" \",\" \"\n contact1=remove(contact1)\n contact2=remove(contact2)\n city=converttostr(city,sep)\n state=converttostr(state,sep)\n pincode=converttostr(pincode,sep)\n address=converttostr(address,sep)\n address=remove(address)\n print(name,email,website,contact1,contact2,city,state,pincode,address)\n params={\"name\":name,\"companyName\":company_name,\"email\":email,\"website\":website,\"contact1\":contact1,\"contact2\":contact2,\"city\":city,\"state\":state,\"pincode\":pincode,\"address\":address}\n print(params)\n return render(request,'show.html',params)\n\ndef show(request):\n if request.method==\"POST\":\n name=request.POST.get(\"name\")\n company_name=request.POST.get(\"cname\")\n email=request.POST.get(\"email\")\n website=request.POST.get(\"website\")\n contact1=request.POST.get(\"contact1\")\n contact2=request.POST.get(\"contact2\")\n city=request.POST.get(\"city\")\n state=request.POST.get(\"state\")\n pincode=request.POST.get(\"pincode\")\n address=request.POST.get(\"address\")\n card1=card(name=name,company_name=company_name,email=email,website=website,contact1=contact1,contact2=contact2,city=city,state=state,pincode=pincode,address=address)\n card1.save()\n return render(request,\"home.html\")\n","sub_path":"card_OCR/app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"247201491","text":"__author__ = 'Janet Green'\nimport sys\nimport datetime as dt\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport json\nimport os\nimport leapseconds\n#import odc_util\nimport math\nfrom scipy.signal import find_peaks\n\ndef check_slash(cdir):\n # This just checks that there is a slash at the end of the directory inputs so nothing\n # goes wonky\n # Find if it is '\\' or '/\n if cdir.find('/')>-1:\n slash = '/'\n else:\n slash = '\\\\'\n if cdir[-1]!=slash:\n cdir = cdir+slash\n\n return cdir\n\ndef find_files(sat,sdate,edate,root_dir, name_fmt,lower_dir = None):\n import glob\n # PURPOSE: To find all the data files between sdate and edate in a variable but fairly\n # common directory structure given by the inputs. Allowing some specification of the\n # directory structure with common directories like year make it faster than just searching\n # through all files in the top root_dir where there are often many, many files.\n # INPUTS:\n # sat : string name of sat. Assumes that the sat name in the directory structure\n # is the same as in the file format. This assumption may not always hold which\n # means a different lower dir with the SAT name would have to be passed\n # example for HEO sat = 'F1'\n # sdate : datetime object with the start day of requested data\n # edate : datetime object with the end day of requested data\n # root_dir: string with the top leve dirctory (no keywords\n # lower_dir: string with the lower level directory structure using fillable keywords\n # example for HEO 15s data lower_dir = 'SAT/exp/YYYY'\n # OUTPUTS: List of files to read\n\n #NOTE: The HEO data is weird in that there are ~2 files per data at random times\n\n n_days = abs((edate - sdate).days) # Number of days from sdate to look through\n file_pattern_list = list()\n lower_dir_list = list()\n\n for nco in range(0,n_days):\n # First replace the keywords in the name_fmt\n tempfile = name_fmt\n newtime = sdate+dt.timedelta(days = nco)\n strvals = {'YYYY':str(newtime.year),'yy':str(newtime.year)[-2::],'MM':str(newtime.month).zfill(2),'SAT':sat,\n 'DD':str(newtime.day).zfill(2),'ddd':str(newtime.timetuple().tm_yday).zfill(3)}\n for val in strvals.keys():\n tempfile =tempfile.replace(val, strvals[val])\n\n # Add the lower directory structure if requested\n if lower_dir:\n # If there is a second directory structure passed then fill in the key words and create\n # a list of those for each file. This is to make it simpler when searching for different types of\n # data under the same root dir but different lower structures which often is the case.\n tempdir = lower_dir\n for val in strvals.keys():\n tempdir = tempdir.replace(val, strvals[val])\n lower_dir_list.append(tempdir)\n\n file_pattern_list.append(tempfile)\n\n # Now search for all the matching files in the given directory\n final_files = list()\n for fco in range(0,len(file_pattern_list)):\n # Create a list of all the files in the expected directory\n if lower_dir:\n all_files = glob.glob(root_dir+lower_dir_list[fco]+file_pattern_list[fco], recursive=True)\n else:\n all_files = glob.glob(file_pattern_list[fco],recursive=True)\n final_files.extend(all_files)\n return final_files\n # First\n\n\ndef read_ascii_data(files, header_lines=0, vars=None,delim=None,datatype = None):\n # PURPOSE: To read HEO data\n # INPUTS:\n # files: A list of files to read\n # vars: the vars you want to read in. If None then all the data is passed back\n #\n # OUTPUTS: A numpy array with the data\n #----------------------------------------------------------------------------------\n\n # Find the columns to get from datatype\n dtype_list = list()\n col_list = list()\n if vars:\n # For var list need column index in file, but dtype list must match vars\n for var in vars:\n i = datatype.names.index(var)\n col_list.append(i)\n dtype_list.append((var, datatype[i]))\n else:\n # If no var list, use all columns\n col_list = range(0, len(datatype.names))\n dtype_list = datatype\n\n # Now we want to find the cols of just vars\n # data = np.zeros(( 0, len( datatype.names )), dtype = datatype )\n data = np.zeros((0, len(col_list)), dtype=dtype_list)\n\n for file in files:\n data = np.append(data,np.loadtxt(file,dtype=dtype_list,delimiter=delim,skiprows=header_lines,usecols=col_list))\n\n return(data)\n\n\ndef get_HEO_text(sat, sdate, edate ,root_dir,lower_dir = None, vars = None):\n # PURPOSE: To create a numpy array of the HEO data in the time period from sdate to\n # edate for the satellite, sat. First it looks in the directories root_dir and\n # lower dir (if given). Then it reads the files and appends them into one\n # numpy array with dtype given by the column names in the first line.\n # There are two kinds of HEO data 'exp' (15 sec averages) and Lbin (.25 Lbin averages)\n # This will read either one but it assumes they are in different directories\n\n # INPUTS:\n # sat : name of satellite ex. 'f1', 'f3' (REQUIRED)\n # sdate : datetime start of data to get (REQUIRED)\n # edate : datetime end of data to get (REQUIRED)\n # root_dir : top directory to search for data ex. '/data/ (REQUIRED)\n # lower_dir : directory under top directory with KEYWORDs like YYYY (Optional)\n # ex. 'SAT/YYYY'\n # vars : list of vars to get ex. ['Year','Month'] (Optional\n\n # Quick check to see if there is a slash at the end of the directories\n root_dir= check_slash(root_dir)\n if lower_dir:\n lower_dir=check_slash(lower_dir)\n\n # The file name format for HEO text data is fixed regrdless of whether it is exp or Lbin\n # If you want to get exp dat then use lower_dir = 'SAT/exp/YYYY/'\n # If you want to get Lbin data then user lower_dir = 'SAT/Lbin/YYYY/'\n\n heo_fmt = 'SAT_YYYYddd_*'\n\n # first find the files\n files = find_files(sat, sdate, edate, root_dir, heo_fmt, lower_dir=lower_dir)\n\n # Check if data is returned\n if len(files)<1:\n print('No data for ',sat, 'between ',sdate.strftime(\"%Y/%m/%d\"),' and ',edate.strftime(\"%Y/%m/%d\"))\n return\n\n # read_ascii is a generic code to read in a typical ascii dataset\n # These are the inputs needed for HEO\n # For the HEO data the header is just one line\n heo_header = 1\n\n # Read the first line of the first file to get the column names\n with open(files[0],'r') as f:\n head_dat = (f.readline()).split()\n f.close()\n\n # Then create the heo_type\n heo_type=list()\n for col in head_dat:\n heo_type.append((col,'f'))\n\n #This will read and concatenate them all together\n\n # Need to order the files in time\n files.sort()\n alldata = read_ascii_data(files,header_lines=heo_header,vars = vars,datatype =np.dtype(heo_type))\n\n return alldata\n\ndef get_ICO_text( sdate, edate ,root_dir, lower_dir = 'ICO_YYYY', vars = None ):\n # PURPOSE: To create a numpy array of the ICO data in the time period from startYr to\n # endYr. The directory structure must follow the format {root path}/ICO_{year}, for\n # the passed range of years.\n # It reads the files and appends them into one\n # numpy array with dtype given by the column names in the first line.\n\n # INPUTS:\n # startDate : start date of data to get (REQUIRED)\n # endDate : end date of data to get (REQUIRED)\n # root_dir : top directory to search for data ex. '/data/ (REQUIRED)\n # vars : list of vars to get ex. ['Year','Month'] (Optional)\n\n # Quick check to see if there is a slash at the end of the directories\n root_dir= check_slash(root_dir)\n if lower_dir:\n lower_dir=check_slash(lower_dir)\n\n # The file name format for ICO text data is fixed \"ico_yyyydoy_v04.l2\"\n # The directory structure is assumed to be {root path}/ICO_YYYY\n\n ico_fmt = 'ico_YYYYddd_*'\n\n # first find the files\n #files = find_files( startDate, endDate, root_dir )\n # The ICO data is in a 7 day ascii format which makes it\n # really hard to find the data you want without opening extra files. Ugh.\n\n # So just to be safe, I add 7 days to sdate to make sure we get the start\n # And then I reduce it down to the requested time at the end.\n # first find the files\n\n new_sdate = sdate-dt.timedelta(days = 7)\n files = find_files( ' ', new_sdate, edate, root_dir, ico_fmt, lower_dir=lower_dir)\n\n # Check if data is returned\n if len(files)<1:\n print('No data between ' + str(sdate) + ' and ' + str(edate))\n return\n\n # read_ascii is a generic code to read in a typical ascii dataset\n # These are the inputs needed for HEO\n # For the HEO data the header is just one line\n ico_header = 1\n\n ico_type=list()\n\n # Read the first line of the first file to get the column names\n with open(files[0],'r') as f:\n head_dat = (f.readline()).split()\n f.close()\n\n # Then create the heo_type (column 1 is year - integer)\n\n for col in head_dat:\n if len(ico_type) == 0 :\n ico_type.append(( col, 'i'))\n else :\n ico_type.append((col,'f'))\n\n # Need to order the files in time\n files.sort()\n\n # This will read and concatenate them all together\n\n alldata = read_ascii_data( files, header_lines=ico_header, vars = vars, datatype = np.dtype( ico_type ))\n\n time1 = [dt.datetime(alldata['Year'][x],1,1)+ dt.timedelta(days=alldata['DecDay'][x]-1) for x in range(0,len(alldata['Year']))]\n\n ginds = np.where((np.array(time1)>sdate) & (np.array(time1)0) & (Ldata<100))[0]\n dL = np.diff(Ldata[goodinds])\n allbreaks = goodinds[np.where(np.diff(np.sign(dL)))]\n #obreaks = 0 * Ldata\n obreaks = np.zeros(len(Ldata),dtype=float)\n obreaks[allbreaks] = 1\n passes = np.cumsum(obreaks)\n\n return passes, allbreaks\ndef getLpassHEO2(L,dist=200,prom=.5):\n #Purpose: To create an arary with pass number for each data point\n # that can be used to more easily average data or plot it pass by pass\n # Limit to between 0 and 100 because weird things happen at large L\n # Need to fix this so that it works on numpy arrays and numpy masked arrays\n # Usage: if the data is netcdf4 returned from poes_utils\n # getLpass(poes['L_IGRF][:],dist=200,prom=.5):\n # if the data is a numpy array\n # getLpass(data['L_IGRF'][:],dist=200,prom=.5\n\n if isinstance(L, np.ma.MaskedArray):\n Ldata = L.data\n else:\n Ldata = L\n goodinds= np.where((Ldata[:]>0) & (Ldata[:]<100))[0]\n peaks = find_peaks(Ldata[goodinds],distance=dist,prominence=prom) # Find the maxima\n valleys = find_peaks(-1*(Ldata[goodinds]),distance=dist,prominence=prom) # Find the minima\n #plt.plot(L.data[goodinds])\n #plt.plot(peaks[0],L.data[goodinds[peaks[0]]],'*')\n #plt.plot(valleys[0], L.data[goodinds[valleys[0]]], '+')\n allbreaks = np.sort(np.append(goodinds[peaks[0]], goodinds[valleys[0]]))\n pbreaks = np.zeros(len(Ldata), dtype=float)\n #pbreaks = 0 * Ldata\n pbreaks[allbreaks] = 1\n passes = np.cumsum(pbreaks)\n\n return passes,allbreaks\ndef get_dsts( sdate, edate ) :\n # PURPOSE: retrieves hourly DST index values between the passed start and end dates\n # from the omniweb (nasa) data retrieval web site. Strips off header and footer info\n # returning only the date-time and dst value lists\n\n dstVarNum = \"40\"\n sdateStr = sdate.strftime( \"%Y%m%d\" )\n edateStr = edate.strftime( \"%Y%m%d\" )\n dstFileStr = \"./DST_\" + sdateStr + \"_\" + edateStr + \".txt\"\n\n queryStr = \" --post-data \\\"activity=retrieve&res=hour&spacecraft=omni2&start_date=\" + \\\n sdateStr + \"&end_date=\" + edateStr + \\\n \"&vars=\" + dstVarNum + \\\n \"&scale=Linear&ymin=&ymax=&view=0&charsize=&xstyle=0&ystyle=0&symbol=0\" + \\\n \"&symsize=&linestyle=solid&table=0&imagex=640&imagey=480&color=&back=\\\" \" + \\\n \"https://omniweb.sci.gsfc.nasa.gov/cgi/nx1.cgi -O \" + dstFileStr\n\n os.system( \"wget\" + queryStr )\n\n dsts = []\n isHeader = True\n with open( dstFileStr ) as fp:\n for cnt, line in enumerate(fp):\n if line.startswith( \"YEAR\" ) :\n isHeader = False\n elif isHeader :\n continue\n else :\n if line.startswith(\"<\") :\n break\n dst_parts = [ int(i) for i in line.split() ]\n dsts.append( dst_parts )\n\n return( dsts )\n\ndef get_omni( sdate, edate, vars ) :\n # PURPOSE: retrieves hourly DST index values between the passed start and end dates\n # from the omniweb (nasa) data retrieval web site. Strips off header and footer info\n # returning only the date-time and dst value lists\n # vars is a list of variables requested\n allvars =['Bartels Roation Number','IMF Spacecraft ID','Plasma Spacecraft ID','Fine Scale Points in IMF avgs',\n 'Fine Scale Points in Plasma Avgs','IMF Magnitude Avg','Magnitude, Avg IMF Vr',\n 'Lat. of Avg. IMF','Long. of Avg. IMF','Bx, GSE/GSM','By, GSE','Bz, GSE',\n 'By, GSM','Bz, GSM','Sigma in IMF Magnitude Avg','Sigma in IMF Vector Avg',\n 'Sigma Bx, nT','Sigma By, nT','Sigma Bz, nT','Proton Temperature, K','Proton Density, n/cc',\n 'Flow Speed, km/sec','Flow Longitude, deg','Flow Latitude, deg','Alpha/Proton Density Ratio','Flow Pressure, nPa',\n 'Sigma-T','Sigma-Np','Sigma-V','Sigma-Flow-Longitude','Sigma-Flow-Latitude','Sigma-Alpha/Proton Ratio',\n 'Ey - Electric Field, mV/m','Plasma Beta','Alfven Mach Number','Kp*10 Index',\n 'R Sunspot Number','Dst Index, nT','AE Index, nT',\n 'Proton Flux* > 1 MeV','Proton Flux* > 2 MeV','Proton Flux* > 4 MeV','Proton Flux* >10 MeV',\n 'Proton Flux* >30 MeV','Proton Flux* >60 MeV','Magnetospheric Flux Flag','ap index, nT','Solar index F10.7',\n 'Polar Cap (PCN) index','AL Index, nT','AU Index, nT','Magnetosonic Mach Number','Lyman Alpha','Proton Quazy-Invariant']\n varnums = [allvars.index(s)+3 for s in allvars if any(xs in s for xs in vars)]\n varstring =''\n for varnum in varnums:\n varstring = varstring +'&vars='+str(int(varnum))\n\n sdateStr = sdate.strftime( \"%Y%m%d\" )\n edateStr = edate.strftime( \"%Y%m%d\" )\n dstFileStr = \"./OMNI_\" + sdateStr + \"_\" + edateStr + \".txt\"\n\n queryStr = \" --post-data \\\"activity=retrieve&res=hour&spacecraft=omni2&start_date=\" + \\\n sdateStr + \"&end_date=\" + edateStr + \\\n varstring + \\\n \"&scale=Linear&ymin=&ymax=&view=0&charsize=&xstyle=0&ystyle=0&symbol=0\" + \\\n \"&symsize=&linestyle=solid&table=0&imagex=640&imagey=480&color=&back=\\\" \" + \\\n \"https://omniweb.gsfc.nasa.gov/cgi/nx1.cgi -O \" + dstFileStr\n\n os.system( \"wget\" + queryStr )\n\n dsts = []\n isHeader = True\n with open( dstFileStr ) as fp:\n for cnt, line in enumerate(fp):\n if line.startswith( \"YEAR\" ) :\n isHeader = False\n elif isHeader :\n continue\n else :\n if line.startswith(\"<\") :\n break\n dst_parts = [ float(i) for i in line.split() ]\n dsts.append( dst_parts )\n os.remove(dstFileStr)\n return( dsts )\n\ndef get_meanDST( dsts ):\n # PURPOSE: return the mean dst value in a list of lists of year doy hr dst\n\n meanDST = 0.0\n for dstData in dsts :\n meanDST += dstData[3] / len(dsts)\n\n return meanDST\n\ndef get_minDST( dsts ):\n # PURPOSE: return the min dst value in a list of lists of year doy hr dst\n\n minDST = 99999.9\n for dstData in dsts :\n if dstData[3] < minDST :\n minDST = dstData[3]\n\n return minDST\n\ndef get_precedingDST( dsts, atDateTime ):\n # PURPOSE: return dst value preceding the passed timestamp in a list of lists of year doy hr dst\n\n yr = atDateTime.year\n doy = atDateTime.timetuple().tm_yday\n hr = atDateTime.hour\n\n precedingDST = 0.0\n for dstData in dsts :\n if dstData[0] < yr :\n precedingDST = dstData[3]\n elif dstData[0] == yr :\n if dstData[1] < doy :\n precedingDST = dstData[3]\n elif dstData[1] == doy :\n if dstData[2] < hr :\n precedingDST = dstData[3]\n else :\n break\n else :\n break\n else :\n break\n\n return precedingDST\n\n\ndef get_GPS_text(sat, sdate, edate ,root_dir,lower_dir = None, vars = None):\n # PURPOSE: To create a numpy array of the GPS data in the time period from sdate to\n # edate for the satellite, sat. First it looks in the directories root_dir and\n # lower dir (if given). Then it reads the files and appends them into one\n # numpy array with dtype given by the column names in the first line.\n\n # INPUTS:\n # sat : name of satellite ex. (REQUIRED)\n # sdate : datetime start of data to get (REQUIRED)\n # edate : datetime end of data to get (REQUIRED)\n # root_dir : top directory to search for data ex. '/data/ (REQUIRED)\n # lower_dir : directory under top directory with KEYWORDs like YYYY (Optional)\n # ex. 'SAT/YYYY'\n # vars : list of vars to get ex. ['Year','Month'] (Optional\n\n # Quick check to see if there is a slash at the end of the directories\n root_dir= check_slash(root_dir)\n if lower_dir:\n lower_dir=check_slash(lower_dir)\n\n gps_fmt = 'SAT_yyMMDD_*'\n\n # The GPS data is in a god awful 7 day ascii format which makes it\n # really hard to find the data you want without opening extra files. Ugh.\n\n # So just to be safe, I add 7 days to sdate to make sure we get the start\n # And then I reduce it down to the requested time at the end.\n # first find the files\n new_sdate = sdate-dt.timedelta(days = 6)\n files = find_files(sat, new_sdate, edate, root_dir, gps_fmt, lower_dir=lower_dir)\n files.sort()\n\n # Check if data is returned\n if len(files)<1:\n print('No data for ',sat, 'between ',new_sdate.strftime(\"%Y/%m/%d\"),' and ',edate.strftime(\"%Y/%m/%d\"))\n return\n\n # read_ascii is a generic code to read in a typical ascii dataset\n # These are the inputs needed for GPS\n # For the GPS data the header is commented out so I think it is 0\n gps_header = 0\n\n # The first many lines of the GPS data have the colum info in json format\n # but they are commented out. So I have to read all the lines into a string variable\n # and then try to read json to create the columns\n head_dat =''\n with open(files[0],'r') as f:\n temp_dat = (f.readline())\n while temp_dat[0]=='#':\n head_dat = head_dat + (temp_dat[1:-1])\n temp_dat = (f.readline())\n f.close()\n\n # This is all the header info but each key in the dict has a\n # separate \"ELEMENT_NAMES\" with the actual columns\n col_info = json.loads(head_dat)\n cols = list()\n for key in col_info:\n if type(col_info[key])==dict:\n cols.extend(col_info[key]['ELEMENT_NAMES'])\n\n # Then create the heo_type\n gps_type=list()\n for col in cols:\n gps_type.append((col,'f'))\n\n #This will read and concatenate them all together\n alldata = read_ascii_data(files,header_lines=gps_header,vars = vars,datatype =np.dtype(gps_type))\n\n gpstimes = [dt.datetime(alldata['year'][x],1,1)+ dt.timedelta(days=alldata['decimal_day'][x]-1) for x in range(0,len(alldata['year']))]\n time1 = [leapseconds.gps_to_utc(x) for x in gpstimes]\n\n ginds = np.where((np.array(time1)>sdate) & (np.array(time1)