content stringlengths 5 1.05M |
|---|
from datetime import datetime
from threading import Thread
from time import sleep
import pytest
import retry
exception_message = 'testing exceptions'
def foo(bar):
if bar < 0:
raise ArithmeticError(exception_message)
return bar
def test_success_criteria():
"""Success criteria successfully rai... |
from .amazon import COMPUTERS, PHOTO, Amazon
from .botnet import C2, CHORD, DEBRU, KADEM, LEET, P2P, Botnet
from .cite_seer import CiteSeer
from .coauthor import CS, PHYSICS, Coauthor
from .cora import Cora
from .ppi import PPI
from .pub_med import PubMed
from .qm9 import QM9, Qm9
__all__ = [
"CiteSeer",
"Cora... |
import time
import random
import pdb
import threading
import logging
from multiprocessing import Pool, Process
import pytest
from utils.utils import *
from common.constants import *
from common.common_type import CaseLabel
TIMEOUT = 120
class TestCreateBase:
"""
**********************************************... |
from .settings import BongSettings, DEFAULT_MESSAGE
from .metadata import VERSION, SUMMARY
import argparse
PARSER = argparse.ArgumentParser(description=SUMMARY)
PARSER.add_argument('-V', '--version', action='version',
version='%(prog)s {}'.format(VERSION),
help='show version')
P... |
import os
from conans import ConanFile, CMake, tools
from conans.errors import ConanInvalidConfiguration
required_conan_version = ">=1.32.0"
class TinyAesCConan(ConanFile):
name = "tiny-aes-c"
license = "Unlicense"
homepage = "https://github.com/kokke/tiny-AES-c"
url = "https://github.com/conan-io/co... |
from conftest import is_valid
import pytest
@pytest.mark.usefixtures("client_class", "empty_test_db")
class TestEmergenyContactsAuthorizations:
def setup(self):
self.endpoint = "/api/emergencycontacts"
def test_emergency_contacts_POST(self, auth_headers):
endpoint = "/api/emergencycontacts"
... |
import pytest
from django.urls import reverse
from model_mommy import mommy
from gs_project.django_assertions import assert_contains
from apps.produto.models import Produto
# criado para testes com o usuário logado
@pytest.fixture
def usuario_logado(db, django_user_model):
usuario_model = mommy.make(django_user_... |
from flaskblog import create_app
app = create_app()
if __name__=="__main__":
app.run(debug=True, port=5500)
|
'''
Created on Dec 13, 2011
@author: sean
'''
from meta.decompiler import decompile_func
from meta.asttools.visitors import Visitor
import ast
from meta.asttools.visitors.print_visitor import print_ast
import clyther as cly
import clyther.runtime as clrt
import opencl as cl
from clyther.array.utils import broadcast_... |
# coding: UTF-8
import getRumors
import createCSV
def getClickedRumors():
clickedRumors = getRumors.getClick("2020-01-01", "2020-09-10", 2000)
# print(len(clickedRumors))
blackList = ["Uc8d4d6282aeeced782be778716d845c3", "Udda3ab30820ab29ac22829a33c516392",
"Ua07336c0212267088e339e2d50a82... |
############################################################################
##
## Copyright (C) 2006-2007 University of Utah. All rights reserved.
##
## This file is part of VisTrails.
##
## This file may be used under the terms of the GNU General Public
## License version 2.0 as published by the Free Software Foundat... |
import requests
import bs4
import numpy as np
import pandas as pd
# Example Code
game_id = 13
url = 'https://www.boardgamegeek.com/xmlapi/boardgame/' + str(game_id)
result = requests.get(url)
soup = bs4.BeautifulSoup(result.text, features='lxml')
# print(soup.find('name').text)
# Task Begins
# Explore the BGG API a... |
"""!
"""
import cv2
import imutils
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
def _get_measures(gt, det, r):
"""!@brief
@note One ground truth point can be associated to
more than one predicted point.
"""
# Assertions
gt = gt[gt['frame'] == 1]
det = det[det['... |
# iniexportfile
#########################################################################################################
# Imports
from configparser import ConfigParser as __ConfigParser
from ..error import SfcparseError
# Exception for Module
class IniExportFile(SfcparseError): __module__ = SfcparseError.set_module_... |
import os
import shutil
def GetFiles(extension):
import glob
file_list = [j for j in glob.glob('*.{}'.format(extension))]
return(file_list)
def docx_opr(file_name):
import docx2txt
from profanityfilter import ProfanityFilter
pf = ProfanityFilter()
document = docx2txt.process(file_name)
... |
"""
Process backend
===============
Run jobs using a process backend.
"""
import sys
import uuid
from subprocess import Popen, PIPE
import threading
# import logging
import random
from ..workflow import get_workflow
# from ..logger import log
from .scheduler import Scheduler
# from .protect import CatchExceptions
fr... |
import matplotlib.pyplot as plt
from numpy import pi, arccos, cos, sin, sqrt, log, log10, exp
from numpy import linspace, meshgrid, where, ndarray, array, float32, float64
from slezanbear import sbmap
from threshold import th
radearth = 6371 * 1e3
dist = lambda f1,l1,f2,l2: arccos( \
cos(f1 * (pi / 180)) * co... |
# pylint: disable=C0103
"""
This module contains vector control for PMSM drives.
"""
# %%
import numpy as np
import matplotlib.pyplot as plt
from cycler import cycler
from helpers import abc2complex, complex2abc
from control.common import PWM
# %%
class VectorCtrl:
"""
This class interconne... |
import matplotlib.pyplot as plt
import pandas as pd
def plot_history(train_acc, val_acc, train_loss, val_loss, figsize=(10, 5),
dpi=300, acc_path='accuracy.png', loss_path='loss.png'):
plt.figure(figsize=figsize)
plt.plot(train_acc)
plt.plot(val_acc)
plt.title("Model Accuracy")
plt.ylabel("... |
'''Crie um programa que leia um número inteiro e diga se o número é PAR ou ÍMPAR'''
print('---------------'*2)
print('Digite número inteiro...')
num = int(input('Diremos se é PAR ou ÍMPAR: '))
print(' -------------------- ')
if num % 2 == 0:
print('Você digitou um número PAR!')
else:
print('O número dig... |
#!/usr/bin/env python
# Copyright 2018 the Deno authors. All rights reserved. MIT license.
# Performs benchmark and append data to //website/data.json.
# If //website/data.json doesn't exist, this script tries to import it from gh-pages branch.
# To view the results locally run ./tools/http_server.py and visit
# http:/... |
from . import source, effect, encode, playback, save
|
#!/usr/bin/python3
# Copyright 2017, Mengxiao Lin <linmx0130@gmail.com>
import mxnet as mx
from mxnet import nd
from .config import cfg
import numpy as np
import cv2
# Model utils
def bbox_transform(anchor, bbox):
w = anchor[:, 2] - anchor[:, 0]
h = anchor[:, 3] - anchor[:, 1]
cx = (anchor[:, 0] + anchor... |
from typing import Optional
from pincer import Client, command
from pincer.objects import TextChannel, MessageContext, InteractionFlags
from app.classes.drink_list import DrinkList
from app.exceptions import DrinkAlreadyExists, DrinkNotFound, BotError
CHANNEL_ID = 888531559861321738
MESSAGE_ID = 888535656542928906
... |
from django.shortcuts import render, redirect
from django.views import View, generic
from django.contrib import messages
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from django.contrib.auth.views import LoginView
from django.contrib.auth import login, logout, authenticate
from django.cont... |
# Copyright (c) 2017 The Khronos Group Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed ... |
# *****************************************************************************
#
# Copyright (c) 2020, the pyEX authors.
#
# This file is part of the pyEX library, distributed under the terms of
# the Apache License 2.0. The full license can be found in the LICENSE file.
#
from .auditanalytics import *
from .brain im... |
from ..models import User
from .resource import ResourceSerializer
import smartchef.serializers.household as HouseholdSerializer
from django.contrib.auth.hashers import make_password
from django.db.transaction import atomic
from rest_framework import serializers
class UserSerializer(ResourceSerializer):
househol... |
# ------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
# -------------------------------------------------------------------... |
class Config(object):
"""项目共用的一些配置"""
SECRET_KEY = '123456'
class DevelopmentConfig(Config):
"""开发环境"""
DEBUG = True # 打开测试
# 数据库相关配置
# 设置数据库的链接地址
SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:mysql@localhost:3306/falsk_text1?charset=utf8'
# 关闭追踪数据库的修改
SQLALCHEMY_TRACK_MODIFICA... |
# -*- coding: utf-8 -*-
"""Convert fiber position result from 3DTIMON model to VTK."""
import sys
import meshio
import numpy as np
if __name__ == "__main__":
in_filename = sys.argv[-1]
out_filename = in_filename.replace(".unv", ".vtk")
print("Converting %s" % in_filename)
with open(in_filename) as i... |
class HipsSkyMaps():
__sky_map_url={
"CFHT":"CDS/P/CFHTLS/W/Color/ugi"
}
@staticmethod
def getMap(archive):
self = HipsSkyMaps()
if archive in self.__sky_map_url:
return self.__sky_map_url[archive]
else:
return None |
import numpy as np
import os,sys
import math
import time
work_path='./work/'
def cross(s1,s2):
length=len(s1)
res=[s1[i] for i in range(length//2)]
#res=s1[:length//2]
for i in range(length//2,length):
if s2[i] not in res:
res.append(s2[i])
for i in range(length//2):
... |
import matplotlib.pyplot as plt
import numpy as np
import math
def ParityCheckMatrix(k) :
sqrtk = int(math.sqrt(k))
sqrtn = int(sqrtk + 1)
n = int(k + 2 * sqrtk + 1)
OfSet = 0
ParityCheckMatrix = np.zeros((n - k, n))
for i in range(0,sqrtk):
for j in range(OfSet,sqrtk + OfSet + 1):
ParityCh... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jan 28 22:01:18 2017
@author: Nadiar
"""
#secretWord = 'apple'
#lettersGuessed = ['e', 'i', 'k', 'p', 'r', 's']
def getGuessedWord(secretWord, lettersGuessed):
'''
secretWord: string, the word the user is guessing
lettersGuessed: lis... |
import csv
import dataclasses
import decimal
import os
import tempfile
import zipfile
from urllib.request import urlretrieve
@dataclasses.dataclass
class Wgs84Coordinates:
longitude: decimal.Decimal
latitude: decimal.Decimal
@dataclasses.dataclass
class Lv95Coordinates:
E: decimal.Decimal
N: decimal... |
# Generated by Django 2.0.6 on 2018-08-12 12:16
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('DublinBusTest', '0005_busrouteinfojoined_weatherforecast'),
('DublinBusTest', '0006_busrouteinfojoined'),
]
operations = [
]
|
"""
This test script is adopted from:
https://github.com/numpy/numpy/blob/main/numpy/tests/test_public_api.py
"""
import pkgutil
import types
import importlib
import warnings
import scipy
def check_dir(module, module_name=None):
"""Returns a mapping of all objects with the wrong __module__ attribute."""
... |
"""
resource_descriptor_models.py
==============================
"""
from sqlalchemy import ARRAY, Column, ForeignKey, Integer, String
from sqlalchemy.orm import relationship
from literature.database.base import Base
class ResourceDescriptorPageModel(Base):
__tablename__ = "resource_descriptor_pages"
reso... |
# -*- coding: utf-8 -*-
"""
Click Parameter Types - URL
"""
from click import ParamType
from validators import url as url_validator
class UrlParam(ParamType):
"""Validate the parameter is a URL.
Examples:
'https://example.com/?test=test'
"""
name = 'URL'
def convert(self, value: str... |
__author__ = 'max'
from overrides import overrides
from typing import Dict, Tuple
import torch
import torch.nn as nn
from torch.nn import Parameter
from macow.flows.flow import Flow
from macow.flows.actnorm import ActNorm2dFlow
from macow.flows.conv import Conv1x1Flow
from macow.flows.nice import NICE
from macow.util... |
import requests
import logging
import json
import boto3
from botocore.exceptions import ClientError
from urllib2 import build_opener, HTTPHandler, Request
logger = logging.getLogger()
logger.setLevel(logging.INFO)
def handler(event, context):
endpoint = event["ResourceProperties"]["SplunkHttpEventCollectorManage... |
# -*- coding: utf-8 -*-
"""Test the TcEx Batch Module."""
import pytest
from ..tcex_init import tcex
# pylint: disable=R0201,W0201
class TestInflect:
"""Test the TcEx Batch Module."""
def setup_class(self):
"""Configure setup before all tests."""
@pytest.mark.parametrize(
'string,result'... |
"""Modules for building and running look-ahead indicators and label generators."""
from vectorbt.labels.enums import *
from vectorbt.labels.generators import (
FMEAN,
FSTD,
FMIN,
FMAX,
FIXLB,
MEANLB,
LEXLB,
TRENDLB,
BOLB
)
__all__ = [
'FMEAN',
'FSTD',
'FMIN',
'FMAX'... |
import json
import sys
import warnings
from nltk.tokenize.punkt import PunktSentenceTokenizer
import numpy as np
from pytorch_pretrained_bert import BertTokenizer
from pytorch_pretrained_bert.modeling import BertConfig
from pytorch_pretrained_bert.optimization import BertAdam
from sklearn.metrics import f1_score
impor... |
"""Demonstrates the Flyweight mixin in caixa.metaclasses"""
from typing import Optional, Any
from caixa.metaclasses import Flyweight
def describe(label: str = 'object', obj: Optional[Any]= None) -> str:
return f"id={id(obj)} type={type(obj)} object={obj}"
class A(str, metaclass=Flyweight):
pass
class B(A):... |
def gen_primes():
""" Generates an infinite sequence of prime numbers.
"""
# Maps composites to primes witnessing their compositeness.
# This is memory efficient, as the sieve is not "run forward"
# indefinitely, but only as long as required by the current
# number being tested.
#
sieve ... |
import os
import reframe as rfm
import reframe.utility.sanity as sn
class Cp2kCheck(rfm.RunOnlyRegressionTest):
def __init__(self, check_name, check_descr):
super().__init__(check_name, os.path.dirname(__file__))
self.descr = check_descr
self.valid_prog_environs = ['PrgEnv-gnu']
s... |
"Main module to be run for training the model."
import json
import torch
import torch.nn as nn
from absl import app
from torch.utils.data import DataLoader, ConcatDataset
import utils.dataset as dataset
import utils.train_utils as train_utils
from model.vqa_model import VQAModel, ModelParams
from train import train
... |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2020 Dremio
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... |
for j in range(int(input())):
_ = int(input("enter n"))
x = input("enter numbers with space\n").split()
a=0
p=input("enter searching No\n")
for i in range (len(x)):
if x[i]==p:
a+=1
t = i
if a==1:
print("\npresent",t+1)
else:
print("\nnot prese... |
#!/usr/bin/env python
import rospy
from hide_and_seek_navigation.msg import listmsg
from std_msgs.msg import String
def planner():
pub = rospy.Publisher('move_base_goal', listmsg, queue_size=5)
rospy.init_node('planner')
rate = rospy.Rate(10)
while not rospy.is_shutdown():
msg = listmsg()
... |
import logging
import os
import redis
import sqlalchemy
from flask import Blueprint, jsonify, request
from web3 import HTTPProvider, Web3
from src.models import Block
from src.utils import helpers
from src.utils.db_session import get_db_read_replica
from src.utils.config import shared_config
from src.utils.redis_cons... |
'''Exercício 1: Escreva uma função que conta a frequência de ocorrência de cada
palavra em um texto (arquivo txt) e armazena tal quantidade em um dicionário, onde a
chave é a palavra considerada.'''
dicionario = {}
file = open(r'C:\Users\maria\Desktop\POO-2\Terceira Lista\exercicio_1.txt')
texto = file.read().lower()... |
import pandas as pd
DATE = 'date'
COUNTY = 'county'
NAME = 'name'
ID = 'id'
POPULATION = 'population'
CONFIRMED_CASES = 'confirmed_cases'
NEW_CASES = 'new_cases'
NEW_CASES_7DAY, NEW_CASES_14DAY = [f'new_cases_{x}day' for x in (7, 14)]
CASE_RATE_7DAY, CASE_RATE_14DAY = [f'case_rate_{x}day' for x in (7, 14)]
df = pd.r... |
#!/usr/bin/env python
# coding: utf-8
import codecs
import sys
import sklearn as sk
import pandas as pd
import numpy as np
import math
from sklearn import preprocessing
from sklearn.decomposition import PCA
from src.pca.algoritmo_QR import eigenvectores_eigenvalores_QR_vf
from src.pca.metodo_potencia_deflation imp... |
import torch
import numpy as np
import yaml, pickle, os, math, logging
from random import choice, randint, sample
from Audio import Audio_Prep
def Calc_RMS(audio):
return np.sqrt(np.mean(np.square(audio), axis= -1))
class Dataset(torch.utils.data.Dataset):
def __init__(self, wav_paths, noise_paths, sample_ra... |
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 16 09:54:40 2021
@author: Marijn Venderbosch
Computes trap depth from eq. 1.6 PhD thesis Ludovic Brossard
"""
#%% Imports
from scipy.constants import Boltzmann, c, pi, hbar, Planck, atomic_mass
import numpy as np
#%% Variables
mRb = 87 * atomic_mass
# Dipole trap
po... |
'''
nbgrader APIs for vserver
Similar to https://github.com/jupyter/nbgrader/issues/659
Authentication
To make things easy, we are simply putting the user id in HTTP GET
parameter or POST data using key `user`.
For example: /api/courses?user=Eric
'''
import os, json, operator
from app import request
from he... |
# -*- coding: utf-8 -*-
# Copyright 2017-TODAY LasLabs Inc.
# License MIT (https://opensource.org/licenses/MIT).
import properties
from ..base_model import BaseModel
from .dispensary import Dispensary
class MenuItem(BaseModel):
"""Menu items for dispensaries."""
name = properties.String(
'Name of ... |
import torch
import torch.nn as nn
from torch.utils.data import Dataset
import os
import numpy as np
from tqdm import tqdm
import glob
from PIL import Image
from torchvision import transforms
from torchvision.models import resnet50
import random
'''
1. 写一个dataset √
2. load他并且所有数据提取特征 √
3. 保存特征和标签txt ... |
import csv
from os import path
file_path = input("Enter The file path: ")
active = True
while active:
if path.exists(file_path) and file_path.endswith('CSV') or file_path.endswith('csv'):
print('File will be ready @ BatmonLogCleaned.csv in root folder')
with open(file_path, 'r+') as inp, open('B... |
# Note this assumes undirected and unweighted right now TMC
import sys
import networkx
import random
random.seed(1234)
class Tab2GMLPlugin:
def input(self, file):
tabfile = open(file, 'r')
nodes = ()#set()
edges = ()#set()
for line in tabfile:
elements = line.split("\t")
... |
from __future__ import print_function
import sys
# Call like this: ngram -ppl <(sed 's/ //g' contextWordCartProd ) -lm train.lm -debug 1 | python ./thisscript
class switch(object):
def __init__(self, value):
self.value = value
self.fall = False
def __iter__(self):
"""Return the match... |
import unittest
from problems.problem46 import Trie
class Test(unittest.TestCase):
def test(self):
trie = Trie()
trie.insert('apple')
self.assertTrue(trie.search('apple'))
self.assertFalse(trie.search('app'))
self.assertTrue(trie.startsWith('app'))
trie.insert('app')
self.assertTrue(trie.search('app'))... |
#!/usr/bin/env python
import argparse
import struct
import sys
import copy
import ipdb
import rospy
from std_msgs.msg import (
Empty,
Header,
Int64
)
import copy
from baxter_core_msgs.msg import EndpointState
from sensor_msgs.msg import JointState
from geometry_msgs.msg import WrenchStamped
from smach_ba... |
# pylint: disable=unused-argument
from dagster import Failure, InputDefinition, Output, OutputDefinition, pipeline, solid
conditional = True
@solid(output_defs=[OutputDefinition(int, "a", is_required=False)])
def my_solid(context):
if conditional:
yield Output(1, "a")
@solid(
output_defs=[
... |
import pandas as pd
def consolidate_home_ownership_values(val):
if val == "HaveMortgage":
val.replace("HaveMortgage", "Home Mortgage")
else:
return val
# TODO - find a more generic way
def consolidate_purpose_values(val):
if val == "other":
return "Other"
elif val == "major_p... |
#!/usr/bin/env python
"""
Created by: Lee Bergstrand
Description: A program that extracts the protein annotations from a fasta file and searches these
annotations using HMMsearch and an HMM file. It then stores hits along with organism
information (gathered from a csv file) in a sqlite3 database.
Requirem... |
# Copyright 2021 Google LLC
# 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
# https://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, sof... |
from unittest import TestCase
from unittest.mock import patch, Mock
from llc1_document_api import blueprints
class TestBlueprints(TestCase):
@patch('llc1_document_api.blueprints.general')
@patch('llc1_document_api.blueprints.generate')
def test_register_blueprints(self, generate_mock, general_mock):
... |
import uuid
import ndjson
import pytest
import requests
from labelbox.schema.annotation_import import AnnotationImportState, MEAPredictionImport
"""
- Here we only want to check that the uploads are calling the validation
- Then with unit tests we can check the types of errors raised
"""
def check_running_state(req... |
import os
import sys
import time
import numpy as np
import matplotlib.pyplot as plt
import torch
from torch.autograd import Variable
sys.path.append(os.path.pardir)
from module.averagemeter import AverageMeter
from module.function import *
def validate(args, val_loader, model, criterion, normalizer, test=False, tran... |
import os
from pychecker.check.extra_dep_detection import detect_extra_deps
from pychecker.check.local_comp_detection import detect_local_comp_detection
from pychecker.check.incomp_feature_detection import detect_incomp_feature_usage
from pychecker.check.no_avl_resource_detection import detect_no_avl_resource_pkg
from ... |
#! /usr/bin/env python
import sys
import os
sys.path.insert(0, os.environ["QUEX_PATH"])
from StringIO import StringIO
from quex.input.regular_expression.exception import *
from quex.blackboard import setup
setup.buffer_limit_code = -1
setup.path_limit_code = -1
import quex.engine.state_machine.index as sm_index
imp... |
import os
import json
import requests
import logging
import asyncio
import discord
dir_path = os.path.dirname(os.path.realpath(__file__))
with open(dir_path+'/client_config.json', 'r') as f:
config = json.load(f)
TOKEN = config['TOKEN']
SERVER_ID = config['GUILD']
ROLES = config['ROLES']
HOST_ROLE_ID = config['... |
from django.shortcuts import redirect
from django.shortcuts import render
#
|
'''
Cost of balloons
You are conducting a contest at your college. This contest consists of two problems and participants. You know the problem that a candidate will solve during the contest.
You provide a balloon to a participant after he or she solves a problem. There are only green and purple-colored balloons ava... |
from .mnist import *
from .svhn import *
from .usps import *
|
# 个人中心模块蓝图
from flask import Blueprint
profile_blu = Blueprint("profile",__name__,url_prefix="/user")
from . import views |
from configuration_loader.mergers.base import Base
class DefaultMerger(Base):
def merge(self, dict_a, dict_b, path=None):
""""
Merges b into a
"""
if path is None:
path = []
for key in dict_b:
if key in dict_a:
if isinstance(dict_... |
from cwlab.database.connector import db
from cwlab.database.sqlalchemy.models import User, Exec, Job, Run
import sqlalchemy
from datetime import datetime
class JobManager():
def create_job(
self,
job_name,
username,
wf_target
):
job = Job(
job_name=job_na... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
import imperial.model.mapper.mapeador as mapeador
mapeador.main() |
"""Boilerplate settings parsing"""
# pragma: no cover
from mitol.common.envs import get_string
MITOL_DIGITAL_CREDENTIALS_VERIFY_SERVICE_BASE_URL = get_string(
name="MITOL_DIGITAL_CREDENTIALS_VERIFY_SERVICE_BASE_URL",
description="Base URL for sing-and-verify service to call for digital credentials",
requir... |
from mpl_toolkits.mplot3d import Axes3D
import pylab
import numpy
def _produce_axis(low, high, bins):
""" This method produces an array that represents the axis between low and
high with bins.
Args:
low (float): Low edge of the axis
high (float): High edge of the axis
bins (int): Number... |
import re
import requests
from bs4 import BeautifulSoup
import urllib
def getHTMLText(url):
try:
r = requests.get(url, timeout = 30)
r.raise_for_status()
r.encoding = r.apparent_encoding
return r.text
except:
return
# 爬取网上回答
def pachong_answer(question):
headers = ... |
# uncompyle6 version 3.7.4
# Python bytecode 3.7 (3394)
# Decompiled from: Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)]
# Embedded file name: T:\InGame\Gameplay\Scripts\Server\sims\university\university_commands.py
# Compiled at: 2020-07-31 03:14:26
# Size of source mod 2**32... |
"""
The module :mod:`~tsfresh.transformers` contains several transformers which can be used inside a sklearn pipeline.
"""
from tsfresh.transformers.feature_augmenter import FeatureAugmenter
from tsfresh.transformers.feature_selector import FeatureSelector
from tsfresh.transformers.relevant_feature_augmenter import R... |
from datetime import datetime
from pydantic import BaseModel, Field
from logcord.models.message import Message
class MessageLog(BaseModel):
"""The model schema for a message log."""
id: str
created_at: datetime = Field(default_factory=datetime.utcnow)
messages: list[Message]
|
import pytest
from unittest.mock import sentinel, Mock
import bokeh.palettes
import pandas as pd
import pandas.testing as pdt
import datetime as dt
import numpy as np
import glob
import forest.drivers
from forest.drivers import earth_networks
LINES = [
"1,20190417T000001.440,+02.7514400,+031.9206400,-000001778,00... |
import string
import secrets
from config import TOKENS_FILE
def generate_tokens(limit=10000000):
"""Generates n number of tokens and dumps them in the token file
Args:
limit (int, optional): number of tokens thats required to be generated. Defaults to 10000000.
"""
alphabet = string.ascii_low... |
from __future__ import annotations
import pathlib
import shutil
import pdfkit
import pymdownx # noqa: F401
from abc import abstractmethod
from typing import Any, cast
from jinja2 import Environment, DictLoader, StrictUndefined
from markdown import markdown
from markdown.extensions import Extension
from markdown.prepro... |
# Copyright 2019 FairwindsOps Inc
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... |
numbers = [1,2,3,[4,5,6],[7,8,9]]
def type_function(l):
output = []
for i in l:
if type(i) == list:
output.append(type(i))
return len(output)
print(type_function(numbers)) |
import os
import numpy as np
def filter_points(points: np.ndarray, eps: float):
"""
Removes points that are within `eps` distance of each other.
# Arguments
points (np.ndarray): point array to filter
eps (float): remove adjacent points within this distance of each other
# Returns
Filtere... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from tensorflow.python import keras
from keras.models import Sequential, model_from_json
from keras.layers import Dense, Flatten, Conv2D, Dropout, MaxPool2D
from keras.callbacks import ReduceLROnP... |
from __future__ import print_function, division, absolute_import
import unittest
import matplotlib
matplotlib.use('Agg')
import numpy as np
from openmdao.api import Problem, Group, pyOptSparseDriver, ScipyOptimizeDriver, DirectSolver
from openmdao.utils.assert_utils import assert_rel_error
from dymos import Phase,... |
# coding=utf-8
# Author: Diego González Chávez
# email : diegogch@cbpf.br / diego.gonzalez.chavez@gmail.com
#
# This class controls the:
# Temperature controler
# LakeShore 311
#
# TODO:
# Make documentation
from .instruments_base import InstrumentBase as _InstrumentBase
__all__ = ['LakeShore_311']
class LakeShore... |
import os
import datetime
import httplib
import json
import logging
import webapp2
from google.appengine.api import app_identity
from google.appengine.api import urlfetch
GCS_BUCKET=os.environ['GCS_BUCKET']
class Export(webapp2.RequestHandler):
def get(self):
access_token, _ = app_identity.get_access_token(
... |
import re
def preprocess(data, lang):
if "evr" in data:
evr = data["evr"]
if evr and not re.match(r'\d:\d[\d\w+.]*-\d[\d\w+.]*', evr, 0):
raise RuntimeError(
"ERROR: input violation: evr key should be in "
"epoch:version-release format, but package {0} h... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.