content
stringlengths
5
1.05M
# Copyright 2015 Canonical Ltd # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by...
import os def exists_and_isfile(filename): """if file does not exist return False if file exisits check if isfile or raise Exception """ if filename is None: return False if os.path.exists(filename): if os.path.isfile(filename): return True else: ...
print('\033[1;93m-=-=-=-=-=-=-=-=-=-=-=-=-=-\033[m') print('\033[1;31m GERADOR DE PA\033[m') print('\033[1;93m-=-=-=-=-=-=-=-=-=-=-=-=-=-\033[m') termo = int(input('Primeiro Termo: ')) razão = int(input('Razão da PA: ')) cont = 0 while cont <= 9: print(termo, end=' ') print('->', end=' ') termo += razã...
""" Stereotype property page. """ from gi.repository import Gtk from gaphor import UML from gaphor.core import gettext, transactional from gaphor.diagram.propertypages import PropertyPageBase, PropertyPages def create_stereotype_tree_view(model, toggle_stereotype, set_slot_value): """ Create a tree view for...
from SCons.Script import * # Needed so we can use scons stuff like builders #UNFINISHED def Init(env): #Checking if vital vars are present checking_vars = ['CRAYON_BASE', 'CRAYON_PROJ_NAME', 'CRAYON_PROJ_LIBS', 'CRAYON_BUILD_DIR' ] for x in checking_vars: if x not in env['ENV']: ...
''' Bing Speech To Text (STT) based on https://github.com/Uberi/speech_recognition ''' import json import uuid import wave import io from urllib import urlencode from urllib2 import Request, urlopen, URLError, HTTPError from bing_base import * class BingVoiceRecognizer(): def __init__(self, bing_base): ...
from django import forms class StudentForm(forms.Form): file = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True})) # for creating file input
import pandas_datareader.data as web import datetime #获取上证指数的2017.1.1日至今的交易数据 df_stockload = web.DataReader("000001.SS", "yahoo", datetime.datetime(2017,1,1), datetime.date.today()) print(df_stockload.head()) # 查看前几行 """ High Low Open Close Volume Adj Close Date ...
from pathlib import Path from urllib.parse import urlparse import click import requests import database_connection # noqa: F401 from matrix_connection import get_download_url from schema import Message def download_stem(message, prefer_thumbnails): image_url = (message.thumbnail_url if prefer_thumbnails else ...
import sys from ansibleflow import config from specter import Spec, fixture from six import StringIO real_stdout = sys.stdout real_stderr = sys.stderr @fixture class BaseSpec(Spec): def before_all(self): config.get_config('./data/test_project.yml') def after_all(self): config._config = No...
"""Different types of Tasks.""" from __future__ import annotations import logging import abc from pathlib import Path from typing import Optional, Dict, List, Tuple from shutil import copytree, rmtree from . import tools from .schema_tags import Tags, LangTags, BuildTags log = logging.getLogger("GHC") OUTPUT_MISM...
''' The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other. Given an integer n, return all distinct solutions to the n-queens puzzle. Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a que...
a = int(input("enter range: " )) d=dict() for i in range(1,a): d[i]=i*i print(d)
import re from typing import List from xml.sax import saxutils from .writers.xml import XMLMaker from ..interpreter import PDFInterpreter, PageInterpreter, logging from ..interpreter import LTImage, LTTextBlock, LTCharBlock, LTChar, LTCurve, LTXObject from ..interpreter.commands import LTItem from ..interpreter.comman...
# -*- coding: utf-8 -*- """ Created on Thu Jan 7 20:33:44 2021 @author: Yefry Lopez You need intall Simplegui You can see the code in action here: https://py3.codeskulptor.org/#user306_YTAa8q66OLDKlLV.py """ # template for "Stopwatch: The Game" import simplegui # define global variables variable = 0 x = 0 y =...
from typing import Optional, List, Dict import graphene from graphql_jwt.decorators import login_required from .types import PerformerType from ..utils import check_permissions, update_and_save from ...reviews.models import Performer, Album class AlbumInputType(graphene.InputObjectType): name = graphene.String(...
from typing import List import numpy as np import tensorflow as tf class AsyncGGNN(object): @classmethod def default_params(cls): return { 'hidden_size': 128, 'edge_label_size': 16, 'propagation_rounds': 4, # Has to be an even number 'propagation_subs...
# # Copyright (c) 2019 Idiap Research Institute, http://www.idiap.ch/ # Written by Angelos Katharopoulos <angelos.katharopoulos@idiap.ch> # """The data module provides interfaces and implementations to generate tf tensors for patches of multi resolution data. We have the following assumptions: 1. The data have n spa...
from types import SimpleNamespace import numpy as np import toml import matplotlib.pyplot as plt from matplotlib.widgets import Cursor import time from unicycle import simulate_unicycle from collision_check import circle_collision_check from lidar import Lidar config = toml.load("config.toml") config_params = config...
#!/usr/bin/python # -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function __metaclass__ = type from socket import gethostname, getfqdn from ansible.module_utils.basic import AnsibleModule, os, re DOCUMENTATION = ''' --- module: oracle_gi_facts short_description: Returns some facts ...
# Generated by Django 2.1.5 on 2019-04-06 16:19 import analyzer.models from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('analyzer', '0001_initial'), ] operations = [ migrations.AlterField( model_name='analysis', na...
"""Oversampling Functions""" # Authors: Jeffrey Wang # License: BSD 3 clause import numpy as np from sklearn.mixture import GaussianMixture as GMM from sleepens.utils import separate_by_label, create_random_state def balance(data, labels, desired=None, balance='auto', seed=None, verbose=0): """ ...
from unittest import TestCase from pylinac import tg51 class TestFunctions(TestCase): def test_p_tp(self): temps = (22, 25, 19) presss = (760, 770, 740) expected_ptp = (1.0, 0.997, 1.0165) for temp, press, exp in zip(temps, presss, expected_ptp): self.assertAlmostEqua...
""" Name: create_semantic_images.py Desc: Creates RGB images using texture UV maps. """ # Import these two first so that we can import other packages from __future__ import division import os import sys sys.path.append(os.path.dirname(os.path.realpath(__file__))) import io_utils # Import remaining packages imp...
from django.db.models import base from django.http import HttpResponse from django.shortcuts import render from django.contrib import messages from typing import Optional import time from typing import Mapping import requests from pprint import pprint import calendar import datetime import brownie from requests.api im...
from .analytical import retarget_from_src_to_target, Retargeting, generate_joint_map from .constrained_retargeting import retarget_from_src_to_target as retarget_from_src_to_target_constrained from .point_cloud_retargeting import retarget_from_point_cloud_to_target from .constants import ROCKETBOX_TO_GAME_ENGINE_MAP, A...
""" navigating.py constants and basic functions for navigation """ from __future__ import absolute_import, division, print_function import sys import math # Import ioflo libs from .sixing import * from .odicting import odict from ..base import excepting from .consoling import getConsole console = getConsole() TWO...
#!/usr/bin/env python3 """Pre-commit hook to verify that all extras are documented in README.rst""" import configparser import re from pathlib import Path repo_dir = Path(__file__).parent.parent.parent config = configparser.ConfigParser(strict=False) config.read(repo_dir / "setup.cfg") all_extra = [] extra_to_exclud...
class Solution: def numPairsDivisibleBy60(self, time: List[int]) -> int: """Array. Running time: O(n) where n == len(time). """ d = collections.defaultdict(int) for t in time: d[t % 60] += 1 res = 0 for k, v in d.items(): if k == 0 or ...
from ..utils import Object class GetBackgroundUrl(Object): """ Constructs a persistent HTTP URL for a background Attributes: ID (:obj:`str`): ``GetBackgroundUrl`` Args: name (:obj:`str`): Background name type (:class:`telegram.api.types.BackgroundType`): ...
import pandas as pd import numpy as np import os import plotly.plotly as py import plotly.graph_objs as go '''Trend CO2''' def trend_co2(co2_anno): # Create a trace trace = go.Scatter( x = co2_anno['Anno'], y = co2_anno['Media CO2'], mode = 'lines+markers', name = 'CO2 Trend' ...
#!/usr/bin/env python # Copyright 2016 Vimal Manohar # 2016 Xiaohui Zhang # Apache 2.0. # we're using python 3.x style print but want it to work in python 2.x, from __future__ import print_function from collections import defaultdict import argparse import sys class StrToBoolAction(argparse.Action): ...
import re from app.utils import email def init(func): """Decorator, that calls function on module import""" func() return func def jsonifyBlunder(data): return { 'id': str(data['id']), 'game_id': str(data['game_id']), 'move_index': data['move_index'], 'forcedLine': d...
from .avm import AVM, NoAVMPresent # noqa __version__ = "0.9.6.dev0"
""" Support for foobar2000 Music Player as media player via pyfoobar2k https://gitlab.com/ed0zer-projects/pyfoobar2k And foobar2000 component foo_httpcontrol by oblikoamorale https://bitbucket.org/oblikoamorale/foo_httpcontrol """ import logging from datetime import timedelta import voluptuous as vol from homeassist...
import pytest from wemake_python_styleguide.violations.consistency import ( WrongMethodOrderViolation, ) from wemake_python_styleguide.visitors.ast.classes import ( ClassMethodOrderVisitor, ) correct_method_order = """ class Test(object): def __new__(self): ... def __init__(self): ......
directory.functions.log_message(u'EntityEmail for Entity ' + str(model) + u') added by: ' + request.user.username + u', value: ' + value + u'\n') return HttpResponse( u'<a class="edit_rightclick" id="EntityEmail_email_' + str(email.id) + u'" href="mailto:' + value ...
import sys import numpy as np import tflearn from tflearn.layers.core import input_data, dropout, fully_connected from tflearn.layers.estimator import regression import utils def build_network(): network = tflearn.input_data(shape=[None, 2]) network = tflearn.fully_connected(network, 64, activation='relu') ...
from discord.ext import commands from ..events.utils import Utils class Reload(commands.Cog): """Reload Command Class""" def __init__(self, bot): self.bot = bot self.desc = "A command that reloads commands 🧠" self.usage = "reload [cogs.category.command]" @commands.co...
# coding=utf8 # Copyright 1999-2017 Alibaba Group. # # 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...
#!/usr/bin/env python3 import statistics # read numbers one line each, then calculate mean nums = [] while True: try: n = float(input()) nums.append(n) except EOFError: break print(statistics.mean(nums))
import os from collections import defaultdict from unittest.mock import Mock import pytest from qtpy.QtWidgets import QAction, QShortcut from napari import Viewer from napari._qt.qt_event_loop import _ipython_has_eventloop, run, set_app_id @pytest.mark.skipif(os.name != "Windows", reason="Windows specific") def tes...
def aumentar(num, porcentagem): """ -> Calcula o valor acrescido de uma determinada porcentagem :param num: numero que será acrescido da porcentagem :param porcentagem: valor da porcentagem a ser calculada :return: o resultado do cálculo """ resultado = num + (num * (porcentagem / 100)) ...
# coding: utf-8 # # Copyright 2022 :Barry-Thomas-Paul: Moss # # 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...
# import sys # import os # sys.path.append(os.path.join(os.path.dirname(__file__), '../')) from aiohttp.test_utils import AioHTTPTestCase, unittest_run_loop from aiohttp import web from motor import motor_asyncio as ma from parser.parser import iteration from parser import settings from parser.views import routes c...
#------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. #-------------------------------------------------------------------------- import torch TrainingMode = torch.onnx.TrainingMode from packaging.versio...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # 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, ...
import random template = """[Fact] public void Test_Func{n}() {{ Func<{types}, object> f = new EmptyFunc<{types}, object>(); Assert.Equal(default(object), f({args})); }} """ def gen(n: int): types = ", ".join("int" for _ in range(n)) args = ", ".join(hex(random.randint(0, 1 << 16)) for _ in range(n)) ...
import os from setuptools import setup import sys # pip workaround os.chdir(os.path.abspath(os.path.dirname(__file__))) packages = [] for rootdir, dirs, files in os.walk('mldebugger'): if '__init__.py' in files: packages.append(rootdir.replace('\\', '.').replace('/', '.')) req = ['numpy', 'zmq', ...
from magic_repr import make_repr from .side import Side from ermaket.utils.xml import XMLObject __all__ = ['Relation'] class Relation(XMLObject): def __init__(self, name, sides): self.name = name self.sides = sides @property def _tag_name(self): return 'relation' @classmeth...
valores = list() while True: num = int(input('Informe um numero: ')) if num not in valores: valores.append(num) print('O numero Foi adicionado!!!') else: print('Este valor já tem!') resp = ' ' while resp not in 'SN': resp = str(input('Quer acrescentar mais numeros? [S...
from flask import Flask, request, redirect import requests import json CLIENT_ID = 'f1e42d14f45491f9ca34' CLIENT_SECRET = '' OAUTH_STATES = [] app = Flask(__name__) @app.route('/auth_state') def auth_state(): # save anti csrf secret secret = request.args.get('state') OAUTH_STATES.append(secret) @app.route('/c...
""" CAT12 segmentation interface utilities. """ from django_mri.analysis.interfaces.matlab.spm.cat12.utils.batch_templates import \ CAT12_TEMPLATES # noqa: E501
# @Author : Wang Xiaoqiang # @GitHub : https://github.com/rzjing # @File : scheduler.py # @Time : 2020/1/2 23:01 from datetime import datetime from apscheduler.jobstores.base import JobLookupError from flask_restful import Resource from app import v1, scheduler, make_response, parser from app.common.util...
# 给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为 1000。 # 方法: DP # 状态方程: # 当字符串长度大于 2 时: dp[i,j] = dp[i+1,j-1] & (S[i] == S[j]) # 当字符串长度等于 1 时: dp[i,j] = true # 当字符串长度等于 2 时: dp[i,j] = (S[i] == S[j]) def longestPalindromeDp(s): n = len(s) dp = [[False] * n for _ in range(n)] ans = '' for l in range(n): ...
import psycopg2 as psy import dash import dash_core_components as dcc import dash_html_components as html import os import glob import pandas as pd import numpy as np from dash.dependencies import Input, Output, State from faker import Factory impo...
from fabric.api import task, env env.is_python3 = True env.project_name = '{{ project_name }}' env.repository = 'git@bitbucket.org:bnzk/{project_name}.git'.format(**env) env.sites = ('{{ project_name }}', ) env.is_postgresql = True # False for mysql! only used for put/get_db env.needs_main_nginx_files = True env.is...
from scrapy.cmdline import execute if __name__ == "__main__": execute(['scrapy','crawl', 'old_house'])
""" Copyright (C) 2021 NVIDIA Corporation. All rights reserved. Licensed under the NVIDIA Source Code License. See LICENSE at the main github page. Authors: Seung Wook Kim, Jonah Philion, Antonio Torralba, Sanja Fidler """ import torch from torch import nn import torch.utils.data import torch.utils.data.distributed i...
from django.conf.urls import url, include from apps.base.views import index, informacion from django.urls import include, path app_name = "base"; urlpatterns = [ url(r'^$', index,name='index'), url(r'^info$',informacion,name='informacion') ]
__author__ = "Frédéric BISSON" __copyright__ = "Copyright 2022, Frédéric BISSON" __credits__ = ["Frédéric BISSON"] __license__ = "mit" __maintainer__ = "Frédéric BISSON" __email__ = "zigazou@protonmail.com" from .PDFToken import PDFToken class PDFName(PDFToken): """A PDF name (starting with /)""" def __init_...
import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt import tempfile from collections import defaultdict from google.cloud import datastore from group_defender.constants import CHAT, FILE_TYPES from group_defender.store import datastore_client as client def update_stats(chat_id, counts): ke...
# -*- coding: utf-8 -*- from nose.tools import * # noqa: F403 import jwe import jwt import mock import furl import time from future.moves.urllib.parse import urlparse, urljoin import datetime from django.utils import timezone import pytest import pytz import itsdangerous from django.contrib.auth.models import Group f...
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2016, Jiri Tyr <jiri.tyr@gmail.com> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type DOCUMENTATION = ''' --- module: jenkins_plugin author...
import matplotlib matplotlib.use('agg') import matplotlib.pyplot as plt import numpy as np import pandas as pd import xlrd from openpyxl import load_workbook import re import collections import json LAB_URLS = {'adolfo-ferrando':['Lab Web Site', 'http://ferrandolab.org/'], 'christine-chio':['Lab Web Site',...
import csv with open('TESTE.csv') as csv_file: csv_reader = csv.reader(csv_file, delimiter=';') csv_reader.__next__ () print('{:^10}|{:^46}| {:^58}|'.format('NF-e', 'CHAVE NF-E', 'RAZÃO SOCIAL')) print('{:^10}|{:^46}| {:^58}|'.format('-' * 8, '-' * 44 , '-' * 57)) for c in csv_reader: prin...
import keras from keras.layers import Activation from keras.layers import Conv2D, BatchNormalization, Dense, Flatten, Reshape class CNN: def __init__(self): self.batch_size = 64 self.epoch = 2 def train(self, x_train, y_train): self.model = keras.models.Sequential() self....
import binascii from flask import Flask, jsonify, render_template import Crypto import Crypto.Random from Crypto.PublicKey import RSA class Transaction: def __init__(self, sender_address, sender_private_key, recipient_address, value): self.sender_address = sender_address self.sender_...
import numpy as np import argparse def gene_conditional_probs(X,thresh): CP = np.eye(X.shape[0]) for i in range(X.shape[0]): a = (X[i] > thresh) for j in range(X.shape[0]): b = (X[j] > thresh) CP[i,j] = np.average(a*b)/np.average(a) return CP if __name__ == '__main__': parser = argparse.ArgumentParser()...
from .server import * # import gzip # from locale import CODESET # import urllib # from datetime import datetime # import pika, sys, os # import nexradaws # import pyart # import base64 # import io # import pytz # from matplotlib import pyplot as plt # from rest_framework.utils import json # from rest_framework.view...
# -*- coding: utf-8 -*- # # Copyright (C) 2017 Edgewall Software # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. The terms # are also available at http://trac.edgewall.org/wiki/TracLicense. # # This software consists o...
import unittest from unittest.mock import Mock from kaggle_gcp import KaggleKernelCredentials, init_gcs from test.support import EnvironmentVarGuard from google.cloud import storage def _make_credentials(): import google.auth.credentials return Mock(spec=google.auth.credentials.Credentials) class TestStorag...
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'lundberg' import sys import os import argparse from collections import defaultdict from apiclient import NIApiClient USER = os.environ.get('USER', '') APIKEY = os.environ.get('API_KEY', '') BASE_URL = os.environ.get('BASE_URL', 'http://localhost') VERBOSE = ...
from hacker_news_assets.resources import RESOURCES_LOCAL, RESOURCES_PROD, RESOURCES_STAGING from dagster import AssetGroup, schedule_from_partitions from . import assets core_assets_prod = AssetGroup.from_package_module( package_module=assets, resource_defs=RESOURCES_PROD ).prefixed("core") core_assets_staging =...
# -*- coding: utf-8 -*- from vecto.data import Dataset from vecto.embeddings import load_from_dir from vecto.benchmarks.analogy.io import get_pairs from numpy import vstack from numpy.linalg import norm from sklearn.manifold import TSNE from sklearn.decomposition import PCA import matplotlib.pyplot as plt import ...
from __future__ import absolute_import, division, print_function import torch import torch.nn as nn import torch.nn.functional as tf def conv(in_planes, out_planes, kernel_size=3, stride=1, dilation=1, isReLU=True): if isReLU: return nn.Sequential( nn.Conv2d(in_planes, out_planes, ker...
#!/usr/bin/env python3 import json import os import sys from collections import defaultdict from argparse import ArgumentParser class cached_mutable_property: """ Decorator that converts a method with a single self argument into a property cached on the instance. Optional ``name`` argument allows yo...
items_dict={'1':'Apple', '2':'Orange','3':'Banana', '4':'Guava','5':'Mango', '6' : 'Peach','7':'Ladies Finger','8':'Peas','9':'Carrot','10':'Radish', '11':'Broccoli','12':'Mushroom','13':'Maggie','14':'Lays', '15':'Doritos', '16':'Pringles','17':'Oreos','18':'Bourbon','19':'Coke','20':'Pepsi','21':'Frooti', '22':'Maaza...
# CodingGears.io # shutil - High-level file operations import shutil # TODO: Copy file shutil.copyfile (destination path must be file) # shutil.copyfile("/home/training/sample/cities.txt", "/home/training/cities.txt.bk") # TODO: Copy file shutil.copy (destination path can be file or directory) # shutil.copy("/home/t...
from django.shortcuts import render # Create your views here. from .forms import BuscarViajeForm from django.db.models import Q,F from django.db.models.expressions import RawSQL from Nucleo.models import Viaje from django.http import HttpResponseRedirect from django.views.generic import ListView class BuscarList(ListV...
import logging import os import subprocess import sys import tempfile def save(doc, outpath, outformat=None): """ Saves document `doc` to a file at `outpath`. By default, this file will be in SVG format; if it ends with .pdf or .png, or if outformat is specified, the document will be converted to PDF...
#!/usr/bin/env python3 # Turns on pdb for opcode replacement # Note: this only works properly on Unix systems. debug_on = False # Imports import sys import json def error(message): """Function called when there's an error.""" #raise SyntaxError(message) print("jlm2asq.py:", message, file=sys.stderr) exit() ...
"""Tests for the module :mod:`esmvaltool.diag_scripts.shared.io`.""" import os from collections import OrderedDict from copy import deepcopy import iris import mock import numpy as np import pytest import yaml from esmvaltool.diag_scripts.shared import io with open(os.path.join(os.path.dirname(__file__), 'configs',...
import numpy as np import math arr = np.random.normal(3, 1, 10) res = [] for value in arr: res.append(math.floor(max(1, min(value, 5)))) print(res)
import grpc from koapy.grpc import KiwoomOpenApiService_pb2_grpc from koapy.grpc.KiwoomOpenApiServiceClientStubWrapper import KiwoomOpenApiServiceClientStubWrapper from koapy.config import config class KiwoomOpenApiServiceClient: def __init__(self, host=None, port=None): self._host = host or config.get_s...
import re import pypeg2 as peg from .grammar_util import IntNumMixin class LevelType: """ A level type, such as "FOUR_LEVEL" or "EIGHT_LEVEL". Matches quotes as well. """ grammar = "\"", peg.attr("name", re.compile(r"([A-Z]|_|\+)*")), "\"" class ScanCodeName: """ A key code such as <UP> or <DOWN> """ ...
#Program to swap two no. without using third variable print("#Program to swap two no. without using third variable") a= int(input("Enter the First Number :-")) b =int(input("Enter the Second Number :-")) a=a+b b=a-b a=a-b print('Value of first no. after swapping is :',a,'\n Value of second no. after swapping :',b) #...
import os import sys base = os.path.join(os.path.dirname(os.path.abspath(__file__)), '../') sys.path.append(base) import random import math import torch def sample_mask(im_size: int, window_size: int): """ Args: - im_size: size of image - window_size: size of window. if -1, return full size mask ...
import re import torch import importlib import numpy as np #from matplotlib import pyplot as plt #from TTS.tts.utils.visual import plot_spectrogram def interpolate_vocoder_input(scale_factor, spec): """Interpolate spectrogram by the scale factor. It is mainly used to match the sampling rates of the tts a...
from django.db import models from phone_field import PhoneField from django.core.validators import RegexValidator from django.utils import timezone # Create your models here. METHOD={ ("Khalti","Khalti"), ("E-Sewa","E-Sewa"), } class Post(models.Model): province=models.CharField(max_length=100...
"""Utilities for the-wizz library. Contains file loading/closing, cosmology, and setting the verbosity of the outputs. """ from astropy.cosmology import WMAP5 from astropy.io import fits import h5py import numpy as np def file_checker_loader(input_file_name): """Utility function for checking the existence of a ...
from django.db import models from django.contrib.auth import get_user_model from django.db.models import Q class Activity(models.Model): title = models.CharField(max_length=200) pub_date = models.DateTimeField(verbose_name="date published", auto_now_add=True) enrolled_users = models.ManyToManyField(get_us...
#!/usr/bin/env python # -*- coding: utf-8 -*- from tedega_share import ( init_logger, get_logger, monitor_connectivity, monitor_system ) from tedega_view import ( create_application, config_view_endpoint ) from tedega_storage.rdbms import ( BaseItem, RDBMSStorageBase, init_storage,...
# -*- coding: utf-8 -*- # yapf: disable """ Module to make available commonly used click arguments. """ from __future__ import absolute_import import click from aiida.cmdline.params import types from aiida.cmdline.params.arguments.overridable import OverridableArgument CALCULATION = OverridableArgument('calculation'...
# MD-TPM -> Module Dependency to be cleared at time of module (Text Processing Module) integration. # Imports import numpy as np import re from collections import defaultdict, OrderedDict from collections import namedtuple import spacy from spacy.tokens import Token import warnings import Functions as F from Function...
# Depth-first search def dfs(node, explored): if node in explored: return explored explored.append(node) for nei in node.neighbors: explored = dfs(nei, explored) return explored # Breadth-first search def bfs(start, goal): explored = [] queue_paths = [[start]] while queue_pa...
from django import forms from .models import * from rest_framework import serializers class UploadForm(forms.ModelForm): class Meta: model = Project fields = ('name','view','description','link') class ProfileForm(forms.ModelForm): class Meta: model = Profile exclude = ['user...
import os,sys import xml.etree.ElementTree as ET def findObjects(xmlFile, category): boxes = [] tree = ET.parse(xmlFile) for child in tree.getroot().findall('object'): if child.find('name').text == category: # and child.find('difficult').text != '1': bn = child.find('bndbox') box = map(float, [bn...
from typing import Dict, Any, List import pytest from checkov.common.bridgecrew.bc_source import SourceType from checkov.common.bridgecrew.platform_integration import BcPlatformIntegration, bc_integration @pytest.fixture() def mock_bc_integration() -> BcPlatformIntegration: bc_integration.bc_api_key = "abcd1234...
print('hellopyhon') print('hhl') print('1223')