content
stringlengths
5
1.05M
''' Created on 29.07.2015 @author: marscher ''' from __future__ import absolute_import import unittest from time import sleep import sys if sys.version_info[0] == 3: from io import StringIO else: from cStringIO import StringIO from progress_reporter import ProgressReporter, ProgressReporter_ class TestPr...
import pygame, Sudoku_IO def solve(snapshot, screen): pygame.time.delay(20) Sudoku_IO.displayPuzzle(snapshot, screen) pygame.display.flip() if isComplete(snapshot): # tests if tree is complete (base case) return True else: clone = snapshot.clone() unsolved = clone.unsolvedC...
'''various utility functions''' import os import stat import sys import platform import multiprocessing import re from packages import yaml host_platforms = { 'Darwin': 'macos', 'Linux': 'linux', 'Windows': 'windows', } python_version = sys.version_info[:3] #---------------------------------------...
# Copyright 2018 BLEMUNDSBURY AI LIMITED # # 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 ...
import gym from gym import spaces from typing import Tuple, Optional import numpy as np import pandas as pd from definitions import ROOT_DIR from scipy.special import softmax class CookieJarsEnv(gym.Env): def __init__( self, split: str, initial_plate: float = 1e6, penalty_factor:...
import copy import errno import inspect import numpy as np import os import sys import torch import pdb class LoggerOutput(object): def __init__(self, fpath=None): self.console = sys.stdout self.file = None if fpath is not None: self.mkdir_if_missing(os.path.dirname(fpath)) ...
# # Example file conditional statements # def main(): x, y = 100, 100 # conditional flow uses if, elif, else if (x < y): st = "x is less than y" elif(x > y): st = "x is greater than y" else: st = "x is the same as y" print (st) # NOTE: No switch statement # c...
# This file is part of the Reproducible Open Benchmarks for Data Analysis # Platform (ROB). # # Copyright (C) 2019 NYU. # # ROB is free software; you can redistribute it and/or modify it under the # terms of the MIT License; see LICENSE file for more details. """Constants and methods to serialize 'Hypermedia As The En...
from panda3d.core import * from direct.showbase.ShowBase import ShowBase from direct.task import Task from PIL import Image from Geometry import normalizer import numpy as np # first time I'm using that crappy lib for game dev import sys # this is a tutorial, and a test at the same time # tuple(L[:1])+TupleSum([(L[x]...
from .stwno_constants import Canteen from .csv_converters import UnknownIngredientException,\ UnknownMealTypeException,\ UnknownNutritionTypeException,\ NoValidDateStringException,\ StwnoFoodIngredient from .stwno_canteen import getMenu,\ StwnoCanteenPricing,\ Dish if __name__ == '__main__': ...
# a basic class for fetching random data class SampleData: def __init__(self): self.names = ['Kitchen','Animal','State', 'Tastey', 'Big','City','Fish', 'Pizza','Goat', 'Salty','Sandwich','Lazy', 'Fun'] self.company_type = ['LLC','Inc','Company','Corporation'] self.company_cuisine = ['Piz...
STATS = [ { "num_node_expansions": 1531, "plan_cost": 215, "plan_length": 215, "search_time": 19.6092, "total_time": 23.3822 }, { "num_node_expansions": 2139, "plan_cost": 221, "plan_length": 221, "search_time": 6.10347, "total_...
# Generated by Django 2.2.26 on 2022-01-26 11:14 import django.db.models.deletion from django.db import migrations, models import waldur_core.core.fields import waldur_core.core.models import waldur_core.core.validators class Migration(migrations.Migration): dependencies = [ ('structure', '0026_project...
# Тип данных СЛОВРИ (dict) # Инициализация dict_temp = {} print(type(dict_temp), dict_temp) dict_temp = {'dict1' : 1, 'dict2' : 2.1, 'dict3': 'name', 'dict4':[1,2,3]} print(type(dict_temp), dict_temp) dict_temp = dict.fromkeys(['a', 'b'], [12, 2020]) print(type(dict_temp), dict_temp) dict_temp = dict(brend = 'vol...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # SPDX-License-Identifier: Apache-2.0 # Copyright (c) 2020 LG Electronics from codecs import open from setuptools import setup, find_packages with open('README.md', 'r', 'utf-8') as f: reamdme = f.read() with open('requirements.txt', 'r', 'utf-8') as f: require...
# -*- coding: utf-8 -*- import scrapy class YahooFinanceSpider(scrapy.Spider): filename="yahoo_finance_text" name = 'yahoo_finance' allowed_domains = ['finance.yahoo.com'] start_urls = ['https://finance.yahoo.com/sector/ms_technology'] def parse(self, response): company_name_list = respon...
from datetime import datetime, date, timedelta from xml.sax.saxutils import escape from bs4 import BeautifulSoup import requests import pytz EPG_XML = '' EPG_URL = 'https://www.antennaeurope.gr/el/tvguide.html' TIMEZONE = datetime.now(pytz.timezone('Europe/Athens')).strftime('%z') CHANNEL = 'ant1eu.ant1europe.eu' ...
from .actor_critic import OffPolicyActorCritic, OnPolicyActorCritic from .q_learning import QLearning
from requre.online_replacing import record_requests_for_all_methods from tests.integration.pagure.base import PagureTests from ogr.abstract import PRStatus, CommitStatus @record_requests_for_all_methods() class PullRequests(PagureTests): def test_pr_create_from_fork(self): pr = self.ogr_fork.create_pr( ...
''' Crie um programa que leia nome, ano de nascimento e carteira de trabalho e cadastre-os (com idade) em um dicionario se por acaso a CTPS for diferente de ZERO, o diconario recebera também o ano de contratação e o salario. Calcule e acrescente, alem da idade, com quantos anos a pessoa vai se aposentar. ''' import dat...
from socket import * from pypy.lang.gameboy import cartridge import socket import sys import threading def map_binary_to_int(binary): return ord(binary) def map_double_binary_to_int(code): #maps a double value to a long return ord(code[0]) + ord(code[1]) >> 8 class DebugSocketMemory(object): ...
from flask import Flask, render_template, send_from_directory, request from python_terraform import * import os import yaml import hcl import uuid import json tf = Terraform() app = Flask(__name__) ROOT_PATH = os.path.join(os.path.dirname(__file__), '..') DEV_MODE = False # Returns list of module objects with metada...
from autoslug import AutoSlugField from django.contrib.auth.models import User from django.core.validators import MaxValueValidator, MinValueValidator from django.db import models from django.db.models import CASCADE from shop.choices import city_choices class Contact(models.Model): id = models.AutoField(primary...
class AppState(): def __init__(self): self.selected_index = -1 self.main_content = [] self.dialog_shown = False
# # fix_framework_weakness.py # from os.path import join, isfile import shutil from pprint import pprint Import("env") if env.MarlinFeatureIsEnabled("POSTMORTEM_DEBUGGING"): FRAMEWORK_DIR = env.PioPlatform().get_package_dir("framework-arduinoststm32-maple") patchflag_path = join(FRAMEWORK_DIR, ".exc-patching-...
import os import sys import re import gzip class GTF: def __init__(self): pass def parse_gtf(self, file_path, feature_type='gene', feature_idtag='gene_id', feature_id=None, output_fmt=3): ''' Input: /path/to/gtf Output: dictionary containing lists of gene an...
import pandas as pd from main_db_script import append_non_duplicates # add wind direction data to database rawdf = pd.read_csv('../wu/norf_data.csv') rawdf.columns = rawdf.columns.str.strip() siteid = 19 varid = 6 qcid = 0 df = pd.DataFrame() df['Datetime'] = rawdf['EST'] df['SiteID'] = siteid df['VariableID'] = vari...
from __future__ import annotations from typing import TYPE_CHECKING, Union from aiohttp import ClientResponse if TYPE_CHECKING: from .ext import commands from .member import Member from .user import User class VoltageException(Exception): """ Base class for all Voltage exceptions. This could be...
import inspect import os import sys from contextlib import contextmanager from io import StringIO from typing import Iterator, TextIO, cast from smartchangelog.scripts import commitmsg_script """Path of the file containing commitmsg_script.py file""" commitmsg_script_path = inspect.getfile(commitmsg_script) @conte...
""" General helper functions and classes that are relevant in Keboola Connection environment. """ from enum import Enum from typing import List, Union class ValidatingEnum(Enum): @classmethod def list(cls): return list(map(lambda c: c.name, cls)) @classmethod def validate_fields(cls, field...
import sys from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * import numpy as np class print_redirect(QObject): """ replace stdout that both prints and emits the text as a signal """ print_signal = pyqtSignal(str) def __init__(self): super().__init__() ...
""" Closuers Free variables and closures Remember: Functions defined inside another function can access the outer (nonLocal) variables """ def outer(): x = 'python' / this x refers to the one in outer's scope', this nonlocal variable x is called a free varia...
def cheese_and_crackers(cheese_count, boxes_of_crackers): print ("You have %r cheesees!" % cheese_count) print ("you have %d boxes of crackers" % boxes_of_crackers) print ("Man that is enough for a party.") print ("get a blanket.\n") print ("We can just give the function numbers directly:") cheese_and...
#!/usr/bin/env python # -*- coding: utf-8 -*- # 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 a...
import json import os import pickle import numpy as np from ..core.result import Result as CoreResult from ..core.utils import ( infft, logger, check_directory_exists_and_if_not_mkdir, latex_plot_format, safe_save_figure ) from .utils import plot_spline_pos, spline_angle_xform, asd_from_freq_series from .dete...
from pathlib import Path from typing import Dict from aws_cdk import aws_cloudformation as cfn from aws_cdk import aws_ec2 as ec2 from aws_cdk import aws_ecr_assets as assets from aws_cdk import aws_ecs as ecs from aws_cdk import aws_s3 as s3 from aws_cdk import core class StorageStack(cfn.NestedStack): def __in...
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################## # # ZopeEdit, client for ExternalEditor # # zopeedit.deb package creator # # Install collective.zopeedit as a python lib # and create a launcher that calls zopeedit.main() # #############...
import tensorflow as tf from deform_conv_wrapper import deform_conv2d def get_weight(weight_shape, name, trainable=True): initial = tf.truncated_normal(weight_shape, stddev=0.1) return tf.Variable(initial, name=name + '_weight', trainable=trainable) def get_bias(bias_shape, name, trainable=True): initi...
import requests import click import os from dotenv import load_dotenv load_dotenv() @click.command() @click.option('--location', default="San Francisco, US", prompt='Give a city (and US state, if necessary), ZIP Code, etc.]') @click.option('--api-key', '-a', help='your API key for the OpenW...
### DB을 연결하는 기능. import pymongo conn = pymongo.MongoClient() print(conn) ### DB와 COL선택 db = conn['local'] db_col = db.items # db['items'] print(db_col)
""" 딕셔너리 구현하기 """ class Dict: def __init__(self): self.items = [None] * 8 def put(self, key, value): idx = hash(key) % len(self.items) self.items[idx] = value def get(self, key): idx = hash(key) % len(self.items) return self.items[idx] my_dict = Dict() my_dict.p...
# for abstract class from abc import ABC class Modul(ABC): def activation_function(self, utterance, rasa_interpreter, node_id, session): pass # raise Exception("This modul does not implement the activation_function.") def create_api_output(self, utterance, node_id, intent_highest_activation,...
#!/usr/bin/python # third party imports import numpy as np from impactutils.extern.openquake import geodetic def get_compass_dir(lat1, lon1, lat2, lon2, format="short"): """Get the nearest string compass direction between two points. :param lat1: Latitude of first point. :param lon1: Longitude of first ...
from validator import foo # <ref>
import os import shutil import pytest from pathlib import Path from subprocess import check_call, check_output, CalledProcessError import numpy as np from pyrate.core import config as cf from tests.common import ( assert_same_files_produced, assert_two_dirs_equal, manipulate_test_conf, TRAVIS, PYTHO...
from fireo.fields import TextField, NumberField from fireo.models import Model class DirectFilterUser(Model): name = TextField() age = NumberField() DirectFilterUser.collection.create(name='Azeem', age=26) def test_single_direct_filter(): user = DirectFilterUser.collection.filter(name='Azeem').get() ...
""" Goal: provide access to the version information """ DEFAULT_VERISON = '0.0.6' try: import pkg_resources __version__ = pkg_resources.require("deduper")[0].version except Exception: from setuptools_scm import get_version try: __version__ = get_version() except Exception: __versio...
import skycoin import tests.utils as utils class verifyTxFeeTestCase: inputHours = 0 outputHours = 0 err = skycoin.SKY_OK def __init__(self, _inputHours, _outputHours, _err=skycoin.SKY_OK): self.inputHours = _inputHours self.outputHours = _outputHours self.err = _err burnFac...
import torch from NLC import NLC from Vocab_word import Vocab def modify_enc_dec(model, enc_layers, dec_layers, unif_init = 0.1): was_training = model.training model.eval() with torch.no_grad(): for layer in enc_layers: model.encoder_GRU[layer].weight_hh_l0.data.uniform_(-unif_init, uni...
# todo 4. Nome na vertical em escada. Modifique o programa anterior de forma a mostrar o nome em formato de escada. nome = str(input('Insira seu nome: ')).strip().upper() for i in range(1, len(nome)+1): print(nome[:i])
""" Day 8: Seven Segment Search https://adventofcode.com/2021/day/8 """ from typing import List def load_input(filepath) -> List[List[str]]: with open(filepath) as f: lines = [line.split('|') for line in f.readlines()] data = [] for line in lines: data.append([part.strip().sp...
# This file is part of EbookLib. # Copyright (c) 2013 Aleksandar Erkalovic <aerkalov@gmail.com> # # EbookLib is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at you...
"""Implementation of Rule L008.""" from typing import Optional, Tuple from sqlfluff.core.parser import WhitespaceSegment from sqlfluff.core.rules.base import BaseRule, LintResult, LintFix, RuleContext from sqlfluff.core.rules.doc_decorators import document_fix_compatible from sqlfluff.core.parser.segments.base impor...
import time def test_customer_get(iamport): customer_uid = 'customer_get_cuid_{}'.format(str(time.time())) try: iamport.customer_get(customer_uid) except iamport.ResponseError as e: assert e.code == 1 assert e.message == u'요청하신 customer_uid({})로 등록된 정보를 찾을 수 없습니다.'.format(customer_...
import pandas import scipy.interpolate import numpy as np from ..j_utils.string import str2time, time2str from ..j_utils.path import format_filepath from collections import OrderedDict class History: """ Store dataseries by iteration and epoch. Data are index through timestamp: the number of iteration sin...
# -*- coding: utf-8 -*- """ @brief @author: Graham Riches @date: Wed May 13 15:44:03 2020 @description module to generate automatic git version string header files """ import subprocess import re import os import sys GIT_REGEX_STR = '(\d+)\.(\d+)\.(\d+)-(\d+)-([\w\d]+)-?(dirty)?' REGEX_TAGS = ['version_major',...
# # Autogenerated by Thrift # # DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING # from thrift.Thrift import * from thrift.transport import TTransport from thrift.protocol import TBinaryProtocol, TProtocol try: from thrift.protocol import fastbinary except: fastbinary = None class CrawlUri(obje...
"""Check the hash of the file and output (or delete) if it is duplicated""" """ファイルのハッシュを確認して重複した場合に出力(or削除)""" #ref https://news.mynavi.jp/article/zeropython-25/ import os, glob, hashlib # 重複ファイルがあるかどうかを調べるディレクトリ target_dir = './check' body_dict = {} # ファイルの内容を返す関数 --- (*1) def get_body(fname): with o...
"""Aparat Video Platform author: Mahdi Khashan data: 1399/02/13 """ import requests import hashlib import json class Base(object): """Base Object""" def __init__(self, dic): """init""" self.dic = dic for key in dic.keys(): setattr(self, key, dic[key]) class Apara...
# pylint: disable=no-member, redefined-outer-name """ Annalist resource types module """ from __future__ import unicode_literals from __future__ import absolute_import, division, print_function __author__ = "Graham Klyne (GK@ACM.ORG)" __copyright__ = "Copyright 2015, G. Klyne" __license__ = "MIT (http://o...
def rank(graph, res): rank_page= {} for page in res.keys(): word_count=res[page] ingoing=graph.ingoing_links(page) num_links=len(ingoing) num_in_links=0 for link in ingoing: if link in res.keys(): num_in_links+=res[link] rank_page[pa...
# -*- coding: utf-8 -*- """ Unittests for wiring (wire logging) module Over the wire logs """ import sys import unittest import os import tempfile import shutil from ioflo.aid.sixing import * from ioflo.aid.consoling import getConsole from ioflo.aio import wiring console = getConsole() def setUpModule(): cons...
import pytest import coremltools as ct from coremltools._deps import ( _HAS_TORCH, MSG_TORCH_NOT_FOUND, ) @pytest.mark.skipif(not _HAS_TORCH, reason=MSG_TORCH_NOT_FOUND) class TestPyTorchConverter: @staticmethod def test_no_inputs(): import torch import torchvision model = tor...
import os import socket import subprocess import sys def receiver(s): """Receive system commands and execute them.""" while True: cmd_bytes = s.recv(4096) # 4096 is better for heavy transfers! cmd = cmd_bytes.decode("utf-8") if cmd.startswith("cd "): os.chdir(cmd[3:]) ...
# coding: utf-8 from collections import OrderedDict import torch import torch.nn as nn from layers import * from ShuffleNetV2 import _make_divisible, DownsampleUnit, BasicUnit class ShuffleNetV2SSD_Detach(nn.Module): def __init__(self, phase, size, num_classes, scale=1): super(ShuffleNetV2SSD_Detach, self)...
import unittest from kvs.kvs import KeyValueStore class TestKeyValueStore(unittest.TestCase): def setUp(self): self.kvs = KeyValueStore() def test_set(self): self.assertTrue(self.kvs.set('a', 'b')) def test_get(self): self.kvs.set('a', 'b') self.assertEqual(self.kvs.get...
from copy import copy from logics.classes.predicate.semantics.models import ModelTheory, TruthPredicateModelTheory from logics.instances.predicate.languages import classical_infinite_predicate_language as classical_language from logics.instances.predicate.languages import classical_function_language, arithmetic_langua...
from dataclasses import dataclass from decimal import Decimal @dataclass class Company: index: int = 0 cnpj_basico: str = "" razao_social: str = "" natureza_legal: str = "0000" qualificacao_responsavel: str = "00" capital_social: Decimal = Decimal(0) porte: int = 1 ente_federativo: str...
# -*- coding: utf-8 -*- # Generated by Django 1.10.4 on 2018-10-23 17:53 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('applications', '0009_default_reimb'), ] operations = [ migrations.AlterFiel...
# define your origins and destinations with latitude/longitude coordinates (take these value from a regular google map from your browser) # each key-value pair from the routes map represents origin (key) and destination (value) for a particular route # E.g. routes = {'cityA':'cityB', 'cityB':'cityA'} would get the traf...
# coding: utf-8 """ SQE API No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 The version of the OpenAPI document: v1 Generated by: https://openapi-generator.tech """ from __future__ import absolute_import import re # noqa: F4...
from okta.constants import FINDING_OKTA_DOMAIN, REPO_URL from okta.error_messages import ERROR_MESSAGE_ORG_URL_MISSING, \ ERROR_MESSAGE_API_TOKEN_DEFAULT, ERROR_MESSAGE_API_TOKEN_MISSING, \ ERROR_MESSAGE_AUTH_MODE_INVALID, ERROR_MESSAGE_CLIENT_ID_MISSING, \ ERROR_MESSAGE_CLIENT_ID_DEFAULT, ERROR_MESSAGE_SCO...
#! /usr/bin/env python import click import os import yaml from subprocess import PIPE, Popen from itertools import product import time from datetime import datetime import xarray as xr import numpy as np import esmlab import pop_tools USER = os.environ['USER'] # set paths gridfile_directory = f'/glade/work/{US...
import imp import os modulename = 'sitchlib' this_file_dirpath = os.path.dirname(os.path.abspath(__file__)) project_basepath = os.path.join(this_file_dirpath, "../../") fixtures_path = os.path.join(this_file_dirpath, "../fixtures/") file, pathname, description = imp.find_module(modulename, [project_basepath]) sitchlib...
#!/usr/bin/env python3 from cereal import car from common.numpy_fast import clip, interp from selfdrive.config import Conversions as CV from selfdrive.controls.lib.drive_helpers import EventTypes as ET, create_event from selfdrive.car.bmw.values import CM, BP, AH, CAR, SteerLimitParams, SteerActuatorParams from selfdri...
from xdoctest import utils from mkinit.formatting import _find_insert_points def test_explicit_insert_points(): lines = utils.codeblock( """ preserved1 = True if True: # <AUTOGEN_INIT> clobbered2 = True # </AUTOGEN_INIT> preserved3 = True ...
def _jupyter_nbextension_paths(): return [{ "section": "notebook", "dest": "logger", "src": "static", "require": "logger/static/main" }]
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################### # Copyright Kitware 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 ...
# Copyright 2022 Google LLC 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 law or ag...
import logging class ImageEffect: AVAILABLE_MODES = {'none', 'negative', 'solarize', 'sketch', 'denoise', 'emboss', 'oilpaint', 'hatch', 'gpen', 'pastel', 'watercolor', 'film', 'blur', 'saturation', 'colorswap', 'washedout', 'posterise', 'colorpoint', 'colorbalance',...
#!/usr/bin/env python # -*- coding: utf-8 -*- from move import select_move, check_move, string_to_move from piece import Piece turn = "White" board = [ ["r", "n", "b", "q", "k", "b", "n", "r"], ["p", "p", "p", "p", "p", "p", "p", "p"], [".", ".", ".", ".", ".", ".", ".", "."], [".", ".", ".", ".", "....
# -*- coding: utf-8 -*- # Copyright (2017-2018) Hewlett Packard Enterprise Development LP # # 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...
import os from datetime import datetime import torch from .preprocessing import Lang, PAD_token, SOS_token, EOS_token def convert_to_text(sample_ids: list, vocab: Lang): words = [vocab.index2word[word_id] for word_id in sample_ids] return ' '.join(words) def save_model(encoder, decoder, epoch, losses_train,...
import pygame # The play scene function def play(window, sprites, s): # init the clock Clock = pygame.time.Clock() # store sprites from previous scenes in variables bird = pygame.sprite.GroupSingle(s[0]) background = s[1] ground = s[2] # Create a pipe group pipes = pygame.sprite.Grou...
# -*- coding: utf-8 -*- ''' Module for managing timezone on POSIX-like systems. ''' from __future__ import absolute_import # Import python libs import os import errno import logging import re import string # Import salt libs import salt.utils import salt.utils.itertools from salt.exceptions import SaltInvocationError...
from django.db import models class ExampleModel(models.Model): title = models.CharField(max_length=255) image = models.ImageField(upload_to='images') def __unicode__(self): return self.title
from datetime import datetime from django import VERSION as DJANGO_VERSION from django import template if DJANGO_VERSION[:2] < (1, 10): from django.core.urlresolvers import reverse else: from django.urls import reverse from django.utils import formats from django.utils.timezone import utc from djeddit.models im...
# -*- coding: utf-8 -*- import numpy as np from ._unuran import unuran_wrapper from scipy._lib.deprecation import _deprecated from scipy._lib._util import check_random_state def rvs_ratio_uniforms(pdf, umax, vmin, vmax, size=1, c=0, random_state=None): """ Generate random samples from a probability density fu...
# -*- coding: utf-8 -*- """ pmutt.test_pmutt_model_reaction Tests for pmutt module """ import unittest import numpy as np from ase.build import molecule from pmutt import constants as c from pmutt import reaction as rxn from pmutt.empirical.nasa import Nasa from pmutt.statmech import StatMech, presets class TestReact...
from math import exp import threading from tqdm import tqdm import cv2 import warnings import os import numpy as np warnings.filterwarnings("ignore") path = 'D:\slowmo\RIFEInterpolation\input' # 图片路径 static_thresold = 0 # 绝对重复帧最小阈值 thresold = 1000 # 阈值(无穷大 = 完全去除一拍N img_load_size = [256,256] flow_scale_si...
import antlr3 import testbase import unittest class t016actions(testbase.ANTLRTest): def setUp(self): self.compileGrammar() def testValid(self): cStream = antlr3.StringStream("int foo;") lexer = self.getLexer(cStream) tStream = antlr3.CommonTokenStream(lexer) ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from flask import Flask, redirect, url_for from flask_appconfig import AppConfig def create_app(configfile=None): from .api_v1 import app_v1 app = Flask(__name__) AppConfig(app, configfile) app.register_blueprint(app_v1) @app.route('/') def bas...
import numpy as np import os import nvidia.dali as dali import nvidia.dali.fn as fn from nvidia.dali.pipeline import Pipeline import nvidia.dali.ops as ops import test_utils def test_unified_arg_placement(): batch_size = 30 pipe = Pipeline(batch_size, 1, None) with pipe: u = ops.random.Uniform()(r...
class Decoder(object): """ abstract decoder: z (latent space) -> x_hat (reconstructed feature space) Usage and Inheritance: - `_build` routine is to be overwritten by more specific `Decoder` child-classes to define the network - `_torch_forward` routine is to be overwritten by more specific `Decoder` ...
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, unicode_literals import sys import warnings from decimal import Decimal from babel import Locale from babel.core import get_global from .l10n import format_money from .utils import cached_property # Default, non-existent, currency DEFAULT_CU...
import os from moonleap.utils.case import sn from moonleap.utils.quote import quote def get_context_admin(module): class Sections: def get_inline_model_fields(self, item_list): return [ x for x in item_list.type_spec.get_field_specs(["relatedSet"]) ...
import os import xml.etree.ElementTree as xml from xcworkspacenode import xcworkspacenode class xcworkspacedata(object): def __init__(self, wsdata_file_path): self.filePath = wsdata_file_path contents = None try: contents = xml.parse(self.filePath) except: ...
''' valorCasa=int(input('Valor da casa:')) salario =float(input('Seu salário:')) anos = int(input('Anos:')) prestacaoMensal= valorCasa/(anos*12) if prestacaoMensal <= salario*0.3: print('aprovado!') else: print('Reprovado') ''' numero = int(input('numero: ')) opcao = int(input('opcao: ')) print('1 para bin,...
# -*- coding: utf-8 -*- from functools import partial from aldryn_client import forms class Form(forms.BaseForm): def to_settings(self, data, settings): from aldryn_addons.utils import djsenv s = settings env = partial(djsenv, settings=settings) s['BROKER_URL'] = env('BROKER_URL...
#Exercício Python 012: Faça um algoritmo que leia o preço de um produto e mostre seu novo preço, com 5% de desconto. preco_inicial = float(input('Preço do produto: ')) desconto = int(input('Porcentagem do desconto (%): ')) valor_final = preco_inicial - (preco_inicial * (desconto/100)) print('Seu produto de R${:.2f} c...