content
stringlengths
5
1.05M
import scipy from torch.nn import functional as F import torch from torch import nn import numpy as np from modules.commons.wavenet import WN from modules.tts.glow import utils class ActNorm(nn.Module): def __init__(self, channels, ddi=False, **kwargs): super().__init__() self.channels = channels ...
from .model import TrainTransformersNER from .model_prediction import TransformersNER from .get_dataset import get_dataset_ner, SHARED_NER_LABEL, VALID_DATASET, PANX as panx_language_list from .japanese_tokenizer import SudachiWrapper from .tokenizer import Transforms
from direct.showbase.DirectObject import DirectObject from direct.directtools.DirectGeometry import * from panda3d.core import NodePath, LineSegs class Mopath(DirectObject): nameIndex = 1 def __init__(self, name = None, fluid = 1, objectToLoad = None, upVectorNodePath = None, reverseUpVector = False): ...
'''OpenGL extension ARB.matrix_palette Automatically generated by the get_gl_extensions script, do not edit! ''' from OpenGL import platform, constants, constant, arrays from OpenGL import extensions from OpenGL.GL import glget import ctypes EXTENSION_NAME = 'GL_ARB_matrix_palette' _DEPRECATED = False GL_MATRIX_PALETT...
''' 开始报数 有 500 个小孩围成一圈,编号从 1 到 500,从第一个开始报数:1,2,3,1,2,3,1,2,3,……每次报到 3 的小孩退出。 问第 n 个被淘汰的小孩,在最开始 500 人里是的编号是几? 输入:正整数 N,表示要计算的为第 N 个淘汰的小孩的编号,0 < N <= 500 输出:第 N 个淘汰的小孩的编号 输入样例 1 2 206 311 输出样例 3 6 176 223 ''' """ @param string line 为单行测试数据 @return string 处理后的结果 """ def solution(line): N = int(line) order = [0] *...
import flow_test as ft import helpers as hpl import numpy as np from PIL import Image import matplotlib as plt # import synthetic_tf_converter as converter import tensorflow as tf import data_reader as dr # import matplotlib.mlab as mlab # import ijremote as ij # import losses_helper as lhpl folder = '../dataset_sy...
import numpy as np import gym from gym import spaces from gym.utils import seeding class Hypercube(gym.Env): """ Note: requires gamma to be set to maintain reward structure. """ def __init__(self, n=5, gamma=0.99): self.pos = None self.dim = n self.radius = 10 # 0 is l...
from flask import Flask, render_template, request, flash from flask_pymongo import MongoClient from forms import ContactForm from flask_mail import Message, Mail mail = Mail() app = Flask(__name__, template_folder="templates") app.secret_key = '1a2b3c4d' app.config["MAIL_SERVER"] = "smtp.gmail.com" app.config["MAIL_PO...
class FillPatternElement(Element,IDisposable): """ An element that represents a fill pattern. """ @staticmethod def Create(document,fillPattern): """ Create(document: Document,fillPattern: FillPattern) -> FillPatternElement Creates a new FillPatternElement. document: The document in ...
import threading import time def thread(): time.sleep(2) print('---子线程结束---') def main(): t1=threading.Thread(target=thread) t1.setDaemon(True) t1.start() print('---主线程---') if __name__=='__main__': main()
import numbers from collections import abc def is_integer(value): return isinstance(value, int) and not isinstance(value, bool) def is_bytes(value): return isinstance(value, (bytes, bytearray)) def is_text(value): return isinstance(value, str) def is_string(value): return isinstance(value, (byte...
'''generate artificial data sets SUMMARY OF APIs bishop_ch1(num_samples) d1(fun, num_samples, x_low, x_high, error_mean, error_variance) outliers(num_features, num_unique_samples) sparse(num_features, num_samples) ALL RETURN x: nparray 2d y: nparray 1d ''' from dataset_bishop_ch1 import bishop_ch1 from dataset_d1 imp...
######## # Copyright (c) 2013-2019 Cloudify Platform 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 ...
# Copyright 2021 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 or agreed to in writing, ...
# -*- encoding: utf-8 -*- """ Copyright (c) 2019 - present AppSeed.us License: https://github.com/app-generator/license-eula """ class COMMON: NULL = None # not set NA = -1 # not set OK = 0 # all ok ERR = 1 # not ok NOT_FOUND = 2 # file or directory no...
from models.base.EntityBase import EntityBase from infrastructure.json.BaseConverter import BaseConverter @BaseConverter.register class SecretSourceBasicAuthenticationBase(EntityBase): def __init__(self, SecretSourceId: int = None, User: str = None, Password: str...
from django.shortcuts import render # Create your views here. def home_fbv(request): return render(request, 'stockdb_app/base.html')
""" Concurrent-learning controller derived for Fossen's dynamic model of a boat. See: http://ieeexplore.ieee.org/abstract/document/7798300/ -- Bell, Zachary, et al. "Adaptive control of a surface marine craft with parameter identification using integral concurrent learning." Decision and Control (CDC), 2016 IEEE 55th ...
import numpy as np from fluiddyn.clusters.legi import Calcul2 as Cluster from critical_Ra_RB import Ra_c_RB as Ra_c_RB_tests prandtl = 1.0 dim = 2 dt_max = 0.005 end_time = 30 nb_procs = 10 nx = 8 order = 10 stretch_factor = 0.0 Ra_vert = 1750 x_periodicity = False z_periodicity = False cluster = Cluster() clu...
#pedir a altura e a largura de uma parede e dizer quantos litros de tinta vai gastar sabendo que cada litro de tinta pinta 2m2 altura = float(input('Qual a altura da parede? ')) largura = float(input('Qual a largura da parede? ')) area = altura * largura tinta = (altura * largura) / 2 print('Voce tem a area de {}x{} ...
# 지형 이동 from collections import deque dy = [-1, 1, 0, 0] dx = [0, 0, -1, 1] def solution(land, height): label_table = [[0 for _ in range(len(land))] for _ in range(len(land))] label = 1 for y in range(len(land)): for x in range(len(land)): if not label_table[y][x]: bfs...
# for loading/processing the images # for everything else import os import pickle from shutil import copyfile import matplotlib.pyplot as plt import numpy as np # models from keras.applications.vgg16 import VGG16 from keras.applications.vgg16 import preprocess_input from keras.models import Model from keras.preprocess...
""" Prepare training and testing datasets as CSV dictionaries Created on 11/26/2018 @author: RH """ import os import pandas as pd import sklearn.utils as sku import numpy as np import re # get all full paths of images def image_ids_in(root_dir, ignore=['.DS_Store', 'dict.csv', 'all.csv']): ids = [] for id i...
"""Implementation of GPU-friendly test-time augmentation for image segmentation and classification tasks. Despite this is called test-time augmentation, these method can be used at training time as well since all transformation written in PyTorch and respect gradients flow. """ from collections import defaultdict from...
# Generated by Django 2.0.5 on 2018-05-03 16:09 import datetime from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Account', ...
# Copyright 2019 Google, LLC. # # 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, ...
n1 = float(input('Digite a primeira nota: ')) n2 = float(input('Digite a segunda nota: ')) m = (n1 + n2) / 2 print('A média das notas {} e {} é {:.1f}.' .format(n1, n2, m))
import inspect import os from powersimdata.design.generation.clean_capacity_scaling import load_targets_from_csv from powersimdata.utility.helpers import PrintManager import postreise from postreise.plot.plot_bar_shortfall import plot_bar_shortfall data = os.path.join(os.path.dirname(inspect.getfile(postreise)), "da...
"""Add Item model Revision ID: 8a20f21a30c3 Revises: Create Date: 2021-06-25 12:45:15.980332 """ from alembic import op import sqlalchemy as sa from sqlalchemy_utils import UUIDType # revision identifiers, used by Alembic. revision = '8a20f21a30c3' down_revision = None branch_labels = None depends_on = None def ...
"""Clean Code in Python - Chapter 2: Pythonic Code > Iterable Objects """ from datetime import date, timedelta class DateRangeIterable: """An iterable that contains its own iterator object.""" def __init__(self, start_date, end_date): self.start_date = start_date self.end_date = end_date ...
# -*- coding: utf-8 -*- ''' Created on Nov 1, 2016 @author: nicolas ''' import os.path as osp import time import pytest import six import lemoncheesecake.api as lcc from lemoncheesecake.matching import * from helpers.runner import run_suite_class, run_suite_classes, run_func_in_test from helpers.report import as...
# -*- coding: utf-8 -*- from __future__ import unicode_literals, absolute_import from django.core.management.base import BaseCommand, CommandError from kchart.charts.chartservice import CHART_SERVICES class Command(BaseCommand): help = 'Refreshes any incomplete charts' def add_arguments(self, parser): ...
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved from typing import Iterable, Optional import torch from .cuda import Variable, zerovar def to_onehot(feat: Variable, size: int) -> Variable: """ Transform features into one-hot vectors """ dim = [d for d i...
from django.contrib import admin from pfss.models import SpecialAbility, Size, Die, Creature, Attack, Skill, CreatureSkill, CreatureType, Feat, Language, CreatureAttack, CreatureGroup, GroupEntry, CreatureExtraType, Alignment, Grouping admin.site.register(Alignment) admin.site.register(CreatureExtraType) admin.site.r...
""" The MIT License (MIT) Copyright (c) 2015-present Rapptz 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, merg...
# Revision of python after exams..... My_favourites = [] My_favourites.append('Eleven') My_favourites.insert(0,'Mike') My_favourites.append('Steve') My_favourites.append('Will') My_favourites.append('Harry') My_favourites.append('Harmoine') My_favourites.append('Rupert') print("I got these persons in my 20 years of lif...
french = (0, 32, 15, 19, 4, 21, 2, 25, 17, 34, 6, 27, 13, 36, 11, 30, 8, 23, 10, 5, 24, 16, 33, 1, 20, 14, 31, 9, 22, 18, 29, 7, 28, 12, 35, 3, 26) american = (0, 28, 9, 26, 30, 11, 7, 20, 32, 17, 5, 22, 34, 15, 3, 24, 36, 13, 1, '00', 27, 10, 25, 29, 12, 8, 19, 31, 18, 6, 21, 33, 16, 4, 23, 35, ...
""" Global configuration file that defines the properties of each campaign """ import campaigns.AI4EU import campaigns.sw_faults_example predefined_cols = () main_csv_path = "table.csv" # Path to the CSV that will keep the main results plans = ( (campaigns.AI4EU.AI4EU), #(campaigns.sw_faults_example.SW_Faults...
import os TEST_ROOT = os.path.dirname(__file__) TEST_DATA = os.path.join(TEST_ROOT, 'data') REPO_ROOT = os.path.dirname(TEST_ROOT)
from telegram.ext import Updater, Filters from telegram.ext import CommandHandler, MessageHandler, CallbackQueryHandler, InlineQueryHandler from telegram.ext.dispatcher import run_async from telegram.parsemode import ParseMode from database import Transaction from action_handlers import create_bill_handler, manage_bill...
import numpy as np from joblib import Memory import os from scipy.spatial.distance import pdist, squareform # cache_dir = '../joblib_cache' cache_dir = 'joblib_cache' os.makedirs(cache_dir, exist_ok=True) # cachedir = mkdtemp(dir=cache_dir) memory = Memory(cachedir=cache_dir, verbose=1) def svd_flip(u, vt, u_base...
train_df = pd.read_csv('/content/drive/MyDrive/HackerEarth Power Generated Challenge /train.csv') test_df = pd.read_csv('/content/drive/MyDrive/HackerEarth Power Generated Challenge /test.csv') train_df.head() test_df train_df.describe() #Replacing low, medium, extremely low in cloud level column with thei...
import pandas as pd import numpy as np import matplotlib.pyplot as plt import shlex from bs4 import BeautifulSoup from math import sin, cos, sqrt, atan2, radians class route(object): def kml_to_df( file_name,tag="LineString",seperator=","): """ to convert .kml file to Pandas DataFra...
from .avis import FormAvis
# ---------------------------------------------------------------------- # | # | Phrase_UnitTest.py # | # | David Brownell <db@DavidBrownell.com> # | 2021-09-23 18:09:13 # | # ---------------------------------------------------------------------- # | # | Copyright David Brownell 2021 # | Distributed ...
# -*- coding: utf-8 -*- """ Created on Mon Apr 04 14:38:34 2016 @author: Stella Psomadaki """ from pointcloud.AbstractBulkLoader import BulkLoader from pointcloud.AbstractQuerier import Querier import time from tabulate import tabulate import pointcloud.oracleTools as ora import os ####################...
#!/usr/bin/env python # -*- coding: utf-8 -*- import json import re import random random.seed(11111111) CORRECT_OPTIONS = { '06050346': '6a_6328349905179.gif', '06050347': '7b_6328349919889.gif', '06050348': '30_6328349926673.gif', '06050350': '2c_6328349936417.gif', '06050361': 'P1_6328349873949.g...
from enum import Enum from random import choice from exceptions import InvalidUsage, NotCorrectDirection class Direction(Enum): UP = "U" DOWN = "D" RIGHT = "R" LEFT = "L" @classmethod def has_value(cls, value): return value in cls._value2member_map_ DIRECTION_VERTICAL = [ Direct...
import keras import os import shutil class PretrainedModelDefinition: __models = { 'inception': keras.applications.inception_v3.InceptionV3, 'resnet': keras.applications.resnet50.ResNet50, 'vgg16': keras.applications.vgg16.VGG16, 'vgg19': keras.applications.vgg19.VGG19, 'xc...
from vcr_unittest import VCRTestCase from ordway import OrdwayClient from ordway.exceptions import OrdwayClientException class VCRIntegrationTestCase(VCRTestCase): @classmethod def setUpClass(cls): super().setUpClass() try: cls.client = OrdwayClient.from_env() except Ordwa...
# -*- coding: utf-8 -*- from __future__ import absolute_import import os import pycountry from pymediainfo import MediaInfo from fractions import Fraction from pyfileinfo.file import File class Medium(File): def __init__(self, file_path): File.__init__(self, file_path) self._video_tracks = Non...
# Copyright (C) 2020-2021 by TeamSpeedo@Github, < https://github.com/TeamSpeedo >. # # This file is part of < https://github.com/TeamSpeedo/FridayUserBot > project, # and is released under the "GNU v3.0 License Agreement". # Please see < https://github.com/TeamSpeedo/blob/master/LICENSE > # # All rights reserved. impo...
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import...
import tensorflow as tf from tensorflow.contrib.layers import fully_connected X = None # tf.placeholder for your inputs n_hidden1 = 100 # By default, fully_connected function uses Xavier initialization # You can change to He initialization he_init = tf.contrib.layers.variance_scaling_initializer() hidden1 = fully_con...
# Copyright © 2020 Ingram Micro Inc. All rights reserved. import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'integration_tests.replica_settings') application = get_wsgi_application()
import numpy as np import scipy.sparse as sp from create_sfactor import create_sfactor def S_create(L0, wvlen, xrange, yrange, N, Npml): #S_CREATE Summary of this function goes here # Detailed explanation goes here ## Set up the domain parameters. eps0 = 8.854e-12 * L0 # vacuum permitt...
from PIL import Image, ImageTk
# MIT License # Copyright (c) 2017 MassChallenge, Inc. from impact.v1.views.patch_mixin import PatchMixin from impact.v1.views.base_detail_view import BaseDetailView from impact.v1.helpers import CriterionHelper class CriterionDetailView(BaseDetailView, PatchMixin): view_name = "criteri...
import pytest from rdkit import Chem import os import glob from analogs_finder.helpers import helpers as hp from analogs_finder.helpers import postfilter as pt from analogs_finder.search_methods import molecule as ml RESULT = 4 DIR = os.path.dirname(__file__) DB = os.path.join(DIR, "data/database.sdf") def test_dupli...
import glob import os import kornia.augmentation as K import numpy as np import pytorch_lightning as pl import torch import torchvision.transforms as T from einops import rearrange from PIL import Image from torch.utils.data import DataLoader, Dataset from torchvision.utils import draw_segmentation_masks from csip.da...
import math from tempfile import NamedTemporaryFile from typing import List from bitarray import bitarray from hypothesis import given, strategies as st from bigsi.cmds.merge_blooms import merge_blooms @given(num_rows=st.integers(min_value=1, max_value=8), byte_values1=st.lists(min_size=1, max_size=100, eleme...
def nth_arg(n): """Returns a function which returns its nth argument""" return lambda *args: args[n]
import argparse parser = argparse.ArgumentParser() parser.add_argument("-a", "--arrangements", help="enable axis arrangements", action="store_true") args, _ = parser.parse_known_args() enable_axis_arrangements = args.arrangements
#!/usr/bin/env python3 r""" Contains xpaths and related string constants applicable for new Vue based OpenBMC GUI. """ class gui_variables(): # Login page xpath_textbox_hostname = "//input[@id='host']" xpath_textbox_username = "//*[@data-test-id='login-input-username']" xpath_textbox_password = "//*...
#!/usr/bin/env python # lse.py # Copyright (c) 2017. All rights reserved. from typing import Sequence, TypeVar, Union, Dict import os import numpy as np import networkx from scipy.stats import rankdata from scipy.stats import norm from sklearn.decomposition import TruncatedSVD from d3m.primitive_interfaces.transfor...
import airflow from airflow.models import DAG from airflow.operators.dummy_operator import DummyOperator from airflow.operators.python_operator import BranchPythonOperator, PythonOperator from airflow.utils.trigger_rule import TriggerRule args = { "owner": "godatadriven", "start_date": airflow.utils.dates.day...
from django import forms from django.contrib import admin from django.contrib.auth.admin import UserAdmin as AuthUserAdmin from django.contrib.auth.forms import UserChangeForm, UserCreationForm from .models import User, UserTenantRelationship class TenantInline(admin.TabularInline): model = UserTenantRelationshi...
# See about Fizz buzz game in here, http://en.wikipedia.org/wiki/Fizz_buzz import time # Whether to print each row result in iteration on not print_rounds = False # Starting rounds amount for game amount = 10 # Get time in milliseconds def curr_mill_time(): return round(time.time() * 1000) # Run game def do_ru...
__author__ = 'Devesh Bajpai' ''' https://codeforces.com/problemset/problem/1141/B Solution: The magic of this solution lies in appending the hour-status list to itself. Why? Well that helps to handle the status of the last hour of prior day with the next day's hours' statuses. Now the problem becomes finding the lon...
from collections import OrderedDict from functools import reduce from typing import Dict from typing import List from typing import Optional from typing import Tuple from typing import Union import torch import torch.nn.functional as Fun from torch_complex.tensor import ComplexTensor from espnet.nets.pytorch_backend....
#!/usr/bin/env python # # Contributors: # Zhendong Li <zhendongli2008@gmail.com> # Qiming Sun <osirpt.sun@gmail.com> # from functools import reduce import numpy import scipy.linalg from pyscf import gto, scf, mcscf from pyscf import tools mol = gto.Mole() mol.verbose = 4 mol.output = 'hs.out' mol.atom = '...
################################################################################ # Author: Orion Crocker # Filename: collage.py # Date: 02/06/20 # # Collage Creator # Creates a collage of images based on directory given ################################################################################ import argparse i...
# -*- coding: utf-8 -*- # # ラベル中のトークン(音素/かな/キャラクター)を, # ニューラルネットワークで扱うため,文字から番号へ変換します. # また,文字-番号の対応を記したトークンリストも作成します. # # osモジュールをインポート import os def token_to_int(label_file_str, label_file_int, unknown_list_file, token_list, silence_tokens): ...
#! /usr/bin/env python ##### import os import sys from subprocess import Popen,PIPE output = Popen(["/bin/ls","/"],stdout=PIPE).communicate()[0] print output
import sys import pysam import configparser import argparse import operator import functools from src.generate_consensus import ConsDataRow from src.get_ref_seq import get_ref_seq def parse_raw_table(cons_file, f_sizes): """Parses a .cons file generated by generate_consensus into VCF entries.""" rows = {...
#!/usr/bin/env python import schemabase from leginon import leginondata class SchemaUpdate17561(schemabase.SchemaUpdate): ''' This schema update converts frame rate to frame time if present ''' def upgradeLeginonDB(self): if not self.leginon_dbupgrade.columnExists('CameraEMData', 'frame rate'): return if n...
""" Copyright © Helicon Tech. All rights reserved. """ import yaml def load_feed(stream): pass
#!/usr/bin/env python # Copyright (c) 2016 Adafruit Industries # Author: Tony DiCola # # 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 ri...
#!/usr/bin/env python try: from setuptools import setup except ImportError: from distutils.core import setup setup( name="vboxtrayico", packages=['vboxtrayico'], version="0.1.9", author="Krzysztof Warunek", author_email="kalmaceta@gmail.com", description="Virtualbox tray tool - list/st...
#!/usr/bin/env python import concurrent import sys from concurrent.futures.thread import ThreadPoolExecutor from typing import Dict, Iterable, Optional, Set import requests import toml from semver import Version def main(): if len(sys.argv) > 3 or len(sys.argv) < 2: script_name = sys.argv[0] prin...
"""This module implements a handler for the Python language. The handler collects data with [`pytkdocs`](https://github.com/pawamoy/pytkdocs). """ import json import os import posixpath import sys import traceback from collections import ChainMap from subprocess import PIPE, Popen # noqa: S404 (what other option, mo...
"""Evaluation Metrics for Semantic Segmentation""" import numpy as np import mxnet.ndarray as F __all__ = ['batch_pix_accuracy', 'batch_intersection_union', 'pixelAccuracy', 'intersectionAndUnion'] def batch_pix_accuracy(output, target): """PixAcc""" # inputs are NDarray, output 4D, target 3D p...
### # # WEIO Web Of Things Platform # Copyright (C) 2013 Nodesign.net, Uros PETREVSKI, Drasko DRASKOVIC # All rights reserved # # ## ## ######## #### ####### # ## ## ## ## ## ## ## # ## ## ## ## ## ## ## # ## ## ## ###### ...
class Solution: def isPalindrome(self, head: ListNode) -> bool: """ Given a singly linked list, determine if it is a palindrome. """ # savlst = [] # while head: # savlst.append(head.val) # head = head.next # return savlst==savlst[::-1] f...
import ee import time import numpy as np import time import sys import json import argparse def UTM_lookup(lon): assert (lon < 180.0) and (lon >= -180.0) # assuming lon in [-180,180) return int(np.floor((lon + 180.0)/6) + 1) def EPSG_lookup(lon,lat): utm_zone = UTM_lookup(lon) if lat >= 0: ...
import pygame import time import sys from constants import DEV_MODE, SCREEN_HEIGHT, SCREEN_WIDTH, FRAME_RATE from controllers import game_controller class HelpController(object): MENU_ITEM_X = 520 MENU_ITEM_WIDTH = 215 MENU_ITEM_HEIGHT = 70 MENU_ITEM_HELP_Y = 380 MENU_ITEM_START_Y = 480 de...
from datetime import timedelta from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent ALLOWED_HOSTS = ['*'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contri...
import numpy as np from PIL import Image import yaml from pyglet.gl import * import pyglet from pyglet import font, graphics, window import argparse class Camera: """ A simple 2D camera that contains the speed and offset.""" def __init__(self, window: pyglet.window.Window, scroll_speed=1, min_zoom=1, max_zo...
from PyQt5.QtCore import QDataStream, QIODevice, QObject, QByteArray, pyqtSignal from PyQt5.QtCore import * from PyQt5.QtWidgets import QApplication, QDialog, QMainWindow, QLineEdit, QPushButton, QVBoxLayout from PyQt5.QtWidgets import * from PyQt5.QtNetwork import QTcpSocket, QAbstractSocket from PyQt5.QtNetwork impor...
import pytest from pysphero.constants import Api2Error from pysphero.exceptions import PySpheroRuntimeError from pysphero.packet import Packet def test_packet_init(): packet = Packet(0x23, 0x42) assert packet.device_id == 0x23 assert packet.command_id == 0x42 assert packet.flags == 0x0a assert pa...
from MPL_functions import * import os ## FUNCTION PURPOSE: A function to WhatsApp or email the user to remind them to practice their instrument. # Function input arg 1: method [string] --> 'email' or 'WhatsApp'. Determins the type of message you recieve. # Function input arg 2: time_threshold [int] --> The number o...
#!/usr/bin/python38 from sqlalchemy import Column, String, Integer, Float, Date # BLOB from sqlalchemy.ext.declarative import declarative_base # from libbasemodel.form import formStockManager from sqlalchemy.sql.schema import ForeignKey from sqlalchemy.orm import relationship Base = declarative_base() class formSt...
import boto.sqs from django.conf import settings from boto.sqs.message import Message import json import logging def push_message_to_sqs_queue(message): """ A utility function that pushes the message to the common SQS queue. :param message: A JSON document with the request details. """ connection...
# # Autogenerated by Thrift Compiler (0.13.0) # # DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING # # options string: py # from thrift.Thrift import TType, TMessageType, TFrozenDict, TException, TApplicationException from thrift.protocol.TProtocol import TProtocolException from thrift.TRecursive impo...
import logging import os import random import argparse import IPython import yaml from PIL import Image import torch import timeit import numpy as np import scipy.misc as misc from imageio import imwrite from os.path import join as pjoin from torch.backends import cudnn from torch.utils import data from ptsemseg.model...
# -*- coding: utf-8 -*- # Generated by Django 1.10.6 on 2017-03-24 19:29 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('isisdata', '0060_auto_20170324_1741'), ] operations = [ migrations.RemoveField( ...
# spark-submit --packages org.apache.spark:spark-avro_2.12:3.0.1 script.py csv random_batch # spark-submit --packages org.apache.spark:spark-avro_2.12:3.0.1 script.py parquet write # du prints kb # orc 191332 kb # avro 286628 kb # parquet 202772 kb # csv 483432 kb # json 1292192 kb # write speed # orc: 16.25 sec # avr...
# -*- coding: utf-8 -*- """SunPy sample data files""" import sys from _sample import sample_files as _sample_files import os.path from sunpy import config as _config _sampledata_dir = _config.get("downloads", "sample_dir") for _key in _sample_files: if os.path.isfile(os.path.join(_sampledata_dir, _sample_files[_...
from sklearn.model_selection import train_test_split import numpy from numpy import zeros, ones from numpy import asarray from keras.preprocessing.text import Tokenizer from keras.models import Sequential from keras.layers import Dense, Conv2D, Permute, MaxPooling2D, AveragePooling2D, LSTM, Embedding, Reshape from ker...
"""Common methods for tests of infer.py.""" import logging import re import sys import textwrap from pytype import convert_structural from pytype import errors from pytype import infer from pytype.pyc import loadmarshal from pytype.pytd import optimize from pytype.pytd import pytd from pytype.pytd import utils as py...