content
stringlengths
5
1.05M
from django.test import TestCase from rest_framework.test import APITestCase from django.test import Client from django.contrib.auth import get_user_model import unittest User = get_user_model() # Create your tests here. class UserAPITestCase(APITestCase): def setUp(self): self.usr = User(phonenumber="+2...
# Python does support boolean logic by making use of the usual operators x = 2 print(x == 2) # True y = False print(y == True) # False print(y == False) # True print(x < 5) # True # if statement. Their code block is delimited by indentation # and gets started from the ":" character. # Tabs or spaces work if x ==...
import os import errno from Crypto.Cipher import AES from ifstools import IFS, GenericFile, GenericFolder from kbinxml import KBinXML from tqdm import tqdm enc_base = r'D:\infinitas\KONAMI\eacloud\beatmania IIDX INFINITAS' dec_base = r'D:\infinitas\beatmania IIDX INFINITAS (Decrypted game files)' # monkeypatching cl...
""" Login Module """ from selenium.webdriver.support import expected_conditions as ec from fixtures.mainteny.app.ui.pages.page_base import PageBase from pylenium.element import Element class LoginPage(PageBase): """ This class contains the elements of login page. """ def __init__(self, py): s...
import math import random from typing import List import numpy as np import shapely.geometry as geom import shapely.ops from numba import jit nautical_miles_to_feet = 6076 # ft/nm class Airplane: def __init__(self, sim_parameters, name, x, y, h, phi, v, h_min=0, h_max=38000, v_min=100, v_max=300):...
from rest_framework import serializers from product.models import ProductVariation class ProductVariationSerializer(serializers.ModelSerializer): product_description = serializers.CharField(source='product.description', read_only=True) class Meta: model = ProductVariation fields = '__all__'
from custodian.vasp.validators import VasprunXMLValidator import os import unittest test_dir = os.path.join(os.path.dirname(__file__), "..", "..", "..", 'test_files') cwd = os.getcwd() class VasprunXMLValidatorTest(unittest.TestCase): def test_check_and_correct(self): os.chdir(os...
# This script has been created to # takes in four strings, of varying characters, numbers, and specials arranges them in a random order # and print it out to the system console to be able to use it # it will also including hashing/encyting the passwords at this stage of the process once produced. import random import ...
try: x = int(input("Ganzahl eingeben: ")) print("Gut gemacht") except ValueError as e: print("Falsche Eingabe") print(e) #-- x = int(input("Ganzahl eingeben: ")) if x < 0: raise ValueError("Falsch gemacht") print("Programmende")
import unittest import strokes_gained_calculations as sgc class SimpleStrokesGainedTestCase(unittest.TestCase): """Tests for the simple numerical calc of SG putting""" def test_single_simple_strokes_gained(self): strokes_gained = sgc.calculate_strokes_gained(1.78, 1) self.assertEqual(strokes_g...
from __future__ import absolute_import, print_function import os import re from setuptools import find_packages, setup try: from myhelpers.setup_helpers import find_location, find_version, read except ImportError as err: import sys print('{0}\nYou may download setup_helpers from'.format(err), 'h...
import requests import time import json from cython_npm.cythoncompile import require # from Interservices import Friend # from ../ Interservices = require('../../microservices_connector/Interservices') Friend = Interservices.Friend # test sanic app timeit = Interservices.timeit # post is the fastest way @timeit def do...
#!/usr/bin/env python from argparse import ArgumentParser, RawDescriptionHelpFormatter from logging import ( getLogger, StreamHandler, FileHandler, Formatter, DEBUG, INFO ) from logging.handlers import ( RotatingFileHandler, TimedRotatingFileHandler ) import platform import sys import time def do_log(args, l...
import numpy as np def expandLP_truelabels( Data_t, curLP_t, tmpModel, curSS_nott, **Plan): ''' Create single new state for all target data. Returns ------- propLP_t : dict of local params, with K + 1 states xcurSS_nott : SuffStatBag first K states are equal to curSS_nott ...
#encoding=utf-8 class MyBaseClass(object): def __init__(self,value): self.value = value class MyChildClass(MyBaseClass): def __init__(self): MyBaseClass.__init__(self,5) class TimesTwo(object): def __init__(self): self.value*=2 class PlusFive(object): def __init__(self): self.value+=5 class OneWay(MyBa...
from bbcode import * from rhizomedotorg.settings import MEDIA_URL import re class Smilies(SelfClosingTagNode): open_pattern = re.compile(':(?P<name>[a-zA-Z-]+):') def parse(self): name = self.match.groupdict()['name'] return '<img src="%smedia/smilies/%s.gif" alt="%s" />' % (MEDIA_URL, name, na...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ ('contenttypes', '0002_remove_content_type_name'), ('auth', '0006_require_contenttypes_0002'), ...
import os import subprocess import re def write_file(filename,a_list): fw = open(filename, 'w') for i in range(len(a_list)): fw.write(a_list[i] +'\n') fw.close() def read_file(filename): f = open(filename, encoding='unicode_escape') doc_str = f.read() f.close() return doc_str def ...
import celestial import logging logging.basicConfig(level=logging.DEBUG, format='%(name)s %(levelname)s %(message)s') for _ in range(10): trial = celestial.Trial(study_id=3) print(trial.parameters) print(trial.submit_result(loss=1-trial.parameters['param1'], accuracy=0.9+trial.parameters['param2']/200).jso...
## sigtools requires numpy; it consumes numpy arrays and emits numpy vectors import numpy as np from numpy import genfromtxt, array from math import pow import os import math ## sigtools has a subpackage sigtools.tosig that analyses time series data import esig import esig.tosig as ts ## fractional brownian motion pa...
from typing import Container, Optional import aioredis from aioredis import Redis class AsyncRedisUtil: """ 异步redis操作, 配置说明: 在startup配置: await AsyncRedisUtil.init(host,port,...),参数 在shutdown配置 await AsyncRedisUtil.close() note: exp是指过期时间,单位是秒. """ r: O...
"""This program will encrypt and decrypt messages using a Caesar cipher. By Ted Silbernagel """ import enum import string from typing import List class Operation(enum.Enum): ENCRYPT = enum.auto() DECRYPT = enum.auto() CRACK = enum.auto() class CaesarCipher: crypt_base: List[str] = [char for char in 'ABCDEF...
#!/usr/bin/env python3 """ Created by https://github.com/phoemur """ import re import urllib.request import urllib.parse import http.cookiejar from lxml.html import fragment_fromstring from collections import OrderedDict from tqdm import tqdm def get_data(*args, **kwargs): url = 'http://www.fundamentus.com.br/re...
from .base import * SECRET_KEY = env('DJANGO_SECRET_KEY', default='ew4peb%u0qi2r*igg^5$m#wh4l+e7^-9h7codkl)uilvopyqfa') DEBUG = env.bool('DJANGO_DEBUG', default=True)
""" Copyright (c) Facebook, Inc. and its affiliates. """ import os import sys # python/ dir, for agent.so sys.path.append(os.path.join(os.path.dirname(__file__), "..")) import faulthandler import itertools import logging import numpy as np import random import re import sentry_sdk import signal import time from mult...
from typing import Any def Main(a: Any, b: Any) -> bool: return isinstance(a, b)
import sys from django.core.management.base import BaseCommand from github import GithubException from utils.gh import get_github_organization, get_github_repo class Command(BaseCommand): help = "List projects associated with an organization" def add_arguments(self, parser): parser.add_argument( ...
import numpy as np from keras.models import Sequential, load_model from keras.layers import Input, Dropout, Flatten, Conv2D, MaxPooling2D, Dense, Activation from keras.optimizers import SGD from keras.utils import np_utils from keras.preprocessing.image import ImageDataGenerator from keras.callbacks import TensorBoard ...
import botfw botfw.test_trade(botfw.BinanceFuture.Trade('BTC/USDT'))
import os import numpy as np import toml from .workspace import get_dirs, create_series_dir from .load_dicom import load_scan_from_dicom def import_dicom( path: str, root_dir: str, id: str, num: int, ww: int, wc: int, crop_x, crop_y, replace=False ): """Imports dicom as a numpy matrix in the project folder ...
import pytest @pytest.fixture(scope="session") def test_fixture1(): print("Run once") return 1
import sys def find_rightmost_char(line): phrase, target = line.strip().split(',') for i, c in enumerate(phrase[::-1]): if c == target: return len(phrase) - i - 1 with open(sys.argv[1]) as input_file: for line in input_file.readlines(): print(find_rightmost_char(line))
from typing import Any, Dict, List import hashlib import re def extract_fragments(items: Dict[Any, Any], res: List[Any]) -> None: for item in items: repository_full_name = item.get("repository").get("full_name") text_matches = item.get("text_matches") for text_match in text_matches: ...
import pytest from pytest import raises from artemis.general.mymath import (softmax, cummean, cumvar, sigm, expected_sigm_of_norm, mode, cummode, normalize, is_parallel, align_curves, angle_between, fixed_diff, decaying_cumsum, geosum, selective_s...
from dotenv import load_dotenv load_dotenv() load_dotenv(verbose=True) from pathlib import Path env_path = Path('.') / '.env' load_dotenv(dotenv_path=env_path)
#!/usr/bin/env python #-*- coding:utf-8 -*- import os, sys from git import Repo import json import requests import base64 if sys.version_info[0] == 2: from Tkinter import * from tkFont import Font from ttk import * #Usage:showinfo/warning/error,askquestion/okcancel/yesno/retrycancel from tkMessageB...
"""Handles incoming route53resolver requests/responses.""" import json from moto.core.exceptions import InvalidToken from moto.core.responses import BaseResponse from moto.route53resolver.exceptions import InvalidNextTokenException from moto.route53resolver.models import route53resolver_backends from moto.route53resol...
########################################################################## # # Copyright (c) 2011-2012, John Haddon. All rights reserved. # Copyright (c) 2012-2013, Image Engine Design Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted prov...
from typing import Any, Generator, Tuple import pytest from dbcat.catalog import Catalog, CatColumn, CatSchema, CatSource, CatTable from sqlalchemy import create_engine from piicatcher.dbinfo import get_dbinfo from piicatcher.generators import ( _get_query, _get_table_count, _row_generator, column_gen...
#!/usr/bin/env python import sys prev_show = " " abc_found = False viewers_total = 0 line_cnt = 0 # count input lines for line in sys.stdin: line = line.strip() # strip out carriage return key_value = line.split('\t') # split line, into key and value, returns a list line_cnt += 1 curr_show = k...
from frontend import db, login_manager from datetime import datetime from flask_login import UserMixin @login_manager.user_loader def load_user(user_id): return User.query.get(int(user_id)) class Project(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(50), nullable=Fal...
"""Provide a model for the Z-Wave JS node's health checks and power tests.""" from dataclasses import dataclass from typing import List, Optional from ...const import TYPING_EXTENSION_FOR_TYPEDDICT_REQUIRED, PowerLevel if TYPING_EXTENSION_FOR_TYPEDDICT_REQUIRED: from typing_extensions import TypedDict else: f...
"""module for fobj modifier.""" from __future__ import annotations from typing import Any, Callable, cast, TYPE_CHECKING from ..jobject import JObject from .modifier import Modifier if TYPE_CHECKING: from ..ctx import Ctx from ..types import Types class FObjModifier(Modifier): """Get object at field from ...
# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license # Copyright (C) 2006, 2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and...
from gensim.models import word2vec import numpy as np from scipy import linalg, stats import sys savePath = "/fs/clip-scratch/shing/output/" def cos(vec1, vec2): return vec1.dot(vec2)/(linalg.norm(vec1)*linalg.norm(vec2)) def rho(vec1, vec2): return stats.stats.spearmanr(vec1, vec2) if __name__ =...
from pcc.AST.statement import Statement class FunctionArgument(Statement): def __init__(self, type_name, type_decl, identifier, depth): super(FunctionArgument, self).__init__(depth) self.type_name = type_name self.type_decl = type_decl self.identifier = identifier def __str__...
# Copyright 2021 MosaicML. All Rights Reserved. """The CPU device used for training.""" from __future__ import annotations import logging from typing import Any, Dict, TypeVar import torch from composer.trainer.devices.device import Device logger = logging.getLogger(__name__) __all__ = ["DeviceCPU"] T_nnModule ...
from abc import ABC, abstractmethod from copy import copy from enum import Enum from typing import List, Tuple, Optional, Sequence, Any, Union from cardbuilder.exceptions import CardBuilderUsageException class Value(ABC): """Abstract base class for all values.""" def __init__(self): self._data = None...
"""Server-side views for items.""" from typing import Any from flask import render_template from inventorymgr.views.blueprint import views_blueprint @views_blueprint.route("/items") def items() -> Any: """List view for items.""" return render_template("items.html.j2") @views_blueprint.route("/items/<item...
from selenium import webdriver from selenium.webdriver.common.desired_capabilities import DesiredCapabilities from ._enums import Browsers as BROWSERS from ._custom_exceptions import DriverException class _Browser: def __init__(self): self.headless = False self.selenium_host = '' self.full...
from airflow.plugins_manager import AirflowPlugin from idea_plugin import BigQueryToFeatherOperator class IdeaPlugin(AirflowPlugin): name = "idea_plugin" operators = [BigQueryToFeatherOperator]
__all__ = ['sub_policies'] ops_names = [ 'ShearX', 'ShearY', 'TranslateX', 'TranslateY', 'Rotate', 'AutoContrast', 'Invert', 'Equalize', 'Solarize', 'Posterize', 'Contrast', 'Color', 'Brightness', 'Sharpness', 'Cutout', ] K = 2 sub_polic...
import unittest from katas.kyu_8.is_this_my_tail import correct_tail class CorrectTailTestCase(unittest.TestCase): def test_true(self): self.assertTrue(correct_tail('Fox', 'x')) def test_true_2(self): self.assertTrue(correct_tail('Rhino', 'o')) def test_true_3(self): self.assert...
import json import logging import utc import pika import isodate from sqlalchemy.exc import OperationalError from sqlalchemy.orm.exc import NoResultFound, MultipleResultsFound from mettle.settings import get_settings from mettle.models import Service, Pipeline, PipelineRun, PipelineRunNack, Job, Checkin from mettle.l...
alien_color = 'green' if alien_color == 'green': print("player get 5 point") elif alien_color == 'yellow': print("player get 5 point") else: print("player get 15 point") alien_color = 'yellow' if alien_color == 'green': print("player get 5 point") elif alien_color == 'yellow': print("player get 10...
# -*- coding: utf-8 -*- # Generated by Django 1.11.6 on 2017-12-21 13:52 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('goods', '0024_auto_20171221_1346'), ] operations = [ migrations.AlterField(...
from typing import Dict from streamlink.exceptions import StreamError from streamlink.stream.stream import Stream from streamlink.stream.wrappers import StreamIOIterWrapper, StreamIOThreadWrapper class HTTPStream(Stream): """ An HTTP stream using the :mod:`requests` library. """ __shortname__ = "htt...
# Copyright 2016 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. from recipe_engine import recipe_api from recipe_engine.types import freeze DEPS = [ 'adb', 'archive', 'chromedriver', 'chromium', 'chromium_andro...
import csv import scipy.misc from random import shuffle import cv2 from skimage.util import random_noise from numpy.random import uniform as random import numpy as np class data_handler(object): def __init__(self, validation_split = 0.2, batch_size = 128, left_and_right_images = False, root_path = '', left_right_o...
from django.conf import settings from social_core.backends.azuread_tenant import AzureADTenantOAuth2 from social_core.backends.google import GoogleOAuth2 def social_uid(backend, details, response, *args, **kwargs): if settings.AZUREAD_TENANT_OAUTH2_ENABLED and isinstance(backend, AzureADTenantOAuth2): """...
from argparse import Namespace from datetime import datetime from os import listdir from os.path import isfile, join from gras.base_miner import BaseMiner from gras.pipermail.downloader import Downloader BUGS_URL = "bugs.python.org" class CPythonMiner(BaseMiner): def __init__(self, args, url, path): try...
import os import csv import json import pickle import logging from random import choice, randint, shuffle from django.core.exceptions import ObjectDoesNotExist import python_football from settings.base import SITE_ROOT from .models import Playbook, City, Nickname, Team from people import names from people.models i...
from functools import reduce from itertools import permutations from typing import Dict from typing import Optional from typing import Tuple import torch from torch_complex.tensor import ComplexTensor from typeguard import check_argument_types from espnet2.enh.decoder.abs_decoder import AbsDecoder from espnet2.enh.en...
# -*- coding: utf-8 -*- import bpy def hRH(pos): #height RIGHT HAND h=bpy.data.objects['3'].pose.bones['hand.ik.R'] c=bpy.data.objects['3'].pose.bones['elbow.pt.ik.R'] cl=bpy.data.objects['3'].pose.bones['clavicle.R'] crh=(0,-0.2,0) #elbow initial position clp=(1,0,0.1,0.05) #clavicle initial posi...
from collections import deque def knight(p1, p2): h1 = { 'a':1, 'b':2, 'c':3, 'd':4, 'e':5, 'f':6, 'g':7, 'h':8} h2 = { 1:'a', 2:'b', 3:'c', 4:'d', 5:'e', 6:'f', 7:'g', 8:'h'} s = set() start = [h1[p1[0]], int(p1[1])] target = [h1[p2[0]],int(p2[1])] que1 = deque() que1.append(start) coun...
import os from espider.dbs.easy_csv import OpenCsv from espider.spider import Spider class MySpider(Spider): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.request_setting.update(max_retry=3) def start_requests(self): url = 'https://desk.zol.com.cn/fengjin...
a = float(input('Digite um valor: ')) b = float(input('Digite outro valor: ')) c = float(input('Digite mais um valor: ')) if a == b or b == c: print('Com os números digitados, formam um triângulo EQUILATERO.') elif a <> b and b <> c and c == a and b == c: print('Com os números digitados, formam um triângulo ISO...
from typing import Dict, Optional import cv2 import numpy from ._params import Params as _Params from ._types import Image, TemplateMatchResult from ._utils import convert_to_hls, crop_rect, match_template from .exceptions import DialsNotFoundError, ImageLoadingError class ImageFile: def __init__( s...
import matplotlib.pyplot as plt import numpy as np import pytest import torch from src import datamodules from src.augmentations.seg_aug import get_composed_augmentations from src.datamodules.cityscapes import Cityscapes from src.datamodules.dadatamodule import DADataModule from src.datamodules.gta5 import GTA5 from s...
from django.db import models from django.utils import timezone from datetime import timedelta class Post(models.Model): # TODO: Add rating # TODO: Link author with a user content = models.CharField(max_length=500) author = models.CharField(max_length=20) created = models.DateTimeField('Created') ...
from flask import Blueprint response = Blueprint('response', __name__) from . import views
#!/opt/cloudera/parcels/Anaconda/bin/python # -*- coding: utf-8 -*- __author__ = 'Robert (Bob) L. Jones' __coauthor__ = 'N/A' __copyright__ = 'Copyright 2018, File' __credits__ = ['Robert (Bob) L. Jones'] __license__ = 'GPL' __version__ = '0.0.1' __maintainer__ = 'Robert (Bob) L. Jones' __status__ = 'Development' __cr...
# DynaMine # /Memoire/dynamine # coding=utf-8 from numpy import * import petl as etl from re import * import operator import glob import pandas as pd import re import csv import matplotlib.pyplot as plt import numpy as np from scipy import stats #dsysmap b = pd.read_csv('all_mutations.dat','\t') #28'695 rows x 11 co...
from base64 import b64encode, b64decode from hashlib import scrypt import os def format_password_hash(password): if len(password) > 1024: raise ValueError("Password is too long") scrypt_n = 2 ** 14 scrypt_r = 9 scrypt_p = 1 salt = os.urandom(16) h = scrypt(password.encode...
from django.contrib import admin from django_blog_example import models # Register your models here. admin.site.register(models.Post) admin.site.register(models.Comment)
from yapypy.extended_python.pybc_emit import * from bytecode import dump_bytecode def emit_function(node: typing.Union[ast.AsyncFunctionDef, ast.FunctionDef, ast.Lambda], new_ctx: Context, is_async: bool): """ https://docs.python.org/3/library/dis.html#opcode-MAKE_FUNCTION MAKE_F...
# Boom!!! def conteo(segundos): if segundos < 1: print('No puedo contar menos de un segundo.') else: for segundo_actual in reversed(range(1, segundos + 1)): print(segundo_actual) print('BOOM!!!') conteo(10)
import unittest import flask_schema.types import flask_schema.errors class StringTest(unittest.TestCase): # STRING TESTS def test_min_only(self): prop = flask_schema.types.String(min_length=0) self.assertEqual(prop("12345"), "12345") def test_min_only_out_of_range(self): prop = ...
from django.urls import reverse from django.http import HttpResponseRedirect from django.views.generic import DetailView from . import models class UserProfileDetail(DetailView): model = models.UserProfile context_object_name = 'profile' slug_field = 'user__slug' def profile_redirect(request): if r...
import pyodbc, re import WordParse def main(): doc = 'jesus.tsv' WordParse.main(file_name=doc) with open(doc, 'r') as f: s = re.split('\n', f.read()) cnxn = pyodbc.connect(r'DSN=mynewdsn;') cursor = cnxn.cursor() cursor.execute("""IF OBJECT_ID('tempdb.dbo.##CSV') IS NOT NULL...
#There are n particles numbered from 0 to n − 1 lined up from smallest to largest ID along the x-axis. #The particles are all released simultaneously. Once released, each particle travels indefinitely in a #straight line along the positive x-axis at a speed. When two particles collide, the faster particle moves throu...
# -*- coding: utf-8 -*- # Generated by Django 1.11.6 on 2017-11-27 14:44 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('reporting', '0013_auto_20171014_1526'), ] operations = [ migrations.AlterFi...
from functools import lru_cache from time import gmtime, strftime from flask import Flask, render_template from flask import url_for from werkzeug.utils import redirect from superhub.pages import DeviceConnectionStatusPage, DhcpReservationPage, IpFilteringPage, MacFilteringPage, PortBlockingPage, PortForwardin...
<code object <module> at #0, file "testcorpus/95_annotation_global_simple.py", line 1> 1 0 LOAD_CONST 0 ('<code object f at #1, file "testcorpus/95_annotation_global_simple.py", line 1>') 2 LOAD_CONST 1 ('f') 4 MAKE_FUNCTION 0 ...
#!/usr/bin/env python import re from pip.req import parse_requirements from setuptools import setup, find_packages try: install_reqs = parse_requirements('requirements.txt', session=False) requirements = [str(ir.req) for ir in install_reqs] except OSError: requirements = [] with open('README.rst') as readme_file...
# Aula 15 - Desafio 70: Estatisticas em produtos # Ler o nome e o preço de varios produtos. O programa deve perguntar se o usuario vai continuar. # No final, mostre: # - qual o total gasto # - quantos produtos custam mais de R$1000 # - qual eh o nome do produto mais barato total = contMil = menor = 0 barato = '' while ...
def yes_no_bool(val): if val.lower() == 'yes': return True elif val.lower() == 'no': return False else: raise ValueError( 'Cannot translate "{}" to bool'.format(val))
""" MobileNet & FD-MobileNet for CUB-200-2011, implemented in torch. Original papers: - 'MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications,' https://arxiv.org/abs/1704.04861. - 'FD-MobileNet: Improved MobileNet with A Fast Downsampling Strategy,' https://arxiv.org...
# This script defines the Header class, whose functionality is to # create and maintain the header of each steganograph. # Builtin modules from re import compile, Pattern # Internal modules from StegLibrary.core import SteganographyConfig as Config from StegLibrary.core.errors import UnrecognisedHeaderError class H...
""" In this file we going to create classes and methods that require run tasks in background asynchronously """ from logging import getLogger from django.conf import settings # noqa from background_task import background from .models import Feed logger = getLogger(__name__) # Execute this task # 20 seconds after c...
#!/usr/bin/env python # # Copyright 2017 Google Inc. # # 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 o...
from typing import Dict, Union import gym import numpy as np from stable_baselines3.common.type_aliases import GymStepReturn class SimpleMultiObsEnv(gym.Env): def __init__( self, num_col: int = 4, num_row: int = 4, random_start: bool = True, discrete_actions: bool = True,...
import csv from pathlib import Path def parse_from_csv(csv_path, outfile, fieldname=None, delimiter=','): if not fieldname: raise ValueError('The CSV fieldname for text content cannot be None') in_csv = Path(csv_path) with open(outfile, 'w') as f_out: with open(in_csv, mode='r') as f_in...
# coding: utf-8 """ Copyright (c) 2021 Aspose.Cells Cloud Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, ...
from flask import Flask, request, jsonify from flasgger import Swagger from flasgger.utils import swag_from from datetime import datetime from argparse import ArgumentParser import json app = Flask(__name__) app.config["SWAGGER"]={"title": "PAN Telemetry Software", "uiversion": 2} # Set up the SwaggerUI API swagger_c...
# Copyright (C) 2018 Garth N. Wells # # SPDX-License-Identifier: MIT """Unit test for the station module""" from floodsystem.station import MonitoringStation, inconsistent_typical_range_stations def test_create_monitoring_station(): # Create a station s_id = "test-s-id" m_id = "test-m-id" label = "...
import re, random from typing import Optional import ast from fastapi import ( FastAPI, Request, Response, Cookie, WebSocket, Form, WebSocketDisconnect, ) from fastapi.staticfiles import StaticFiles from fastapi.templating import Jinja2Templates from fastapi.responses import RedirectResponse...
# -*- coding:UTF-8 -*- import tensorflow as tf from deepctr.estimator.inputs import input_fn_tfrecord from deepctr.estimator.models import DeepFMEstimator sparse_features = ['C' + str(i) for i in range(1, 27)] dense_features = ['I' + str(i) for i in range(1, 14)] dnn_feature_columns = [] linear_feature_columns = [] ...
import boto3 from django.conf import settings class Bucket: """CDN Bucket Manager This is Method Create Connection """ def __init__(self): session = boto3.session.Session() self.conn = session.client( service_name=settings.AWS_SERVICE_NAME, aws_access_key_id=s...
import os import struct import numpy as np import pygltflib as gltf from transformations import quaternion_from_matrix from PIL import Image import io BYTE_LENGTHS = dict() BYTE_LENGTHS[gltf.UNSIGNED_SHORT] = 2 BYTE_LENGTHS[gltf.FLOAT] = 4 FORMAT_MAP = dict() FORMAT_MAP[gltf.UNSIGNED_SHORT] = "H" FORMAT_MAP[gltf.FL...