content
stringlengths
5
1.05M
# ----------------------------------------------------------------------------- # @author: # Tingwu Wang # @brief: # The environment wrapper for the depth environment of roboschool # ----------------------------------------------------------------------------- from mbbl.config import init_path from mbb...
import numpy as np import utils_driving as utils import theano as th import theano.tensor as tt from trajectory import Trajectory import feature class Car(object): def __init__(self, dyn, x0, color='yellow', T=5): self.data0 = {'x0': x0} self.bounds = [(-1., 1.), (-1., 1.)] self.T = T ...
from django.contrib import admin from .models import Event, Contact, EventImage # Register your models here. class EventImageInline(admin.TabularInline): model = EventImage extra = 3 class EventAdmin(admin.ModelAdmin): inlines = [ EventImageInline, ] admin.site.register(Event, EventAdmin) admin.site.regi...
"""Trainer Class""" from pathlib import Path from tqdm import tqdm import torch import torch.nn as nn from tensorboardX import SummaryWriter from utils.logger import get_logger LOG = get_logger(__name__) class Trainer: def __init__(self, **kwargs): self.device = kwargs['device'] self.model = kw...
# Copyright 2020 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
''' *********************************************************************************************************************** * Main process file solar estimation tool * * Created by P.Nezval ...
from genericpath import isfile import unittest from moonboard import MoonBoard, get_moonboard # class BaseAPITestClass(unittest.TestCase): # """ # BaseClass for testing # """ # def setUp(self): # """ # Set up method that will run before every test # """ # pass # de...
import logging import concurrent.futures from EOSS.critic.critic import Critic from EOSS.models import EOSSContext logger = logging.getLogger('EOSS.critic') def general_call(design_id, designs, session_key, context): eosscontext = EOSSContext.objects.get(id=context["screen"]["id"]) critic = Critic(eossconte...
# # PySNMP MIB module CXACTE-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CXACTE-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 18:16:28 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:...
def extractWwwSigmanovelCom(item): ''' Parser for 'www.sigmanovel.com' ''' if 'Teasers' in item['tags']: return None vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or "preview" in item['title'].lower(): return None tagmap = [ ('Martial God Conquerer', ...
#!/usr/bin/env python """igcollect - Redis Keys Copyright (c) 2017 InnoGames GmbH """ import redis from argparse import ArgumentParser from subprocess import Popen, PIPE from time import time def parse_args(): parser = ArgumentParser() parser.add_argument('--prefix', default='redis') parser.add_argument...
from __future__ import print_function from burlap import Satchel from burlap.constants import * from burlap.decorators import task #http://askubuntu.com/a/555366/13217 class VirtualboxSatchel(Satchel): name = 'virtualbox' @task(precursors=['packager']) def configure(self): """ Enables th...
import os import signal class SignalHandler(object): """Class to detect OS signals e.g. detect when CTRL+C is pressed and issue a callback """ def __init__(self, sig=signal.SIGINT, callback=None, resignal_on_exit=False): self.sig = sig self.interrupted = False self.release...
from django.views.generic import ListView from django.shortcuts import render from django.http import HttpResponse from blog.views import CommonViewMinxin from .models import Link class LinkListView(CommonViewMinxin, ListView): queryset = Link.objects.filter(status=Link.STATUS_NORMAL) template_name = 'config/links...
from typing import List import probflow.utils.ops as O from probflow.distributions import Normal from probflow.models import ContinuousModel from probflow.modules import DenseNetwork from probflow.parameters import ScaleParameter from probflow.utils.casting import to_tensor class DenseRegression(ContinuousModel): ...
import pytest from houston.configuration import Configuration, option def test_option_construction(): class X(Configuration): foo = option(int) assert set(o.name for o in X.options) == {'foo'} def test_constructor(): class X(Configuration): foo = option(int) conf = X(foo=0) ass...
from enum import Enum from eth_utils import int_to_big_endian from raidex.raidex_node.architecture.event_architecture import dispatch_events from raidex.utils import pex from raidex.utils.timestamp import to_str_repr, time_plus from raidex.utils.random import create_random_32_bytes_id from raidex.raidex_node.commit...
from __future__ import absolute_import, with_statement import sys import os from gevent.hub import get_hub from gevent.socket import EBADF from gevent.os import _read, _write, ignored_errors from gevent.lock import Semaphore, DummySemaphore try: from fcntl import fcntl, F_SETFL except ImportError: fcntl = Non...
import urllib.request import time def check_website(website, timeout=30): startTime = time.time() while time.time() - startTime <= timeout: try: print(urllib.request.urlopen(website).getcode()) return True except: pass return False if __name__ == "__ma...
from rest_framework import serializers from lotus_dashboard.models import * class DashboardColumnSerializer(serializers.ModelSerializer): class Meta: model = DashboardColumn fields = ('id', 'site', 'columns') class CapUpdateResultSerializer(serializers.ModelSerializer): class Meta: m...
""" Given a logfile, plot a graph """ import json import argparse from collections import defaultdict import matplotlib.pyplot as plt import numpy as np plt.switch_backend('agg') def plot_value(logfile, min_y, max_y, title, max_x, value_key, out_file): epoch = [] reward = [] with open(logfile, 'r') as ...
#!/usr/bin/env python import OpenImageIO as oiio # Print the contents of an ImageSpec def print_imagespec (spec, subimage=0, mip=0, msg="") : if msg != "" : print str(msg) if spec.depth <= 1 : print (" resolution %dx%d%+d%+d" % (spec.width, spec.height, spec.x, spec.y)) else : p...
from unittest import TestCase from phi import math, geom from phi.geom import Box, Sphere from phi.math import batch, channel, spatial class TestGeom(TestCase): def test_box_constructor(self): box = Box(0, (1, 1)) math.assert_close(box.size, 1) self.assertEqual(math.spatial(x=1, y=1), bo...
import numpy as np import msgpack def toCameraCoord(pose_mat): """ Convert the pose of lidar coordinate to camera coordinate """ R_C2L = np.array([[0, 0, 1, 0], [-1, 0, 0, 0], [0, -1, 0, 0], [0, 0, 0, 1]]) inv_R_C2L = np.linalg.i...
from contextlib import contextmanager from urllib.parse import urlparse import psycopg2 import psycopg2.extras from psycopg2.pool import ThreadedConnectionPool POOL = None def setup(url): global POOL u = urlparse(url) POOL = ThreadedConnectionPool(1, 20, database=u.path...
#String Building algorithm for the Overwatch Workshop # #Heavily inspired by Deltins ParseString algorithm #https://github.com/ItsDeltin/Overwatch-Script-To-Workshop/blob/91f6d89cae2dda77d40139a589c22077def7654f/Deltinteger/Deltinteger/Elements/Values.cs#L729 #Parts copied are used with permission. import logging impo...
import math import re from KlasaDecyzyjna import KlasaDecyzyjna def unique(list1): unique_list = [] for x in list1: if x not in unique_list: unique_list.append(x) return unique_list class SystemDecyzyjny: NUMBER_OF_ATTRIBUTES = 15 def printFile(self): f = open(self) ...
import base64 import dash_html_components as html def get_banner(): banner = html.Div( id='app-page-header', children=[ html.A( id='dashbio-logo', children=[ html.Img( src="./assets/MarianneLogo-3-90x57.png" ...
from rs4 import asyncore import socket class WhoisRequest(asyncore.dispatcher_with_send): # simple whois requestor def __init__(self, consumer, query, host, port=43): asyncore.dispatcher_with_send.__init__(self) self.consumer = consumer self.query = query self.create_socket(s...
import numpy import os def readrcp(rcpfile): # tab depth used for dictionary nesting def getKeyDepth(key): counter = (len(key) - len(key.lstrip())) / 4 return counter f = open(rcpfile, "rU") rcp = f.readlines() f.close() # make d[k, v] from lines of 'k: v', recurse function c...
import sys from .board import GameBoard def main(size, win): game = GameBoard(size, win) actions = {'l': game.shift_left, 'r': game.shift_right, 'u': game.shift_up, 'd': game.shift_down, 'undo': game.undo, 'exit': None} stop = Fals...
# domain to company by hand import json import string import clearbit from pprint import pprint with open('companies.json') as company_dump: companies = json.load(company_dump) # with open('baddata.txt') as baddata: # dirtyComp = baddata.readlines() # i =0 # for comp in dirtyComp: # i=i+1 # if (i%3 ==0): # ...
import logging import json from PyQt5.QtCore import Qt, QAbstractTableModel, QVariant class Model(QAbstractTableModel): def __init__(self, parent): QAbstractTableModel.__init__(self) self.gui = parent self.colLabels = ['Title', 'Video', 'Audio', 'Progress', 'URL'] self._data = [] ...
''' MobileHairNet models ''' from .hairnet import MobileHairNet
import os import time import grpc from formant.protos.agent.v1 import agent_pb2_grpc from formant.protos.model.v1 import datapoint_pb2, file_pb2 path = os.path.dirname(os.path.realpath(__file__)) channel = grpc.insecure_channel("localhost:5501") agent = agent_pb2_grpc.AgentStub(channel) file_datapoint = file_pb2.Fi...
from __future__ import annotations from typing import List, Any, Dict, Optional, Type from .base import IonSerializer class IonBoolSerializer(IonSerializer): """ Serializes bool values as ``flagcontent`` """ def __init__(self, name: str, data: bool, **kwargs) -> None: super().__init__(name, ...
class Disjoint: def __init__(self): self.parent=None self.rank=0 self.element=None self.e=[] class Set: def __init__(self): #self.repre=Disjoint() self.repre=None def makset(self,x,data): self.repre=x x.parent=x x.rank=0 x.eleme...
from setuptools import setup, find_packages setup( name='pytorch_h5dataset', version='0.2.4', packages=find_packages(), url='https://github.com/CeadeS/PyTorchH5Dataset', license='BSD-3-Clause License', author='Martin Hofmann', author_email='[email protected]', description='Ac...
# mailstat.metric.counts # Performs counting statistics of emails. # # Author: Benjamin Bengfort <[email protected]> # Created: timestamp # # Copyright (C) 2013 Bengfort.com # For license information, see LICENSE.txt # # ID: counts.py [] [email protected] $ """ Performs counting statistics of emails. """ #...
from typing import Union import numpy as np import tensorflow.keras as keras from numpy import ndarray from pandas import DataFrame from .model_helpers import make_tensorboard_callback, make_save_path from ..utils import naming class SimpleModel: def __init__(self, directory_name: str, n_input: int, n_output: i...
class Trampoline() : called = False def __init__(self, func) : self.func = func def __get__(self, obj, objtype) : if not hasattr(self.func, '__self__') : self.func.__self__ = obj return self.__call__ def __call__(self, *args, **kwargs) : r = (self.func, [self.func.__s...
for i in range(1,int(input())+1): if i%2!=0:print(i)
from code.render.glfunctions import draw_rect, draw_rounded_rect from code.constants.common import HACK_PANEL_WIDTH, HACK_PANEL_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT, INPUT_SELECTION_LEFT, INPUT_SELECTION_RIGHT, INPUT_SELECTION_UP, INPUT_SELECTION_DOWN, INPUT_SELECTION_ACTIVATE, HACK_PANEL_TEMPORARY_STATUS_DURATION fro...
# -*- coding: utf-8 -*- # @File : geoip.py # @Date : 2021/2/25 # @Desc : import os import geoip2.database from django.conf import settings from Lib.log import logger from Lib.xcache import Xcache class Geoip(object): def __init__(self): pass @staticmethod def get_city(ip): result = ...
# Licensed under a 3-clause BSD style license - see LICENSE.rst """Test `astropy.utils.timer`. .. note:: The tests only compare rough estimates as performance is machine-dependent. """ from __future__ import (absolute_import, division, print_function, unicode_literals) # STDLIB impor...
# -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # (C) British Crown Copyright 2017-2020 Met Office. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions a...
import ptf from ptf.base_tests import BaseTest from ptf.mask import Mask from ptf import config import ptf.testutils as testutils class DataplaneBaseTest(BaseTest): def __init__(self): BaseTest.__init__(self) def setUp(self): self.dataplane = ptf.dataplane_instance self.dataplane.flush...
#!/usr/bin/env python3 import lib N=1_000_000 MX=1000 def partition2(n): """ Coin partitions. Let partition(n) represent the number of different ways in which n coins can be separated into piles. For example, five coins can be separated into piles in exactly seven different ways, so partition(5)=7. """ # dyna...
# imports import matplotlib.pyplot as plt import numpy as np import os # load log files files = [os.path.join('log', file) for file in os.listdir('./log/') if file.endswith('.bin')] files = [file for file in files if os.path.isfile(file)] linestyles = ['-', '--', '-.'] colorwheel = ['r', 'g', 'b', 'k'] # lo...
from django.shortcuts import render from django.http import HttpResponse import subprocess import re import random import string import time import os ''' For this code to work: 1) The user running the web server (www-data) must be in the group lp. 2) The command scanimage -L must be available. ''' # Constants SCAN...
import pytest from py_cdk_utils import DeployEnv, get_config test_default = "default" test_overrides = {DeployEnv.DEV: "dev val", DeployEnv.LOCAL: "local val"} def test_no_args(): with pytest.raises(TypeError): get_config() def test_default_value(): with pytest.raises(TypeError): get_config...
import pandas as pd import gspread import os import requests from oauth2client.service_account import ServiceAccountCredentials def connect_to_twitter(): bearer_token = os.environ.get("BEARER_TOKEN") return {"Authorization": "Bearer {}".format(bearer_token)} def make_request(headers): url = "https://ap...
import numpy as np import xarray as xr import pandas as pd from xgcm import Grid WRF_NEW_DIMS = {'south_north': 'y_c', 'south_north_stag': 'y_g', 'west_east': 'x_c', 'west_east_stag': 'x_g'} WRF_NEW_COORDS = {'XLONG_M': 'lon_T', 'XLAT_M': 'lat_T', 'XLONG_U': 'lon_U', 'XLAT_U': 'lat_U...
from .admin_controller import AdminController, add_admin_handler __all__ = ['AdminController', 'add_admin_handler']
''' python3 + numpy routine to calculate magnetic curvature from MMS data. Uses pyspedas for MMS data file loading ***************************************************************************** Example script for loading required data and calculating the curvature vector: import time import re import numpy as np ...
# This sample tests the check for non-overlapping types compared # with equals comparison. from typing import Literal, TypeVar, Union OS = Literal["Linux", "Darwin", "Windows"] def func1(os: OS, val: Literal[1, "linux"]): if os == "Linux": return True # This should generate an error because there ...
from functools import partial from logging import getLogger from multiprocessing import Pool from typing import Any, Callable, Dict, Optional, Set, Tuple from ordered_set import OrderedSet from tqdm import tqdm from sentence2pronunciation.core import (get_words_from_sentence, get_words_from_sentences, is_annotation, ...
# NOTE: All sets default for development DJANGO_ENV = "development" PG_DEFAULT_DB_NAME = "jc_developer" PG_DEFAULT_DB_HOST = "localhost" PG_DEFAULT_DB_PORT = "5432" PG_DEFAULT_DB_USER = "jc_developer" PG_DEFAULT_DB_PASS = "jc_developer" MONGO_DEFAULT_DB_NAME = "suandao" MONGO_DEFAULT_DB_PORT = 27017 MONGO_DEFAULT_DB_...
from integraisGaussLegendre import iterar import math a = 0 b = 5 e = 10**-6 f1 = lambda x: (math.log(2*x) * math.cos(4*x)) # f1 = lambda x: (2*x)**3 #Resposta 2 # f2 = lambda x: math.cos(4*x) #Resposta -0.1892006 # f3 = lambda x: (math.sin(2*x) + 4*(x**2) + 3*x)**2 #Resposta 17.8764703 # f4 = lambda x: ...
# -*- coding: utf-8 -*- # Generated by Django 1.10.2 on 2016-10-18 10:03 from __future__ import unicode_literals import shoptools.abstractions.models import shoptools.util import datetime from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrat...
import math N, K = map(int, input().split()) girls, boys = [], [] while N: S, Y = map(int, input().split()) if S == 0: girls.append(Y) else: boys.append(Y) N -= 1 count = 0 girls = sorted(girls) boys = sorted(boys) for i in range(6): count += math.ceil(girls.count(i+1)/K) count ...
import pythoncom import pyHook from os import path from time import sleep from threading import Thread import urllib, urllib2 import datetime import win32com.client import win32event, win32api, winerror from _winreg import * import shutil import sys import base64 import requests ironm = win32event.CreateMutex(None, 1,...
from enum import Enum class Action(Enum): """Class for enumerations of agent actions.""" UP = (-1, 0) DOWN = (1, 0) LEFT = (0, -1) RIGHT = (0, 1)
from math import inf from typing import Dict, List, Tuple, Optional from .calculate_score import ( calculate_score, calculate_complexity_adjusted_score, ) from .matrices import AlignMatrix from .performance import timeit @timeit() def fill_align_matrix( lambda_values: List[float], column_count: int, ...
from __future__ import print_function, division import sys import gdal import png import numpy as np import matplotlib.pyplot as pl def write_png(z, name): # Use pypng to write z as a color PNG. with open(name, 'wb') as f: writer = png.Writer(width=z.shape[1], height=z.shape[0], bitdepth=16) ...
import platform from wordcloud import WordCloud import matplotlib as mpl def add_args(parser): return parser.parse_args() def run(db, args): if platform.system() == "Darwin": mpl.use("TkAgg") import matplotlib.pyplot as plt title = "Top reused passwords for {}".format(args.domain) pas...
from datetime import datetime import pandas as pd import fxsignal import fxcmpy import yaml import logging logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)-8s %(message)s', handlers=[logging.FileHandler("./logs/algo.log"), logging.StreamHandler()]) #major...
import os,json from ehive.runnable.IGFBaseProcess import IGFBaseProcess from igf_data.utils.tools.bwa_utils import BWA_util from igf_data.utils.fileutils import get_datestamp_label from igf_data.utils.tools.reference_genome_utils import Reference_genome_utils class RunBWA(IGFBaseProcess): def param_defaults(self): ...
# Copyright 2013-2018 Adam Karpierz # Licensed under the Apache License, Version 2.0 # http://www.apache.org/licenses/LICENSE-2.0 # <AK> added # from __future__ import absolute_import import jpype from . import common class DirectBufferTestCase(common.JPypeTestCase): DATA_SIZE = 5 * 1024 * 1024 # 5 MB @c...
# Generated by Django 3.2.11 on 2022-01-25 09:48 import django.core.validators from django.db import migrations, models import main.models class Migration(migrations.Migration): dependencies = [ ("main", "0062_alter_resourcingrequest_is_ir35"), ] operations = [ migrations.AlterField( ...
#!/usr/bin/python # coding: utf8 import logging import os import json from flask import Blueprint, Response, Markup, render_template_string, send_file, make_response from flask import current_app, _app_ctx_stack logger = logging.getLogger(__name__) echarts_bp = Blueprint("echarts", __name__, url_prefix=...
from pathlib import Path from collections import OrderedDict import torch import torch.nn as nn from torch import optim from torch.nn import init import torch.nn.functional as F from torch.nn.parallel import DistributedDataParallel class FoldModel(nn.Module): def __init__(self, models): super(FoldModel,...
# クラス定義 # 2年生向け # # 課題 https://colab.research.google.com/drive/13An5bAh5Kg1TEg7jUoP0pHtoYdcXmidv?usp=sharing # !git clone https://github.com/kkuramitsu/tatoeba.git # import tatoeba.vec from Vec import math class Vec(object): x: float y: float def __init__(self, x, y): self.x = x self.y ...
SERVER_URL = "http://172.16.239.141:8080" BOT_ID = "" DEBUG = False IDLE_TIME = 120 REQUEST_INTERVAL = 10 PAUSE_AT_START = 1 AUTO_PERSIST = False
#!/usr/bin/env python #Module for IO functionality that is relatively general. The functions in #this module are tested versions of ioutilst.py in sntools. #R. Biswas, Thu Jan 30 19:42:19 CST 2014 #HISTORY: #Copied loadfile2array from ioutilst in sntools without further checking. #R. Biswas, Sat May 10 18:57:23 CDT 2...
"""2017 - Day 11 Part 2: Hex Edh test.""" from src.year2017.day11b import solve def test_solve(): assert solve("n,n,n,s") == 3
import re import os import config def clear_screen(): os.system('cls' if config.OS == 'Windows' else 'clear') def emoji_dealer(d): regex = re.compile('^(.*?)(?:<span class="emoji (.*?)"></span>(.*?))+$') match = re.findall(regex, d['NickName']) if len(match) > 0: d['NickName'] = ''.join(matc...
# 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 # distributed under the Li...
from templates.Templates import Template
from setuptools import setup with open('requirements.txt') as f: required = f.read().splitlines() setup( name = 'AirLibre', py_modules = ['AirLibre'], install_requires = required, version = '0.0.2', description = 'UBNT Config API', author = 'Nathan Shimp', author_email = 'johnnshimp@gm...
from rotkehlchen.assets.asset import Asset, EthereumToken from rotkehlchen.constants.misc import ZERO from rotkehlchen.fval import FVal from rotkehlchen.tests.utils.rotkehlchen import BalancesTestSetup from rotkehlchen.utils.misc import from_wei, satoshis_to_btc def get_asset_balance_total(asset_symbol: str, setup: B...
from django.test import TestCase # Create your tests here. from .models import Profile,Neighbourhood,Post from django.contrib.auth.models import User import datetime as dt class ProfileTestClass(TestCase): ''' images test method ''' def setUp(self): self.user = User.objects.create(id =1,userna...
""" Plugin for OpenStack compute / Rackspace cloud server mock. """ from mimic.rest.nova_api import NovaApi nova = NovaApi()
import pytest import smartsheet @pytest.mark.usefixtures("smart_setup") class TestZSearch: """Sometimes these pass, sometimes they don't. As the documentation says, items recently created may not be searchable right away. So, we test for successful request, successful creation of SearchResult objec...
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
from __future__ import unicode_literals __version__ = '2021.11.29'
from cc3d import CompuCellSetup from .diffusion_2D_steppables_player import ExtraFieldVisualizationSteppable CompuCellSetup.register_steppable(steppable=ExtraFieldVisualizationSteppable(frequency=10)) CompuCellSetup.run()
#!/usr/bin/env python import Tkinter as Tk root=Tk.Tk() root.title(u"winfo") def f_btn(): print("width=%d height=%d" % (root.winfo_width(), root.winfo_height())) btn=Tk.Button(root, text="window size", width=30) btn.pack() btn["command"]=f_btn root.mainloop()
# -*- coding: utf-8 -*- # Copyright 2013 Pierre de Buyl # Copyright 2013 Konrad Hinsen # # This file is part of pyh5md # # pyh5md is free software and is licensed under the modified BSD license (see # LICENSE file). # This file is based on code from the h5py project. The complete h5py license is # available at license...
import errno import os import re import sys from ipaddress import IPv4Address, AddressValueError from itertools import groupby from pathlib import Path from string import Template from typing import Callable, List, Union, Any, Dict import click import pytoml from click._compat import term_len from click.formatting imp...
def findThreeLargestNumbers(array): # Write your code here. numList = [None, None, None] for i in array: compareThreeLargest(i, numList) return numList def compareThreeLargest(num, numList): if numList[2] is None or num > numList[2]: updateList(num, 2, numList) elif numList[1] is None or num > numList[1]:...
# 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, ...
def say_hello(): print("Hello World!") def say_hello_with_name(name): print(f"Hello {name}!")
from funcoes import Funções import os class Personagem: def __init__(self, nome, altura, atributo): self.nome = nome self.altura = altura self.atributo = atributo def escolhaAtributo(self): func = Funções(genero='') if self.atributo == 'Força': # tecla.play...
# -*- coding: utf-8 -*- import re import numpy as np from math import factorial as fac def numgrab(string, delim=' '): """Find the numerical values in a string """ strspl = re.split(delim, string) numlist = [] for s in strspl: try: numlist.append(float(s)) except: ...
import glob import os import pickle import numpy as np import seaborn as sns from tqdm import tqdm from matplotlib import pyplot as plt # Get all event* runs from logging_dir subdirectories logging_dir = './storage/' plot_dir = './plots' clrs = sns.color_palette("husl", 5) if not os.path.isdir(plot_dir): os.mkdir(...
""" MIT License Copyright (c) 2021 Thomas Leong 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, publish, ...
import string import random from django.conf import settings SHORTCODE_MIN = getattr(settings,"SHORTCODE_MIN",6) def code_generator(size = SHORTCODE_MIN, chars=string.ascii_lowercase + string.digits): new_code = '' for _ in range(size): new_code += random.choice(chars) return new_code # or we simply...
import json import time import requests # TODO use only until python lib supports ILM from requests.auth import HTTPBasicAuth # TODO use only until python lib supports ILM def _put_towers_mapping(es): if not es.indices.exists('towers'): with open('./utilities/config/cell_mapping.json', 'r') as f: ...
# -*- coding: utf-8 -*- import numpy as np #--------------------------------------------------- class RateDecay(object): '''Basic class for different types of rate decay, e.g., teach forcing ratio, gumbel temperature, KL annealing. ''' def __init__(self, burn_down_steps, decay_steps, limit_...