content
stringlengths
0
894k
type
stringclasses
2 values
#!/usr/bin/env python # coding=utf-8 from setuptools import setup # setup configuration is in `setup.cfg` setup()
python
import hashlib import requests # import uuid import os import tempfile def get_file(logger, storage_root, doc_uuid, image_url): # local_path = "%s/%s/images/tmp/%s.%s" % (storage_root, doc_uuid, uuid.uuid4(), image_url["extension"]) try: r = requests.get(image_url["url"]) temp = tempfile.Named...
python
import socket import sys import pickle import time from tkinter import * from tkinter import ttk from tkinter import messagebox, BooleanVar from tkinter import font from PIL import Image import glob import os from PIL import Image, ImageTk import argparse import pprint import random import numpy as np import struct i...
python
import sys import collections Record = collections.namedtuple('Record', ['timestamp', 'action', 'km']) class Car: def __init__(self, plate): self.plate = plate self.records = [] def add_record(self, record): record[2] = int(record[2]) self.records.append(Record(*record)) ...
python
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * import glob class Efivar(MakefilePackage): """Tools and libraries to work with EFI variables""" ...
python
# Copyright (c) 2019 Sony Corporation. 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 applicabl...
python
import os import subprocess import shutil import datetime import pandas as pd SNAPSHOT_FOLDER = "big_test_snapshots_diarios" RETROACTIVE_FOLDER = "retroactive_data" def daterange(start_date, end_date, step=None): for n in range(0,int((end_date - start_date).days),step): yield start_date + datetime.timedelta(day...
python
import os import numpy as np import mdtraj as md from simtk import unit from simtk.openmm import LangevinIntegrator from simtk.openmm.app import Simulation from simtk.openmm.app.pdbfile import PDBFile from cg_openmm.cg_model.cgmodel import CGModel from cg_openmm.utilities.iotools import write_pdbfile_without_to...
python
#!/usr/bin/env python import asyncio import sys import logging import unittest import conf from os.path import join, realpath from hummingbot.market.bitcoin_com.bitcoin_com_websocket import BitcoinComWebsocket from hummingbot.market.bitcoin_com.bitcoin_com_auth import BitcoinComAuth sys.path.insert(0, realpath(join(_...
python
# -*- coding: utf-8 -*- """ Created on Tue Oct 13 13:57:29 2020 @author: lentzye """ import mykeys
python
from IBM_diffprivlib import diffprivlib_single_query from smartnoise import smartnoise_single_query from openmined_pydp import openmind_pydp_single_query library_name = 'smartnoise' # libraries: 'difforivlib', 'smartnoise', additive_noise', 'openmined_pydp' dataset_folder_path = 'E:\\MS_Thesis\\publication_stuff\\c...
python
N = int(input()) A = [] for ii in range(N): A.append(int(input())) s = set() for ii in range(len(A)): s.add(A[ii]) print(len(s))
python
# -*- coding: UTF-8 -*- """ This module provides the abstract base classes and core concepts for the model elements in behave. """ import os.path import sys import six from behave.capture import Captured from behave.textutil import text as _text from enum import Enum PLATFORM_WIN = sys.platform.startswith("win") def...
python
#!/usr/bin/env python3 from pybf import BloomFilter def test_bf_int(num_items=1000000, error=0.01): """Test the BloomFilter with parameters 'num_items' & `error`""" print(f"Bloom filter test for integer keys") bf = BloomFilter(num_items, error) sz = len(bf) print(f'size: {sz}') # checking ...
python
# -*- coding: utf-8 -*- """ """ from __future__ import absolute_import import mock import pytest import easy_acl.rule as rule __copyright__ = "Copyright (c) 2015-2019 Ing. Petr Jindra. All Rights Reserved." def test_init_without_wildcard(): definition = "foo.bar.foo-bar" parts = ("foo", "bar", "foo-bar")...
python
import socket import re try: url = input('Enter - ') # http://data.pr4e.org/romeo.txt HOST = re.findall(r'http[s]?://([\S\d.]*)/.*?', url) mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) mysock.connect((HOST[0], 80)) cmd = 'GET ' + url + ' HTTP/1.0\r\n\r\n' cmd = cmd.encode() my...
python
"""Tests for envs module. Need rework. """ from __future__ import absolute_import # import unittest # from numpy.testing import * import inspect from functools import partial import SafeRLBench.envs as envs import numpy as np import gym gym.undo_logger_setup() from mock import Mock class TestEnvironments(object...
python
''' Tipo String Em Python, um dado é considerado do tipo string sempre que: - Estiver entre aspas simples -> 'uma string', '234', 'a', 'True', '42.3' - Estiver entre aspas duplas -> "uma string", "234", "a", "True", "42.3" - Estiver entre aspas simples triplas; - Estiver entre aspas simples duplas. nome = 'Geek Univ...
python
# -*- coding: utf-8 -*- __version__ = '1.0.3' from .fixedrec import RecordFile, RecordFileError
python
import json import os import time from abc import ABC import numpy as np import torch from agent0.common.utils import set_random_seed from agent0.ddpg.agent import Agent from agent0.ddpg.config import Config from ray import tune from ray.tune.trial import ExportFormat class Trainer(tune.Trainable, ABC): def __in...
python
"""Bay Bridge simulation.""" import os import urllib.request from flow.core.params import SumoParams, EnvParams, NetParams, InitialConfig, \ SumoCarFollowingParams, SumoLaneChangeParams, InFlows from flow.core.params import VehicleParams from flow.core.params import TrafficLightParams from flow.core.experiment i...
python
import logging from queue import Queue from common.configuration import ConfigurationService from common.reddit import get_relevat_subreddits from common.settings import Setting from common.storage import StorageService from functools import wraps from telegram import Bot, ChatAction, Update from telegram.ext import C...
python
#!/usr/bin/env python # # __COPYRIGHT__ # # 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, ...
python
import bz2 import re import sys from collections import namedtuple from pathlib import Path from xml.etree import cElementTree as ElementTree from urllib.parse import urljoin from urllib.error import URLError import mwparserfromhell import numpy import pycountry from sklearn.feature_extraction.text import CountVectori...
python
#! /usr/bin/env python3 ### # KINOVA (R) KORTEX (TM) # # Copyright (c) 2018 Kinova inc. All rights reserved. # # This software may be modified and distributed # under the terms of the BSD 3-Clause license. # # Refer to the LICENSE file for details. # ### import sys import os from kortex_api.RouterClient import Route...
python
class Gif: pass
python
#!/usr/bin/env python # -*- coding: utf-8 -*- # """ """ from setuptools import setup, find_packages from Cython.Build import cythonize import pysam setup( name='svtk', version='0.1', description='Structural variation toolkit', author='Matthew Stone', author_email='mstone5@mgh.harvard.edu', p...
python
from colour import Color from utils.animation_maker import * import numpy as np from time import time song = 1 in_file = f'./Songs/Song0{song}.wav' c1, c2 = Color('#fceaa8'), Color('#00e5ff') #c1, c2 = Color('#000000'), Color('#00fffb') c3, c4 = Color('#000000'), Color('#000000') gradient_mode = 'hsl' n_points = 100 a...
python
import argparse import asyncio import rlp from typing import Any, cast, Dict from quarkchain.p2p import auth from quarkchain.p2p import ecies from quarkchain.p2p.exceptions import ( HandshakeFailure, HandshakeDisconnectedFailure, UnreachablePeer, MalformedMessage, ) from quarkchain.p2p.kademlia import ...
python
"""redux_field_creator URL Configuration""" from django.conf.urls import include, url from django.contrib import admin from django.views.generic import RedirectView urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^fields/', include('fields.urls')), ]
python
# echo_04_io_multiplexing.py import socket import selectors sel = selectors.DefaultSelector() def setup_listening_socket(host='127.0.0.1', port=55555): sock = socket.socket() sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind((host, port)) sock.listen() sel.register(sock, sele...
python
import json import sys import getopt from os import system sys.path.insert(0, '/requests') import requests def getBridgeIP(): r = requests.get('http://www.meethue.com/api/nupnp') bridges = r.json() if not bridges: bridge_ip = 0 else: bridge_ip = bridges[0]['internalipaddress'] r...
python
load("@bazel_skylib//lib:paths.bzl", "paths") load("@bazel_skylib//lib:structs.bzl", "structs") load("//ocaml/_functions:utils.bzl", "capitalize_initial_char") load("//ocaml/_functions:module_naming.bzl", "normalize_module_label", "normalize_module_name") load("//ocaml/_rules:impl_common.bzl", "module_sep")...
python
#!/usr/bin/python3 # -*- coding:utf-8 -*- # # Copyright (c) [2020] Huawei Technologies Co.,Ltd.All rights reserved. # # OpenArkCompiler is licensed under Mulan PSL v2. # You can use this software according to the terms and conditions of the Mulan PSL v2. # You may obtain a copy of Mulan PSL v2 at: # # http://licens...
python
from os import listdir from os.path import isfile, join import pandas as pd import pickle def get_latest_file(filename_str_contains, datapath='../data/', filetype='parquet'): """ Method to get the latest file to given a certain string value. Parameters ---------- filename_str_contains :...
python
class SymbolTableError(Exception): """Exception raised for errors with the symbol table. Attributes: message -- explanation of the error """ def __init__(self, message): self.message = message
python
# Created by woochanghwang at 12/07/2021 import toolbox.drugbank_handler_postgres as drug_pg import pandas as pd def get_DDI_of_a_drug(drug): # drug_a = row['DrugA_ID'] # drug_b = row['DrugB_ID'] sql = "SELECT * from structured_drug_interactions where subject_drug_drugbank_id = \'{}\' " \ "or ...
python
import unittest from machinetranslation import translator from translator import englishToFrench from translator import frenchToEnglish class TestTranslator(unittest.TestCase): # test function def test_englishToFrench(self): self.assertIsNotNone(englishToFrench('Hello'),'Bonjour') self.assertE...
python
import tkinter as tk import tkinter.ttk as ttk from ..elements import TreeList from ...head.database import Database as db from ...globals import SURVEY_TYPES from .templates import ListFrameTemplate class SurveysListFrame(ListFrameTemplate): def __init__(self, top): super().__init__(top) self.dat...
python
import unittest import os import plexcleaner.database as database from plexcleaner.media import Library, Movie __author__ = 'Jean-Bernard Ratte - jean.bernard.ratte@unary.ca' # flake8: noqa class TestMediaLibrary(unittest.TestCase): _nb_movie = 98 _effective_size = 100275991932 def test_init(self): ...
python
#coding=utf-8 import os import jieba import shutil dirs = [] for d in os.listdir(os.getcwd()): if os.path.isfile(d): continue dirs.append(d) imgs = [] with open("data.txt",'w') as fw , open("imgs.txt","w") as fi: for d in dirs: for f in os.listdir(os.path.join(d)): ...
python
from urllib.parse import parse_qsl from establishment.socialaccount.providers.base import Provider class OAuth2Provider(Provider): def get_auth_params(self, request, action): settings = self.get_settings() ret = settings.get("AUTH_PARAMS", {}) dynamic_auth_params = request.GET.get("auth_p...
python
# coding: utf-8 from __future__ import annotations from datetime import date, datetime # noqa: F401 import re # noqa: F401 from typing import Any, Dict, List, Optional # noqa: F401 from pydantic import AnyUrl, BaseModel, EmailStr, validator # noqa: F401 from acapy_wrapper.models.credential_offer import Credentia...
python
from pyilluminate import Illuminate import numpy as np import pytest pytestmark = pytest.mark.device @pytest.fixture(scope='module') def light(): with Illuminate() as light: yield light def test_single_led_command(light): light.color = 1 # setting led with an integer light.led = 30 def te...
python
"""Tests for deletion of assemblies.""" import os import unittest from hicognition.test_helpers import LoginTestCase, TempDirTestCase # add path to import app # import sys # sys.path.append("./") from app import db from app.models import ( Dataset, Assembly, ) class TestDeleteAssembly(LoginTestCase, TempDirT...
python
import ccxt def build_exchange(name): exchange = getattr(ccxt, name) return exchange({ 'enableRateLimit': True }) def timestamps_to_seconds(data): for datum in data: datum[0] = datum[0] // 1000 def secs_to_millis(datum): return datum * 1000
python
# TODO: add more filetypes paste_file_types = [ ["All supprted files", ""], ("All files", "*"), ("Plain text", "*.txt"), ("Bash script", "*.sh"), ("Batch script", "*.bat"), ("C file", "*.c"), ("C++ file", "*.cpp"), ("Python file", "*.py"), ("R script file", "*.R") ] for _, extension ...
python
'Faça um script de menu que mostra na tela, com o título de "Menu Principal" e mais três opções:' # 1. FIM # 2. CADASTRO # 3. CONSULTA "O programa recebe um input do teclado a opção desejada e mostra uma mensagem confirmando a opção escolhida." # Caso a opção escolhida seja inválida, mostrar uma mensagem de erro "Opç...
python
from django.http import HttpResponse, JsonResponse, Http404 from django.views.decorators.csrf import csrf_exempt from rest_framework.parsers import JSONParser from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from tasks.models import Task from tasks....
python
from math import sqrt import torch import torch.nn.functional as F from torch.autograd import Variable from torch.utils import data as data from torchvision import transforms as transforms from data.datasets import MNIST_truncated, FEMNIST, FashionMNIST_truncated, SVHN_custom, CIFAR10_truncated, Generated ...
python
class Solution(object): def maxDistance(self, nums): """ :type arrays: List[List[int]] :rtype: int """ low = float('inf') high = float('-inf') res = 0 for num in nums: # We can use num[0] && num[-1] only because these lists are sorted ...
python
from django.conf.urls import include, url from mailviews.previews import autodiscover, site autodiscover() app_name = 'mailviews' urlpatterns = [ url(regex=r'', view=site.urls) ]
python
# THIS FILE IS SAFE TO EDIT. It will not be overwritten when rerunning go-raml. from flask import jsonify, request from ..models import FarmerRegistration, FarmerNotFoundError def GetFarmerHandler(iyo_organization): try: farmer = FarmerRegistration.get(iyo_organization) except FarmerNotFoundError: ...
python
import web from web import form import socket import sensor from threading import Thread localhost = "http://" + socket.gethostbyname(socket.gethostname()) + ":8080" print(localhost) urls = ( '/','Login', '/control','Page_one', '/left', 'Left', '/right', 'Right', '/...
python
import os import sys command = " ".join(sys.argv[1:]) os.system(command)
python
from __future__ import unicode_literals, print_function from pprint import pprint import xmltodict with open("show_security_zones.xml") as infile: show_security_zones = xmltodict.parse(infile.read()) print("\n\n") print("Print the new variable and its type") print("-" * 20) pprint(show_security_zones) print(typ...
python
# https://www.urionlinejudge.com.br/judge/en/problems/view/1012 entrada = input().split() a = float(entrada[0]) b = float(entrada[1]) c = float(entrada[2]) print(f"TRIANGULO: {a*c/2:.3f}") print(f"CIRCULO: {3.14159*c**2:.3f}") print(f"TRAPEZIO: {(a+b)*c/2:.3f}") print(f"QUADRADO: {b**2:.3f}") print(f"RETANGU...
python
import torch tau = 6.28318530718 class FractalPerlin2D(object): def __init__(self, shape, resolutions, factors, generator=torch.random.default_generator): shape = shape if len(shape)==3 else (None,)+shape self.shape = shape self.factors = factors self.generator = generator s...
python
import json from unittest.mock import Mock import graphene from django.conf import settings from django.shortcuts import reverse from django_countries import countries from django_prices_vatlayer.models import VAT from tests.utils import get_graphql_content from saleor.core.permissions import MODELS_PERMISSIONS from ...
python
# Copyright 2019 Huawei Technologies Co., Ltd # # 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...
python
#!/usr/bin/env python3 """ # scripts/manifest/lib/verify_input.py # (c) 2020 Sam Caldwell. See LICENSE.txt. # # input verification functions. # """ from .hasher import SUPPORTED_HASH_ALGORITHMS def url_string(s: str) -> bool: """ Verify the given string (s) is a URL. :param s: string :r...
python
from flask import Flask, request, jsonify import customs.orchestrator as orch import customs.validator as valid app = Flask(__name__) @app.route('/customs', methods=['POST']) def customs(): content = request.get_json(silent=True) # exception? check = valid.is_json_correct(content) if check is True: ...
python
a = float(input("Zadej velikost polomeru kruhu v cm: ")) obsah = a*a*3.14 obvod = 2*3.14*a print("Obsah je", "", obsah, "cm") print("Obvod je", "", obvod, "cm")
python
# --- # jupyter: # jupytext: # formats: ipynb,py:light # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.5.0 # kernelspec: # display_name: Python [conda env:PROJ_irox_oer] * # language: python # name: conda-env-PROJ...
python
#import random package import random #get random number between 1 and 10 #print(random.randint(0, 1)) choice = random.randint(0,3) if choice == 0: print("Tails") elif choice == 1: print("Heads") else: print("Your quarter fell in the gutter.") #get random number between 1 and 100 # print(random.randint(0,...
python
# Copyright (c) 2018, Neil Booth # # All rights reserved. # # The MIT License (MIT) # # 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 r...
python
from mopidy import backend class KitchenPlaybackProvider(backend.PlaybackProvider): def translate_uri(self, uri): return self.backend.library.get_playback_uri(uri)
python
url = "https://lenta.ru/parts/news/" user_agent = "text"
python
#Given a list of numbers and a number k, return whether any two numbers from the list add up to k. #For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17. #Bonus: Can you do this in one pass? def k_sum_in_list(k, list): needed = {} for n in list: if needed.get(n, False): ...
python
"""Test suits for Anytown Mapper.""" import math import os import unittest import sqlite3 import tempfile from main import app from main import get_db from main import init_db from anytownlib.kavrayskiy import coords_to_kavrayskiy from anytownlib.kavrayskiy import make_global_level_image from anytownlib.map_cache im...
python
# flake8: noqa # Import all APIs into this package. # If you have many APIs here with many many models used in each API this may # raise a `RecursionError`. # In order to avoid this, import only the API that you directly need like: # # from .api.chamber_schedule_api import ChamberScheduleApi # # or import this pack...
python
from flask import Flask,render_template,request,redirect,url_for import os, git def styleSheet(): stylesheet = "/static/styles/light_theme.css" if request.cookies.get('darktheme') == 'True': stylesheet = "/static/styles/dark_theme.css" return stylesheet def create_app(test_config=None): # cre...
python
#!/usr/bin/env python try: from scapy.all import * #from scapy.layers.dot11 import Dot11, Dot11Elt, Dot11Auth, Dot11Beacon, Dot11ProbeReq, Dot11ProbeResp, RadioTap from gui.tabulate_scan_results import Gui from multiprocessing import Process import time, threading, random, Queue import signal, os import scapy_e...
python
from pyibex import Interval, tan, bwd_imod, atan import math def Cmod(x,y): xx = Interval(x) yy = Interval(y) bwd_imod(xx,yy,2*math.pi) return yy def Catan2(x,y,th): iZeroPi2 = Interval(0)| Interval.PI/2. iPi2Pi = Interval.PI/2. | Interval.PI if x.is_empty() or y.is_empty() or th.is_empty(): return...
python
#!/usr/bin/env python import maccleanmessages import sys from setuptools import setup requires=[] if sys.version_info[:2] == (2, 6): requires.append('argparse>=1.1') setup( name='maccleanmessages', version=maccleanmessages.__version__, description='Remove macOS Messages app history (chats / texts ...
python
# -*- coding: utf-8 -*- from abc import ABCMeta, abstractmethod from pyparsing import lineno, col """ Base classes for implementing decoder parsers. A decoder parser receives a data structure and returns an instance of a class from the domain model. For example, it may receive a JSON and return a CWRFile instance. ...
python
# MIT License # # Copyright (c) 2020 Adam Dodd # # 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, pu...
python
import torch import torch.nn as nn import torch.nn.functional as F import logging def categorical_accuracy(preds, y): """Return accuracy given a batch of label distributions and true labels""" max_preds = preds.argmax(dim=1, keepdim=True) correct = max_preds.squeeze(1).eq(y) return correct.sum().floa...
python
from pathlib import Path import pandas as pd DATA_DIR = Path('data') DIR = DATA_DIR / 'raw' / 'jigsaw-unintended-bias-in-toxicity-classification' def load_original_dataset(): df = pd.read_csv(DIR / 'train.csv', index_col=0) df['label'] = (df.target >= 0.5) df = df[['comment_text', 'label']] df.column...
python
import yunionclient from yunionclient.common import utils import json @utils.arg('--limit', metavar='<NUMBER>', default=20, help='Page limit') @utils.arg('--offset', metavar='<OFFSET>', help='Page offset') @utils.arg('--order-by', metavar='<ORDER_BY>', help='Name of fields order by') @utils.arg('--order', metavar='...
python
inter = dict.fromkeys([x for x in a if x in b])
python
n1 = int(input('Digite um valor: ')) n2 = int(input('Digite outro valor: ')) s= n1 + n2 m = n1 * n2 d = n1 / n2 di = n1 // n2 e = n1 ** n2 print(f'A soma é: {s}, o produto é: {m}, a divisão é: {d:.3f},', end=' ') print(f'a divisão inteira é: {di} e a potência é: {e}')
python
""" Utility functions ======================= """ import time from . import RUNNING_ON_PI if RUNNING_ON_PI: # pragma: no cover import RPi.GPIO as GPIO def digital_write(pin, value): # pragma: no cover GPIO.output(pin, value) def digital_read(pin): # pragma: no cover return GPIO.input(pin) def del...
python
from unittest.mock import patch from django.test import TestCase from vimage.core.base import VimageKey, VimageValue, VimageEntry from .const import dotted_path class VimageEntryTestCase(TestCase): def test_entry(self): ve = VimageEntry('app', {}) self.assertIsInstance(ve.key, VimageKey) ...
python
# -*- coding: utf-8 -*- """Utilities related to reading and generating indexable search content.""" from __future__ import absolute_import import os import fnmatch import re import codecs import logging import json from builtins import next, range from pyquery import PyQuery log = logging.getLogger(__name__) def...
python
from django.test import TestCase from wagtailimportexport import functions class TestNullPKs(TestCase): """ Test cases for null_pks method in functions.py """ def test_null(self): pass class TestNullFKs(TestCase): """ Test cases for null_fks method in functions.py """ def tes...
python
from django import forms from django.contrib.contenttypes.forms import generic_inlineformset_factory from django.contrib.contenttypes.models import ContentType from django.db import models from django.test import TestCase from django.test.utils import isolate_apps from .models import ( Animal, ForProxyMode...
python
from django.db import models class Core(models.Model): name = models.CharField(max_length=100) description = models.TextField(max_length=100) back_story = models.TextField() height = models.CharField(max_length=50) weight = models.FloatField() strength = models.IntegerField() wisdom = model...
python
# high-level interface for interacting with Brick graphs using rdflib # setup our query environment from rdflib import RDFS, RDF, Namespace, Graph, URIRef class BrickGraph(object): def __init__(self, filename='metadata/sample_building.ttl'): self.bldg = Graph() self.bldg = Graph() self.bldg...
python
#!/usr/local/bin/python3 from random import randint def sortea_numero(): return randint(1, 6) def eh_impar(numero: float): return numero % 2 != 0 def acertou(numero_sorteado: float, numero: float): return numero_sorteado == numero if __name__ == '__main__': numero_sorteado = sortea_numero() ...
python
import pytest from datetime import datetime, timedelta import xarray as xr import cftime import numpy as np import vcm from vcm.cubedsphere.constants import TIME_FMT from vcm.convenience import ( cast_to_datetime, parse_current_date_from_str, parse_timestep_str_from_path, round_time, parse_datetime...
python
# This code is based off the DUET algorithm presented in: # O. Yilmaz and S. Rickard, "Blind separation of speech mixtures via time-frequency masking." # S. Rickard, "The DUET Blind Source Separation Algorithm" # # At this time, the algorithm is not working when returning to the time domain # and, to be honest, I haven...
python
# -*- mode: python; coding: utf-8 -*- # Copyright 2016 the HERA Collaboration # Licensed under the BSD License. """The way that Flask is designed, we have to read our configuration and initialize many things on module import, which is a bit lame. There are probably ways to work around that but things work well enough ...
python
from PyQt5.QtWidgets import * from PyQt5.QtCore import * from PyQt5.QtGui import * from datetime import datetime import pandas as pd class Funcion_salida: def Retirar_desplegar_teclado(self): MOV = -100 # movimiento botones self.salida_nombre.setGeometry(self.width/3.6, (self.height/2.7)+...
python
class Command: def __init__(self, name, obj, method, help_text): assert hasattr(method, '__call__') self._name = str(name) self._obj = obj self._method = method self._help = str(help_text) @property def name(self): return self._name @property def hel...
python
from __future__ import print_function from hawc_hal import HAL import matplotlib.pyplot as plt from threeML import * import pytest from conftest import point_source_model @pytest.fixture(scope='module') def test_fit(roi, maptree, response, point_source_model): pts_model = point_source_model hawc = HAL("HAWC...
python
#!/usr/bin/env python import os import sys sys.path.insert(0,os.environ['HOME']+'/P3D-PLASMA-PIC/p3dpy/') import numpy as np from mpi4py import MPI from subs import create_object import AnalysisFunctions as af # # MPI INITIALIZATION # comm = MPI.COMM_WORLD size = comm.Get_size() rank = comm.Get_rank() status = MPI.St...
python
import unittest from sharepp import SharePP, Coin class SharePPTest(unittest.TestCase): def test_valid_input(self): price = SharePP.get_etf_price("LU1781541179") self.assertTrue(float, type(price)) def test_invalid_input(self): try: SharePP.get_etf_price("invalid_isin") ...
python
#!/usr/bin/env python # -*- encoding: utf-8 -*- # vim: set et sw=4 ts=4 sts=4 ff=unix fenc=utf8: # Author: Binux<i@binux.me> # http://binux.me # Created on 2014-10-19 16:23:55 from __future__ import unicode_literals from flask import render_template, request, json from flask import Response from .app import a...
python
import os import shutil import subprocess def create_videos(video_metadata, relevant_directories, frame_name_format, delete_source_imagery): stylized_frames_path = relevant_directories['stylized_frames_path'] dump_path_bkg_masked = relevant_directories['dump_path_bkg_masked'] dump_path_person_masked = rel...
python