content
stringlengths
5
1.05M
import unittest from app.models import Article class ArticleTest(unittest.TestCase): ''' Test Class to test the behaviour of the Article class ''' def setUp(self): ''' Set up method that will run before every Test ''' self.new_article = Article("Manish Singh","Indian f...
import pytest class TestRedirect: def test_not_auth_redirect(self, client): urls = [ '/new_words/', '/get_words/', '/familiar_words/', '/get_familiar/', '/translate/', '/get_new/', '/get_known/' ] for url ...
import nltk import numpy as np import tensorflow as tf from nltk.stem import WordNetLemmatizer import json from google.colab import files from tensorflow import keras from keras.models import Sequential from keras.layers import Dropout, Activation, Dense, Flatten import pickle from nltk import punkt import random #pri...
#!/usr/bin/env python PKG = 'manhole_detector' import roslib; roslib.load_manifest(PKG) import rospy import fileinput from sensor_msgs.msg import Image from std_msgs.msg import Bool import numpy as np import sys from keras.models import load_model import time from cv_bridge import CvBridge, CvBridgeError import cv2 fr...
from datetime import datetime import timebomb.models as models def test_Notification(): notif = models.Notification("message") assert notif.content == "message" assert notif.read is False assert str(notif) == "message" def test_Player(): player = models.Player("name", "id") assert player....
# -*- coding: utf-8 -*- # import numpy def _z(): return numpy.array([[0, 0]]) def _symm_r_0(r): return numpy.array([[+r, 0], [-r, 0], [0, +r], [0, -r]]) def _symm_r0(r): z = numpy.zeros_like(r) return numpy.array([[+r, z], [-r, z], [z, +r], [z, -r]]) def _symm_s(s): return numpy.array([[+s, ...
from Strategies.AbstractStrategies.scheduleStrategy import scheduleStrategy from redis_client import redisClient # This strategy has to keep a memory of the past variables and their use/call times # In order to keep the consistency of multiple contexts, the use of a key value cache server was recommended from redis_cl...
def memo_fib(input_value, save_memo): if input_value == 0: # 에러케이스를 만들어둬야 한다. return 0 elif input_value == 1: return 1 elif input_value in save_memo: return save_memo[input_value] else: res = memo_fib(input_value-2,save_memo) + memo_fib(input_value-1,save_memo) ...
import functools import generic from abc import ABCMeta, abstractmethod from typing import Tuple, List, Optional, Generator from enum import Enum class CheckStatus(Enum): OK = 1 WARNING = 2 CRITICAL = 3 def combine_statuses_and(s1: CheckStatus, s2: CheckStatus): if s1 == CheckStatus.CRITICAL or s2 ==...
# -*- coding: utf-8 -*- # # comparison_schemes.py # """ Features extraction script. """ __author__ = "Ahmed Albuni, Ngoc Huynh" __email__ = "ahmed.albuni@gmail.com, ngoc.huynh.bao@nmbu.no" import argparse import logging from csv import DictWriter from msilib.schema import Error from os import listdir from os.path i...
def format_response(response): return { 'url': response.url, "status_code": response.status_code, "response_time": f"{response.elapsed.total_seconds()}s." }
from ..IReg import IReg class R1391(IReg): def __init__(self): self._header = ['REG', 'DT_REGISTRO', 'QTD_MOID', 'ESTOQ_INI', 'QTD_PRODUZ', 'ENT_ANID_HID', 'OUTR...
# Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Path setup -------------------------------------------------------------- # If ex...
from __future__ import absolute_import import os from .. import utils, platform from netlib import http_auth, certutils from .primitives import ConstUpstreamServerResolver, TransparentUpstreamServerResolver TRANSPARENT_SSL_PORTS = [443, 8443] CONF_BASENAME = "mitmproxy" CONF_DIR = "~/.mitmproxy" class ProxyConfig: ...
from datetime import date from staff.models import Staff from django.views.generic import ListView from django.views.generic import DeleteView from survey.models import Surveyordermodel from django.shortcuts import render, redirect from django.urls import reverse from collar.models import Customers from .forms import L...
import types import torch import torch.nn as nn from torchvision import models from torchvision.models.mnasnet import MNASNet from .build import META_ARCH_REGISTRY __all__ = [ 'MNASNet', 'MNASNet0_5', 'MNASNet0_75', 'MNASNet1_0', 'MNASNet1_3', ] class MNASNet(nn.Module): # Modify attributs ...
import pytest from protoactor.actor import PID from protoactor.actor.message_envelope import MessageEnvelope from protoactor.actor.message_header import MessageHeader @pytest.fixture() def message_envelope(): message = "test" sender = PID() sender.address = "test" sender.id = "test" header = Mess...
import subprocess, re import json import itertools from time import perf_counter import numpy as np with open("true_cardinality.json","r") as j: true_cardinalities = json.load(j) with open("queries.json","r") as j2: queries = json.load(j2) with open("attr_range.json","r") as j3: attr_range = json.load(j3...
import argparse import re import json import matplotlib.pyplot as plt import numpy as np from scipy.io import savemat keys = {} metrics = {} token_families = {} line_structure = {} notes = {} song_token_counts = {} def sort_by_label(data): labels = [] values = [] for key, val in data.items(): labe...
# This parameter file contains the parameters related to the primitives located # in the primitives_gnirs.py file, in alphabetical order. from geminidr.core import parameters_preprocess class associateSkyConfig(parameters_preprocess.associateSkyConfig): def setDefaults(self): self.distance = 1.
import os import streamlit as st import pandas as pd DATADIR = os.path.join(os.path.expanduser('~'), 'Desktop/DATA/') CODEBOOK = "Big5_codebook.txt" DATAFILE = "Big5_data_small.csv" with open(os.path.join(DATADIR, DATAFILE)) as fh: df = pd.read_csv(fh) st.write(df)
""" *... iteration ...* """ from .iterator import Iterator from .page import Page from .redirect import Redirect from .revision import Revision from .comment import Comment from .contributor import Contributor from .text import Text
import numpy as np lbl = [1, 1, 2, 3, 3, 3, 6, 7, 8, 8, 9, 10] # a = np.asarray(a) a = np.asarray(lbl) print(a) print() np.random.shuffle(a) print('a =', a) sort_idx = np.argsort(a) print(sort_idx.dtype, sort_idx.shape, sort_idx) b = a[sort_idx] print('b =', b) _, unique_idx = np.unique(b, return_index=True) print(u...
import MySQLdb def connectDB(): mysql = MySQLdb.connect('localhost', 'StockUser', 'StockPass', 'StockDB', charset="utf8", use_unicode=True) cursor = mysql.cursor() SQL = """ select Close from SpotValueOfNifty50 where Date= 12012014; """ cursor.execute(SQL) print int(cursor.fetchone...
# Copyright 2018 University of Basel, Center for medical Image Analysis and Navigation # # 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 # # U...
# Copyright (c) Charl P. Botha, TU Delft. # All rights reserved. # See COPYRIGHT for details. import config from install_package import InstallPackage import os import re import shutil import sys import utils BASENAME = "ExposureRender" GIT_REPO = "http://code.google.com/p/exposure-render" #GIT_TAG = "v5.6.1" depend...
#!/usr/bin/env python """ Given a set of genomic coordinates in BED format: chr start end ... calculates a GC matched set of genomic coordinates. Only first 3 columns of input file will be used- all other columns are ignored. """ ### imports ### import os import sys import numpy as np import argparse import inspect ...
from typing import Dict from typing import TypedDict class Lang(TypedDict): title: str description: str LangData = Dict[ str, # two letter locale code Lang, ]
"""Miscellaneous utility classes and functions. """ import sys from typing import Any class Logger: """Redirect stderr to stdout, optionally print stdout to a file, and optionally force flushing on both stdout and the file. """ def __init__(self, file_name: str = None, file_mode: str = 'w', shou...
# -*- encoding:utf8 -*- from fabric import colors from fabric.api import put, env from denim import paths, utils SERVICE_NAME = 'supervisor' def upload_config(name_prefix=None): """ Upload configuration file. :param name_prefix: Prefix to append to service name to provide alternate configurati...
# -*- coding: utf-8 -*- # @Author : William # @Project : TextGAN-william # @FileName : sentigan_instructor.py # @Time : Created at 2019-07-09 # @Blog : http://zhiweil.ml/ # @Description : # Copyrights (C) 2018. All Rights Reserved. import torch import torch.optim as optim import config...
#!/usr/bin/env python3 import pytest from networkpolicy_manager.policy import Singleton class TestSingleton(): """ make sure singleton class works appropriately """ def test_singleton_is_none(self): context = Singleton.get_instance() assert context.get() == None def test_singleton_...
# Generated by Django 2.2b1 on 2019-03-11 13:32 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('openbook_auth', '0026_auto_20190309_1527'), ] operations = [ migrations.AlterField( model_name=...
# =========================================================================== # rsshow.py --------------------------------------------------------------- # =========================================================================== # import ------------------------------------------------------------------ # -----...
#Write a function that accepts two input lists and returns a new list #which contains only the unique elements from both lists. def unique_both_lists(list1, list2): list1.extend(list2) listaFinal = [] for x in list1: if x not in listaFinal: listaFinal.append(x) return listaFinal
import pytest import numpy as np from edflow.debug import DebugDataset from edflow.data.agnostics.subdataset import SubDataset def test_sub(): D = DebugDataset(10) I = np.array([9, 1, 2, 4, 3, 5, 7, 6, 8, 0]) S = SubDataset(D, I) ref0 = {"val": 9, "other": 9, "index_": 0} ref2 = {"val": 2, "oth...
from django.utils.deprecation import MiddlewareMixin from common import errors from common.errors import LogicException, LogicError from lib.http import render_json from user.models import Users class AuthMiddleware(MiddlewareMixin): WHITE_LIST = [ '/api/user/verify-phone', '/api/user/login', ...
number = 2 ** 38 print(number)
# Concord # # Copyright (c) 2019 VMware, Inc. All Rights Reserved. # # This product is licensed to you under the Apache 2.0 license (the "License"). # You may not use this product except in compliance with the Apache 2.0 License. # # This product may include a number of subcomponents with separate copyright # notices a...
''' Midpoint of Linked list For a given singly linked list of integers, find and return the node present at the middle of the list. Note : If the length of the singly linked list is even, then return the first middle node. Example: Consider, 10 -> 20 -> 30 -> 40 is the given list, then the nodes present at the middle...
#!/usr/bin/env python3 # Copyright (c) 2008-9 Qtrac Ltd. All rights reserved. # This program or module is free software: you can redistribute it and/or # modify it under the terms of the GNU General Public License as published # by the Free Software Foundation, either version 2 of the License, or # version 3 of the Lic...
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
import numpy as np import rospy import fasttext class StaticWordEmbeddings(object): """ Utility class to work with fasttext static word embeddings """ def __init__(self, pretrained_embeddings_file): """ Static word embedding model contructor """ self.model = fasttext.load_model(pre...
""" Script to divide data into training, validation and testing datasets. """ import os import pandas as pd import numpy as np from sklearn.model_selection import StratifiedShuffleSplit DATA_DIR = "data/" ORIG_DATA_DIR = os.path.join(DATA_DIR, "orig_data/nlp-getting-started") TRAIN_DIR = os.path.join(DATA_DIR, "trai...
import pytest from tartiflette import Scalar, create_engine from tartiflette.scalar.builtins.string import ScalarString from tartiflette.types.exceptions.tartiflette import GraphQLSchemaError @pytest.mark.asyncio async def test_issue370_double_values(): with pytest.raises( GraphQLSchemaError, ma...
nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4] def maxSubArray(nums): n = len(nums) # 确定终止分割的条件 if n == 1: return nums[0] left = maxSubArray(nums[:n // 2]) right = maxSubArray(nums[n // 2:]) max_l = nums[n // 2 - 1] tmp = 0 for i in range(n // 2 - 1, -1, -1): tmp += nums[i] ...
#!/usr/bin/env python # Copyright (c) 2018, Xilinx # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright # notice, this lis...
#!/usr/bin/env python # license removed for brevity # Directed Study, Spring 2020 # Charles DeLorey # Department of Computer Science, Tufts University # Example publisher for Arduino-based robotic hand # Sends Adc message (6 uint16's), ignoring last, to hand to set joint angle import sys import rospy import serial f...
# Copyright 2014 Netflix, 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...
def strings(w): index = 0 c = len(w) while index < len(w): letter = w[c-1] print(letter) c = c-1 index = index + 1 w = input("Ingrese una palabra:\n") strings(w)
''' The match module allows for match routines to be run and determine target specs. ''' import salt.minion __func_alias__ = { 'list_': 'list' } def compound(tgt): ''' Return True if the minion matches the given compound target CLI Example:: salt '*' match.compound 'L@cheese,foo and *' ...
from enum import IntEnum class SteamAppId(IntEnum): HALF_LIFE_2 = 220 HALF_LIFE_2_EP_1 = 380 HALF_LIFE_2_EP_2 = 420 PORTAL = 400 PORTAL_2 = 620 LEFT_4_DEAD = 500 LEFT_4_DEAD_2 = 550 TEAM_FORTRESS_2 = 440 COUNTER_STRIKE_GO = 730 SOURCE_FILMMAKER = 1840 BLACK_MESA = 362890
import chancapmc import numpy as np import os from itertools import product def test_memory(): print("PID:", os.getpid()) input() print("Created arrays in Python") n = 6 a1 = np.arange(n**2, dtype=float).reshape([n]*2) * 1.3123 a2 = np.arange(n**3, dtype=float).reshape([n]*3)*1.5 a3 = np.ar...
from pygame import display,font font.init() police = font.Font('Roboto.ttf',50) scr = display.get_surface() scrrect = scr.get_rect() class Levelmess(object): t = 0 @staticmethod def update(mess): Levelmess.mess = police.render(mess,1,(200,200,200)) Levelmess.messrect = Levelm...
# author: Roy Kid # contact: lijichen365@126.com # date: 2021-09-11 # version: 0.0.1 from mollab.abc import Item, Template import numpy as np class Atom(Item): serial = 1 def __init__(self): self.serial = Atom.serial Atom.serial += 1 self.bondAtoms = [] self.propertie...
""" parser_usda.py Parses data from the USDA text files. """ from bs4 import BeautifulSoup import urlparse from urllib2 import urlopen from urllib import urlretrieve import os import sys import time import glob from random import randint import codecs import json import inspect from cheese import Cheese, CheeseLibrar...
# -*- coding: utf-8 -*- """Command line interface for Axonius API Client.""" from ...context import CONTEXT_SETTINGS, click from ...options import AUTH, add_options USER_NAME = click.option( "--name", "-n", "name", help="Name of user", required=True, show_envvar=True, show_default=True, ) ...
# synth.__main__ import argparse import configparser import pathlib import subprocess import typing import synth.metadata import synth.config class CommandlineParsingError(RuntimeError): pass class CustomFormatter(argparse.RawDescriptionHelpFormatter): def _format_action(self, action: argparse.Action) -> st...
from .for_events import prompt_event_occurred, prompt_event_category, \ prompt_event_weight, edit_event_description, prompt_event_artifacts from .for_init import prompt_init_config
'''------------------------------------------------------------------------------- Tool Name: CreateInflowFileFromECMWFRunoff Source Name: CreateInflowFileFromECMWFRunoff.py Version: ArcGIS 10.3 Author: Environmental Systems Research Institute Inc. Updated by: Alan D. Snow, US Army ERDC Descript...
# # filter-build-log.py - Cuts out cruft to focus on build failure details. # # This script filters build logs down to only [WARNING] and [ERROR] lines, # and consolidates lengthy duplicate class listings down to packages only. import sys def print_filtered_log(log): dups = [] parsingdups = False atbegin...
from gpiozero import Button, LED from gpiozero.pins.pigpio import PiGPIOFactory from gpiozero.tools import all_values from signal import pause factory3 = PiGPIOFactory(host='192.168.1.3') factory4 = PiGPIOFactory(host='192.168.1.4') led = LED(17) button_1 = Button(17, pin_factory=factory3) button_2 = Button(17, pin_f...
from collections import namedtuple import os import azure.mgmt.keyvault import azure.mgmt.batch from azure_devtools.scenario_tests.preparers import ( AbstractPreparer, SingleValueReplacer, ) from azure_devtools.scenario_tests.exceptions import AzureTestError from devtools_testutils import AzureMgmtPreparer, ...
#!/usr/bin/env python3.9 """ Test the `zendesk_common.py` file under main/upstream. """ import os import pytest @pytest.fixture() def variables(): """ Retrieve environment variables for testing, and pass their values to the test functions. """ # get environemnt variable values for testing sub...
#!/usr/bin/env python3 from functools import partial import unittest from unittest.mock import Mock, patch from sap.rest.connection import Connection from sap.rest.errors import UnauthorizedError def stub_retrieve(response, session, method, url, params=None, headers=None, body=None): req = Mock() req.metho...
from sparselayer_tensorflow.sparselayer_tensorflow import SparseLayerDense, SparseLayerConv2D
import json class Paragraph: def __init__(self, text, tickers): self.text = text self.tickers = tickers def toJson(self): return json.dumps({ "text": self.text, "tickers": self.tickers })
import logging import logging.config import yaml import os def get_logger(name:str)->logging.Logger: """ get_logger function Parameters: name: the name of the logger to get. If it's not defined in config it will be the root use a name that allows the i...
from direct.directnotify import DirectNotifyGlobal from direct.interval.IntervalGlobal import * from toontown.battle import BattlePlace from direct.fsm import ClassicFSM, State from direct.fsm import State from toontown.toonbase import ToontownGlobals from toontown.building import Elevator from panda3d.core import * fr...
import os import subprocess import sys from multiprocessing.pool import ThreadPool from pathlib import Path timeout = 20 cpus = 10 num_threads = 10 def call_ta2search(command): print(command) p = subprocess.Popen(command, shell=True) try: p.communicate(timeout=timeout * 60) except TimeoutEx...
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: kv.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection...
#!/usr/bin/python import sys pre = [] args = [] for l in sys.stdin.readlines(): l = l.strip() if l.find('=') == -1: continue k = l.split('=')[0].strip() if k == 'Arguments' or k == 'arguments': args.append(l) else: pre.append(l) for p in pre: print p args.reverse() for a in args: ...
# Generated by Django 2.1.11 on 2019-08-13 06:03 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('contenttypes', '0002_remove_content_type_name'), migrations.sw...
# coding: utf-8 import os ''' xcode clang compile command line: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang \ -c -x c++ -arch x86_64 -O0 -g -mmacosx-version-min=10.14 \ -std=c++11 -MMD -MT dependencies \ -MF /Users/nsw/src/frameflow/third_party/work/jsoncpp-arm64/s...
import torch from torch import nn, autograd from torch.utils.data import DataLoader, Dataset import numpy as np import random from sklearn import metrics from torch import nn import torch.nn.functional as F import torchtext def evaluate_validation(scores, loss_function, gold): guesses = scores.argmax(dim=1) n_...
from setuptools import setup setup( name="geneutils", version="0.0.6", packages=["geneutils"], data_files=[("", ["LICENSE"])], url="https://github.com/samapriya/geneutils", install_requires=[ "biopython>=1.77", "pandas>=1.1.5", "requests>=2.26.0", "beautifulsoup4...
contains_a = lambda word: "a" in word print contains_a("banana") print contains_a("apple") print contains_a("cherry") #Write your lambda function here long_string = lambda str: len(str) > 12 print long_string("short") print long_string("photosynthesis") #Write your lambda function here ends_in_a = lambda str: str[l...
# -*- coding = utf-8 -*- import torch import torch.autograd as autograd import torch.nn as nn # hyper parameters EMBEDDING_DIM = 50 LEARNING_RATE = 1e-3 EPOCH = 100 HIDDEN_DIM = 6 NUM_LAYERS = 1 # load data training_data = [ ("The dog ate the apple".split(), ["DET", "NN", "V", "DET", "NN"]), ("Everybody rea...
# (C) Datadog, Inc. 2021-present # All rights reserved # Licensed under a 3-clause BSD style license (see LICENSE) import os import pytest from datadog_checks.dev import run_command from datadog_checks.dev.kind import kind_run from datadog_checks.dev.kube_port_forward import port_forward try: from contextlib imp...
# from django.shortcuts import render from django.views.generic.base import ContextMixin from .models import PageHelp class HelpContextMixin(ContextMixin): def get_context_data(self, **kwargs): context = super(HelpContextMixin, self).get_context_data(**kwargs) page_help, create = PageHelp.object...
# -*- coding: utf-8 -*- # Copyright (c) 2015 Spotify AB __all__ = ["RAMLLoader"] try: from collections import OrderedDict except ImportError: # pragma: no cover from ordereddict import OrderedDict import os import yaml from .errors import LoadRAMLError class RAMLLoader(object): """ Extends YAML ...
# Credit to Lester Leong and his "Python Risk Management: Monte Carlo Simulations" # article which helped with starting off and understanding the material. import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import datetime as dt import json import numpy as np import pandas as pd import pandas_dat...
# -*- coding: utf-8 -*- """ Created on Fri Dec 3 23:57:21 2021 @author: Connor """ import numpy as np def parse_input(filename): with open(filename, "r") as fh: lines = fh.readlines() # Get just the list of drawings drawings = np.array([int(item) for item in lines[0].split(",")]) # ...
import os import sys import subprocess import shutil ENV_NAME = "pyxl_test_env_" + os.path.basename(sys.executable) if not os.path.exists(ENV_NAME) or os.stat(sys.executable).st_mtime > os.stat(ENV_NAME + "/bin/python").st_mtime: print "Creating virtualenv to install testing dependencies..." VIRTUALENV_SCRIPT...
import os import sys import json import operator import requests import tempfile from pathlib import Path import sys import boto3 BUCKET = "covid-19-aggregates" WEBHOOK_URL = os.environ.get("SLACK_WEBHOOK_METRICS_URL", None) def to_isodate(d): mm, dd, yyyy = d.split("-") return f"{yyyy}-{mm}-{dd}" def get...
#!/usr/bin/python # # 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 in writing, software #...
import pygame LETGO_PIDGEON = pygame.USEREVENT + 1
from util import timeit @timeit def trailing_zeros(n: int) -> int: """ [Easy] https://cses.fi/problemset/task/1618 [Help] https://www.geeksforgeeks.org/count-trailing-zeroes-factorial-number/ [Solution] https://cses.fi/paste/e30a1f7b61c0770e239417/ Your task is to calculate the number of trailing...
import types import pytest from indy_client.test.helper import genTestClient from plenum.common.constants import VERKEY from plenum.common.signer_simple import SimpleSigner from plenum.common.messages.node_messages import PrePrepare, Commit from plenum.common.signer_did import DidSigner from plenum.common.util import...
import unittest from moduls import get_random_spectators_and_players import logging logger = logging.getLogger(__name__) PLAYERS = ["player01", "player02", "player03", "player04", "player05", "player06", "player07", "player08", "player09"] class MyTestCase(unittest.TestCase): def test_something(self): s...
from flask import Flask from flask_bootstrap import Bootstrap from flask_mail import Mail from flask_moment import Moment from flask_sqlalchemy import SQLAlchemy from flask_login import LoginManager from flask_pagedown import PageDown from config import config bootstrap = Bootstrap() # mail = Mail() # moment = Moment(...
# coding utf-8 import os import face_recognition import cv2 def func_encodings(image_path, known_encodings, known_names): name = image_path.split(os.path.sep)[-2] # 读取路径中文件夹名,并分隔出人名 image = cv2.imread(image_path) # opencv读取图像函数读出图像为bgr形式 rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) # ...
# coding: utf-8 ''' Memory Game where players look for matches in a grid of 'cards' Tapping the card turns it over, tap another and if they match you get to add a point to your total. ''' from scene import * # import sound import random from math import sqrt # sin, cos, pi # A = Action # - - - - - - - # grid dimens...
import numpy as np import tensorflow as tf from tensorflow import keras from tensorflow.keras.layers import Dense, Flatten, Conv2D, Input, BatchNormalization, Activation, Add import copy import os from typing import Any, Tuple import constants as c os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' parent_dir = os.path.dirname...
"""AuthZ Adapter implementations of hierarchy sessions.""" # pylint: disable=no-init # Numerous classes don't require __init__. # pylint: disable=too-many-public-methods # Number of methods are defined in specification # pylint: disable=too-many-ancestors # Inheritance defined in specification from ..osid...
""" Configuration file for scripts. Author: Tang Yew Siang Date: July 2019 """ import os import sys import argparse import numpy as np # =============================== Algorithm Details =============================== # A: Combines the PC with the 3D box by using planes of the 3D box # B: Combines the PC with the ...
from googletrans import Translator as google_translator from src.inc.lang_detection_utils import * class Translator: def __init__(self, text: str, target: str) -> None: self.text = text self.target = target # Can be code or full name self.translator = google_translator() self.l...
import pygame from settings import * from hero import * from walls import * class Game: def __init__(self): self.walls = None self.hero = None self.done = False pygame.init() self.screen = pygame.display.set_mode(WINDOW_SIZE) self.clock = pygame.time.Clock() ...
# Lint as: python3 """Tests for custom tensorflow operators in HDRnet (CUDA only).""" import collections import hdrnet_ops as ops import numpy as np from parameterized import parameterized import tensorflow.compat.v1 as tf def _assert_tf_shape_equals(test_case, expected_shape, tf_tensor): tf_shape = tf_tensor.sha...
import logging import sys import time from contextlib import contextmanager import pandas as pd from ..rpc import RPC from ..taskqueue.objs import current_job_id from .. import settings from ..serialization import serializer, deserializer logger = logging.getLogger(__name__) def cancel_all(): keys = settings.re...