content
stringlengths
5
1.05M
#! /usr/bin/env python3 import asyncio import typer from httpx import URL, AsyncClient from pydantic.networks import EmailStr from pydantic.types import SecretStr async def logout_current_user(client: AsyncClient): path = "/auth/logout" r = await client.post(path) r.raise_for_status() async def regist...
# Copyright 2019, OpenTelemetry Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to i...
from brown.core.path_element_type import PathElementType from brown.utils.point import Point from brown.utils.units import GraphicUnit class PathElementInterface: """An element of a path or subpath. Becuase QPainterPath::Element instances can't be directly created, to instantiate an instance of this cla...
import logging import sys from pathlib import Path import click from extra_model._errors import ExtraModelError from extra_model._run import run from extra_model._setup import setup logger = logging.getLogger(__name__) OUTPUT_PATH = "/io" OUTPUT_FILENAME = "result.csv" EMBEDDINGS_PATH = "/embeddings" @click.comm...
import numpy as np from sklearn.externals import joblib from feature_handler_v3 import extract_features models = [joblib.load("model/train-{}.m".format(i)) for i in range(1, 6)] def pred(in_name): ''' 预测大五人格 :param in_name: 某用户的数据文件名 :return: 大五人格分数,分别为neuroticism,extraversion,openness,agreeableness,...
from ....engine.local_rib import LocalRib from ....announcement import Announcement from ....enums import Prefixes, Timestamps, ASNs, ROAValidity class HijackLocalRib(LocalRib): """Local Rib for Subprefix Hijack for easy test writing""" def __init__(self, prefix_vic_as_path=None, ...
# Copyright 2020,2021 Sony Corporation. # Copyright 2021 Sony Group Corporation. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless ...
def kukoin_run(): # First importing the needed libraries: import pandas as pd import numpy as np import os import requests import json import base64 import time import base64 import hmac import hashlib # Now importing the env file so the script can access the KuC...
# -*- coding: utf-8 -*- class Dark(object): """Classe para o tema Dark da calculadora""" def __init__(self): self.master_bg = '#252729' self.frame_bg = '#252729' self.INPUT = { 'bg': '#252729', 'fg': 'white', 'borderwidth': 0, 'highlightt...
from flask_restful import Resource from flask import Response,request import json import pandas as pd import networkx as nx date_list=list(range(20200101,20200132)) date_list+=list(range(20200201,20200230)) date_list+=list(range(20200301,20200332)) date_list+=list(range(20200401,20200431)) def transform_format(date): ...
# -*- coding: utf-8 -*- """ Project : nuke.irrigator File name : moisture.py @ UTF-8 Version : 0.0.1 Author : Gabor Wnuk <gabor.wnuk@me.com> Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOT...
#from unittest import TestCase from AdresseParser import AdresseParser import pytest """Run python -m unittest discover tests""" """Run pytest -v""" class TestAdresseParser(): adresse_parser = AdresseParser() adresse1 = adresse_parser.parse("88 rue de rivoli 75002 paris") adresse2 = adresse_parser.parse("...
"""Library for reading in AIS remittance EDI excel sheets. It checks to make sure that sheet that has been read in actually is self consistent. There is no difference in the format for these documents before and after the addition of the prompt payment discount (PPD). It doesn't cover those EDI documents where there...
from robot.api.deco import keyword import extract_msg import re from extract_msg.message import Message as OutlookMessage class MsOutlook: ROBOT_LIBRARY_VERSION = '0.0.1' REGEX_BODY_PARSER = r"(?P<recipient_address>[\w\.-]*@[\w\.-]*\.[a-zA-Z]{2,3})[\r]?\n#.*smtp;(?P<smtp_response>\d{3}).*#SMTP#" BODY_PAR...
# -*- coding: utf-8 -*- import numpy as np def get_axis(self): """Get the value of variables stored in Solution. Parameters ---------- self : SolutionMat an SolutionMat object Returns ------- axis_dict: dict a dict of axis names containing axis sizes """ return ...
# Generated by Django 3.0.6 on 2021-07-06 12:03 import datetime from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('games', '0001_initial'), ] operations = [ migrations.AddField( model_name='bot', name='pub_date', ...
a = int(input()) print(a+a*a+a*a*a)
from __future__ import print_function, absolute_import, division import boto3 import json from .ses_plugin import AwsSesPlugin class StatusMailPlugin(AwsSesPlugin): def __init__(self, unwanted_resources, problematic_resources, dry_run, **kwargs): self.subject = 'AWS Compliance Checker - Your action is r...
#//https://www.youtube.com/watch?v=QGVCnjXmrNg from typing import List class TrieNode: def __init__(self, isWord: bool, children: dict): self.isWord = isWord self.children = children class Solution: def __init__(self): self.trie = None def buildTrie(self, words: List[str]) -> None: self.trie ...
from random import choice from models.dataset import Dataset from models.classifiers import IntentClassifier from models.mixins import CommandsMixin class Chatbot(IntentClassifier, CommandsMixin): def __init__(self, corpus): dataset = Dataset(corpus.data) super().__init__(dataset) self.r...
from django.apps import AppConfig class PatiosConfig(AppConfig): name = 'patios'
import pyqtgraph as pg from PyQt5.QtWidgets import QWidget, QVBoxLayout, QLabel, QMessageBox, QLineEdit, QColorDialog, QCheckBox, QApplication from PyQt5.QtCore import Qt import numpy as np import sys from pyqtgraph.widgets.MatplotlibWidget import MatplotlibWidget import copy class PlotWidget(QWidget): """ Th...
from .gget_ref import ref from .gget_search import search from .gget_info import info from .gget_seq import seq from .gget_muscle import muscle from .gget_blast import blast from .gget_blat import blat from .gget_enrichr import enrichr from .gget_archs4 import archs4 import logging logging.basicConfig( format="%(...
from os import path import sublime class PathResolver(object): """Provides default paths for plugin""" curr_dir = path.dirname(path.realpath(__file__)) package_dir = path.realpath(path.join(curr_dir, '..')) database_folder = path.join(package_dir, 'database') index_folder = 'index' scanner_fol...
from django.db import models from django.contrib.auth import get_user_model from django.urls import reverse User = get_user_model() class PostView(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey('Post', on_delete=models.CASCADE) def __str__(self): re...
# Copyright (c) 2021, Element Labs and contributors # For license information, please see license.txt import frappe,json from frappe.model.document import Document from cefiro_customizations.filters import create_bundle_name class RepackageBundle(Document): def validate(doc): pb_list = [] for item in doc.items:...
from random import randint, choice from flask_restful import Resource from app import models from app.api.schemas import CiteSchema class CiteAPI(Resource): def __init__(self): self.schema = CiteSchema(many=False) # @login_required this annotation will work def get(self, id=None): cit...
from godmode.groups.base import BaseGroup from godmode.acl import ACL class DemoGroup(BaseGroup): acl = ACL.MODERATOR name = "Demo" policy = "demo_group" index = 1000
# -*- coding: utf-8 -*- """ This module offers a parser for ISO-8601 strings It is intended to support all valid date, time and datetime formats per the ISO-8601 specification. ..versionadded:: 2.7.0 """ from datetime import datetime, timedelta, time, date import calendar from dateutil import tz from functools impor...
# множественное присваивание name, surname = 'Timur', 'Guev' print('Имя:', name, 'Фамилия:', surname) name, surname = input("name: "), input("surname: ") print('Имя:', name, 'Фамилия:', surname) name1 = 'Timur' name2 = 'Gvido' print(name1, name2) name1, name2 = name2, name1 # обмен значениями переменных print(name1, ...
import tempfile import genonets.test.utils as utils import genonets.test.compare_result_files as comparator from genonets.cmdl_handler import CmdParser from genonets.interface import Genonets class TestRNA: @staticmethod def run_test(cmd_args, ground_truth_dir, data_dir): args = CmdParser(arguments...
""" Django settings for bulkvote project. """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os from django.conf import global_settings from environment_settings import * BASE_DIR = os.path.dirname(os.path.dirname(__file__)) # Application definition INSTALLED_APPS = ( 'django.con...
from __future__ import absolute_import from __future__ import unicode_literals __version__ = '0.1.3'
""" tests.functional.test_sys_stats ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Tests related to processes system statistics enabled by the `--sys-stats` flag. """ import pytest def test_basic_sys_stats(pytester): pytester.makepyfile( """ def test_one(): assert True """ ) ...
def filter_positive_even_numbers(numbers): """Receives a list of numbers, and returns a filtered list of only the numbers that are both positive and even (divisible by 2), try to use a list comprehension.""" return [n for n in numbers if n % 2 == 0 and n > 0] print(filter_positive_even_numbers(l...
""" Given an array of strings, group anagrams together. Example: Input: ["eat", "tea", "tan", "ate", "nat", "bat"], Output: [ ["ate","eat","tea"], ["nat","tan"], ["bat"] ] Note: All inputs will be in lowercase. The order of your output does not matter. Solution: 1. Categorize by Sorted String Maintain a map ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import sys from pymongo import MongoClient def get_rank(user_id): client = MongoClient() db = client.shiyanlou pipeline=[ {'$match':{'user_id':user_id}}, {'$group':{ '_id':'$user_id', 'total_score'...
from rest_framework import serializers from .models import ProjectBudget, ResourceSpending, ContractSpending class CreateUpdateListSerializer(serializers.ListSerializer): def create(self, validated_data, *args, **kwargs): return [self.child.create(attrs) for attrs in validated_data ] class ProjectBudget...
# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import mock from django.test import TestCase from ralph.util.tests.utils import ( RegionFactory, ) from ralph_assets.licences.models import ...
# ---------------------------------------------------------------------------- # - Open3D: www.open3d.org - # ---------------------------------------------------------------------------- # The MIT License (MIT) # # Copyright (c) 2018-2021 www.open3d.org # # Permission i...
import torch import torch.nn as nn import torch.nn.init import torchvision.models as models from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence import torch.backends.cudnn as cudnn from torch.nn.utils import clip_grad_norm_ import numpy as np import sklearn from collections import OrderedDict from ...
"""Server execution functions.""" import logging import asyncio from asyncio import Queue from notify_server.network.connection import create_publisher, create_pull, \ Connection from notify_server.settings import Settings log = logging.getLogger(__name__) async def _publisher_server_task(connection: Connectio...
import pybullet as p import os class Goal: def __init__(self, client, base): f_name = os.path.join(os.path.dirname(__file__), 'simplegoal.urdf') p.loadURDF(fileName=f_name, basePosition=[base[0], base[1], 0], physicsClientId=client)
import os from typing import Any, Generator, List import pytest from determined import gpu def pytest_addoption(parser: Any) -> None: parser.addoption("--runslow", action="store_true", default=False, help="run slow tests") def pytest_collection_modifyitems(config: Any, items: List[Any]) -> None: if config...
from peewee import Model, Database, SqliteDatabase from typing import Dict, List, Type from contextlib import contextmanager import os class InvalidModelException(Exception): pass class DatabaseManager: db: Database = None models_by_plugin: Dict[str, List[Type[Model]]] = {} db_dir: str def __in...
import os import sys import base64 import pathlib import json import requests import csv import threading import queue import time from urllib.parse import urlencode from datetime import datetime, timedelta google_trend_api_list = os.environ.get("GOOGLE_TREND_API_LIST", "") afscreener_url = os.environ.get("AF_URL", "...
from locust import HttpUser, task, between import json import uuid class MyUser(HttpUser): wait_time = between(1, 3) def create_name(self): self.name = str(uuid.uuid1()) @task(1) def index(self): self.client.get("items/") self.client.get("items/1/") name = str(uuid.uui...
from __future__ import unicode_literals from django.db import models class ProjectStatus(models.Model): """ Status of the analyzed project. Kind of status: - Initializing (Just the beginning) - Downloading repository... - Preparing... (Between downloading and analyzing, short period) ...
import csv from io import StringIO FILE = 'profile_example.txt' data = [] def splitArray(s): if not ',' in s: return s f = StringIO(s) reader = csv.reader(f) for row in reader: return row with open(FILE, newline='') as f: reader = csv.reader(f) for row in reader: ...
import requests import json import argparse from copy import copy from getpass import getpass from bs4 import BeautifulSoup from random import random from pprint import pprint from base64 import b64decode, b64encode SETTINGS = None URLs = None def parse_arguments(): parser = argparse.ArgumentParser( desc...
# Copyright (c) 2021 Graphcore Ltd. All rights reserved. import argparse import numpy as np import popart import json import copy import logging_util import text_utils # set up logging logger = logging_util.get_basic_logger(__name__) def add_conf_args(run_mode): """ define the argument parser obj...
# Import libraries import pandas as pd import numpy as np # Read data df = pd.read_csv('data/telecom_churn.csv') # Dimensions/Shape of data df.shape # List column names df.columns # View columns and data types for each column df.info() # Change data type using `astype` method df['Churn'] = df['Churn'].astype('in...
import warnings import numpy as np import scipy.linalg as spla import scipy.special as spsp class CovMatAdapt: """ Covariance Matrix Adaption Evolution Strategy Implements the Covariance Matrix Adaption Evolution Strategy as described in 'The CMA Evolution Strategy: A Tutorial' by Nikolaus Hansen. F...
# Code generated by lark_sdk_gen. DO NOT EDIT. import typing from pylark.lark_request import Response from pylark.api_service_chat_create import ( CreateChatReq, CreateChatResp, _gen_create_chat_req, ) from pylark.api_service_chat_get_old import ( GetChatOldReq, GetChatOldResp, _gen_get_chat_o...
import pytest @pytest.fixture def supplier(): a, b, c = 25, 35, 45 return a, b, c
# coding: utf-8 # Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved. # This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c...
import os import sys import grammaire from datalabs.operations.edit.editing import editing sys.path.append( os.path.abspath(os.path.join(os.path.dirname(__file__), "../../../../")) ) def readfile(file): with open(file, encoding="utf8") as input: lines = input.readlines() return lines def load...
#!/usr/bin/env python2 # coding: utf-8 import unittest from pykit import mysqlconnpool from pykit import mysqlutil from pykit import ututil from . import base dd = ututil.dd mysql_test_user = 'root' mysql_test_db = 'test' mysql_test_table = 'errlog' class TestMysqlScanIndex(base.Base): def test_scan_index(s...
# Copyright 2018 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Helper methods for dealing with a SQLite database with pandas. """ import pandas # pylint: disable=import-error def _EmptyFrame(column_types): df = ...
"""Addresses serializers.""" # Django REST Framework from rest_framework import serializers # Models from apartacho.addresses.models import Address class AddressSerializer(serializers.ModelSerializer): """Addresses serializers.""" number_building = serializers.CharField( required=True, max_...
import re # AhnLab-V3 : Trojan/Win32.WannaCryptor.R200571 # ALYac : Trojan.Ransom.WannaCryptor file_path = r"./samples/faee802f30ff0815d8e4ad640d9e5bfd.vir" with open(file_path, 'rb') as f: file_data = f.read() for s in re.findall(b"[\x20-\x7e]{6,}", file_data): print(s.decode())
# Copyright L.P.Klyne 2013 # Licenced under 3 clause BSD licence # $Id: TestEventRouter.py 2612 2008-08-11 20:08:49Z graham.klyne $ # # Unit testing for event router functions (see also TestEventRouter) # See http://pyunit.sourceforge.net/pyunit.html # import sys import unittest import logging import time sys.path...
#!/usr/bin/env python from setuptools import setup, find_packages install_requires = [ # 'prettytable' 'rich', 'pyreadr', 'prettytable', 'pandas', 'numpy', 'pytabix' ] tests_require = [ # 'nose', # 'mock' ] extras_require = { 'docs': [] } setup(name='ukbsearch', version='...
import logging from datetime import datetime, timedelta from typing import Dict, Optional, Tuple import pytz from apscheduler.job import Job from apscheduler.schedulers.asyncio import AsyncIOScheduler from apscheduler.triggers.cron import CronTrigger from apscheduler.triggers.date import DateTrigger from apscheduler.t...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri May 7 11:45:20 2021 @author: zaidanma """ import pandas as pd import matplotlib.pyplot as plt # We read data from Vaisala sensors installed in SORPES: #df1 = pd.read_csv('clean_vaisala_data2/P1720668.csv') # Ngaco (in Tower) df2 = pd.read_csv('clea...
"""Test importing the monitors. By calling this test, you will define the monitors as in define_monitors.py """ import subprocess from psychopy import monitors def test_monitors(): """Test that monitors get defined.""" cmd = ['python', 'sp_experiment/define_monitors.py'] subprocess.call(cmd) my_mon...
import sys from rpython.rtyper.lltypesystem import rffi, lltype from pypy.module.cpyext.api import ( cpython_api, cpython_struct, bootstrap_function, build_type_checkers, CANNOT_FAIL, Py_ssize_t, Py_ssize_tP, PyObjectFields, slot_function) from pypy.module.cpyext.pyobject import ( decref, PyObject, make_ref...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jan 18 10:03:59 2021 @author: luke """ # Package ID: knb-lter-ntl.10001.3 Cataloging System:https://pasta.lternet.edu. # Data set title: Globally distributed lake surface water temperatures collected in situ and by satellites; 1985-2009. # # This ...
# getting false positives in vscode from pyspark.sql import SparkSession # pylint: disable=no-name-in-module,import-error from pyspark.rdd import RDD # pylint: disable=no-name-in-module,import-error from dagster import ( Bool, Dict, Field, Selector, Path, String, as_dagster_type, chec...
import math import torch from .abstract_convex_cell import AbstractConvexCell class FeedForwardCell(AbstractConvexCell): def __init__(self, in_features_per_dendrite, out_features): super().__init__(in_features_per_dendrite, out_features) def sample(self, g0, u0): return u0 + torch.sqrt(self....
__title__ = "objects.py" __Version__ = "1.1" __author__ = "Ali Saberi" __email__ = "ali.saberi96@gmail.com" import numpy as np import cv2 from utills import cal_dis class Object: def __init__(self, oid, tracker): self.tracker = tracker self.id = oid s...
# from threading import Thread, Lock import configparser import os, sys, re from lib.couple import Couple from lib.config import Config from lib.converter import Converter converter = Converter config = configparser.ConfigParser() configs = None couples = None def load_project(): global couples global confi...
''' This module stores regular expressions of PDB and GRO file formats to easily read and write those structure files -- XXX_STRING_FORMAT can be used along the .format() function -- XXX_PATTERN is the regular expression the separates the entries and stores all information in regex gr...
from torch.autograd import Variable import threading import sys if sys.version_info[0] == 2: import Queue as queue else: import queue class GpuLoader(object): """ https://github.com/pytorch/pytorch/blob/master/torch/utils/data/dataloader.py Convert a dataloader above to a gpu dataloader This is...
# Calorie & Macro Tracker # Libraries import datetime import calendar import matplotlib.pyplot as plt # Functions def display_menu(): print("\n*-----Calorie & Macro Tracker-----*") print("1. Set goals (daily)") print("2. Calculate today's net calorie") print("3. Enter today's macros") print("4. ...
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not...
""" dealing with NMEA sentences from a text file """ import pygpsnmea.nmea as nmea def open_file_generator(filepath): """ open a file line by line using a generator Args: filepath(str): path to the file Yields: line(str): a line from the open file """ with open(filepath, 'r'...
import pickle import gzip import numpy as np from keras.datasets import mnist from svm_classification import svm_classify from models import create_model from keras.optimizers import Adam from objectives import lda_loss if __name__ == '__main__': save_to = './new_features.gz' outdim_size = 10 epoch_num =...
import sqlite3 def convertToBinaryData(filename): #Convert digital data to binary format with open(filename, 'rb') as file: blobData = file.read() return blobData def insertBLOB(id, name, cost, details, category_id, sid, image_file1, image_file2, image_file3, image_file4, stock): try: ...
import threading import multiprocessing as mp import multiprocessing.connection as mpc from pipeline_cluster import util from pipeline_cluster import pipeline import pipeline_cluster.multiprocess_logging as mpl import signal import traceback import time import os import subprocess import importlib import sys class Com...
from pathlib import Path import cv2 from PIL import Image import numpy as np import os import glob import random import shutil # HE_path = Path("/data04/shared/mahmudul/HE_to_IHC/data/HE_to_IHC_patches/925-multires_paired_HE") # IHC_path = Path("/data04/shared/mahmudul/HE_to_IHC/data/HE_to_IHC_patches/925-mult...
import abc from railrl.qfunctions.nn_qfunction import NNQFunction from railrl.qfunctions.optimizable_q_function import OptimizableQFunction from railrl.qfunctions.separable_q_function import SeparableQFunction class NAFQFunction(NNQFunction, OptimizableQFunction, SeparableQFuncti...
import os import sys import subprocess import pytest def run_dist_kernel(kernel): pytest.importorskip("mpi4py") here = os.path.dirname(__file__) return subprocess.check_call( [sys.executable, "-m", "mpi4py", os.path.join(here, kernel)], stderr=subprocess.STDOUT, timeout=300 ) def test_gath...
from pathlib import Path from setuptools import find_packages from setuptools import setup import versioneer README = Path("README.rst").read_text() PROJECT_URLS = { "Documentation": "https://github.com/pytask-dev/latex-dependency-scanner", "Github": "https://github.com/pytask-dev/latex-dependency-scanner",...
import copy import enum import os from collections import defaultdict from typing import Dict from scipy.cluster.hierarchy import linkage, fcluster from PIL import Image from commonroad.geometry.shape import * from commonroad.scenario.traffic_sign import TrafficSign, \ TrafficLight, \ TrafficSignIDUsa from com...
import os from typing import Dict, Callable, List, Tuple, Union import deepdish import numpy as np import pyspiel import ray from open_spiel.python import rl_environment from open_spiel.python.algorithms.exploitability import exploitability from open_spiel.python.policy import Policy as OpenSpielPolicy, tabular_policy...
import psycopg2 # I think the DATABASE API in this particular case # is actually postgres. So I don't need a seperate # layer (personally written object) for the DatabaseAPI
import unittest from form.generators import Generator, StandardFormatGenerator, \ StandardFormatWithInputGenerator, PushDownFormatWithInputGenerator from form.readers import Reader class TestParser(unittest.TestCase): def test_abstraction(self): with self.assertRaises(TypeError): test = G...
# python3 # Copyright 2021 InstaDeep Ltd. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applic...
from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home'), path('add', views.add, name='add'), path('addmore', views.ammount, name='ammount'), path('reset', views.home, name='reset') ]
from django.contrib import admin from django.contrib.auth import admin as auth_admin from django.contrib.auth import get_user_model User = get_user_model() @admin.register(User) class UserAdmin(auth_admin.UserAdmin): list_display = ["username", "is_active", "is_superuser", "date_joined"] search_fields = ["u...
from connectfour.agents.agent import Agent class StudentAgent(Agent): def __init__(self, name): super().__init__(name) self.MaxDepth = 4 def get_move(self, board): """ Args: board: An instance of `Board` that is the current state of the board. R...
""" Given an infinite supply of ‘n’ coin denominations and a total money amount, we are asked to find the minimum number of coins needed to make up that amount. Example 1: Denominations: {1,2,3} Total amount: 5 Output: 2 Explanation: We need minimum of two coins {2,3} to make a total of '5' ...
from .stage import Stage from ..error import InvalidModuleError from .graph import DependencyGraph from ..util.decs import as_list from ..util.log import Log _log = Log('stage.graph') def _inferred_dependencies(targets): _log.debug('Inferring module dependencies...') _log.debug('Building output variable index...
from microsetta_public_api.repo._base import DiversityRepo from microsetta_public_api.exceptions import UnknownID, InvalidParameter class NeighborsRepo(DiversityRepo): def __init__(self, resources): super().__init__(resources) def exists(self, sample_ids, metric): nearest_ids = self._get_res...
from twitter import * import nltk nltk.data.path.append('nltk_data') from nltk.tokenize import word_tokenize from nltk.corpus import stopwords import json, pickle, os from flask import jsonify twitter = Twitter(auth = OAuth(os.environ['AccessToken'], os.environ['AccessTokenSecret'], ...
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2016-2018 CERN. # # Invenio is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """Test helpers.""" from jsonresolver import JSONResolver from jsonresolver.contrib....
import os import unittest import json from flask_sqlalchemy import SQLAlchemy from flaskr import create_app from models import setup_db, Question, Category QUESTIONS_PER_PAGE = 10 class TriviaTestCase(unittest.TestCase): """This class represents the trivia test case""" def setUp(self): """Define te...
import re import os import io import copy import time import json import logging import requests from collections import defaultdict from django.db import models from django.conf import settings from django_mysql.models import JSONField from django.contrib.auth.models import User from rest_framework.authtoken.models i...
# coding = utf-8 import requests from requests.exceptions import ConnectionError