content stringlengths 5 1.05M |
|---|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright SquirrelNetwork
import asyncio
from core import decorators
from core.utilities.message import message,messageWithId, messageWithAsyncById
from core.utilities.strings import Strings
from core.database.repository.community import CommunityRepository
from telegram... |
import os
import io
import math
import copy
import random
import numpy as np
import tensorflow as tf
import cv2
import matplotlib.pyplot as plt
from PIL import Image, ImageDraw
from itertools import permutations
# Helper data generation functions.
def serialize_array(array):
array = tf.io.serialize_tensor(array)
... |
token = '264862990:AAEODOt9LfE3qRBOpOpiawq5iECp8yPPkuU' # Add Your Token
is_sudo = '90516804.172561830' # add Your ID
|
from django.http import HttpResponse
from rest_framework import generics
from django.contrib.auth.models import User
from rest_framework.response import Response
from api import serializers
from api.models import Post, Comment, Category
from rest_framework import permissions
from api.permissions import IsOwnerOrReadOn... |
# -*- coding: utf-8 -*-
"""
log_it.extensions
-----------------
Flask Extensions used by Log-It
:copyright: (c) 2020 by John te Bokkel
:license: BSD, see LICENSE for more details
"""
from sqlalchemy import MetaData
from flask_sqlalchemy import SQLAlchemy
from flask_debugtoolbar import DebugTool... |
from re import search
import requests
from bs4 import BeautifulSoup as bs
def _find_real_page(url):
soup = bs(requests.get(url).text, "html.parser")
real_url = [
m
for m in [
search(r"(?:go\_to\"\:\")([^\s]+)(?:\"\}\;)", str(sc))
for sc in soup.find_all("script")
... |
# Copyright 2020 The PyMC Developers
#
# 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 os
import math
import numpy as np
import matplotlib.pyplot as plt
from simuran.plot.figure import SimuranFigure
from neurochat.nc_utils import butter_filter
from lfp_atn_simuran.analysis.lfp_clean import LFPClean
def mne_plot(recording, base_dir, figures, **kwargs):
method = kwargs.get("clean_method", "a... |
#!python3
import os
import sys
import logging
import json
import shutil
from util.validate import validate_init_params
from util.downloaders import DownloadGenomeToFNA , DownloadFASTQs, \
GetGenomeOrganismName, download_mutantpool
"""
This function needs to do a number of things:
1.... |
from shutil import rmtree
from tarfile import open as tar_open
from os.path import join
from django.conf import settings
from django.contrib import admin, messages
from django.core.exceptions import ValidationError
from django import forms
from django.core.management import call_command
from django.urls import reverse_... |
import os, stat
import subprocess
from odoo_env.__init__ import __version__
from odoo_env.messages import Msg
from odoo_env.odoo_conf import OdooConf
msg = Msg()
class Command:
def __init__(self, parent, command=False, usr_msg=False, args=False,
client_name=False):
"""
:param par... |
#!/usr/bin/env python
# William Lam
# www.virtuallyghetto.com
"""
vSphere Python SDK program for listing all ESXi datastores and their
associated devices
"""
import argparse
import atexit
import json
from pyVim import connect
from pyVmomi import vmodl
from pyVmomi import vim
from tools import cli
def get_args():
... |
### example code of GIN using DGL
import torch
from torch.utils.data import DataLoader
import dgl.function as fn
import dgl
import torch.optim as optim
import torch.nn.functional as F
from tqdm import tqdm
import argparse
import time
import numpy as np
### importing OGB
### for loading dataset
from ogb.graphproppred... |
from lib import agent
from lib import congaboard
from lib import node
#
# end-of-game logging
#
def log (loser, movecount):
winner = 1 if 0 == loser else 0
print 'GAME OVER. PLAYER ', winner, 'WINS.'
for p in range(0,2):
print 'player', p, ': moved', movecount[p], 'times'
#human will play as player 1
p... |
import unittest
import os, glob
from test_all import db, test_support, get_new_environment_path, \
get_new_database_path
#----------------------------------------------------------------------
class DBEnv(unittest.TestCase):
def setUp(self):
self.homeDir = get_new_environment_path()
self.... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
from __future__ import print_function
import glob
import imp
import inspect
import logging
import os
import subprocess as sp
import sys
try:
from lxml import etree as et
except ImportError:
logging.critical("Cannot run the program!")
logging.critical("Are you ... |
'''This plots the results of the parameter sweep for the long-term bubbling
example.
'''
from os import mkdir
from os.path import isdir
from pickle import load
from numpy import arange, array, atleast_2d, hstack, sum, where, zeros
from matplotlib.pyplot import axes, close, colorbar, imshow, set_cmap, subplots
from mpl_... |
import logging
from progress.bar import IncrementalBar
import numpy as np
from counter_attack import utils
logger = logging.getLogger(__name__)
def get_iterator(name, logger, loader):
if logger.getEffectiveLevel() == logging.INFO:
return IncrementalBar(name).iter(loader)
else:
return loader
... |
c = get_config()
c.NotebookApp.port = 8998
c.NotebookApp.open_browser = False
c.KernelRestarter.time_to_dead = 6.0
c.NotebookApp.ip = "*"
c.NotebookApp.allow_origin = "*"
|
import datetime
from sqlalchemy import Column, DateTime, Integer, String
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class Migration(Base):
__tablename__ = "migrations"
id = Column(Integer, primary_key=True)
name = Column(String(50))
migrated_at = Column(DateT... |
"""
Computation engines for executing Pipelines.
This module defines the core computation algorithms for executing Pipelines.
The primary entrypoint of this file is SimplePipelineEngine.run_pipeline, which
implements the following algorithm for executing pipelines:
1. Determine the domain of the pipeline. The domain... |
import scipy
import datetime
import calendar
import numpy as np
from dateutil.relativedelta import relativedelta
import math
# Takes in the start date for the Day Ahead and converts in into a datetime with daily resolution.
def da_date(start_date):
return datetime.date(start_date.year, start_date.month, start_date... |
from lib.imports.default import *
import lib.permissions.applications.get as get_application
import lib.permissions.users.add as add_user
def call(**kwargs):
manager = Manager()
db = manager.db("appinit")
cursor = db.permissions.find_one({
"application": kwargs["application"],
"uid": kwargs["uid... |
# -*- coding: utf-8 -*-
# pylint: disable=C0103,R0201,W0401,W0614,W0621
# C0103 Invalid name (setUp(), ...)
# R0201 Method could be a function
# W0401 Wildcard import
# W0614 Unused import ... from wildcard import
# W0621 Redefining name ... from outer scope
from __future__ import absolute_import
i... |
from vcf2fhir.converter import Converter
|
import numpy as np
import random
import matplotlib.pyplot as plt
'''
בנו מערך שמכיל עשרה מספרים שלמים רנדומליים. .a
'''
random_int_array = np.random.randint(1,50,10)
'''
מערך הזה יהיה .x שברים( ושמרו אותו במשתנה ( floats בנו מערך שמכיל עשרה .b
הבסיס לבניית שלושת הדאטהסטים בהמשך.
'''
random_frac... |
from .base import Field, Model
class TicketData(Model):
authority = Field(str)
level = Field(str)
price = Field(float)
price_child = Field(float)
def __eq__(self, other):
if not isinstance(other, TicketData):
return False
if self.price != other.price:
retu... |
from imgaug import augmenters as iaa
from keras.preprocessing.image import *
import cv2
from tqdm import tqdm
from config import *
# rotate images
def rotate(image, angle, center=None, scale=1.0):
(h, w) = image.shape[:2]
if center is None:
center = (w / 2, h / 2)
M = cv2.getRotationMatrix2D(center... |
#------------------------------------------------------------------------------
# Copyright (c) 2008, Riverbank Computing Limited
# All rights reserved.
#
# This software is provided without warranty under the terms of the BSD
# license included in enthought/LICENSE.txt and may be redistributed only
# under the conditi... |
import sys
import os
import tempfile
import subprocess
SMINA_PATH = os.path.join(os.getcwd(), 'nanome_docking', 'smina', 'smina_binary')
class DockingCalculations():
def __init__(self, plugin):
self.plugin = plugin
self.requires_site = True
self.loading_bar_counter = 0
async def st... |
import sys, wx, numpy, wx.lib.plot, plot, thread, time
wx.lib.plot = plot
from __main__ import DEBUG, USE_THREADS
DEBUG = '--debug' in sys.argv
class PlotCanvas(plot.PlotCanvas):
def __init__(self, parent, color='green'):
plot.PlotCanvas.__init__(self, parent)
self.mutex = thread.allocate_lock()
... |
import logging
import logging.config
import os
import shutil
import sys
from typing import List, Optional
import click
import pkg_resources
from plumbum import ProcessExecutionError
from pyfzf import FzfPrompt
from . import utils
from .config import config
from .parse import parse_pipeline_file
from .runner import Pi... |
#! /usr/bin/env python
import sys
for linha in sys.stdin:
try:
campos = linha.split(';')
mercadoria = str(campos[3])
print '%s\t%s' % (mercadoria, 1)
except:
continue
|
import cv2
import numpy as np
from PIL import Image
import os
os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
import tensorflow as tf
from tensorflow.python.platform import gfile
def image_normalized(img):
'''
tif,size:512*512,gray
:param dir_path: path to your images directory
:return:
'''
MAX_LEN ... |
# -*- coding: utf-8 -*-
#--------------------------------------------------------------------------
#
# Copyright (c) Microsoft Corporation. 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 fil... |
"""Module in charge of generating mocks."""
__all__ = ["GeneratedMock", "FileGenerator"]
import os
import re
from copy import deepcopy
from jinja2 import Environment, PackageLoader
from pycparser import c_ast as node
from pycparser.c_generator import CGenerator
from . import __version__
def decl(name, type):
... |
def _normalize_text(s):
"""Removing articles and punctuation, and standardizing whitespace are all typical text processing steps."""
import string, re
def remove_articles(text):
regex = re.compile(r"\b(a|an|the)\b", re.UNICODE)
return re.sub(regex, " ", text)
def white_space_fix(text)... |
import cv2
import numpy as np
choice = -1
while choice != 1 and choice != 2:
choice = int(input("Which set would you like to use? Enter 1 or 2:"))
# Training #
if choice == 2:
samples = np.loadtxt('set2generalsamples.data', np.float32)
responses = np.loadtxt('set2generalresponses.data', np.float32)
... |
import json
import requests
from .base import (
AreaCollection, EventCollection, MembershipCollection, PersonCollection,
OrganizationCollection, PostCollection)
class Popolo(object):
@classmethod
def from_filename(cls, filename):
with open(filename) as f:
return cls(json.load(f)... |
#1014 - Consumo de combustível
distanciakm = int(input())
litros = float(input())
consumo = distanciakm/litros
print("%.3f km/l"%consumo) |
import sys
import warnings
from inspect import isfunction
import numpy as np
import matplotlib.pyplot as plt
from pysprint.core.methods.fftmethod import FFTMethod
from pysprint.core.phase import Phase
from pysprint.core._fft_tools import find_roi
from pysprint.core._fft_tools import find_center
from pysprint.utils.de... |
__all__ = ['publisher']
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# This file was part of Flask-Bootstrap and was modified under the terms of
# its BSD License. Copyright (c) 2013, Marc Brinkmann. All rights reserved.
#
# This file was part of Bootstrap-Flask and was modified under the terms of
# its MIT License. Copyright (c) 2018 Grey ... |
from numpy import arange, newaxis, sin
from pylab import randn, plot, scatter, hold
from monte.arch.neuralnet import NeuralnetIsl
from monte.gym import trainer
mynn = NeuralnetIsl(1,10,1) #neural network with one input-, one output-,
#and one hidden layer with 10 sigmoid u... |
# *****************************************************************************
#
# Copyright (c) 2019, the Perspective Authors.
#
# This file is part of the Perspective library, distributed under the terms of
# the Apache License 2.0. The full license can be found in the LICENSE file.
#
def line(dat, col, index='in... |
# Implementar la funcion crear_tabla_peso, que cree una tabla PersonaPeso con:
# - IdPersona: Int() (Clave Foranea Persona)
# - Fecha: Date()
# - Peso: Int()
# Implementar la funcion borrar_tabla, que borra la tabla creada anteriormente.
from frro_soporte_2019_01.practico_03a.ejercicio_01 import crear_tabla, borrar_t... |
import smbus
import time
# Register Map
Scale_Registers = {'NAU7802_PU_CTRL': 0x00,
'NAU7802_CTRL1': 1,
'NAU7802_CTRL2': 2,
'NAU7802_OCAL1_B2': 3,
'NAU7802_OCAL1_B1': 4,
'NAU7802_OCAL1_B0': 5,
'NAU7802_GCA... |
from operator import eq
from typing import AbstractSet, Tuple
import pytest
from ...exceptions import NeuroLangException
from ...expressions import Constant, FunctionApplication, Symbol
from ...relational_algebra import (ColumnInt, ColumnStr, Difference,
NameColumns, NaturalJoin, Pr... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_get_user_config
--------------------
Tests formerly known from a unittest residing in test_config.py named
TestGetUserConfig.test_get_user_config_valid
TestGetUserConfig.test_get_user_config_invalid
TestGetUserConfig.test_get_user_config_nonexistent
"""
import o... |
class SettingStateException(Exception):
def __str__(self):
return "invalid values for state massive: values in each row have to be distinct"
class SettingWinningCombinationsException(Exception):
def __str__(self):
return "invalid values for dict combinations:"
class CombinationLengthExceptio... |
import numpy as np
class LineElement:
"""LineElement represents a finite arc in the discretization of the domain boundary."""
def __init__(self, a, b, n, is_fault):
"""Constructor.
:param a: Start point
:param b: End point
:param n: Outward-pointing normal
:param is_fa... |
from ftfy import fix_text
from config import normalization
from date_detector import Parser as dParser
import re
# regexp to remove multiple whitespaces
# https://stackoverflow.com/a/2077906/1169798
_RE_COMBINE_WHITESPACE = re.compile(r"\s+")
# init common objects
dDetector = dParser()
def decode(text):
# https... |
from tkinter import *
import random
import subprocess
startWindow = Tk()
startWindow.title('Enigma')
startWindow.geometry('1920x1080')
startWindow.resizable(0, 0)
# startWindow.overrideredirect(True)
# startWindow.geometry("{0}x{1}+0+0".format(startWindow.winfo_screenwidth(), startWindow.winfo_screenheight()))
startWi... |
from math import sin, cos, sqrt, atan2, radians
from pprint import pprint
from random import random, shuffle
import matplotlib.pyplot as plt
import gspread
from oauth2client.service_account import ServiceAccountCredentials
import ast
scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/d... |
from Clientes import Cliente
class Mercado:
''' Modelagem de um sistema de mercadinho'''
def __init__(self, usuario):
self._usuario = usuario
self._produtos = {'arroz': [2.50, 1000], 'feijao': [4.50, 1500]}
self._status = False
self._extrato = []
@property
def usuario... |
'''
Functions for loading the zBUS, PA5 and RPcoX drivers and connecting to the
specified device. In addition to loading the appropriate ActiveX driver, some
minimal configuration is done.
Network-aware proxies of the zBUS and RPcoX drivers have been written for
TDTPy. To connect to TDT hardware that is running... |
from __future__ import absolute_import
from PIL import Image
from torchvision import models, transforms
from torch.autograd import Variable
from torch.nn import functional as F
from matplotlib import pyplot as plt
import numpy as np
from pathlib import Path
import cv2
__all__ = ['CAM']
features = []
class CAM(objec... |
from handler import PingpongHandler as Handler
OMP_NUM_THREADS = 2
|
'''Junos implementation of ShowRun class'''
class ConfigureSnapshotCommand(object):
"""ConfigureSnapshotCommands class
`ConfigureSnapshotCommands` class provides the functionality to
retrieve the platform specific configurations command.
"""
@property
def command(self):
"""Method to... |
"""Pure-Python scanner and parser, used if _speedups is not available."""
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
from collections import deque
import re
DEBUG = False
# TODO copied from __init__
_blocks_re = re.compile(r'[{},;()\'"\n]')
... |
import os
import threading
import logging
import platform
from pocketsphinx import get_model_path
from pocketsphinx.pocketsphinx import Decoder
import alexapi.triggers as triggers
from .basetrigger import BaseTrigger
logger = logging.getLogger(__name__)
class PocketsphinxTrigger(BaseTrigger):
type = triggers.TYP... |
import hashlib
import math
import multiprocessing as mp
import time
from math import pi, sqrt
import cython
import numpy as np
import numpy.typing as npt
from scipy.special import erf, expi
from .mesh import Element
from .quadrature import (DuffyScheme2D, ProductScheme2D,
gauss_quadrature_sch... |
import sys
import os
import torch
import torch.nn as nn
from models.gen_components import Filtration, PositionwiseFeedForward, ResUnet
import unittest
class TestFilteringCNN(unittest.TestCase):
def test_shape(self):
sino = torch.randn(1, 1, 180, 512)
_ , _ , n_angles, detect_len = sino.shape
... |
# coding: utf-8
# # Machine learning - Protein Chain Classification
#
# In this demo we try to classify a protein chain as either an all alpha or all beta protein based on protein sequence. We use n-grams and a Word2Vec representation of the protein sequence as a feature vector.
#
# [Word2Vec model](https://spark.a... |
from django.db import migrations, transaction
class Migration(migrations.Migration):
dependencies = [
('auth', '__latest__'),
('AcadeMeData', '0001_initial'),
]
def generate_data(apps, schema_editor):
from AcadeMeData.models import Degree
test_data = [
(1, 'C... |
from pyfluidsynth3 import fluidaudiodriver, fluidhandle, fluidplayer, fluidsettings, fluidsynth
import sys
''' Based on the examples from pyfluidsynth by MostAwesomeDude. '''
if len( sys.argv ) < 4:
print( "Usage: {0} library soundfont.sf2 song.mid".format(sys.argv[0]) )
sys.exit()
handle = fluidhandle.Flui... |
import numpy as np
import argparse
from MultinomialNBClassifier import multinomial_nb_classifier
from NBClassifier import nb_classifier
from LogisticRegressionClassifer import lr_classifer
from SGDClassifier import sgd_classifier
from Parser import get_vocabulary, bag_of_words, bernoulli
def main():
parser = argp... |
# -*- encoding: utf-8 -*-
import time
import allure
# Одновременное изменение всех контактных данных Клиента
@allure.title("Одновременное изменение всех контактных данных Клиента (позитивный тест)")
def test_changing_client_info(app):
print("test_changing_client_info.py is running")
client_name = "Autotes... |
import tldextract
try:
from django.utils.deprecation import MiddlewareMixin
except ImportError:
MiddlewareMixin = object
class SubDomainMiddleware(MiddlewareMixin):
"""
Append subdomain ie. UUID to the request object to identify projects.
"""
def process_request(self, request):
try:
... |
# -*- encoding: utf-8 -*-
'''
@Func : transfer file to bert-readable style
@Time : 2021/03/04 17:36:47
@Author : Yixiao Ma
@Contact : mayx20@mails.tsinghua.edu.cn
'''
import os
import re
import numpy as np
import json
import argparse
from tqdm import tqdm
import sys
sys.path.append('/work/mayixiao/www2... |
"""
The module of tools for parallelization (MPI)
"""
import numpy as np
try:
from mpi4py import MPI
def get_id_within_node(comm=MPI.COMM_WORLD):
rank = comm.rank
nodename = MPI.Get_processor_name()
nodelist = comm.allgather(nodename)
return len([i for i in nodelist[:rank] if i=... |
#!/usr/bin/python3
import os, requests, sys, json
import asyncio
import argparse
import random
RPi_IPs = [
{"column_num": 1, "ip_addr": "129.217.152.74", "mac_id": "b8:27:eb:41:99:a0", "hostname": "raspberrypi"},
{"column_num": 2, "ip_addr": "129.217.152.111", "mac_id": "b8:27:eb:c0:fd:6a", "h... |
# ---------------------------------------------------------------------
# Parse OSM XML and return address to coodinates bindings
# ---------------------------------------------------------------------
# Copyright (C) 2007-2020 The NOC Project
# See LICENSE for details
# ------------------------------------------------... |
#strings
a = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print(a)
#string as array
a = "Hello, World!"
print(len(a))
print(a[1])
print(a[2:5])
print(a[-5:-2])
print(" sss s sss s ".strip())
print(a.lower())
print(a.upper())
print... |
import numpy as np
from scipy.optimize import leastsq
import matplotlib
matplotlib.use('TkAgg') # Actually lets the graph be displayed
import pylab as plt
from process_data import *
fig = plt.figure(1, figsize=(9, 5), dpi=150)
#fig.suptitle('\\textbf{Torque Felt by Driven Gear vs. Difference in Displacements}', fontw... |
from datetime import date
from decimal import Decimal
import pytest
from biip import ParseError
from biip.gln import Gln
from biip.gs1 import GS1ApplicationIdentifier, GS1ElementString, GS1Prefix
from biip.gtin import Gtin, GtinFormat
from biip.sscc import Sscc
@pytest.mark.parametrize(
"value, expected",
[... |
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='users-index'),
path('<username>/profile', views.profile, name='user-profile'),
path('<username>/update', views.update, name='user-update'),
path('<username>/delete', views.delete, name='user-delete'),
path(... |
__author__ = "Kyle Beyer"
__email__ = "beykyle@umich.edu"
import glob
import sys
import os
import argparse
import numpy as np
from numpy.linalg import multi_dot
import xml.etree.ElementTree as et
from pathlib import Path
from enum import Enum
# plottting
import matplotlib
from matplotlib import pyplot as plt
from mp... |
#/usr/bin/env python
# Matthieu Brucher
# Last Change : 2007-08-22 14:01
from __future__ import absolute_import
import unittest
import numpy
from PyDSTool.Toolbox.optimizers.line_search import GoldsteinRule
class Function(object):
def __call__(self, x):
return (x[0] - 2) ** 3 + (2 * x[1] + 4) ** 2
def gr... |
from django.utils.translation import ugettext_lazy as _
label = _('expenses')
VERSION = '0.3.0'
|
from pathlib import Path
import argparse
from sys import getsizeof
from base64 import b85encode
from zlib import compress
from hashlib import sha256
parser = argparse.ArgumentParser()
parser.add_argument("target", help="build target")
args = parser.parse_args()
target: str = args.target
stem: str = Path(target).stem
... |
import so3g
from spt3g import core
import numpy as np
from so3g import hk
class HKScanner:
"""Module that scans and reports on HK archive contents and compliance.
Attributes:
stats (dict): A nested dictionary of statistics that are updated as
frames are processed by the module. Elements:
... |
# backend/urls.py
from django.urls import re_path
from backend.views import views, tenant_model_view_set, user_model_view_set, aws_model_view_set, \
resource_view_set, monitor_view_set, notification_destination_model_view_set, \
notification_group_view_set,\
schedule_view_set, backup_view_set, operatio... |
from Constants import constant
from WatchYourBack.Board import Board
from Agents.NegamaxTranspositionTable import Negamax
from ActionBook.ActionBook import ActionBook
from random import randint
'''
THIS IS THE FINAL SUBMISSION:
THIS PLAYER IMPLEMENTS THE FOLLOWING TO INFORM ITSELF ON WHAT MOVE TO MAKE NEXT:
- N... |
#!/usr/bin/env python
#
# Copyright (C) 2016 Inkton <thebird@nest.yt>
#
# This file is part of nester
#
# 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
#... |
"""Constants for the Threshold integration."""
DOMAIN = "threshold"
CONF_HYSTERESIS = "hysteresis"
CONF_LOWER = "lower"
CONF_UPPER = "upper"
DEFAULT_HYSTERESIS = 0.0
|
import re
import urllib.request
import pytest
from jaraco import services
class TestHTTPStatus:
def http_error(self, url):
raise urllib.error.HTTPError(
url, code=400, msg='Bad Request', hdrs=dict(), fp=None
)
def test_HTTPError(self, monkeypatch):
monkeypatch.setattr(ur... |
# Third Party
from delta import DeltaTable, configure_spark_with_delta_pip # noqa
from pyspark.sql import SparkSession
from pytest import fixture
# About pytest fixtures
# https://docs.pytest.org/en/latest/how-to/fixtures.html#how-to-fixtures
@fixture(scope="session")
def spark():
"""Start a local pyspark instan... |
import os
from argparse import ArgumentParser
if __name__ == "__main__":
# Argument parsing setup
parser = ArgumentParser()
parser.add_argument('--path', type=str, default='~/Downloads', help='The path to the directory where data files are stored. Defaults to ~/Downloads.')
args = parser.parse_args()
... |
import os
import pytest
import requests
import requests_mock
from valor import Schema
@pytest.fixture
def schema_fname():
return os.path.join(os.path.dirname(__file__), 'schema.json')
@pytest.fixture
def schema():
return Schema.from_file(os.path.join(os.path.dirname(__file__), 'schema.json'))
@pytest.fixture... |
#from .asyncdistribute import AsyncDistribute
from .workerresource import *
from .workerprocess import *
from .workerpool import *
from .messaging import *
from .exceptions import *
|
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from c3d.utils.video_util import *
def visualize_clip(clip, convert_bgr=False, save_gif=False, file_path=None):
num_frames = len(clip)
fig, ax = plt.subplots()
fig.set_tight_layout(True)
... |
#Introduction to Sets
def average(array):
# your code goes here
return sum(set(array))/len(set(array))
#_____________________________________________________________
#Symmetric Difference
# Enter your code here. Read input from STDIN. Print output to STDOUT
a,b=(int(input()),input().split()) #a it is size of ... |
__author__ = "Flora"
__version__ = "2020.10.28"
"""
This componment gets the x,y,z list and creates seperate x,y,z, lists per AA
atom.
Inputs:
AA: Amino Acid id number (int list)
AA_name: Amino Acid name (string list)
xyz: coordinates in 3Dspace per atom (3d point rhino item)
atom... |
from output.models.saxon_data.zone.zone205_xsd.zone205 import (
Doc,
DocValue,
)
__all__ = [
"Doc",
"DocValue",
]
|
import pyaf.tests.transformations.test_ozone_transf_generic as gen
gen.test_transformation('None');
|
"""
admin.py
"""
from django.contrib import admin
from django.contrib import messages
from .models import Element
class ComposerElementAdmin(admin.ModelAdmin):
"""
Admin for the composer elements.
"""
fields = ('content', 'context_example')
readonly_fields = (
'template_name', 'name', 'is... |
import pathlib
import tempfile
import unittest
from unittest.mock import patch
import yaml
from click.testing import CliRunner
from data_pipelines_cli.cli import _cli
from data_pipelines_cli.cli_commands.prepare_env import prepare_env
from data_pipelines_cli.errors import JinjaVarKeyError
class GenHomeProfilesComma... |
BASE_DIR = ".\\"
BASE_PREPROCESSEDIMAGES_DIR = BASE_DIR + "data_preprocessed_images\\"
BASE_TRAIN_SEGMENT_DIR = BASE_DIR + "data_segmenter_trainset\\"
PATIENT_PRED_DIR = BASE_DIR + "data_patient_predictions\\"
# Quick mode does away with training in different folds.
# It does overfit a little in the calibration and su... |
from os import path
from pathlib import Path
from shutil import make_archive
from time import sleep
from requests import get, post, put
class AuthorizationError(Exception):
pass
class RequestError(Exception):
pass
def needs_authorization(func):
def inner(self, *args, **kwargs):
if self._access... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.