content
stringlengths
5
1.05M
#!/usr/bin/env python import os, sys from typing import Union, List import pprint pp = pprint.PrettyPrinter(indent=4, stream=sys.stderr) from google.protobuf.compiler import plugin_pb2 as plugin from google.protobuf.descriptor_pool import DescriptorPool from google.protobuf.descriptor import Descriptor, FieldDescrip...
import json import os import toml # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) CONFIG_FILE = 'config.toml' CONFIG_FILE_DIR = os.path.join(BASE_DIR, CONFIG_FILE) CONFIG_DATA = toml.load(CONFIG_FILE_DIR) # SECURITY WARNI...
from location import GeoCoordinate, geo_to_cartesian import time class Value: def __init__(self, value, unit): self.value = value self.unit = unit class Measurement: def __init__(self, row): self.parameter = row["parameter"] self.value = Value(row["value"], row["unit"]) ...
""" LC89. Gray Code The gray code is a binary numeral system where two successive values differ in only one bit. Given a non-negative integer n representing the total number of bits in the code, print the sequence of gray code. A gray code sequence must begin with 0. Example 1: Input: 2 Output: [0,1,3,2] Explanation...
"""The IPython HTML Notebook""" import os # Packagers: modify this line if you store the notebook static files elsewhere DEFAULT_STATIC_FILES_PATH = os.path.join(os.path.dirname(__file__), "static") del os from .nbextensions import install_nbextension
import unittest import pytest from anchore_engine.db import Image, get_thread_scoped_session from anchore_engine.services.policy_engine.engine.tasks import ImageLoadTask from anchore_engine.services.policy_engine.engine.policy.gate import ExecutionContext from anchore_engine.services.policy_engine import _init_distro_m...
#!/usr/bin/python import csv import pycurl import json def insertToElasticSearch(data): esData={'year' : data[0], 'week': data[1], 'state' : data[2], 'area': data[3], 'location' : data[4], 'totalCase' :...
# -*- coding: utf-8 -*- # Copyright 2015 Metaswitch Networks # # 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 applicab...
# vim: fdm=marker ''' author: Fabio Zanini date: 11/12/14 content: Get trees of haplotype alignments. ''' # Modules import os import argparse from operator import itemgetter, attrgetter import numpy as np from matplotlib import cm import matplotlib.pyplot as plt from Bio import Phylo from hivwholeseq.pati...
#!/usr/bin/env python from csvkit.unicsv import UnicodeCSVReader, UnicodeCSVWriter class CSVKitReader(UnicodeCSVReader): """ A unicode-aware CSV reader with some additional features. """ pass class CSVKitWriter(UnicodeCSVWriter): """ A unicode-aware CSV writer with some additional features. ...
#! /usr/bin/env python from tkinter import NoDefaultRoot, Tk, ttk, filedialog from _tkinter import getbusywaitinterval from tkinter.constants import * from math import sin, pi import base64, zlib, os ################################################################################ ICON = b'eJxjYGAEQgEBBiApwZDBzMAgxsDA...
# Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import os import subprocess from typing import Tuple import torch try: torch.classes.load_library( f"{os.environ['CONDA_PREFIX']}/...
from unittest.mock import patch from datetime import datetime import httpx import pytest from src.zever_local.inverter import ( Inverter, InverterData, ZeversolarError, ZeversolarTimeout, ) _registry_id = "EAB241277A36" _registry_key = "ZYXTBGERTXJLTSVS" _hardware_version = "M11" _software_version = ...
""" Tests for the game class """ import unittest import numpy as np from nashpy.algorithms.vertex_enumeration import vertex_enumeration class TestVertexEnumeration(unittest.TestCase): """ Tests for the vertex enumeration algorithm """ def test_three_by_two_vertex_enumeration(self): A = np.a...
#!/usr/bin/env python3 __author__ = "Will Kamp" __copyright__ = "Copyright 2013, Matrix Mariner Inc." __license__ = "BSD" __email__ = "will@mxmariner.com" __status__ = "Development" # "Prototype", "Development", or "Production" '''This is the wrapper program that ties it all together to complete this set of programs...
import time import numpy as np import dolfin as df from finmag.energies import Demag from finmag.field import Field from finmag.util.meshes import sphere import matplotlib.pyplot as plt radius = 5.0 maxhs = [0.2, 0.4, 0.5, 0.6, 0.7, 0.8, 0.85, 0.9, 0.95, 1.0] unit_length = 1e-9 m_0 = (1, 0, 0) Ms = 1 H_ref = np.array(...
from datetime import datetime, timezone from hamcrest.core.string_description import StringDescription from pytest import mark, raises from preacher.core.datetime import DatetimeWithFormat from preacher.core.verification.hamcrest import after, before ORIGIN = datetime(2019, 12, 15, 12, 34, 56, tzinfo=timezone.utc) ...
#!/usr/bin/env python from setuptools import setup, find_packages import dbbackup def get_requirements(): return open('requirements.txt').read().splitlines() def get_test_requirements(): return open('requirements-tests.txt').read().splitlines() keywords = [ 'django', 'database', 'media', 'backup', ...
from utils.rooster_utils import prediction, get_model, load_configurations, set_seed import torch import sys TARGET_SR = 44100 settings = load_configurations(mode="detector") if(settings == -1): print("Error: Failed while loading configurations") sys.exit() set_seed(settings["globals"]["seed"]) melspectrogra...
# Given an integer array nums, find the contiguous # subarray (containing at least one number) which # has the largest sum and return its sum. # Example: # Input: [-2,1,-3,4,-1,2,1,-5,4], # Output: 6 # Explanation: [4,-1,2,1] has the largest sum = 6. # Follow up: # If you have figured out the O(n) solution, try c...
from funcx_endpoint.endpoint.utils.config import Config from parsl.providers import LocalProvider config = Config( scaling_enabled=True, provider=LocalProvider( init_blocks=1, min_blocks=1, max_blocks=1, ), max_workers_per_node=2, funcx_service_address='https://api.funcx.org...
import abc from numpy import ndarray class AbstractGAN(abc.ABC): def __init__(self, run_dir: str, outputs_dir: str, model_dir: str, generated_datasets_dir: str, resolution: int, channels: int, epochs: int, output_save_frequency: int, model_save_frequency: int, loss_save_frequenc...
#! /usr/bin/env python3 # -*- coding: utf-8 -*- import os from comnetsemu.cli import CLI, spawnXtermDocker from comnetsemu.net import Containernet, VNFManager from mininet.link import TCLink from mininet.log import info, setLogLevel from mininet.node import Controller, RemoteController if __name__ == "__main__": ...
import streamlit as st import pandas as pd import joblib model = joblib.load('/content/drive/MyDrive/models/cc_foodrcmdns.pkl') df = pd.read_csv('dataset/indianfoodMAIN.csv') recp_name = st.selectbox("Select Recipe", df['recp_name'].values) st.write(recp_name) def findRcmdn(value): data = [] index = df[df['...
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. import torch import torch.nn as nn # Some utility functions def average_norm_clip(grad, clip_val): ''' Compute...
import gc import numpy as np import pandas as pd from datetime import datetime from functools import partial import tensorflow as tf from sklearn import preprocessing from .. import utils from ..config import cfg from .base_model import BaseModel class Graph(): '''Container class for tf.Graph and associated variab...
import cosypose import os import yaml from joblib import Memory from pathlib import Path import getpass import socket import torch.multiprocessing torch.multiprocessing.set_sharing_strategy('file_system') hostname = socket.gethostname() username = getpass.getuser() PROJECT_ROOT = Path(cosypose.__file__)....
from django.contrib.auth.models import User from django.core import mail from django.test import TestCase from hc.api.models import Check from hc.test import BaseTestCase class LogoutTestCase(BaseTestCase): def test_it_logs_out_users(self): form = {'email': 'alice@example.org', 'password': 'password'} ...
""" Human-explainable AI. This is the class and function reference of FACET for advanced model selection, inspection, and simulation. """ __version__ = "1.2.0" __logo__ = ( r""" _ ____ _ _ ___ __ ___ _____ _-´ _- / ___\ / \ /\ /\ /\ /\ / \ ...
"""LiveSimulator: This class reads in various Bro IDS logs. The class utilizes the BroLogReader and simply loops over the static bro log file, replaying rows and changing any time stamps Args: eps (int): Events Per Second that the simulator will emit events (default...
from unittest import TestCase from dynamic_fixtures.fixtures.basefixture import BaseFixture class BaseFixtureTestCase(TestCase): def test_load_not_implemented(self): """ Case: load is not implemented Expected: Error get raised """ fixture = BaseFixture("Name", "Module") ...
from empregado import Empregado class Operario(Empregado): def __init__(self, nome, endereco, telefone, codigo_setor, salario_base, imposto, valor_producao, comissao): super().__init__(nome, endereco, telefone, codigo_setor, salario_base, imposto) self._valor_producao = valor_producao self...
import inspect import typing from chia import instrumentation class Factory: name_to_class_mapping: typing.Optional[typing.Dict] = None default_section: typing.Optional[str] = None i_know_that_var_args_are_not_supported = False @classmethod def create(cls, config: dict, observers=(), **kwargs): ...
from useintest.modules.consul.consul import ConsulServiceController, consul_service_controllers, \ Consul1_0_0ServiceController, Consul0_8_4ServiceController, ConsulDockerisedService
import math # S1: A quick brown dog jumps over the lazy fox. # S2: A quick brown fox jumps over the lazy dog. # With the two sentences above I will implement the calculation based on calculation # values. def magnitude(v1): vResult = [abs(a * b) for a, b in zip(v1, v1)] mag = math.sqrt(sum(vResult, 0)) r...
import time import asyncio from typing import List import threading import numpy as np import spotipy from spotipy.oauth2 import SpotifyOAuth from eventhook import EventHook class NotPlayingError(Exception): def __init__(self): self.message = "Spotify not playing" class MonitorConfig: def __init_...
a, b = input().split() print("Yes" if (int(a + b) ** (1 / 2)).is_integer() else "No")
# pip3 install PySocks import socks import socket from urllib import request from urllib.error import URLError socks.set_default_proxy(socks.SOCKS5, '127.0.0.1', 9742) socket.socket = socks.socksocket try: response = request.urlopen('http://httpbin.org/get') print(response.read().decode('utf-8')) except URLE...
import torch from kondo import Spec from torchrl.experiments import BaseExperiment from torchrl.utils.storage import TransitionTupleDataset from torchrl.contrib.controllers import DDPGController class DDPGExperiment(BaseExperiment): def __init__(self, actor_lr=1e-4, critic_lr=1e-3, gamma=0.99, tau=1e...
#!/usr/bin/env python # -*- coding: utf-8 -*- from numap import NuMap def hello_world(element, *args, **kwargs): print "Hello element: %s " % element, print "Hello args: %s" % (args,), print "Hello kwargs: %s" % (kwargs,) return element ELEMENTS = ('element_0', 'element_1', 'element_2', 'element_3', '...
import collections import itertools import json from pathlib import Path import re import sqlite3 import string import attr import nltk import numpy as np def clamp(value, abs_max): value = max(-abs_max, value) value = min(abs_max, value) return value def to_dict_with_sorted_values(d, key=None): re...
# SPDX-FileCopyrightText: 2022 Eva Herrada for Adafruit Industries # SPDX-License-Identifier: MIT import board from kmk.kmk_keyboard import KMKKeyboard as _KMKKeyboard from kmk.matrix import DiodeOrientation class KMKKeyboard(_KMKKeyboard): row_pins = (board.D10, board.MOSI, board.MISO, board.D8) col_pins =...
# -*- coding: utf-8 -*- counter = 100 # An integer assignment miles = 1000.0 # A floating point name = "John" # A string print (counter) print (miles) print (name)
from .tests import _index def main(): suites = _index.suites passes = 0 fails = 0 for s in suites: s.run() print(s) passes += s.passes fails += s.fails print(f'###################\nSUMMARY OF ALL TEST SUITES\nTotal Passing Tests: {passes}\nTotal Failing Tests: {fails...
#!/usr/bin/python # -*- coding: latin-1 -*- import os, subprocess import numpy as np import GenericUsefulScripts as GUS from astropy import units as u from astropy.io import ascii, fits from astropy.convolution import convolve from astropy.stats import SigmaClip from astropy.coordinates import SkyCoord from photutils....
def model_to_dicts(Schema, model): # 如果是分页器返回,需要传入model.items common_schema = Schema(many=True) # 用已继承ma.ModelSchema类的自定制类生成序列化类 output = common_schema.dump(model) # 生成可序列化对象 return output
"""OsservaPrezzi class for aio_osservaprezzi.""" from .const import ENDPOINT, REGIONS from .models import Station from .exceptions import ( RegionNotFoundException, StationsNotFoundException, OsservaPrezziConnectionError, OsservaPrezziException, ) from typing import Any import asyncio import aiohttp im...
import telebot import os TOKEN = os.getenv('TELE_TOKEN') bot = telebot.TeleBot(TOKEN) @bot.message_handler(commands=['start']) def start_message(message): markup = telebot.types.ReplyKeyboardMarkup() # start_btn = telebot.types.KeyboardButton("/start") help_btn = telebot.types.KeyboardButton("/help") ...
# [h] paint and arrange groups '''Paint each group of glyphs in the font with a different color.''' # debug import hTools2 reload(hTools2) if hTools2.DEBUG: import hTools2.modules.color reload(hTools2.modules.color) # import from hTools2.modules.color import paint_groups # run f = CurrentFont() paint_gr...
""" 3->7->5->12->None """ class SinglyListNode(object): def __init__(self, value): self.value = value self.next = None a = SinglyListNode(3) b = SinglyListNode(7) c = SinglyListNode(5) d = SinglyListNode(12) a.next = b b.next = c c.next = d print(a.next) print(b) print(b.next) print(c) d...
from __future__ import absolute_import, unicode_literals import logging from django.core.management.base import BaseCommand from housing_counselor.geocoder import BulkZipCodeGeocoder, GeocodedZipCodeCsv logger = logging.getLogger(__name__) class Command(BaseCommand): help = 'Geocode all possible zipcodes' ...
""" Ejercicio 6 Escriba un programa que pida la fecha segun el formato 04/12/1973 y lo retome segun el formato 1973/12/04 """ from datetime import date from datetime import datetime fecha = str(input("Ingrese una fecha(formato dd/mm/aaaa): ")) fecha1 = datetime.strptime(fecha, "%d/%m/%Y") fecha3 = datetime.strftime(f...
from .registries import Registry, meta_registry, QuerySet, Manager, MultipleObjectsReturned, DoesNotExist __version__ = "0.2.1"
# Copyright 2019 The MACE Authors. 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 applicable la...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Tests for the tag_linux.txt tagging file.""" import unittest from plaso.containers import events from plaso.lib import definitions from plaso.parsers import bash_history from plaso.parsers import docker from plaso.parsers import dpkg from plaso.parsers import selinux ...
__author__ = 'surya' # plot each IntegralInteraction S values and save a plot in the end for the respective plate def plot(file,nslen,slen): import matplotlib.pyplot as plt start=5 list=[] with open(file+"_IntegralIntensity.txt") as files: next(files) for lines in files: s...
from django.db import models from django.utils import timezone from django.utils.translation import ugettext_lazy as _ from django.db.models.signals import post_save from django.dispatch import receiver from django.contrib.postgres import fields as pgfields from django.contrib.auth.models import User # about user # h...
import requests from bs4 import BeautifulSoup #define a founction that get text from a html page def gettext(url, kv=None): try: r = requests.get(url,headers = kv) r.raise_for_status() r.encoding = r.apparent_encoding return r.text except: print("Failure") #defi...
"""\ wxDatePickerCtrl objects @copyright: 2002-2007 Alberto Griggio @copyright: 2014-2016 Carsten Grohmann @copyright: 2016 Dietmar Schwertberger @license: MIT (see LICENSE.txt) - THIS PROGRAM COMES WITH NO WARRANTY """ import wx from edit_windows import ManagedBase, EditStylesMixin from tree import Node import commo...
from util.html import HTML import numpy as np import os import ntpath import time from . import util import matplotlib.pyplot as plt from util.util import load_validation_from_file, smooth_kernel, load_loss_from_file class Visualizer(): """This class includes several functions that can display/save images and prin...
# Copyright 2009-2010 by Ka-Ping Yee # # 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 w...
import pytest import NAME
import os import numpy as np import joblib class proba_model_manager(): def __init__(self, static_data, params={}): if len(params)>0: self.params = params self.test = params['test'] self.test_dir = os.path.join(self.model_dir, 'test_' + str(self.test)) self.istra...
"""Test the cli_data_download tool outputs.""" # TODO review and edit this import argparse from pathlib import Path from cmatools.cli_data_download import cli_data_download from cmatools.definitions import SRC_DIR DEBUG = True """bool: Debugging module-level constant (Default: True).""" # Define cli filepath CLI =...
import sys, json from PIL import Image from parser.png_diff import PNG_DIFF from format.util import * def diff(file_before, file_after): """diff png file args: file_before (str) file_after (str) returns: png_diff (PNG_DIFF) """ png_before = Image.open(file_before) png_...
# -*- coding: utf-8 -*- # Check if the move of v can satisfied, makebetter, or notsatisfied from .FMConstrMgr import FMConstrMgr class FMBiConstrMgr(FMConstrMgr): def select_togo(self): """[summary] Returns: dtype: description """ return 0 if self.diff[0] < self.diff...
from django.shortcuts import get_object_or_404, render from .models import Card, Group, Product def searching(request, keyword): products = Product.objects.filter(title__contains=keyword) return render(request, 'main/catalog.html', {'products': products, 'keyword': keyword}) def index(request): offers =...
# # project-k Forth kernel in python # Use the same kernel code for all applications. # FigTaiwan H.C. Chen hcchen5600@gmail.com 21:14 2017-07-31 # import re, sys name = "peforth" vm = __import__(__name__) major_version = 1; # major version, peforth.py kernel version, integer. ip = 0; stack = [] ; rstack = []; voc...
from wallet import Wallet wallet = Wallet() address = wallet.getnewaddress() print address
from config.settings_base import * ##### EDIT BELOW API_KEY = "Paste your key in between these quotation marks"
from rest_framework import serializers from .models import Homework class HomeworkStudentSerializer(serializers.ModelSerializer): owner = serializers.ReadOnlyField(source='owner.username') course = serializers.ReadOnlyField(source='course.id') lecture = serializers.ReadOnlyField(source='lecture.id') g...
#!/usr/bin/env python ''' Copyright (C) 2019, WAFW00F Developers. See the LICENSE file for copying permission. ''' NAME = 'Open-Resty Lua Nginx (FLOSS)' def is_waf(self): schema1 = [ self.matchHeader(('Server', r'^openresty/[0-9\.]+?')), self.matchStatus(403) ] schema2 = [ self.ma...
from pypy.rlib import _rffi_stacklet as _c from pypy.rlib import objectmodel, debug from pypy.rpython.annlowlevel import llhelper from pypy.tool.staticmethods import StaticMethods class StackletGcRootFinder: __metaclass__ = StaticMethods def new(thrd, callback, arg): h = _c.new(thrd._thrd, llhelper(_...
# coding: utf-8 from __future__ import unicode_literals import re from django import forms from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage from django.utils.encoding import iri_to_uri, smart_text try: from urllib.parse import urljoin except ImportError: from urlparse import urljoin _...
from typing import List import torch import numpy as np # details about math operation in torch can be found in: http://pytorch.org/docs/torch.html#math-operations # convert numpy to tensor or vise versa np_data = np.arange(6).reshape((2, 3)) # reshape 重塑 把1X6矩阵变为2X3矩阵 # numpy.arange([start=0, ]stop, [step=1, ]dtype...
# --- # jupyter: # jupytext: # formats: ipynb,py # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.9.1+dev # kernelspec: # display_name: Python [conda env:core_acc_env] * # language: python # name: conda-env-core_ac...
from rest_framework import viewsets, filters, status from rest_framework.authentication import TokenAuthentication from rest_framework.authtoken.views import ObtainAuthToken from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from rest_framework.settings import api_settin...
import json, yaml import logging DEBUG =0 logger = logging.getLogger() if DEBUG: #coloredlogs.install(level='DEBUG') logger.setLevel(logging.DEBUG) else: #coloredlogs.install(level='INFO') logger.setLevel(logging.INFO) strhdlr = logging.StreamHandler() logger.addHandler(strhdlr) formatter = logging.F...
#!/usr/bin/env python3 """ Makes Maven multi module project. """ from argparse import ArgumentParser from os import makedirs from os.path import realpath, relpath, dirname, normpath from sys import argv import vang.maven.pom as pom POM_TEMPLATE = """<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xs...
from sparkpost import SparkPost sp = SparkPost() response = sp.templates.update( 'TEST_ID', name='Test Template', from_email='test@test.com', subject='Updated Test email template!', html='<b>This is a test email template! Updated!</b>' ) print(response)
# Copyright 2013 - Noorul Islam K M # # 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 w...
import json import logging import os import boto3 from get_and_parse_hiscores.lib.hiscores import rs_api logger = logging.getLogger() logger.setLevel(logging.DEBUG) ddb = boto3.resource("dynamodb") table = ddb.Table(os.environ["HISCORES_TABLE_NAME"]) def handler(event, context): """Call HiScores API, parse res...
import sys import copy import math def extra(): fp = open("23.input") nums = list(map(int, fp.readline())) next_nums = {} for i in range(len(nums) - 1): next_nums[nums[i]] = nums[i + 1] MAX_VAL = 1_000_000 next_nums[nums[-1]] = 10 for i in range(10, MAX_VAL): next_nums[i] ...
# coding=utf-8 """ Common methods for UI code. """ from __future__ import absolute_import from datacube.utils import is_supported_document_type def get_metadata_path(dataset_path): """ Find a metadata path for a given input/dataset path. :type dataset_path: pathlib.Path :rtype: Path """ # T...
import sys import json import collections MEM_TOKEN_SIZE = 4 def build_vocab(tokens, vocab_count): token_list = tokens.split() for tok in token_list: if tok in vocab_count.keys(): vocab_count[tok] += 1 else: vocab_count[tok] = 1 def process_one_conversation(text, voc...
import os, wifisec, platform from speedtest import SpeedTest from hku import fetch_heroku from rich import print from rich.table import Table def display(): plat = platform.system() global clear if plat == "Linux": clear = lambda: os.system('clear') elif plat == "Windows": clear = lambd...
from scripttease.library.commands.base import Command, ItemizedCommand, Sudo from scripttease.library.overlays.common import python_pip class TestCommand(object): def test_getattr(self): c = Command("ls -ls", extra=True) assert c.extra is True def test_get_statement(self): c = Comman...
from AtomicContributions.ContributionsOfAtomsToModes import AtomicContributionsCalculator import unittest import numpy as np import os path_here = os.path.dirname(__file__) class AtomicContributionToModesTest(unittest.TestCase): def setUp(self): self.Contributions = AtomicContributionsCalcula...
from typing import Type from serflag import SerFlag from handlers.graphql.utils.query import resolve_from_root def resolve_myactions(actions_type: Type[SerFlag]): def resolver(root, info, **args): actions = resolve_from_root(root, info) if not actions: return [] return actio...
#!/usr/bin/python3 import math import pygame import random import sys from pygame import K_d, K_a, K_w, K_s, K_SPACE SIZE = WIDTH, HEIGHT = 500, 500 BLACK = 0, 0, 0 WHITE = 255, 255, 255 SHIP_W = 12 SHIP_H = 25 MAX_SPEED = 3 ASTEROID_LIMIT = 2 class Game_Space: """Initiates and holds all variables needed for t...
import logging import os.path from os import getenv import telegram.ext from dotenv import load_dotenv from telegram.ext import Updater, CommandHandler, MessageHandler from telegram.ext.filters import Filters from bot.commands import hello_cmd, echo_cmd, pin_message_cmd, slap_cmd, me_cmd, \ unknown_command_cmd, s...
from pyHS100 import Discover for dev in Discover.discover().values(): print(dev) print("host:" + dev.host)
from collections import namedtuple Meta= namedtuple('Meta', ('long_name', 'units', 'comment')) Meta.__new__.__defaults__ = (None,) * len(Meta._fields) METADATA = { 'FileCode': Meta( long_name='file_code'), 'HeaderLen': Meta( long_name='header_length', units='bytes'), 'StartTime': M...
# Generated by Django 2.2.6 on 2019-10-12 18:48 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('fashion_catalogue', '0001_initial'), ] operations = [ migrations.RemoveField( model_name='category', name='color', )...
# eqcmd.py: Basic routines for interfacing with EQ. import asyncio from asyncio.subprocess import create_subprocess_shell, PIPE import eqlog import os import re import shlex import random class CommandError(Exception): """A problem running a command""" pass class NotReadyError(Exception): """EverQuest ...
# Generated by Django 2.0.5 on 2018-08-03 11:05 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('surveys', '0005_answer_training_set'), ] operations = [ migrations.CreateModel( name='Translate_Hired_Power', fields...
# Copyright 2021 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, ...
import numpy as np import tensorflow as tf import time import keras def KL_generated_images(dec, cla, N, dimZ, task, sample_W = True): z = tf.random_normal(shape=(N, dimZ)) x_gen = dec(z, sampling = sample_W) y_gen = tf.clip_by_value(cla(x_gen), 1e-9, 1.0) y_true = np.zeros([N, 10]); y_true[:, task] = ...
#!/usr/bin/python # Written By: Sahar Hathiramani # Date: 01/07/2021 import os import socket from termcolor import colored os.system("clear") print("🄱🄰🄳 🄱🄾🅈 🄱🅄🅃 🄰 🅂🄰🄳 🄱🄾🅈") sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) socket.setdefaulttimeout(2) host = input("[*] Please Specify a Host to ...
import gzip import warnings from pkg_resources import resource_stream, resource_filename import numpy as np import matplotlib.image as mpimg from os.path import dirname, join def load_hill_topography(): """ Load hillshading and return elevation :return: np.array """ stream = resource_stream(__name...