text stringlengths 1 927k |
|---|
"""ERRORS"""
class Error(Exception):
"""Main Error Class"""
def __init__(self, message):
self.message = message
@property
def serialize(self):
return {
'message': self.message
}
class CompositeError(Error):
pass
class GeostoreNotFound(Error):
pass |
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.properties import NumericProperty, ReferenceListProperty,\
ObjectProperty
from kivy.vector import Vector
from kivy.clock import Clock
from random import randint
class PongBall(Widget):
velocity_x = NumericProperty(0)
velocity_y = Numeri... |
# pylint: disable=invalid-name,missing-module-docstring,missing-function-docstring
def func(x):
return x + 1
def test_answer():
assert func(3) == 4 |
# encoding: utf-8
from south.db import db
from south.v2 import SchemaMigration
class Migration(SchemaMigration):
def forwards(self, orm):
# Changing field 'TwitterAccount.social_id'
db.alter_column('twitter_twitteraccount', 'social_id', self.gf('django.db.models.fields.BigIntegerField')(u... |
from pacman.model.routing_tables.multicast_routing_table\
import MulticastRoutingTable
from pacman.model.routing_tables.multicast_routing_tables\
import MulticastRoutingTables
from spinn_machine.utilities.progress_bar import ProgressBar
from spinn_machine.multicast_routing_entry import MulticastRoutingEntry
im... |
# Copyright 2021 ONDEWO GmbH
#
# 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 writing, ... |
# The MIT License (MIT)
#
# Copyright (c) 2018 Dean Miller for Adafruit Industries
#
# 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... |
import pytest
from numpy.random import randn
from numpy.random import random
import numpy as np
def test_non_detection():
from ..cube import EmissionCube
from astropy.coordinates import SkyCoord
import astropy.units as u
'''
Test that an anti-center pointing returns zero emission
'''
l = 18... |
import unittest
from hypothesis import given, settings
from hypothesis.strategies import text
from sys import getsizeof
from compressStr import compress_string, decompress_string
class TestMyGzip(unittest.TestCase):
"""
Unit tests for the my_gzip module.
"""
@given(string=text())
@settings(max_ex... |
# coding: utf-8
#
# Copyright 2019 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "lice... |
# coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
from __future__ import unicode_literals
import sys
import re
import datetime
from collections import namedtuple
import json
from six.moves import map, cStringIO
from six import string_types
from monty.json i... |
# *************** SETTINGS *************** #
MODEL_NAME = 'VGG16-TL'
BATCH_SIZE = 6
EPOCHS = 100
EXIF_FLAG = 0 # Set on 1 if the program is running for the first time with a dataset D, 0 otherwise.
MODELS_DIR = 'models/'
trainingset = "Train_New/"
testset1 = "Test_New/"
testset2 = "Weather_Testset/"
blindtest = "Bli... |
# coding=utf-8
# Copyright 2021 The Trax Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... |
"""
test_wuvt.py - tests for the wuvt module
author: mutantmonkey <mutantmonkey@mutantmonkey.in>
"""
import re
import unittest
from mock import MagicMock
from modules import wuvt
from web import catch_timeout
@catch_timeout
class TestWuvt(unittest.TestCase):
def setUp(self):
self.phenny = MagicMock()
... |
class Node:
def __init__(self, data):
self.data = data
self.next = None
class Solution:
def insert(self, head, data):
p = Node(data)
if head is None:
head = p
elif head.next is None:
head.next = p
else:
start = head
... |
import importlib
import torch
from torch import nn
from torch.nn import functional as F
from heads import FCNHead
class ModelBuilder(nn.Module):
def __init__(self, net_config, aux_config=None):
super(ModelBuilder, self).__init__()
num_classes = net_config['num_classes']
out_planes = int... |
from math import floor
from numpy import delete, fliplr
from itertools import chain
from random import random, sample
from copy import deepcopy
from chromosome import fitness, pmx, obx
from utils import create_shuffle_array
from genetic import POPULATION_SIZE, PROBABILITY_ELITISM, \
NUMBER_TOURNAMENT_SELECTION, CRO... |
"""
Duo Security Accounts API reference client implementation.
<http://www.duosecurity.com/docs/accountsapi>
"""
import client
class Accounts(client.Client):
def get_child_accounts(self):
"""
Return a list of all child accounts of the integration's account.
"""
params = {}
... |
# -*- coding: utf-8 -*-
#
# PIR documentation build configuration file, created by
# sphinx-quickstart on Fri Mar 13 20:02:20 2015.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All c... |
import numpy as np
import scipy.interpolate
from .. import distributions as D
np.random.seed(1)
def sampltest(distr, left=None, right=None, bounds=None):
# check that mean and stddev from the generated sample
# match what we get from integrating the PDF
def FF1(x):
return distr.pdf(x) * x
d... |
'''
Parallel implementation of the Augmented Random Search method.
Horia Mania --- hmania@berkeley.edu
Aurelia Guy
Benjamin Recht
'''
import os
import socket
import time
import gym
import numpy as np
import ray
from arsrl import utils, logz, optimizers
from arsrl.policies import LinearPolicy
from arsrl.shared_noise ... |
import os
from nose.core import TestProgram
os.chdir(os.path.abspath(os.path.dirname(__file__)))
TestProgram() |
import librosa
import librosa.filters
import numpy as np
import tensorflow as tf
from scipy import signal
from scipy.io import wavfile
def load_wav(path, sr):
return librosa.core.load(path, sr=sr)[0]
def save_wav(wav, path, sr):
wav *= 32767 / max(0.01, np.max(np.abs(wav)))
#proposed by @dsmiller
wav... |
from datetime import datetime, timedelta, time
import numpy as np
from collections import MutableMapping
import pandas.lib as lib
import pandas.tslib as tslib
from pandas.types.common import (_ensure_object,
is_datetime64_ns_dtype,
is_datetime64_dtype,... |
# ------------------------------------------------------------------------------
# Access to the CodeHawk Binary Analyzer Analysis Results
# Author: Henny Sipma
# ------------------------------------------------------------------------------
# The MIT License (MIT)
#
# Copyright (c) 2016-2020 Kestrel Technology LLC
# C... |
# -*- coding: utf-8 -*-
""" OneLogin_Saml2_Utils class
Copyright (c) 2010-2021 OneLogin, Inc.
MIT License
Auxiliary class of OneLogin's Python Toolkit.
"""
import base64
import warnings
from copy import deepcopy
import calendar
from datetime import datetime
from hashlib import sha1, sha256, sha384, sha512
from iso... |
from larlib import *
""" Visualization of indices of the boundary triangulation """
V,[VV,EV,FV,CV] = larCuboids([1,1,1],True)
cubeGrid = Struct([(V,FV,EV)],"cubeGrid")
cubeGrids = Struct(2*[cubeGrid,t(1.5,1.5,0),r(0,0,PI/6)])
V,FV,EV = struct2lar(cubeGrids)
VIEW(EXPLODE(1.2,1.2,1.2)(MKPOLS((V,FV))))
V,CV,FV,EV,CF,C... |
import unittest
import numpy as np
from megnet.utils.general import expand_1st, to_list, fast_label_binarize
class TestGeneralUtils(unittest.TestCase):
def test_expand_dim(self):
x = np.array([1, 2, 3])
self.assertListEqual(list(expand_1st(x).shape), [1, 3])
def test_to_list(self):
x... |
import re
DECORATOR_GROUP_PATTERN = r"([^\w\d\s\']+)"
DECORATOR_GROUP_REGEX = re.compile(DECORATOR_GROUP_PATTERN)
DOUBLE_QUOTE_PATTERN = r"\""
DOUBLE_QUOTE_REGEX = re.compile(DOUBLE_QUOTE_PATTERN)
QUOTED_TEXT_PATTERN = r"\'([^\"\'\s]+)\'"
QUOTED_TEXT_REGEX = re.compile(QUOTED_TEXT_PATTERN)
MEANINGLESS_PATTERN = r"^... |
from talon import Context, actions, scope
# Main page (subpath 2)
# /[Page/<page>]
ctx = Context()
ctx.matches = r"""
app: anandtech
browser.path: /^\/(Page\/\d+\/?)?$/
"""
ctx.tags = ["user.pages"]
@ctx.action_class("user")
class UserActions:
# user.pages
def page_current():
tokens = scope.get("brows... |
# -*- coding: utf-8 -*-
# Copyright 2020 Green Valley Belgium NV
#
# 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 appl... |
# Copyright 2021 The Kubeflow Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... |
'''
The MIT License (MIT)
Copyright (c) 2014 Eugene Zhukov
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 rights
to use, copy, modify, merge... |
from __future__ import annotations
from abc import ABC, abstractmethod, abstractmethod
from dataclasses import dataclass
from itertools import chain
from operator import itemgetter
import sys
from typing import Iterable, Iterator, NamedTuple, TYPE_CHECKING
from rich import segment
import rich.repr
from rich.control ... |
__author__ = 'patras'
from domain_springDoor import *
from timer import DURATION
from state import state, rv
DURATION.TIME = {
'unlatch1': 5,
'unlatch2': 5,
'holdDoor': 2,
'passDoor': 3,
'releaseDoor': 2,
'closeDoors': 3,
'move': 7,
'take': 2,
'put': 2,
}
DURATION.COUNTER = {
... |
#!/usr/bin/env python
#coding:utf-8
"""
Author: --<v1ll4n>
Purpose: ThreadPool From Twisted and Add Common Resource
Created: 05/13/17
"""
from __future__ import unicode_literals
import uuid
import threading
import traceback
try:
import queue
except:
import Queue as queue
import time
import random
cla... |
"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.
openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:
http://license.coscl.org.cn/MulanPSL2
THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, W... |
import datetime
import re
from rest_framework_jwt.settings import api_settings
from django.contrib.auth.backends import ModelBackend
from .models import User
# def get_user_by_account(account):
# """
# 根据帐号获取user对象
# :param account: 账号,可以是用户名,也可以是手机号
# :return: User对象 或者 None
# """
# try:
# ... |
import logging
import os
from collections import OrderedDict
from pathlib import Path
import torch
import itertools
import detectron2.utils.comm as comm
from detectron2.checkpoint import DetectionCheckpointer
from detectron2.config import get_cfg
from detectron2.data import MetadataCatalog
from detectron2.engine impor... |
import os
import time
import scratchconnect
login = scratchconnect.ScratchConnect("-IntensifyServer-", "Intens1!")
print("Logged In!")
project = login.connect_project(project_id=599331245)
print("Connected Project!")
variables = project.connect_cloud_variables()
print("Connected Cloud Variables!")
while True:
print("... |
from functools import reduce
from operator import mul
from .basic_layers import Dense, HybridBlock
from .conv_layers import _Conv
from ...base import numeric_types
from ...symbol import Symbol
from sys import version_info
class BinaryLayerConfig:
def __init__(self, grad_cancel=1.0, bits=1, bits_a=1, activation=... |
#
# Autogenerated by Thrift
#
# DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
#
from thrift.Thrift import *
from ttypes import *
from thrift.Thrift import TProcessor
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
try:
from thrift.protocol import fastbinary
exce... |
ó
˜fÃac@s yðddlZddlZddlZddlZddlZddlZddlZddlZddlZddl Z ddl
Z
ddl
Z
ddl
Z
ddl
Z
ddlZddlZddlZddlmZddlmZWn+ek
r
ejdƒejdƒnXddlmZddlmZd„Zd d
d
gZed
Zieej
d
dƒƒd6eej
ddƒƒd6eej
ddƒƒd6dd6dd6dd6dd6d
d
6Z
y
e
j
d
ƒe
j... |
"""
Django settings for telelbirds project.
Generated by 'django-admin startproject' using Django 3.1.2.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
import os
... |
# Time: O(n + w), n is the size of S, w is the size of words
# Space: O(1)
import collections
class Solution(object):
def numMatchingSubseq(self, S, words):
"""
:type S: str
:type words: List[str]
:rtype: int
"""
waiting = collections.defaultdict(list)
for... |
"""Setup for the f_tools package."""
import setuptools
with open('README.md') as f:
README = f.read()
setuptools.setup(
author="Filipe Ferreira",
author_email="py@filipeandre.com",
name='f_tools',
license="MIT",
description='A set of low level framework utilities',
version='1.2.3',
long_description=README,
... |
"""Test that each script can be compiled and executed."""
#
# (C) Pywikibot team, 2014-2021
#
# Distributed under the terms of the MIT license.
#
import os
import sys
import unittest
from contextlib import suppress
from pywikibot.tools import has_module
from tests import join_root_path, unittest_print
from tests.aspec... |
import tensorflow as tf
import cv2 as cv
import numpy as np
from PIL import Image
from core import utils
classesPath = "../../data/coco.names"
modelPath = "../../checkpoint/yolov3_cpu_nms.pb"
IMAGE_H, IMAGE_W = 416, 416
classes = utils.read_coco_names(classesPath)
num_classes = len(classes)
input_tensor, output_tens... |
import json
import os
projectpath ="./"
reuterspath = "./Reuters"
def writeToFile(item,filename):
# 将数据写入到文件中
file = open(filename,'w')
str = json.JSONEncoder().encode(item)
file.write(str)
file.close()
#获取文档名中的文档的id
def getDocID(filename):
end = filename.find('.')
docId = filename[0:end... |
import datetime
import copy
import pprint
from .base import CommandBase
from akebono.inspector import get_scenario_summary
def _get_fixed_length_str(s, length):
if not isinstance(s, str):
raise TypeError('invalid type')
l = length - len(s)
if l < 0:
raise Exception('invalid length')
r... |
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser(description='T-1000 bot')
parser.add_argument('-a', action="store", dest='assets', nargs='+', help='assets to test')
parser.add_argument('-c', action="store", dest="currency", type=str, default='DAI')
parser.add_argument('-g', action="sto... |
import sys
import os
import boto3
import datetime
import argparse
def cleanup_s3db(args):
s3 = boto3.resource('s3', aws_access_key_id=os.environ['AWS_ACCESS_KEY_ID'], aws_secret_access_key=os.environ['AWS_SECRET_ACCESS_KEY'], region_name=os.environ['AWS_S3_REGION_NAME'], endpoint_url=os.environ['AWS_S3_ENDPOINT_UR... |
import time
import psycopg2
def get_conn(conn_string):
conn = psycopg2.connect(conn_string)
conn.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)
return conn
def get_conn_string(username, password, hostname, db_name, port='5432'):
return 'postgresql://{username}:{password}@{hostn... |
import logging
from eth_typing import Address
from eth.abc import MessageAPI
from eth.constants import (
CREATE_CONTRACT_ADDRESS,
)
from eth.typing import (
BytesOrView,
)
from eth.validation import (
validate_canonical_address,
validate_is_bytes,
validate_is_bytes_or_view,
validate_is_integer... |
import graphene
from graphene import (
String,
Int
)
# Org schema Base class
from schema_models import Org
class OrgCreateInput(graphene.InputObjectType):
orgCode = String(required=True)
strCode = String()
parentOrgCode = String()
orgTypeCode = String()
orgDesc = String()
createdBy = ... |
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 25 23:09:40 2020
5.4 池化层
https://tangshusen.me/Dive-into-DL-PyTorch/#/chapter05_CNN/5.4_pooling
@author: bejin
"""
import torch
from torch import nn
def pool2d(X, pool_size, mode='max'):
X = X.float()
p_h, p_w = pool_size
Y = torch.zeros(X.shape[0] ... |
#Project Euler Problem-78
#Author Tushar Gayan
#Multinomial Theorem
import math
import numpy as np
def mod_list(pow,terms):
m = []
for i in range(terms):
if i%pow == 0:
m.append(1)
else:
m.append(0)
return m[::-1]
def partition(n):
num_l... |
import datetime as dt
from src.repos.metricsData.metricsDataRepo import MetricsDataRepo
import pandas as pd
import matplotlib.pyplot as plt
plt.rcParams.update({'figure.max_open_warning': 0})
import matplotlib.dates as mdates
def fetchWrInjGraphContext(appDbConnStr: str, startDt: dt.datetime, endDt: dt.datetime) -> ... |
import json
from app.service.http_client_async import async_http_client
service_name = 'umm'
async def create_task(task, jwt):
return await async_http_client('post', service_name, '/api/tasks', body=json.dumps(task.__dict__), jwt=jwt)
async def update_task(task, jwt):
return await async_http_client('put',... |
from dataclasses import dataclass
from bindings.gmd.abstract_coordinate_system_type import AbstractCoordinateSystemType
__NAMESPACE__ = "http://www.opengis.net/gml"
@dataclass
class VerticalCstype(AbstractCoordinateSystemType):
class Meta:
name = "VerticalCSType" |
"""
Copyright (c) 2021 Olivier Sprangers as part of Airlab Amsterdam
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 require... |
student = {"Name":"Drax", "Age":13, "Class":"First"}
print(student["Name"])
print(student["Age"])
print(student["Class"])
student["Name"] = "Quill"
print(student["Name"])
student["School"] = "Falletone"
print(student["School"])
print(student)
print(len(student))
#del student["Name"]
print(student)
#student.clear()
prin... |
n = 18
number_of_guesses=1
print("Number of guesses is limited to only 9 times from 1 to 100")
while (number_of_guesses<=9):
guess_number = int(input("Guess the number :\n"))
if guess_number<20:
print("You enter Less No. Please enter greator no.\n")
elif guess_number<40:
print("Please enter ... |
import openpyxl
import json
from datetime import datetime
class bank:
def __init__(self):
self.log = dict()
self.log['server'] = list()
self.data = dict()
self.goods = {1 : 1000, 2 : 800, 3 : 600, 4 : 550, 5 : 500, 6 : 400, 7 : 350, 8 : 300, 9 : 100, 10 : 50}
self.files = ... |
# -*- coding: utf-8 -*- #
# Copyright 2020 Google LLC. 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 requir... |
##############################################################################
#
# Copyright (c) 2001, 2002 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# TH... |
#!/usr/bin/env python
import sys
import os
import subprocess
import optparse
__all__ = ['export_db_file', 'module_versions', 'process_options']
def export_db_file(module_versions, path=None):
"""
Use the contents of a dictionary of module versions to create a database
of module release stringin PVs. Th... |
# quick script to automate build/run of titanium developer
import os, sys, platform, shutil, distutils.dir_util as dir_util
import titanium_version
cwd = os.path.dirname(os.path.abspath(__file__))
os_map = { 'Windows': 'win32', 'Darwin': 'osx', 'Linux': 'linux' }
os_name = os_map[platform.system()]
developer_path = os... |
from django.conf import settings
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django.urls import reverse
class Speaker(models.Model):
full_name = models.CharField(max_length=200)
bio = models.TextF... |
"""Django settings for cykel project.
Generated by 'django-admin startproject' using Django 2.0.4.
For more information on this file, see
https://docs.djangoproject.com/en/2.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.0/ref/settings/
"""
import os
impo... |
import zmq
import time
context = zmq.Context()
socket = context.socket(zmq.ROUTER)
socket.connect("tcp://127.0.0.1:5556")
time.sleep(1)
socket.send_multipart([b'router',b'Hello'])
address, msg = socket.recv_multipart()
print(msg) |
a = int(10)
print(a, type(a))
b = 1.0
# b = float(1.0)
print(b,type(b))
c = 1+2j
print(c,type(c))
l = [1,2,3,4,5]
print(l ,type(l))
t = (1,2,3,4,5)
print(t,type(t))
s = 'Sudhanwa Kaveeshwar'
print(s,type(s)) |
from django.db.models.query import QuerySet
import pytest
from tasks.models import Comment, Priority, Status, Task
from users.models import Role, User
NUM_COMMENTS_PER_USER = 3
@pytest.mark.django_db
class TestTaskComments:
@pytest.fixture
def user_and_manager(self, users):
user = users[1][0]
... |
import FWCore.ParameterSet.Config as cms
L1TowerCalibrationProducer = cms.EDProducer("L1TowerCalibrator",
# Choosen settings 6 March 2019, 10_3_X MTD samples
HcalTpEtMin = cms.double(0.5),
EcalTpEtMin = cms.double(0.5),
HGCalHadTpEtMin = cms.double(0.25),
HGCalEmTpEtMin = cms.double(0.25),
HFTp... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = '''
---
module: aws_api_gateway
version_added: 1.0... |
# -*- coding: utf8 -*-
# Copyright (c) 2017-2021 THL A29 Limited, a Tencent company. 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... |
from typing import Dict, List
from overrides.overrides import overrides
from datasets.dataset_base import DatasetBase
class DocumentDatasetBase(DatasetBase):
def __init__(self):
super().__init__()
def get_indices_per_document(self) -> Dict[int, List[int]]:
return {}
def use_collate_func... |
#!/usr/bin/env python
from tkinter import *
import time, docker, subprocess, sys, json, os
# List of allowed devices with their type id.
devices = {"doctor":1, "patient":2, "ambulance":3,"smoke":4,"weather":5,"air":6, "nurse":7, "stretcher":8}
# stores the number of devices by type.
num_devices = {"doctor":0, "patien... |
"""
Django settings for helloworld project on Heroku. For more info, see:
https://github.com/heroku/heroku-django-template
For more information on this file, see
https://docs.djangoproject.com/en/2.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.0/ref/setting... |
import re
import struct
from .compat import Mapping
from datetime import datetime, timedelta
from io import BytesIO
from .compat import timezone, range, byte_as_integer, unpack_float16
from .types import (
CBORDecodeValueError, CBORDecodeEOF, CBORTag, undefined, break_marker,
CBORSimpleValue, FrozenDict)
time... |
import os
import os.path
import copy
import hashlib
import errno
import numpy as np
from numpy.testing import assert_array_almost_equal
def check_integrity(fpath, md5):
if not os.path.isfile(fpath):
return False
md5o = hashlib.md5()
with open(fpath, 'rb') as f:
# read in 1MB chunks
... |
from ._version import __version__
from . import physics
from . import statistics
from . import io
from . import parameters
from . import measurements
from . import classes
from .classes import Measurement, Parameter, ParameterConstraints, Observable, NamedInstanceClass
from .config import config
from flavio.physics.eft... |
from tester import test_case, Node, NodePoll
import concurrent.futures
@test_case("multi_transfer")
def main(env, logger):
settings_node_1 = Node.Settings(Node.Id(20300, 50150))
settings_node_2 = Node.Settings(Node.Id(20301, 50151), nodes=[settings_node_1.id, ])
with Node(env, settings_node_1, logger) as... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''=====================================
@Author :Kaifang Zhang
@Time :2021/7/5 1:31
@Contact: kaifang.zkf@dtwave-inc.com
========================================'''
import numpy as np
def LFM_grad_desc(R, K, max_iter, alpha=1e-4, lamda=1e-4):
"""
实现矩阵缺失元素补全使用梯度... |
# 532. K-diff Pairs in an Array
'''
Given an array of integers nums and an integer k, return the number of unique k-diff pairs in the array.
A k-diff pair is an integer pair (nums[i], nums[j]), where the following are true:
0 <= i, j < nums.length
i != j
|nums[i] - nums[j]| == k
Notice that |val| denotes the absolute... |
# coding=gbk
# the main view of this software including friends list
import Tkinter
from view_chat import ChatView
from socket import *
import time
import thread
import os
# the class of main view
class MainView(Tkinter.Frame):
# ADDR is the socket address
# udpCliSock is the udp socket object which input by ... |
"""
Django settings for reqs project.
Generated by 'django-admin startproject' using Django 2.1.3.
For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/ref/settings/
"""
import os
# Bu... |
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
def load_address_and_contact(doc, key=None):
"""Loads address list and contact list in `__onload`"""
from frappe.contacts.doctype.addre... |
import logging
import json
import requests
from ga4gh.drs.cli.methods.get import get
def api_reponse(postresult):
if postresult.status_code != 200:
error = str(json.loads(postresult.text))
logging.error(error)
raise Exception(error)
return json.loads(postresult.text)
class DRSClien... |
#
# Copyright 2016 The BigDL Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... |
from typing import List, Optional
import numpy as np
import xarray as xr
from .parse_ad2cp import Ad2cpDataPacket, Field, HeaderOrDataRecordFormats
from .set_groups_base import SetGroupsBase, set_encodings
def merge_attrs(datasets: List[xr.Dataset]) -> List[xr.Dataset]:
"""
Merges attrs from a list of datas... |
import regionmask
import numpy as np
import dask
def create_windmax_dict(u, v, names, borders, longitude, latitude):
"""Produce a dictionary of masked maximum wind speeds in units of mph."""
if u.units != "m s**-1":
raise ValueError("U field does not have units m/s")
if v.units != "m s**-1":
... |
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def home():
return "<h1>Hello world</h1>"
if __name__ == "__main__":
app.run(host='0.0.0.0', debug=True) |
def regularization(InputImage, StructuringElementRadius=3):
"""
Compute the 3D scalar field that will be used to regularize the seeds propagation
Inputs:
* InputImage: the 3D image that will be segmented. Must be a 3D numpy array.
* StructuringElementRadius: A structuring element of size (1+2*St... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... |
def resumo(n, credito, debito, brasao='R$', conversao=False):
moeda(n, brasao)
print('-'*60)
print('RESULTADO'.center(60))
print('-'*60)
print(f'O juros de {credito}% sobre {moeda(n, brasao)} corresponde a \t{aumentar(n, credito, brasao, conversao)}')
print(f'O desconto de {debito}% sobre {moed... |
"""Implementation for Eldes Cloud"""
import asyncio
import async_timeout
import logging
import aiohttp
from homeassistant.const import (
STATE_ALARM_ARMED_AWAY,
STATE_ALARM_ARMED_HOME,
STATE_ALARM_DISARMED
)
from ..const import API_URL, API_PATHS
_LOGGER = logging.getLogger(__name__)
ALARM_STATES_MAP = ... |
# cython: language_level=3
from distutils.core import setup, Extension
from Cython.Build import cythonize
import numpy
# import cython_utils
import os
os.environ["CC"] = "g++"
os.environ["CXX"] = "g++"
setup(ext_modules = cythonize(["graphsaint/cython_sampler.pyx","graphsaint/cython_utils.pyx","graphsaint/norm_aggr.p... |
from collections import defaultdict, OrderedDict
from enum import Enum
import json
import math
import os
import pickle
import random
import time
from typing import Any, Callable, Dict, List, Optional, Tuple
import ray
from ray import ObjectRef
from ray.actor import ActorHandle
from ray.exceptions import RayActorError,... |
from django.shortcuts import render,redirect
from .models import Image
from .forms import UploadForm
from django.db.models import Q
from django.db.models.base import ObjectDoesNotExist
from django.http import HttpResponse,Http404
def home(request):
pictures = Image.objects.all()
ctx = {'pictures':pictures}
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.