content
stringlengths
5
1.05M
#---------------------------------------------------------------------------------------------- ''' What to expect from this script: 1- This will generate list of patients with sepsis and no-sepsis in each sets. 2- More details be mentioned in the csv files "info_training_train/test" ''' #-----------------------...
# -*- coding: UTF-8 -*- #Exercício Python 34: Escreva um programa que pergunte o salário de um funcionário e calcule o valor do seu aumento. Para salários superiores a R$1250,00, calcule um aumento de 10%. Para os inferiores ou iguais, o aumento é de 15%. from time import sleep print("-=-=--=-=--=-=--=-=- |SISTEMA FIN...
from guillotina.tests.utils import make_mocked_request from guillotina_amqp.utils import make_request from guillotina_amqp.utils import metric_measure from guillotina_amqp.utils import serialize_request import pytest class MockPrometheusMetric: def __init__(self, labels=None): self.labels_called = False ...
''' creates a user, item, rating, user_id, item_label csv file cord-19 corpus ''' import pandas as pd import configargparse from data import * import sys import json from create_rec_sys_dataset import * import numpy as np import unidecode import rdflib from rdflib import URIRef pd.set_option('display.max_columns', ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Script taken from http://stackoverflow.com/a/17579949/4070143 by inspectorG4dget # to remove lines above and below certain string match. # Minor modifications to read and write from stdin/stdout respectively # and to remove some extra newlines getting added import sys...
from flask import Flask, jsonify, request import pymysql app = Flask(__name__) class Database: def __init__(self): host = "csc648.cxyapjc8a04v.us-west-1.rds.amazonaws.com" user = "admin" password = "rdsmysql" db = "proddb" self.con = pymysql.connect(host=host, user=user, p...
import sys import os sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) import src.pattern.PatternBuilder as PB def test_build3(): colorsA = [0, 0, 0, 10, 10, 10, 1, 1, 1, 11, 11, 11, 2, 2, 2, 12, 12, 12, 3, 3, 3, 13, 13, 13, 4, 4, 4, 14, 14, 14, 5, 5, 5, 15, 15, 15, 6, 6, 6, 16, 16, 16...
import copy from hearthbreaker.constants import CHARACTER_CLASS, CARD_RARITY, MINION_TYPE from hearthbreaker.game_objects import Card, Minion, MinionCard, SecretCard import hearthbreaker.targeting class ArcaneMissiles(Card): def __init__(self): super().__init__("Arcane Missiles", 1, CHARACTER_CLASS.MAGE, ...
import numpy as np import math import pdb from .defaults import eps from .util import find, add_value from .polint import polint from .gls.gls import gls def csearch(fun, data, x, f, u, v, hess=None): n = len(x) x = np.minimum(v, np.maximum(x, u)) nohess = False if hess is None: nohess = Tr...
from unittest import TestCase from django.http import HttpRequest from django.test import override_settings from wagtail.wagtailcore.models import Site from v1.middleware import StagingMiddleware class StagingMiddlewareTestCase(TestCase): @override_settings(STAGING_HOSTNAME='content.localhost') def test_req...
from .market import * from .etx import * from .bond import *
from __future__ import division from __future__ import print_function from __future__ import absolute_import # noinspection PyUnresolvedReferences from six.moves import range import numpy as np import tensorflow as tf from ..framework import Layer from ..utils import tf_int_shape class SpatialGlimpse(Layer): d...
# (emacs/sublime) -*- mode:python; coding: utf-8-unix; tab-width: 4; st-trim_trailing_white_space_on_save: true; st-ensure_newline_at_eof_on_save: true; -*- # sublime version compatiblity layer # * backports ST3 API to ST2 from __future__ import absolute_import, division, print_function, unicode_literals # from __fu...
from ptrlib import * import math def search(x): if x <= 255 * 255: lx = ly = 1 for x1 in range(1, 0x100): for x2 in range(1, 0x100): if abs(x - x1 * x2) < abs(x - lx * ly): lx, ly = x1, x2 return {lx: 1, ly: 1} l = search(math.sqrt(x)) ...
# -*- coding: utf-8 -*- import wx import rmodel import h5py import rttov import util from rview import layeritem import locale import numpy import matplotlib import sys import copy import logging from profileframeutils import GenericPlotItemPanel, MyNotebook from profileframeutils import kindOfItem, PlotItemPanelAll ...
from collections import OrderedDict from allauth.account.models import EmailAddress, EmailConfirmation from django.urls import reverse from rest_framework.validators import UniqueValidator, UniqueTogetherValidator from rest_framework import serializers from .serializers import BaseSerializer __all__ = [ 'EmailSer...
import ac, acsys import traceback from math import sin, cos, pi from colourfader import ColourFader from moving_average_plotter import MovingAveragePlotter class TractionCircleView: FINAL_COLOUR_DATA_POINTS = (0.25, 0.50, 0.10, 1.00) START_COLOUR_DATA_POINTS = (0.00, 0.75, 0.00, 0.00) FINAL_COLOUR_M...
from __future__ import print_function from __future__ import absolute_import import numpy as np import warnings import xarray as xr import pysat def set_data_dir(path=None, store=True): """ Set the top level directory pysat uses to look for data and reload. Parameters ---------- path : string ...
# -*- coding: utf-8 -*- from __future__ import print_function import argparse import json import cv2 import numpy as np from os.path import isabs, realpath, join, dirname from scipy import sparse from .softmax import softmax class BaseEngineLineOCR(object): def __init__(self, json_def, gpu_id=0, batch_size=8): ...
from testutils import assert_raises def no_args(): pass no_args() assert_raises(TypeError, no_args, 'one_arg', _msg='1 arg to no_args') assert_raises(TypeError, no_args, kw='should fail', _msg='kwarg to no_args') def one_arg(arg): return arg one_arg('one_arg') assert "arg" == one_arg(arg="arg") assert_ra...
#!/usr/bin/python # encoding: utf-8 """ @author: Ian @contact:[email protected] @file: text.py.py @time: 2019/3/20 14:02 """ title = '智能金融起锚:文因、数库、通联瞄准的kensho革命' text = '''2015年9月13日,39岁的鲍捷乘上从硅谷至北京的飞机,开启了他心中的金融梦想。 鲍捷,人工智能博士后,如今他是文因互联公司创始人兼CEO。和鲍捷一样,越来越多的硅谷以及华尔街的金融和科技人才已经踏上了归国创业征程。 在硅谷和华尔街,已涌现出Alphasense、Kensho...
__author__ = 'thorwhalen' # utils to get from a pfile to... something else from ut.pfile.name import replace_extension import os import gzip def string(filename): """ returns the string contents of a pfile """ fid = file(filename) s = fid.read() fid.close() return s def zip_file(source_...
from .sed import Sed, SedException, main
sum_square = square_sum = 0 for i in range(1, 101): sum_square += 1**2 square_sum += i square_sum = square_sum ** 2 resultat = square_sum ** 2 - sum_square print("Résultat") print(resultat)
# ProDy: A Python Package for Protein Dynamics Analysis # # Copyright (C) 2010-2012 Ahmet Bakan # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your...
# Copyright 2021 The Flax Authors. # # 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 wri...
#!/usr/bin/env python import os import sys import unittest DIR = os.path.dirname(os.path.abspath(__file__)) sys.path[0] = os.path.dirname(DIR) from yorbay.lang import get_lang_chain class TestLangChain(unittest.TestCase): def test_get_lang_chain(self): self.assertEqual(get_lang_chain('root'), ['root']...
from Functions.Featurespace import Classifier from Functions.Featurespace import FeatureSpace from Functions.Featurespace import find_annodir import os import cv2 import numpy as np featurelist = FeatureSpace() type_list = find_annodir() # Run through all types for types in type_list: print(f"Importing {types}") ...
def simpleiterator(): yield 2 yield 4 yield 6 for element in simpleiterator(): print('iterator returned: %d' % element) input("press enter to continue")
from discord.ext import commands import traceback import discord errors = { commands.MissingRequiredArgument: "{e.param} is a required argument.", commands.BadArgument: "Invalid argument.", commands.PrivateMessageOnly: "This command can only be used in private messages.", commands.NoPrivateMessage: "Th...
# Generated by Django 4.0.3 on 2022-04-07 11:24 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('user', '0001_initial'), ] operations = [ migrations.AddField( model_name='user', name='first_name', fiel...
from __future__ import unicode_literals import os import random import re import subprocess import sys import time import urllib with open(sys.argv[1]) as input: for line in input: page = line.decode('utf-8').rstrip('\n') page_quote = re.sub(r'\/', '%2F', urllib.quote(page.encode('utf-8'))) ...
import os import pandas as pd from pandas.plotting import scatter_matrix import matplotlib.pyplot as plt from pathlib import Path """CONSTANTES (en mayuscula)""" path = Path(__file__) # PATH A LA FILE EN CUALQUIER ORDENADOR path2 = Path(path.parent) # Un directorio hacia atras path3 = Path(path2.parent) PATH4 = str(...
from __future__ import division import numpy as np import os import pytest from autoperiod import Autoperiod from pytest import approx from autoperiod.helpers import load_google_trends_csv, load_gpfs_csv def data(name): return os.path.join(os.path.dirname(__file__), "data", name) def test_clean_sinwave(): ...
from typing import List import cv2 import numpy as np import matplotlib.pyplot as plt def get_color(idx) -> List[int]: colors = [ (111, 74, 0), (81, 0, 81), (128, 64, 128), (244, 35, 232), (250, 170, 160), (230, 150, 140), (70, 70, 70), (102, 102, 1...
""" Play namidaga kirari by spitz """ from time import sleep from pyroombaadapter import PyRoombaAdapter PORT = "/dev/ttyUSB0" adapter = PyRoombaAdapter(PORT) adapter.send_song_cmd(0, 10, [66, 67, 69, 67, 66, 62, 64, 66, 67, 66], [16, 16, 16, 32, 32, 16, 16, 16, 16, 64...
weapons_dict = { 1: { 'name': 'Grape', 'damage': 4, 'cost': 0}, 2: { 'name': 'Strawberry', 'damage': 6, 'cost': 1000}, 3: { 'name': 'Peach Slices', 'damage': 8, 'cost': 2000}, 4: { 'name': 'Pizza', 'damage': 12, 'cost': 4000}, 5: { 'name': 'Mixed Veggies', 'damage': 16, 'cost': 8000}, 6: { 'name': 'Hamburger', 'd...
"""Constants for Dune HD integration.""" from __future__ import annotations from typing import Final ATTR_MANUFACTURER: Final = "Dune" DOMAIN: Final = "dunehd" DEFAULT_NAME: Final = "Dune HD"
from __future__ import print_function from .conda_interface import get_index import conda_build.config #import conda_build_all.logging import conda_build_all.version_matrix as vn_matrix from conda_build_all.version_matrix import setup_vn_mtx_case class ResolvedDistribution(object): """ Represents a conda p...
import asyncio from typing import * import aio_pika from twitterscraper.utils import Singleton ConsumerCallback = Callable[[bytes], Awaitable[None]] class AMQPClient(Singleton): get: Callable[..., "AMQPClient"] _connection: aio_pika.Connection _channel: aio_pika.Channel def __init__(self, uri: st...
from django.core.urlresolvers import reverse from seahub.test_utils import BaseTestCase class PasswordChangeTest(BaseTestCase): def test_can_render(self): self.login_as(self.user) resp = self.client.get(reverse('auth_password_change')) self.assertEqual(200, resp.status_code) sel...
from flask import Flask, request from flask_restful import Resource, Api from json import dumps from flask_cors import CORS import time from pymongo import MongoClient import os import copy # Create Flask RESTful api with CORS app = Flask(__name__) CORS(app) api = Api(app) # Load DB client = MongoClient('mongodb://ad...
from tweetguessr.tweetguessr import TweetGuessr args = vars(TweetGuessr.parse_arguments()) tweetguessr = TweetGuessr(args) tweetguessr.main(args)
#!/usr/bin/env python # (c) 2017-2018, ETH Zurich, Institut fuer Theoretische Physik # Author: Dominik Gresch <[email protected]> import numpy as np import pymatgen as mg import pymatgen.symmetry.analyzer import symmetry_representation as sr POS_In = (0, 0, 0) POS_As = (0.25, 0.25, 0.25) orbitals = [] for spin in (sr....
#!/usr/bin/env python #coding: utf8 """Zipper A class that can zip and unzip files. """ __author__ = "José Lopes de Oliveira Júnior" __license__ = "GPLv3+" import os import zipfile try: import zlib has_zlib = True except: has_zlib = False class Zipper(object): """This is the main class. ...
import unittest from talipp.indicators import SMMA from TalippTest import TalippTest class Test(TalippTest): def setUp(self) -> None: self.input_values = list(TalippTest.CLOSE_TMPL) def test_init(self): ind = SMMA(20, self.input_values) print(ind) self.assertAlmostEqual(in...
import glob import json import elasticsearch as es from elasticsearch import helpers es_client = es.Elasticsearch(["es01:9200"]) # TODO: POST setup.json if index doesn't exist. if not es_client.indices.exists("articles"): body = json.load(open("setup.json")) es_client.indices.create("articles", body) N=100 ...
try: import requests except ImportError: print('Requests Module Not Found !!') imp = input('Do You Want To Install Requests? y/n ') if imp=='y' or 'Y': import os os.system('pip install requests') os.system('clear') os.system('clear') os.system('clear') print('Installation Completed!') print('Now Check...
import fasttext import os import pandas as pd import numpy as np import pickle from tqdm import tqdm from scipy.stats import sem from prettytable import PrettyTable # Tensorflow import tensorflow as tf from tensorflow import keras import kerastuner as kt from kerastuner.tuners import Hyperband # Scikit-learn from skl...
#!/usr/bin/python # Copyright 2017 Google Inc. 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...
#!/usr/bin/env python import Tkinter as Tk root=Tk.Tk() b=Tk.Button(root, text="Hello!!", ) b.pack() cb=Tk.BooleanVar() def disable_b(): if cb.get()==True: b['state']='disable' else: b['state']='normal' c=Tk.Checkbutton(root, text="disabled", va...
#here's where we'll interact with gcloud datastore to manage the database from google.cloud import datastore import data _USER_ENTITY = 'ideaHubUser' _IDEA_ENTITY = 'idea' def _get_client(): """Build a datastore client.""" return datastore.Client() def log(msg): """Log a simple message.""...
import sublime import sublime_plugin if int(sublime.version()) < 3000: from sublime_haskell_common import attach_sandbox, get_cabal_project_dir_and_name_of_view, get_setting else: from SublimeHaskell.sublime_haskell_common import attach_sandbox, get_cabal_project_dir_and_name_of_view, get_setting class Subli...
#!/usr/bin/env python3 """ A module to work with MITRE D3FEND """ import argparse import csv import logging from rdflib import Graph, Namespace from rdflib.namespace import OWL, RDFS, RDF D3FEND_JSON_LD = "https://d3fend.mitre.org/ontologies/d3fend.json" D3FEND_NAMESPACE = "http://d3fend.mitre.org/ontologies/d3fend.o...
""" Copyright 2013, 2014 Ricardo Tubio-Pardavila 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 ...
# -*- coding: utf-8 -*- #this document is used to combine theory and simulation result together to generate #some new files which is easy to analyze import pandas as pd filename_base_theory = 'D:\\document\\matching probability\\data\\version2\\theory\\' filename_base_simulation = 'D:\\document\\matching probabi...
from django.db import models # Create your models here. class User(models.Model): uid = models.IntegerField(primary_key=True) age = models.PositiveSmallIntegerField() sex = models.CharField(max_length=5, choices=(("M", "Man"), ("F", "Femme"))) postal_code = models.CharField(max_length=500) occupa...
""" Piecewise convolutional networks as encoder """ import torch import torch.nn as nn class PcnnEncoder(nn.Module): def __init__(self, opt): super(PcnnEncoder, self).__init__() self.opt = opt self.activation = nn.ReLU(inplace=True) self.dropout = nn.Dropout(opt.dropout_keep...
# -*- coding: utf-8 -*- DESC = "tmt-2018-03-21" INFO = { "TextTranslate": { "params": [ { "name": "SourceText", "desc": "待翻译的文本,文本统一使用utf-8格式编码,非utf-8格式编码字符会翻译失败,请传入有效文本,html标记等非常规翻译文本会翻译失败。单次请求的文本长度需要低于2000。" }, { "name": "Source", "desc": "源语言,参照Target支持语言列表" ...
import flask import config def render_rivets_client(page_mode, sign_response=None, send_response=None, release_response=None): return flask.render_template( "client.html", page_mode=page_mode, environment=config.ENVIRONMENT, public_apigee_url=config.PUBLIC_APIGEE_URL, base_u...
from .classic_model import ClassicModel from .classic_user import ClassicSystemUser
from parsimonious import Grammar ws = r""" _ = comment / line_comment / ~"\s*" ws = ~"\s+" le = ~"(\r\n|\r|\n)" comment_start = "/*" comment_end = "*/" comment_content = comment / (!comment_start !comment_end ~"."s) comment = com...
import ast import types from sherlock.errors import CompileError, SyntaxNotSupportError, FunctionIsNotAnalyzedError from sherlock.codelib.analyzer.variable import Variables, Type from sherlock.codelib.analyzer.function import Functions from sherlock.codelib.generator.temp_variable import TempVariableManager CONTEXT_ST...
# -*- coding: utf-8 -*- """ :authors: - Tobias Grosch """ import os class RegisterFactory: @staticmethod def get_register(arguments, config_parser): return SimpleRegister() class SimpleRegister: def check(self, file_path): return os.path.isfile(file_path) def add(self, file_path):...
import json from unittest import mock from django.contrib.auth import get_user_model from django.test import RequestFactory, testcases import graphene from graphene_django.views import GraphQLView from graphql.execution.execute import GraphQLResolveInfo from graphql_jwt.decorators import jwt_cookie from graphql_jwt....
# Generated by Django 2.1.9 on 2019-07-02 03:50 from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('contacts', '0005_auto_20190630_0943'), ('hackathons', '0006_sponsorship_notes'), ] ...
#!/usr/bin/env python3 import sys sys.path.insert(0,'../') from aoc_input import * import networkx as nx if len(sys.argv) != 2: print('Usage:', sys.argv[0], '<input.txt>') sys.exit(1) a = input_as_lines(sys.argv[1]) G = nx.Graph() for line in a: a, b = re.findall(r'([A-Za-z]+)', line) if not a in G...
TEXTS_COLLECTION = "texts" CHAPTERS_COLLECTION = "chapters" FRAGMENTS_COLLECTION = "fragments"
from .vannilla import SimpleModel import tensorflow as tf import numpy as np import os.path as osp import random class DropOutModel(SimpleModel): def __init__(self, *args, **kwargs): SimpleModel.__init__(self, *args, **kwargs) self.keep_prob = kwargs.get('keep_prob') self.n_bayes_samples ...
def leiaint(msg): while True: try: i = int(input(msg)) except KeyboardInterrupt: print('entrada de dados interrompida pelo usuario.') break except (ValueError, TypeError): print(f'\033[0;31m ERRO! digite um numero valido \033[m') co...
import os import pickle from sys import platform import time import timeit import itertools import file_object import mimeDict from test_import import * # aList = [1,2,3] # bList = [4,5,6] # a, b = tuple(aList), tuple(bList) # print(type(b)) # print(a) # print(b) # print(os.path.isdir('...
#This is the main application handler for Hippocrates experiment creation #it provides functionality for its main route /experiment #Arkangel AI #Responsible: Nicolas Munera from flask import Flask, jsonify, request, send_from_directory from flask_cors import CORS,cross_origin from six.moves import http_client from ap...
import argparse import numpy as np import scipy.io as sio from pathlib import Path from tqdm import tqdm from PIL import Image def main(): parser = create_argument_parser() args = parser.parse_args() generate_ccp_dataset(args) def create_argument_parser(): parser = argparse.ArgumentParser() parser.add_argument(...
from lark import Tree from src.interpreter.expression import Expression import src.interpreter.globals as globals from src.interpreter.userfunction import UserFunction def func(name, args: Tree, body): parsed_name = Expression(name, globals.codebase) parsed_args = list(map(lambda x: Expression(x, globals.code...
import setuptools with open("README.md", "r", encoding="utf-8") as fh: long_description = fh.read() with open("VERSION", "r", encoding="utf-8") as ver: version = ver.read() setuptools.setup( name="simple-api", version=version, author="Karel Jilek", author_email="[email protected]", d...
import abc import atexit import contextlib import os import pathlib import random import tempfile import time import typing import logging from . import constants from . import exceptions from . import portalocker logger = logging.getLogger(__name__) DEFAULT_TIMEOUT = 5 DEFAULT_CHECK_INTERVAL = 0.25 DEFAULT_FAIL_WHE...
from math import ceil import asyncio import os from PIL import Image from pynq import Xlnk from numpy import array from ctypes import * from . import Arduino from . import MAILBOX_OFFSET from . import MAILBOX_PY2IOP_CMD_OFFSET ARDUINO_CAM_UART_PROGRAM = "arduino_cam_uart.bin" WRITE = 0x2 READ = 0x3 class Arduino_CAM...
import pdb import os import math import random import argparse import numpy as np from graph_utils import incidence_matrix, get_edge_count from dgl_utils import _bfs_relational from data_utils import process_files, save_to_file def get_active_relations(adj_list): act_rels = [] for r, adj in enumerate(adj_lis...
import time import torch import torch.nn as nn import torchvision.models import torchvision.transforms as transform from torchvision.datasets import DatasetFolder from PIL import Image from torch.utils.data import Dataset, DataLoader, ConcatDataset import numpy as np import matplotlib.pyplot as plt config = { 'epo...
''' Copyright (c) 2018, UChicago Argonne, LLC. All rights reserved. Copyright 2018. UChicago Argonne, LLC. This software was produced under U.S. Government contract DE-AC02-06CH11357 for Argonne National Laboratory (ANL), which is operated by UChicago Argonne, LLC for the U.S. Department of Energy. The U.S. Government...
# 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 agreed to in...
def sum_squares(lst): """" This function will take a list of integers. For all entries in the list, the function shall square the integer entry if its index is a multiple of 3 and will cube the integer entry if its index is a multiple of 4 and not a multiple of 3. The function will not change the entr...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('billing', '0012_product_is_food'), ('billing', '0015_merge'), ] operations = [ ]
from typing import Any, Dict, List, Type, TypeVar, Union import attr from ..models.generated import Generated from ..types import UNSET, Unset T = TypeVar("T", bound="CredDefValuePrimary") @attr.s(auto_attribs=True) class CredDefValuePrimary: """ """ n: Union[Unset, str] = UNSET r: Union[Unset, Genera...
from __future__ import annotations from fisher_py.net_wrapping import NetWrapperBase, ThermoFisher from typing import List from fisher_py.data.business import Range, TraceType from fisher_py.utils import to_net_list class ChromatogramTraceSettings(NetWrapperBase): """ Setting to define a chromatogram Trace. ...
import pytest import numpy as np from numpy.testing import assert_allclose from sklearn.compose import ColumnTransformer from sklearn.datasets import load_boston from sklearn.datasets import load_iris from sklearn.datasets import make_classification from sklearn.datasets import make_regression from sklearn....
"""Implementation of the "init" method.""" import sys from ._helpers import (get_path, combine, dictify, undictify, load_yaml, dump_yaml, dump_yaml_into_str, to_literal_scalar) # The standard "minimal-cluster-config.yml" is not used here because # it contains too many extra documents MINIMAL_E...
from django.urls import path from . import views ''' This file specifies the mapping between urls and views Note: The "name" parameter is used in tests to decouple the urls from tests. This mean that you can change the urls and not affect the tests if the name parameter is unchanged ''' app_name = 'backend' urlpatte...
import tkinter from tkinter import * import cv2 import PIL.Image, PIL.ImageTk import time import argparse import os from keras import backend as K import tensorflow as tf from scipy.spatial import distance as dist from imutils.video import VideoStream from imutils import face_utils from threading import Thread import n...
""" like batched_inv, but this implementation runs the sparse matrix stuff in a set of separate processes to speed things up. """ import numpy as np import wmf import batched_inv import multiprocessing as mp import Queue def buffered_gen_mp(source_gen, buffer_size=2, sleep_time=1): """ Generator that runs a...
from audio.insertor import Inserter from helper.file import File file_dir = 'sample/audio/StarWars3.wav' secret_message_dir = 'sample/text/message.txt' key = "kuncirahasia" insert = Inserter(file_dir, secret_message_dir, key) frame_modified = insert.insert_message( randomize_bytes=False, randomize_frames=Fa...
from pyglottolog.links import endangeredlanguages, wikidata def test_el(elcat): res = endangeredlanguages.read() assert len(res) == 1 assert len(res[0].coordinates) == 1 assert res[0].url.endswith('1') def test_wikidata(mocker, api_copy): class wd(object): def post(self, *args, **kw): ...
#!/usr/bin/env python """The setup script.""" from setuptools import setup, find_packages if "__main__" == __name__: setup( author="Hao-Ting Wang", author_email='[email protected]', python_requires='>=3.7', description="Crawl public BIDS dataset on AWS to datalad", name='...
""" A threaded shared-memory scheduler See async.py """ from __future__ import absolute_import, division, print_function from multiprocessing.pool import ThreadPool from threading import current_thread from .async import get_async, inc, add from .compatibility import Queue from .context import _globals default_pool...
import numpy as np from cogue.crystal.utility import klength2mesh class Imaginary: def __init__(self, phonon, distance=200): self._phonon = phonon # Phonopy object self._lattice = np.array(phonon.get_unitcell().get_cell().T, dtype='...
import unittest from my_test_api import TestAPI class TestCreateIssue(TestAPI): def test_create_issue(self): params = { 'project': 'API', 'summary': 'test issue by robots', 'description': 'You are mine ! ', } response = self.put('/issue/', params) ...
import imageio import os filenames=sorted((fn for fn in os.listdir('.') if fn.endswith('.png'))) print filenames images = [] for filename in filenames: images.append(imageio.imread(filename)) imageio.mimsave('run_2_anom.gif', images)
import unittest from geom2d import Point, Size, Rect from graphic.svg.image import svg_content class TestSvgImage(unittest.TestCase): size = Size(200, 350) viewbox = Rect(Point(4, 5), Size(180, 230)) def test_parse_width(self): svg = svg_content(self.size, []) self.assertTrue('width="20...
import numpy as np import onnx from collections import defaultdict from typing import Any, Dict, List, Union from .. import operations from ..graph import OperationGraph from ..operations import Operation from ..utils import NUMPY_TO_ONNX_DTYPE from ..visitors import OperationVisitor def convert(op_graph: Operation...
def lstm_prediction(se, stock_symbol): import pandas as pd import numpy as np def fetch_stock_data(se, stock_symbol): from pandas_datareader import data as pdr import yfinance as yf yf.pdr_override() if se == 'NSE': stock_symbol += ".NS" return pdr.get_data_yahoo(stock_symbol, period="5y") from sklea...