content stringlengths 5 1.05M |
|---|
import uvicorn
from fastapi import FastAPI
from app.routers import routers
app = FastAPI()
app.include_router(routers.app)
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8000)
|
from functools import reduce
import numpy as np
from manimlib.constants import *
from manimlib.animation.animation import Animation
from manimlib.animation.movement import Homotopy
from manimlib.animation.composition import AnimationGroup
from manimlib.animation.composition import Succession
from manimlib.animation.c... |
#!/usr/bin/env python
# coding: utf-8
# ## Questionário 32 (Q32)
# Orientações:
#
# - Registre suas respostas no questionário de mesmo nome no SIGAA.
# - O tempo de registro das respostas no questionário será de 10 minutos. Portanto, resolva primeiro as questões e depois registre-as.
# - Haverá apenas 1 (uma) tenta... |
from servo import *
from TempSensor import *
from DistanceSensor import *
import time
import threading
import json
import urllib.request
from urllib.parse import urlencode
from programs import *
DHT11 = temp_sensor(23)
command = dict()
command["motor1"] = 0 #base left right
command["motor2"] = 0 ... |
import inspect
import logging
import traceback
import sys
from functools import wraps, update_wrapper, partial # Todo!
from timeit import default_timer as timer
from typing import Callable, Any, TypeVar, cast
default_log_level = logging.DEBUG
'''
Override for default logging level.
'''
default_performance_measure =... |
import django
from django.conf import settings
from example.project import settings as project_settings
import feats
from feats.storage import Memory
if not settings.configured:
settings.configure(INSTALLED_APPS=['feats.django'], FEATS=feats.App(storage=Memory()))
django.setup()
|
#!/usr/bin/env python -i
# -*- mode: Python; tab-width: 4; indent-tabs-mode: nil; -*-
# ex: set tabstop=4
# Please do not change the two lines above. See PEP 8, PEP 263.
'''Tanium Software Management Tool
This is a proof of concept showing how to use the following workflow using Tanium via PyTan
1) Shows available app... |
#!/usr/bin/python
import serial
from time import sleep
##################################################
#
##################################################
port = "/dev/ttyACM0"
baud = 57600
# Open the serial port.
ser = serial.Serial(port, baud, timeout=1)
# open the serial port
if ser.isOpen():
print(ser.name... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
import requests
import mlbapi.version
import mlbapi.exceptions
from mlbapi.utils import to_api_keys
from mlbapi.utils import check_kwargs
#TEST_URL = "https://statsapi.mlb.com/api/v1/game/447440/boxscore"
API_VERSION = "v1"
BASE_URL = 'https://statsapi.mlb.c... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import torch
from maskrcnn_benchmark.modeling.rbox_coder import RBoxCoder
from maskrcnn_benchmark.structures.bounding_box import RBoxList
from maskrcnn_benchmark.structures.rboxlist_ops import cat_boxlist
from maskrcnn_benchmark.structures.rboxlis... |
# add a key to list in dictionary relation ship here.
# pole_list_list is a list of lists which will contain the following
# pole_list[pole number]=[current,time,individual_result]
class Test:
def __init__(self, test_name, pole_list_list, continuous, final_result):
self.test_name = test_name
self... |
from __future__ import print_function
import argparse
import torch
import torch.utils.data
from torch import nn, optim
from torch.nn import functional as F
from torchvision import datasets, transforms
from torchvision.utils import save_image
import time
import os
import uuid
from tensorboardX import SummaryWriter
from ... |
def sanitize_version(raw_version):
if raw_version[0] == 'v':
return raw_version[1:]
elif raw_version.startswith('release/'):
return raw_version[8:]
return raw_version
|
# -*- coding: utf-8 -*-
"""This module contains the main code for Procem RTL workers."""
# Copyright (c) TUT Tampere University of Technology 2015-2018.
# This software has been developed in Procem-project funded by Business Finland.
# This code is licensed under the MIT license.
# See the LICENSE.txt in the project r... |
Enonce = """
Large sum
Problem 13
Work out the first ten digits of the sum of the following one-hundred 50-digit numbers.
37107287533902102798797998220837590246510135740250
46376937677490009712648124896970078050417018260538
74324986199524741059474233309513058123726617309629
9194221336357416157252243056330181107240615... |
# Basic Frame Differencing Example
#
# Note: You will need an SD card to run this example.
#
# This example demonstrates using frame differencing with your OpenMV Cam. It's
# called basic frame differencing because there's no background image update.
# So, as time passes the background image may change resulting in iss... |
import ipaddress
import logging
import pyrfc3339
from . import model, tag, jasyncio
from .annotationhelper import _get_annotations, _set_annotations
from .client import client
from .errors import JujuError
from juju.utils import juju_ssh_key_paths
log = logging.getLogger(__name__)
class Machine(model.ModelEntity):... |
import discord
from cogs.embed import *
from discord.ext import commands
class Kick(commands.Cog):
def __innit__(self, bot):
self.bot = bot
@commands.command()
@commands.guild_only()
@commands.has_permissions(kick_members=True)
async def kick(self, ctx, user: discord.Member, *, reason=Non... |
#Copyright 2021, Battelle Energy Alliance, LLC
import logging
from stix2 import Infrastructure, IPv4Address, Relationship, Software, NetworkTraffic
from stix2.datastore import Filter, FilterSet
from autodiscover.util.helper import gen_uuid
from autodiscover.util.fetchers import CSVFetcher
from autodiscover.util.remotec... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 29 11:52:09 2019
@author: deepglint
"""
import re
import matplotlib.pyplot as plt
import numpy as np
def main():
file = open('cal.log','r')
list = []
# search the line including accuracy
count = 0
reward = 0
av = 5#38*1... |
import sys
import csv
import itertools
import argparse
parser = argparse
parser = argparse.ArgumentParser()
parser.add_argument("-n", "--numeric", help="items are numeric",
action="store_true", default=False)
parser.add_argument("support", help="support threshold")
parser.add_argument("-p", "--perc... |
from master import *
from nose.tools import nottest
import pexpect
import random
import sys
from containers import *
NUM_TESTS = 1
PASSRATE = 0.9
DOCKER = False
class Client(object):
def __init__(self, command, verbose=True):
self.command = command
self.client = pexpect.spawn(command)
self... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import Tkinter as tk
from pycomm.ab_comm.slc import Driver as SlcDriver
import logging
from PIL import ImageTk, Image
import tkMessageBox
WindowsSize = "780x1050"
PLC_IP_Adress = '172.23.1.70'
Update_Program_Every_ms = 50
class DripControl:
def __init__(self, maste... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import grpc
import time
import base64 as b64
import requests
from .config import SE_URL_HTTP, SE_URL_GRPC, SEStatusCode, SEUrls
from .svc_jobs_pb2_grpc import JobStub
from .svc_jobs_pb2 import Problem, JobRequest, CreateJobRequest
from .helper import _get_logger, unusual_... |
import os
import shutil
import qiime2
import unittest
import tensorflow as tf
from songbird.q2._method import multinomial
from songbird.q2._summary import summarize_single, summarize_paired
from songbird.util import random_multinomial_model
class TestSummary(unittest.TestCase):
def setUp(self):
res = ran... |
from django.contrib.auth.models import User
from django.shortcuts import get_object_or_404
from django.utils.translation import ugettext as _
from django.http import HttpResponseForbidden, HttpResponse, \
HttpResponseBadRequest, Http404
from utils.logger_tools import disposition_ext_and_date
fr... |
# -*- coding: utf-8 -*-
# SPDX-License-Identifier: ISC
# Copyright (c) Justus Winter <4winter@informatik.uni-hamburg.de>
from __future__ import print_function, absolute_import, unicode_literals
try:
# py3k
import configparser
except ImportError:
import ConfigParser as configparser
class GetListMixIn(obje... |
#!/usr/bin/env python
## Program: VMTK
## Module: $RCSfile: vmtksurfacemodeller2.py,v $
## Language: Python
## Date: $Date: 2014/10/24 16:35:13 $
## Version: $Revision: 1.10 $
## Copyright (c) Luca Antiga, David Steinman. All rights reserved.
## See LICENCE file for details.
## This software is... |
from git import Repo
from git_inspector.formatter.report_type_oriented_report_formatter import (
format_git_reports,
)
from git_inspector.reports import ReportType, GIT_REPORT_LEVEL_ALERT, Report
example_report = ReportType("has_remote", "Repos with remotes", GIT_REPORT_LEVEL_ALERT)
def test_output_contains_remo... |
"""Microsoft Azure Blobs Storage: System"""
import re
from azure.storage.blob import ( # type: ignore
PageBlobService,
BlockBlobService,
AppendBlobService,
BlobPermissions,
ContainerPermissions,
)
from azure.storage.blob.models import _BlobTypes # type: ignore
from airfs.storage.azure import _ha... |
#################################################################
# Libraries
#################################################################
import sys, os
import pytest
import json
from magma import metawfl as wfl
#################################################################
# Tests
######################... |
import os
import logging
import json
import ijson
import shutil
import copy
import datetime
from tqdm import tqdm
import numpy as np
import re
import string
from nltk.tokenize import word_tokenize
from core.config import *
logger = logging.getLogger(__name__)
IGNORE_PUNCT = '"#$&()*,-/;<=>@[\\]^_`{|}~' # keep . ! ? ... |
import numpy as np
import cv2
import os, sys
def segmentation_image_summary(kwargs, **inputs):
num_img_logs = 10
img_logs = []
for i in range(num_img_logs):
batch_id = np.random.randint(0, kwargs['batch_size'])
#image log
images = inputs['images'][batch_id].copy()
... |
import traceback
import sys
def division():
try:
1/0
except ZeroDivisionError:
traceback.print_stack(file=sys.stdout)
division()
|
__author__ = 'benjamin'
# general settings
# visu
x_min_view = -1
x_max_view = 3
y_min_view = -2
y_max_view = 2
# control degree
t_value_min = 0
t_value_max = 1
t_value_step = .01
t_value_init = 0
resolution = 100
sample_curve_names = [
("circle", "circle"),
("shifted circle", "shift_circle"),
("cardioi... |
import cv2
import pickle
import os.path
import numpy as np
from imutils import paths
from imutils import resize
from sklearn.preprocessing import LabelBinarizer
from sklearn.model_selection import train_test_split
from keras.models import Sequential
from keras.layers.convolutional import Conv2D, MaxPooling2D
from keras... |
# -*- coding: utf-8 -*-
import os
import requests
BASE_URL = "https://{}.harvestapp.com".format(os.environ["HARVEST_SUBDOMAIN"])
CLIENTS_URL = "{}/clients".format(BASE_URL)
INVOICES_URL = "{}/invoices".format(BASE_URL)
PROJECTS_URL = "{}/projects".format(BASE_URL)
USER_AUTH = (os.environ["HARVEST_USERNAME"], os.env... |
"""
try to identify users / hosts doing illegal / questionable things
"""
import time
from collections import defaultdict
from django.core.management.base import BaseCommand
from django.db import transaction
from django.db.utils import OperationalError
from nsupdate.main.models import Host
from nsupdate.main import ... |
class FoodResponse(object):
"""
Specifies the response to be sent for the zomato details.
"""
def __init__(self, *args, **kwargs):
self.restaurant_id = int(kwargs.get("id", -1))
self.restaurant_name = kwargs.get("name", "")
self.restaurant_url = kwargs.get("url", "#")
se... |
# -*- coding: utf-8 -*-
"""
pyboleto.html
~~~~~~~~~~~~
Classe Responsável por fazer o output do boleto em html.
:copyright: © 2011 - 2012 by Eduardo Cereto Carvalho
:license: BSD, see LICENSE for more details.
"""
import os
import barcode
class BoletoHTML(object):
"""Geração do Boleto em HTM... |
from __future__ import absolute_import, division, print_function
import os
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import colors
from matplotlib.patches import Patch
from vivarium.core.emitter import timeseries_from_data
def plot_activity(data, out_dir='out', filename='motor_control'):
... |
from __future__ import division
import os
import numpy as np
import pickle as pick
from sklearn.ensemble import RandomForestClassifier
full_path = os.path.dirname(__file__)
def to_categorical(labels, n):
retVal = np.zeros((len(labels), n), 'int')
ll = np.array(list(enumerate(labels)))
retVal[ll[:, 0], ... |
from . import functional as F
__all__ = [
'Levenshtein', 'SegmentErrorRate'
]
class Levenshtein:
"""levenshtein distance
returns number of deletions, insertions, or substitutions
required to convert source string into target string.
Parameters
----------
source, target : str
Returns... |
tree = [None] * 10
def root(k):
if tree[0] != None:
print("Tree already had root.")
else:
tree[0] = k
def setLeft(k, i):
if tree[i] == None:
print("child is not at", (i* 2)+1, "No parent is found.")
else:
tree[(i* 2)+1]= k
def setright(k, i):
if tree... |
"""
This example acts as a keyboard to peer devices.
"""
# import board
import sys
import time
from adafruit_hid.keyboard import Keyboard
from adafruit_hid.keyboard_layout_us import KeyboardLayoutUS
import adafruit_ble
from adafruit_ble.advertising import Advertisement
from adafruit_ble.advertising.stan... |
import hashlib
import random
import sys
if __name__ == "__main__":
randomNumSize = 8 # 随机数长度
num = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
# 参数错误
if len(sys.argv) != 2:
print("Wrong argument number!")
exit(0)
pswd = sys.argv[1] # 密码
print("Password: " + pswd)
# 生成随机数
# l... |
# Copyright (c) 2019 Karl Sundequist Blomdahl <karl.sundequist.blomdahl@gmail.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the righ... |
from django.db import models
import datetime as dt
from cloudinary.models import CloudinaryField
class Image(models.Model):
# image = models.ImageField(upload_to = 'pictures/')
image = CloudinaryField('pictures')
name = models.CharField(max_length =30)
description = models.CharField(max_length = 100)
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Common models."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from collections import namedtuple
from django.contrib.auth.models import User
from django.db import... |
pcgamer = ["gabinete cooler master","placa de video GeForce RTX 2080Ti","processador i9","placa mãe asus TUF","water cooler"]
print(pcgamer)
pcgamer.remove("gabinete cooler master")
pcgamer.remove("placa de video GeForce RTX 2080Ti")
print(pcgamer) |
from ..common import cloudcli_server_request, assert_only_one_server, assert_no_matching_servers, get_server_id
def test_server_tags_only_one_server(session_server_powered_on, session_server_powered_off):
assert_only_one_server([session_server_powered_on, session_server_powered_off], "/server/tags")
def test_se... |
"""
Example of Pymunk Physics Engine Platformer
"""
import math
from typing import Optional
import arcade
SCREEN_TITLE = "PyMunk Platformer"
# How big are our image tiles?
SPRITE_IMAGE_SIZE = 128
# Scale sprites up or down
SPRITE_SCALING_PLAYER = 0.5
SPRITE_SCALING_TILES = 0.5
# Scaled sprite size for tiles
SPRITE_... |
# Generated by Django 2.2.6 on 2019-12-24 18:08
import ckeditor_uploader.fields
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('blog', '0004_auto_20191224_1739'),
]
operations = [
migrations.AlterField(
model_name='article',
... |
# Copyright: 2005 Marien Zwart <marienz@gentoo.org>
# License: BSD/GPL2
from io import StringIO
import sys
from pkgcore.config import cparser, central, errors
from snakeoil.test import TestCase
class CaseSensitiveConfigParserTest(TestCase):
def test_case_sensitivity(self):
cp = cparser.CaseSensitiveCon... |
# Python
'''
Note Python 3's int doesn't have a max size (bounded by memory)
float('inf') is for infinity, guaranteed to be higher than any other int value
range vs. xrange (deprc in python3)
If you want to write code that will run on both Python 2 and Python 3, use range() as the xrange function is deprecat... |
import asyncio
import datetime
import discord
from discord.ext import commands
from Exceptions import NotLinkedException
from utilty import id_to_uuid, uuid_to_mcid, getservername
class CreateTicket(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command(name="new", a... |
#!/usr/bin/env python3
# -*- encoding: utf-8 -*-
import re
def gen_doc(s):
m = re.search('([a-zA-Z_]+)\(', s)
if m:
t = m.group(1).split('_')
print('//! @brief {} a {}'.format(' '.join(t[1:]), t[0]))
|
# !/usr/bin/env python
# _*_ coding:utf-8 _*_
from django.conf.urls import url
from . import views
urlpatterns = [
# 1.获取图形验证码 image_codes/(?P<uuid>[\w-]+)/
url(r'^image_codes/(?P<uuid>[\w-]+)/$', views.ImageCodeView.as_view(), name='img_code'),
# 2. 短信验证码sms_codes/(?P<mobile>1[3-9]\d{9})/
ur... |
import pytest
import tubes
def test_single_index_get_on_json_value():
tube = tubes.Each(["[]", "[1, 2, 3]"]).json().get(1, 'null')
assert list(tube) == [None, 2]
def test_single_index_get_on_json_value():
tube = tubes.Each(["[1,2,3]", "[8,9,10]", '["a", "b", "c"]']).json().multi(lambda x: (
x.get... |
import numpy as np
from io import StringIO
import PIL.Image
from IPython.display import Image, display
def showBGRimage(a, fmt='jpeg'):
a = np.uint8(np.clip(a, 0, 255))
a[:,:,[0,2]] = a[:,:,[2,0]] # for B,G,R order
f = StringIO()
PIL.Image.fromarray(a).save(f, fmt)
display(Image(data=f.getvalue()))... |
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
#classifiers: https://pypi.python.org/pypi?%3Aaction=list_classifiers
setup(
name = "grocerytrends",
version = "0.1",
author = "Jacob Hooey",
author_email = "jacob@pompouspanda.com",
description = ("A Pyt... |
import sys, error
def die(err=False, msg=False):
print('Exiting...')
if err != False:
raise(error.dead())
else:
if msg != False:
sys.exit(msg)
sys.exit()
def arg(pos):
try:
return(sys.argv[pos])
except IndexError:
return(False)
|
from . import EcoDevicesRT2
from .const import RT2_API
class Post:
"""Class representing the Post or Sub-Post"""
def __init__(
self, ecort2: EcoDevicesRT2, id_post: int, id_subpost: int = None
) -> None:
self._ecort2 = ecort2
self._id_post = id_post
self._id_subpost = id_s... |
# Binary heap implementation based on Sedgewick and Wayne's
# IndexMaxPQ.java: http://algs4.cs.princeton.edu/24pq/IndexMaxPQ.java
import array
class Heap:
def __init__(self):
self.pq = array.array('i', [-1])
self.qp = array.array('i', [-1])
self.keys = array.array('f', [-1])
s... |
import pdb
import time
import itertools
import os
import sys
import pagexml
import cv2
import torch
from torch.utils.data import Dataset, DataLoader
from torchvision import datasets, models, transforms
from dataloader import CSVDataset, collater, Resizer, AspectRatioBasedSampler, Augmenter, UnNormalizer, Normalizer
im... |
from numpy import nan
import codecs
import math
from ..data.data import PUNCTUATION_VOCABULARY, PUNCTUATION_MAPPING, SPACE
def compute_error(target_path, predicted_path):
"""Computes and prints the overall classification error and precision, recall, F-score over punctuations."""
MAPPING = {}
counter = 0
... |
from netapp.netapp_object import NetAppObject
class MediascrubDetailInfo(NetAppObject):
"""
Information about media scrubbing.
"""
_raid_group = None
@property
def raid_group(self):
"""
Name of the RAID group.
"""
return self._raid_group
@raid_group.sett... |
import os
from gears.assets import Dependencies
from .helpers import GearsTestCase
class AssetDependenciesTests(GearsTestCase):
fixtures_root = 'asset_dependencies'
def test_adds_dependency_only_once(self):
fixture_file = self.find_fixture_file('adds_dependency_only_once', 'dependency')
depe... |
"""
Application for managing the acquisition (download/upload) of data sets.
"""
from .config import DasConfig
# DO NOT TOUCH - version is changed automatically by Bumpversion
__version__ = '0.6.0'
|
from modules.server import Server
from dbmodules.base import CoreDBServer
from dbmodules.good import GoodTable
from com.pe_service_error import UNKNOW_ERROR
from sqlalchemy.engine.result import ResultProxy
import logging
from sqlalchemy import text
class GoodServer(Server):
def __init__(self):
self.dbser ... |
########################################
# Overview
#
# This file defines a helper function that
# creates ideal data for a generalized
# linear model
########################################
import numpy as np
# Helper function to create dataset with
# true relationship between Y and X follows
# the glm model exactl... |
# coding: utf-8
## MatplotLib
# In[2]:
import numpy as np
import matplotlib.pyplot as plt
# In[3]:
x = np.linspace(0, 10)
print x
# In[4]:
y_sin = np.sin(x)
y_cos = np.cos(x)
# In[5]:
get_ipython().magic(u'pylab inline')
# In[10]:
plt.plot(x, y_sin, "-r", label = "Sine Wave")
plt.plot(x, y_cos, "-b", la... |
#!/usr/bin/env python
import math
import re
import serial
N = 100
port = serial.Serial('/dev/ttyUSB0', 9600)
port.setRTS(True)
while True:
# Reset counters
n = 0
Sx = 0.0
Sx2 = 0.0
cts = 0
# Collect data
while n < N:
line = port.readline()
match = re.match(r'ADC (-?\d+)', l... |
import json
from pathlib import Path
def parse_modifs():
json_dump = json.load(Path('newPlaceRIDs_raw.json').open(encoding='utf-8-sig'))
rid_dict = {}
for rid, entry in json_dump.items():
name = ''
if 'bo' in entry['langs'].values() or 'bo-x-ewts' in entry['langs'].values():
lg... |
"""Constants for amcrest component."""
DOMAIN = "amcrest"
DATA_AMCREST = DOMAIN
CAMERAS = "cameras"
DEVICES = "devices"
BINARY_SENSOR_SCAN_INTERVAL_SECS = 5
CAMERA_WEB_SESSION_TIMEOUT = 10
COMM_RETRIES = 1
COMM_TIMEOUT = 6.05
SENSOR_SCAN_INTERVAL_SECS = 10
SNAPSHOT_TIMEOUT = 20
SERVICE_UPDATE = "update"
|
import os
import utils
import argparse
import deployment_options
parser = argparse.ArgumentParser()
parser.add_argument("--secret")
parser.add_argument("--id")
deploy_options = deployment_options.load_deployment_options(parser)
def main():
ocm_secret = deploy_options.secret
if ocm_secret == "":
ocm_se... |
import ReID_net.Constants as Constants
from .COCO.COCO import COCODataset
from .DAVIS.DAVIS import DAVISDataset, DAVIS2017Dataset
from ReID_net.datasets.COCO.COCO_detection import COCODetectionDataset
from ReID_net.datasets.COCO.COCO_instance import COCOInstanceDataset
from ReID_net.datasets.COCO.COCO_interactive impor... |
FAKE_SERVER_PATH = "test/fake_server.py"
if __name__ == "__main__":
import sys
import common
sys.path.append(common.ROOT_DIR)
FAKE_SERVER_PATH = "fake_server.py"
import unittest
import asyncio
import subprocess
import json
import time
from sutil.async_http_client import AsyncHttpClient
from test.fake_se... |
"Various text manipulation utilities"
import re
def cmd_replace(ensoapi, old, new):
"Replace old with new in the selected text"
seldict = ensoapi.get_selection()
text = seldict.get("text", "")
if not text:
ensoapi.display_message("No selection!")
else:
result = text.replace(old, new)
ensoapi.set... |
class id_drive_to_download:
ids_dataset={
"imagenet_validation.zip":"1QA2HeOxusHicdbUxg54M8PG2GorB8ukG",
} |
# standard library
import datetime
# Django
from django.db import models
# Local Django
from user.models import Patient
# This class defines the fields necessary to invite a patient to register in
# the system.
class SendInvitationProfile(models.Model):
patient = models.OneToOneField(Patient)
activation_key... |
def permutationCoeff(n, k):
P = [[0 for i in range(k + 1)]
for j in range(n + 1)]
for i in range(n + 1):
for j in range(min(i, k) + 1):
if (j == 0):
P[i][j] = 1
else:
P[i][j] = P[i - 1][j] + (
... |
import logging
from typing import Optional
import osm2geojson
import requests
from django.db import IntegrityError
from mainapp.models import SearchStreet, Location, Body
overpass_api = "http://overpass-api.de/api/interpreter"
logger = logging.getLogger(__name__)
streets_query_template = """
[out:json];area["de:am... |
from .const import *
from .client import Client
from . import smart_cache
from . import errors
from . import utils
|
from pathlib import Path
from typing import Dict, List
# Define a path to the `govcookiecutter` template directory, and its `.envrc` file
DIR_TEMPLATE = Path("{{ cookiecutter.repo_name }}")
PATH_TEMPLATE_ENVRC = DIR_TEMPLATE.joinpath(".envrc")
# Define a list of directory names to recursively ignore, as well as a lis... |
# coding: utf-8
#
# Copyright (c) 2020-2021 Hopenly srl.
#
# This file is part of Ilyde.
#
# 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
#
#... |
## This function takes the dictionary of probability results, and the screening
## code to output a list of threshold values to apply for that screening code,
## that has been defined through iteration to find the values of change in TPR
## and FPR
def defineThresholds(dictionary,screeningCode):
## Define an i... |
from collections import deque
from . import Config
import platform
def get_number_of_images():
if '64' in platform.architecture()[0]:
return Config.images64bit
else:
print("WA: working on 32bit architecture, only {} images stored per camera.".format(Config.images32bit))
return Config.i... |
"""Authentication views and helpers."""
from os import environ
from flask import Blueprint, redirect, url_for
from flask_oidc import OpenIDConnect
from okta import UsersClient
bp = Blueprint("auth", __name__, url_prefix="/")
oidc = OpenIDConnect()
okta_client = UsersClient("https://dev-384355.okta.com", "00HBYsneK... |
##Testing to make sure hashs are the same.
import hashlib
f=open("C:/Users/danha/Desktop/webapp/uploads/test.txt","r")
data=f.read()
x="there are examples, and there is the correct way to do something."
text0_digest = sha_hash = hashlib.sha256(bytes(data,encoding='utf-8')).hexdigest()
text1_digest = sha_hash = has... |
# Copyright 2019 Jussi Löppönen
#
# 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 ... |
import requests
import json
import configparser
import sqlite3
from multiprocessing import Pool, Value, Lock
from ctypes import c_int
import time
# Set the file paths
db_path ='./data/foursquare.db'
config_path = './code/00_collection/config.ini'
outfile_path = './data/json_photo_cat.txt'
# Read in the config.ini to ... |
from typing import List
import datetime
from dateutil import rrule
import webbrowser
from django.utils import timezone
from ...accounts import models as ac_models
from .. import legacy_workers
from .. import models as gc_models
def create_greendomain(hosting_provider, sitecheck):
green_domain = gc_models.GreenD... |
import dbExe
import urllib.request
import urllib.parse
import time
from lxml import etree
def query(content):
# 请求地址
url = 'https://baike.baidu.com/item/' + urllib.parse.quote(content)
# 请求头部
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) ... |
'''
Created on 24.08.2017
@author: Peer
'''
from setuptools import setup
setup(name='gitexplorer',
version='0.1',
description='Git repository analyzer',
author='Peer Wagner',
author_email='wagnerpeer@gmail.com',
url='http://gitexplorer.readthedocs.io',
packages=['gitexplorer'],
... |
# coding: utf-8
from __future__ import absolute_import
from datetime import date, datetime # noqa: F401
from typing import List, Dict # noqa: F401
from rbb_swagger_server.models.base_model_ import Model
from rbb_swagger_server.models.bag_store_summary import BagStoreSummary # noqa: F401,E501
from rbb_swagger_serv... |
import requests
import json
from alpha_vantage.timeseries import TimeSeries
from alpha_vantage.cryptocurrencies import CryptoCurrencies
from alpha_vantage.foreignexchange import ForeignExchange
from alpha_vantage.fundamentaldata import FundamentalData
from alpha_vantage.sectorperformance import SectorPerformances
fr... |
import shutil
from benchmarks.base import BaseBench
class CheckoutBench(BaseBench):
repeat = 3
params = ["copy", "symlink", "hardlink"]
param_names = ["link_type"]
def setup(self, link_type):
super().setup()
self.init_git()
self.init_dvc()
self.dvc("config", "cache... |
from django.test import TestCase
from django.contrib.admin.sites import AdminSite
from ..models import MeasurementType, Container
from ..admin import MeasurementTypeAdmin, ContainerAdmin
from .factories import MeasurementTypeFactory, ContainerFactory
class MeasurementTypeAdminTests(TestCase):
def setUp(self):
... |
from __future__ import annotations
from datetime import date, datetime
from pyproject_fmt import __version__
company, name = "tox-dev", "pyproject-fmt"
release, version = __version__, ".".join(__version__.split(".")[:2])
copyright = f"2022-{date.today().year}, {company}"
master_doc, source_suffix = "index", ".rst"
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.