content stringlengths 5 1.05M |
|---|
# Copyright 2013-2019 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Qgis(CMakePackage):
"""QGIS is a free and open-source cross-platform desktop geographic
... |
from django.apps import AppConfig
class DancesConfig(AppConfig):
name = 'dances'
|
from tcontrol.plot_utility import plot_pzmap
from tcontrol.transferfunction import TransferFunction
from tcontrol.lti import LinearTimeInvariant as LTI
__all__ = ["pzmap"]
def pzmap(sys_, title='pole-zero map', *, plot=True):
"""
Use:
Draw the pole-zero map
Example:
>>> import tcontrol a... |
#!/usr/bin/env python3
import json
import yaml
import os
import sys
import logging
import logging.config
import time
import datetime
import base64
import multiprocessing
import hashlib
from kubernetes import client, config as k8s_config
from kubernetes.client.rest import ApiException
from kubernetes.stream import str... |
import struct, time, serial
class Serial:
HDLC_FLAG_BYTE = 0x7e
HDLC_CTLESC_BYTE = 0x7d
TOS_SERIAL_ACTIVE_MESSAGE_ID = 0
TOS_SERIAL_CC1000_ID = 1
TOS_SERIAL_802_15_4_ID = 2
TOS_SERIAL_UNKNOWN_ID = 255
SERIAL_PROTO_ACK = 67
SERIAL_PROTO_PACKET_ACK = 68
SERIAL_PROTO_PACKET_NOACK = 69
SERIAL_PRO... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from tree_node import TreeNode
class BinarySearchTree(object):
def __init__(self):
self._root = None;
##################
## Iterator method
def __iter__(self):
current = self._find_minmum(self._root)
# and then, until we have reach... |
# This file is a part of:
#‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
# ███▄▄▄▄ ▀█████████▄ ▄████████ ███ ▄██████▄ ▄██████▄ ▄█
# ███▀▀▀██▄ ███ ███ ███ ███ ▀█████████▄ ███ ███ ███ ███ ███
# ███ ███ ███ ███ ███ █▀ ▀███▀▀██ ███ ... |
import urllib.request
class Urban_Dictionary:
def __init__(self, word):
self.word = word
self.dict_base_url = 'http://www.urbandictionary.com/define.php?term='
self.base_content = "property='og:description'>"
self.counter = 0
# def convert_word(self):
# self.word = self.word[0].up... |
"""Magnetic Module protocol commands."""
from .disengage import (
Disengage,
DisengageCreate,
DisengageParams,
DisengageResult,
DisengageCommandType,
)
from .engage import (
Engage,
EngageCreate,
EngageParams,
EngageResult,
EngageCommandType,
)
__all__ = [
# magneticModule... |
# Copyright (c) Facebook, Inc. and its affiliates.
# Code based off https://github.com/microsoft/Oscar
# modified for MMF
# Licensed under the MIT license.
import logging
from collections import namedtuple
from dataclasses import asdict, dataclass
from typing import Any, Dict, Optional, Tuple
import torch
from mmf.c... |
dataset_list = ['csqa', 'obqa', 'socialiqa']
dataset_setting = {
'csqa': 'inhouse',
'obqa': 'official',
'socialiqa': 'official',
}
dataset_num_choice = {
'csqa': 5,
'obqa': 4,
'socialiqa': 3,
}
max_cpt_num = {
'csqa': 40,
'obqa': 40,
'socialiqa': 60,
}
dataset_no_test = ['social... |
from .ip_proxy_tool import ip_proxy_tool,ip_info
import json
import logging
logger=logging.getLogger(__name__)
class JingDongWanXiang(ip_proxy_tool):
def __init__(self):
super(JingDongWanXiang,self).__init__()
self.url="https://way.jd.com/jisuapi/proxy?num=10&area=&areaex=&port=8080,80&portex=3306&... |
from model import AffinityPropagation
import numpy as np
from scipy import sparse
from sklearn.model_selection import train_test_split
import pandas as pd
from alive_progress import alive_bar
def load_edges(path):
edges_list = np.loadtxt(path).tolist()
values = [max(edge[0], edge[1]) for edge in edges_list]
... |
"""
Copyright (c) 2016, Jose Dolz .All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the f... |
import convert
import exc
from lxml import etree
import json
import os
import shutil
import time
script_dir = os.path.dirname(os.path.realpath(__file__))
data_dir = os.path.abspath(os.path.join(script_dir, "..", "data"))
def ensure_data_path(path):
path = os.path.join(data_dir, path)
if not os.path.isdir(pa... |
"""Annette Graph Utils
This Module contains the Graph Utilities to generate Annette readable graphs from MMDNN
or read directly from json.
"""
from __future__ import print_function
import json
import logging
import numpy as np
import sys
import os
import mmdnn.conversion.common.IR.graph_pb2 as graph_pb2... |
#!/usr/bin/env python3
# coding:utf-8
import datetime
from sqlalchemy import Integer, Column, String, DateTime, Boolean
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
Base = declarative_base()
class BaseModel(object):
keys = []
def __init__(self, id, engine, ... |
from models.Devices import Devices
from models.Logs import Logs
import datetime
def setStatusArduino(ard, matricola):
dispositivo = Devices.objects(mat = matricola)[0]
if ard.attivaZone(matricola, dispositivo.statusFirstSensor, dispositivo.statusSecondSensor) == "OK":
return 200
else:
retu... |
""" scripts.gencmds.kpn_timg.gen_cp_orig
"""
import json
import scripts.gencmds.common as common
def _create_parser():
help_str = 'Create commands to copy original image files to datadirs'
return common.parser(help_str)
def main(args):
cmds = []
md = json.load(args.input)
cmds.append('cp {} {}/'.... |
"""Defines LightCurveFile classes, i.e. files that contain LightCurves."""
from __future__ import division, print_function
import os
import logging
import warnings
import numpy as np
import matplotlib as mpl
from matplotlib import pyplot as plt
from astropy.io import fits as pyfits
from .utils import (bkjd_to_astro... |
# -*- coding: utf-8 -*-
"""Plotting.py for notebook 01_Exploring_DM_Halos
This python file contains all the functions used for plotting graphs and maps in the 1st notebook (.ipynb) of the repository: 01. Exploring parameters in DM halos and sub-halos
Script written by: Soumya Shreeram
Project supervised by Johan Com... |
import copy
import sync_infra_configurations.main as sic_main
import sync_infra_configurations.lib as sic_lib
import sync_infra_configurations.common_action as common_action
import sync_infra_configurations.aws as sic_aws
################################################################################################... |
# Copyright (c) 2020 Sony Corporation. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicabl... |
import json
import re
def get_children(questions_dict):
children_json = questions_dict.get('claimant_children', '[]')
if isinstance(children_json, dict):
children_json = children_json.get('value', '[]')
return json.loads(children_json)
def get_num_children_living_with(questions_dict, living_arra... |
"""
File: time_signature_event.py
Purpose: Defines a time signature as an Event.
"""
from timemodel.event import Event
from timemodel.position import Position
class TimeSignatureEvent(Event):
"""
Defines a time signature as an Event.
"""
def __init__(self, time_signature, time):
"""
... |
# fbdata.anon
# FBDATA
from .models import AnonName
def anon_name():
return '%s %s' % tuple(AnonName.objects.all().order_by('?')[:2])
|
# -*- coding: utf-8 -*-
import django_dynamic_fixture as fixture
from django.test import TestCase
from django.test.utils import override_settings
from readthedocs.projects.models import Project
@override_settings(
USE_SUBDOMAIN=True, PUBLIC_DOMAIN='public.readthedocs.org', SERVE_PUBLIC_DOCS=True,
)
class Redirec... |
from viewmodels.shared.viewmodel import ViewModelBase
class RegisterViewModel(ViewModelBase):
pass
|
import numpy as np
import pandas as pd
import keras.backend as K
from keras.models import save_model
from sklearn.metrics import roc_auc_score
from deepsky.gan import normalize_multivariate_data
from deepsky.metrics import brier_score, brier_skill_score
from sklearn.linear_model import LogisticRegression
from deepsky.m... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import time
import threading
from src.client import test_sdk_client
import src.helpers
import src.util
import src.algo_multilateral_arbitrage
import test_sdk_client
if __name__ == '__main__':
logger = src.util.base_logger(__name__, "test-logs/debug.log")
test_algo... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
__a... |
##########################################################################
#
# MRC FGU Computational Genomics Group
#
# $Id$
#
# Copyright (C) 2009 Andreas Heger
#
# 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 ... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import os
import re
import json
import requests
import nltk
def request_theguardian(params):
### theguardian endpoint URL
r = requests.get('http://content.guardianapis.com/search', params=params)
response = json.loads(r.text)
### pagination rules
if res... |
import os
import pytest
import mock
from capsule.lib.config_handler import DEFAULT_CONFIG_FILE_ENV_VAR, get_config_file, get_config
import asyncio
TEST_CONFIG_FILE_RELATIVE_PATH = "./capsule/lib/settings/config.toml"
TEST_CONFIG_FILE_LOCATION = os.path.abspath(
os.path.expandvars(
o... |
# -*- coding: utf-8 -*-
import argparse
import atexit
import pkg_resources # part of setuptools
from winnaker.models import *
from winnaker.notify import *
from winnaker.settings import *
def main():
print("""
____ __ ____ __ .__ __. .__ __. ___ __ ___ _______ .______
\ \ / \ / ... |
#!/usr/bin/python
"""
(C) Copyright 2020 Intel Corporation.
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 ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2021 Julian Betz
#
# 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 re... |
from ctypes.wintypes import *
from wintypes_extended import *
from winapi_error import *
import ctypes
import enum
MAX_PATH = 260
CW_USEDEFAULT = 0x80000000
def MAKELONG(wLow, wHigh):
return ctypes.c_long(wLow | wHigh << 16)
def MAKELPARAM(l, h):
return LPARAM(MAKELONG(l, h).value)
def LOWORD(l):
re... |
#!/usr/bin/python
from turtle import *
'''draws stars from input, formula
internal angle = 180 / number of points
turtle has to turn to the right such that the internal angle is
internalAngle, so has to turn 180 - internalAngle
for a 5 pointer
internal angle = 180 / 5
and therefore turn angle is
180 - 36 = 144
also
set... |
from contas.conta import Bank
class Corrente(Bank):
def __init__(self, nome, idade, saldo, numero, limite=200):
super().__init__(nome, idade, saldo, numero, limite)
def depositar(self, valor):
if not isinstance(valor, (int, float)):
raise ValueError('Valor do deposito precisa ser ... |
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
from djaesy.menu import Menu, MenuItem
from djaesy.models import Role, User
if settings.DJAESY_USER_MENU:
Menu.add_item(
"main",
MenuItem(
_('Usuários'), 'user_list', no_link=True, icon='mdi mdi-... |
if __name__ == '__main__':
s = input()
print(any(char.isalnum()for char in s))
print(any(char.isalpha()for char in s))
print(any(char.isdigit()for char in s))
print(any(char.islower()for char in s))
print(any(char.isupper()for char in s))
|
import re
from .post_model import Post, posts_list, UpdateError
from .user_model import User, users_list
email_pattern = re.compile(r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)")
password_pattern = re.compile(r"(?=^.{12,80}$)(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%^;*()_+}{:'?/.,])(?!.*\s).*$")
|
# Test code for find_pairs_pt.py
import pytest
import find_pairs_pt as fp
def test_no_pairs():
test_array = [9]
response = []
assert fp.find_pairs_simple(test_array) == response
assert fp.find_pairs(test_array) == response
def test_one_pair():
test_array = [1,9]
response = [(... |
#!/usr/local/bin/python
import pathlib
import sys
import subprocess
p = pathlib.Path(sys.argv[1])
sys.exit(subprocess.call(["node", p.name], cwd=p.parent))
|
from netapp.connection import NaConnection
from quota_entry import QuotaEntry # 14 properties
from quota_state_zapi import QuotaStateZapi # 0 properties
from size_or_dash import SizeOrDash # 0 properties
from unsigned64_or_dash import Unsigned64OrDash # 0 properties
from true_false import TrueFalse # 0 properties
from ... |
"""
System tests for execute updated policies
"""
from test_repo.autoscale.fixtures import AutoscaleFixture
from time import sleep
class ExecuteUpdatedPoliciesTest(AutoscaleFixture):
"""
System tests to verify execute updated scaling policies scenarios,
such that each policy executes after policy cooldow... |
import numpy as np
import pytest
from ml_utils.metrics import lift_score, confusion_matrix, sorted_feature_importance
from ml_utils.metrics.metrics import MetricError
# noinspection PyTypeChecker
def test_lift_score_fails_if_passed_non_ndarray():
with pytest.raises(MetricError):
lift_score([1, 2, 3], [4, ... |
"""
This example demonstrates how to generate some test placeholders.
It requires codenode to run:
https://github.com/0xf0f/codenode
"""
import codenode as cn
import codenode.python as py
import inspect
def generate_class_tests(cls):
test_list_name = f'{cls.__name__.lower()}_tests'
file = cn.File()... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import pprint
import spacy
from base import BaseObject
class DisplacyNerGenerator(BaseObject):
""" Annotate the Input Text with the spaCy NER model
Sample Input:
The investment arm of biotech giant Amgen has led a new $6 million
round of fundi... |
import sys
sys.path.insert(0,"../build/build.dir/packages/PyTrilinos/src/stk/PyPercept")
from mpi4py import MPI
from PerceptMesh import *
from math import *
import random
import time
import unittest
from numpy import *
class CheckCoordMag(GenericFunction):
def __init__(self, name=""):
self.name = name
... |
import dash_html_components as html
import dash
from NuRadioReco.detector.detector_browser import detector_map
from NuRadioReco.detector.detector_browser import station_info
from NuRadioReco.detector.detector_browser import channel_info
from NuRadioReco.detector.detector_browser import hardware_response
import NuRadi... |
p=float(input('Insira o valor do produto R$'))
print('O produto custará R${} com o desconto de 5%.'.format(p-(5/100*p)))
|
print("HOLA MUNDO") |
# -*- coding: utf-8 -*-
# Copyright (c) 2019, Silvio Peroni <[email protected]>
#
# Permission to use, copy, modify, and/or distribute this software for any purpose
# with or without fee is hereby granted, provided that the above copyright notice
# and this permission notice appear in all copies.
#
# THE SOFTWARE I... |
'''
Testing Serial Module Ports
Setup:
Create "loopbacks". Connect ports 1-4 to 5-8 using RS485
Algorithm:
- import modules: serial
- configure gpio on all ports to RS485
- send test message on all ports sequentially
- verify test message received on all ports sequentially
- display results
'''
import serial
import s... |
# Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: [email protected]
# Maintained By: [email protected]
from collections import defaultdict
from datetime import date, datetime
from ggrc.extens... |
"Here be dragons."
from .context import Context
from .template import Template
from .tokenizer import TokenKind
LOOKUP = "context.lookup({!r}){}"
LOOKUP_NIL = "context.lookup({!r}, []){}"
RAW = "str({})".format(LOOKUP)
VAR = "escape({})".format(RAW)
WHEN = "{func}(blocks, context) if {var} else ''"
UNLESS = "{func}(b... |
from query_builder.core import InsertBuilder
from simulator.menu import cost_menu
# TODO: class name will be group not one user.
class User:
"""
Q)
Is it right to make user class?
If we make virtual user instants for simulation, it can be expensive (mem & time)
What are... |
# Author Munis Isazade create log file for Threading
from django.utils import timezone
import os
import sys
import traceback
VERSION = "0.5.1"
class Logger(object):
"""
Logger objects create a log file
if not exist and append string to
log file
"""
def __init__(self, file='messa... |
from pika import BasicProperties
from pika.exceptions import ChannelClosedByBroker
from petisco.base.domain.message.domain_event import DomainEvent
from petisco.base.domain.message.domain_event_bus import DomainEventBus
from petisco.extra.rabbitmq.application.message.configurer.rabbitmq_message_configurer import (
... |
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="dadmatools",
version="1.3.8",
author="Dadmatech AI Company",
author_email="[email protected]",
description="DadmaTools is a Persian NLP toolkit",
long_description=long_description,
... |
# coding=utf-8
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.db.models import Max
from django.http.response import Http404, JsonResponse
from django.shortcuts import get_object_or_404, redirect, render
from django.urls import reverse
from trojsten.contests.mo... |
#!/usr/bin/env python
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
import torch
import math
from torch import nn
from torch.nn import init
from torch.nn.modules.utils import _pair
from ..functions.modulated_deform_conv2d_func import ModulatedDeformConv2d... |
from fastapi.middleware.cors import CORSMiddleware
def init_cors(app):
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
|
#!/usr/bin/env python
import argparse
import os
import sys
import logbook
from subprocess import check_call
from subprocess import CalledProcessError
import pygithub3
LOG = logbook.Logger('GitHub Backup')
track_all_branches = """
for branch in `git branch -a | grep remotes | grep -v HEAD | grep -v master`; do
... |
__all__ = ['nmf']
|
import scrapy
from poem_spider.items import PoemItem, PoetItem
import re
import uuid
class PoetSpider(scrapy.Spider):
name = "poet"
# allowed_domains = ["www.gushiwen.org"]
poet_count = 1
def start_requests(self):
start_url = 'https://so.gushiwen.org/authors/Default.aspx?p=1&c=先秦'
yie... |
# Copyright 1996-2019 Cyberbotics Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in... |
# Be sure to connect GPIO16 (D0) to RST or this won't work!
import machine
# configure RTC.ALARM0 to be able to wake the device
rtc = machine.RTC()
rtc.irq(trigger=rtc.ALARM0, wake=machine.DEEPSLEEP)
# set RTC.ALARM0 to fire after 10 seconds (waking the device)
seconds = 10
rtc.alarm(rtc.ALARM0, 1000 * seconds)
# pu... |
from django.test import TestCase, Client
from httmock import with_httmock, urlmatch
from .utils import get_base_claims, encode_jwt
from django.contrib.auth.models import User, Group
client = Client()
@urlmatch(path=r"^/adfs/oauth2/token$")
def token_response(url, request):
claims = get_base_claims()
token = ... |
# Copyright 2021 National Technology & Engineering Solutions of
# Sandia, LLC (NTESS). Under the terms of Contract DE-NA0003525 with
# NTESS, the U.S. Government retains certain rights in this software.
"""Demonstrate calling a command using the raw GRPC packets, not the
preferred Client interface."""
from paho.mqtt.... |
import logging
import threading
logger = logging.getLogger('[WORKER]')
logger.setLevel(logging.INFO)
__author__ = 'Andres'
'''
This class simplifies thread usage. Examples:
1 - Worker.call(aFunction).withArgs(arg1, arg2..argN).start() / Runs a normal thread starting at aFunction
2 - Worker.call(aFunction).withArg... |
# Generated by Django 3.0.5 on 2020-07-17 15:41
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Post',
fields=[
('id', models.AutoField(aut... |
#Crie um Alo mundo em inglês
print(" Alô mundo em inglês")
|
##!/usr/bin/env python
# -*- coding: utf-8 -*-
from collections import OrderedDict
from masters_project_config import *
from subprocess import Popen, PIPE, STDOUT
import re
models_dir = '/ltg/angelii/space_on_svn/angelii/PARSEABILITY/21_section/Bohnet_Nivre/parser/models/'
anna_dir = '/ltg/angelii/space_on_svn/angel... |
"""Asciicast v2 record formats
Full specification: https://github.com/asciinema/asciinema/blob/develop/doc/asciicast-v2.md
"""
import abc
import codecs
import json
from collections import namedtuple
utf8_decoder = codecs.getincrementaldecoder('utf-8')('replace')
class AsciiCastRecord(abc.ABC):
"""Generic Asciic... |
from decimal import Decimal
from django.urls import reverse
from ...models import Order
from ....core.utils import build_absolute_uri
def get_error_response(amount: Decimal, **additional_kwargs) -> dict:
"""Create a placeholder response for invalid or failed requests.
It is used to generate a failed transa... |
# Copyright (C) 2007 Alexandre Conrad, alexandre (dot) conrad (at) gmail (dot) com
#
# This module is part of FormAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
from formalchemy.i18n import _
__all__ = ['ValidationError', 'required', 'integer', 'float_', 'decimal_'... |
# -*- coding: utf-8 -*-
"""
test.etsi_3gpp_s6a_6d.test_avps
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This module contains the Diameter protocol AVP unittests
for 3GPP S6a/S6d Diameter Application Id.
:copyright: (c) 2020 Henrique Marques Ribeiro.
:license: MIT, see LICENSE for more details.
"""
impo... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'zhj'
"""
requests模块:
可以看作是urllib打包封装的模块,作用是一样的但是有一点不同:
1.urllib需要先构建,再发请求
2.requests可以边构建边发送
1.安装requests模块:
pip install requests
pip install -i https://pypi.douban.com/simple requests
2.常用方法:
... |
class TestWeibo:
def test_case1_01(self, open_weibo):
print("查看微博热搜")
def test_case1_02(self, open_weibo):
print("查看微博范冰冰") |
###########################################################
# #
# License: GPL (http://www.gnu.org/licenses/gpl-3.0.html) #
# #
# info: you must host message.txt and add its address to #
# message_xml_url b... |
from .test.fixtures import app, client
def test_when_create_app(app):
assert app
def test_app_hello_world(client):
with client:
res = client.get('/')
assert res.status_code == 200
assert res.is_json
assert res.json == 'hello world'
|
#!/usr/bin/python
import unittest
import schemaobject
class TestSchema(unittest.TestCase):
def setUp(self):
self.db = schemaobject.SchemaObject(self.database_url + 'sakila')
self.db2 = schemaobject.SchemaObject(self.database_url)
def test_database_version(self):
assert self.db.version == "5.1.30"
... |
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
from sqlalchemy_utils import create_database, database_exists, drop_database
import pymysql
import connexion
pymysql.install_as_MySQLdb()
import MySQLdb
# Conectando a DB e criando a database, ou deletar e criar c... |
#!/usr/bin/env python3
from pywarpx import picmi
# Physical constants
c = picmi.constants.c
q_e = picmi.constants.q_e
# Number of time steps
max_steps = 100
# Number of cells
nz = 256
# Physical domain
zmin = -56e-06
zmax = 12e-06
# Domain decomposition
max_grid_size = 64
blocking_factor = 32
# Create grid
grid... |
'''
Tool 0: Run in serial
'''
import pylab as pl
import numpy as np
import sciris as sc
from model import run_sir
if __name__ == '__main__':
# Initialization
n_runs = 10
seeds = np.arange(n_runs)
betas = np.linspace(0.5e-4, 5e-4, n_runs)
# Run
sc.tic()
sirlist = []
for r in range(n_r... |
from netapp.connection import NaConnection
from treemigrate_migrations import TreemigrateMigrations # 3 properties
from treemigrate_status_info import TreemigrateStatusInfo # 15 properties
from treemigrate_fh_map_memory import TreemigrateFhMapMemory # 3 properties
from treemigrate_files_estimate import TreemigrateFiles... |
import torch
from torch.utils.data import Dataset
from PIL import Image
import os
import glob
class UCMayo4(Dataset):
"""Ulcerative Colitis dataset grouped according to Endoscopic Mayo scoring system"""
def __init__(self, root_dir, transform=None):
"""
root_dir (string): Path to parent folder... |
import decneo
from decneo.commonFunctions import *
from decneo import geneLists
import DigitalCellSorter
wfile = 'DCS output/PanglaoDBendothelialAllv0.h5'
cwfile = wfile[:-3] + '_combined.h5'
conffile = 'data/allConfidencePanglaoDB.h5'
if __name__ == '__main__':
# Annotate all datasets of PanglaoDB
if False:... |
"""
Module containing private utility functions
===========================================
The ``scipy._lib`` namespace is empty (for now). Tests for all
utilities in submodules of ``_lib`` can be run with::
from scipy import _lib
_lib.test()
"""
from __future__ import division, print_function, absolute_im... |
def bubble_sort_2(l):
for iteration in range(len(l)):
for index in range(1, len(l)):
this_hour, this_min = l[index]
prev_hour, prev_min = l[index - 1]
if prev_hour > this_hour or (prev_hour == this_hour and prev_min > this_min):
continue
l[in... |
import sys
import os
import random
from pyspark import SparkContext, SparkConf
from pyspark.sql import SparkSession
from pyspark.sql.types import *
from pyspark.sql import SQLContext
from pyspark.sql import Row
def createTrackData(shipRows):
trackData={}
for r in shipRows:
mmsi=r[0]
dt=r[1]
... |
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from blog import Config
addr: str = Config.sql_address()
name: str = Config.sql_name()
password: str = Config.sql_pass()
db: str = Config.sql_db()
'''
MARIADB_DATABASE_URL = f"mariadb+... |
"""Logging module."""
import logging
import sublime
log = logging.getLogger("OpenContextPath")
def update_logger():
"""Update the logger based on the current settings."""
settings = sublime.load_settings("OpenContextPath.sublime-settings")
# set the verbosity level
if settings.get("debug", False)... |
import csv
class DataSet():
#This class reads and organizes a CSV file (can be a .txt file)
def __init__(self,filename):
filestream = open(filename,'r')
csv_reader = csv.reader(filestream,delimiter=',')
self.raw_inputs = [[int(r) for r in row] for row in csv_reader]
def getRaw(self)... |
#!/usr/bin/python
import sys
import os
if len(sys.argv) >= 3:
psl_filename = sys.argv[1]
skip_Nine = int(sys.argv[2])
else:
print("usage:hist_psl.py psl_file skip_Nine")
print("or ")
sys.exit(1)
################################################################################
def process_temp_list(... |
# Copyright (c) 2015 OpenStack Foundation.
#
# 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... |
from eth_tester.exceptions import TransactionFailed
from pytest import fixture, raises
from utils import longTo32Bytes, PrintGasUsed, fix
from constants import BID, ASK, YES, NO
from datetime import timedelta
from old_eth_utils import ecsign, sha3, normalize_key, int_to_32bytearray, bytearray_to_bytestr, zpad
def tes... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.