text stringlengths 1 927k |
|---|
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from ..functional import epipolar as E
class PerspectiveTransformerLayer(nn.Module):
def __init__(self, bv_size, pv_size, intrinsics, translate_z = -10.0, rotation_order='xyz', device='cuda:0', dtype=torch.float32):
'''... |
from . import export
import numpy
from numpy.testing import assert_array_equal
import pytest
import tifffile
expected = numpy.ones((10, 10))
@pytest.mark.parametrize('stack_images', [True, False])
def test_export(tmp_path, example_data, stack_images):
''' runs a test using the plan that is passed through to it
... |
import time
import board
import busio
from digitalio import DigitalInOut, Direction # pylint: disable=unused-import
import adafruit_miniesptool
print("ESP32 mini prog")
# With a Metro or Feather M4
uart = busio.UART(board.TX, board.RX, baudrate=115200, timeout=1)
resetpin = DigitalInOut(board.D5)
gpio0pin = DigitalI... |
from django.test import Client
def test_home_status_code(client:Client):
response = client.get('/')
assert response.status_code == 200 |
# coding: utf-8
"""
Copyright 2015 SmartBear Software
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 applica... |
# -*- coding: utf-8 -*-
"""
solace._openid_auth
~~~~~~~~~~~~~~~~~~~
Implements a simple OpenID driven store.
:copyright: (c) 2010 by the Solace Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import with_statement
from time import time
from has... |
import sys
s = list(map(int,input().split()))
S = s[0]
T = s[1]
X = s[2]
if(T>S):
for i in range(S,T,1):
if(i == X):
print("Yes")
sys.exit()
print("No")
else:
for i in range(S,T+24,1):
if((i%24) == X):
print("Yes")
sys.exit()
print("No") |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 大整数与字节的相互转换
Desc :
"""
def int_bytes():
data = b'\x00\x124V\x00x\x90\xab\x00\xcd\xef\x01\x00#\x004'
print(len(data))
print(int.from_bytes(data, 'little'))
print(int.from_bytes(data, 'big'))
x = 94522842520747284487117727783387188
pri... |
from dartcms import get_model
from dartcms.utils.config import DartCMSConfig
from .forms import ProductForm
app_name = 'products'
Product = get_model('shop', 'Product')
config = DartCMSConfig({
'model': Product,
'parent_kwarg_name': 'section',
'parent_model_fk': 'section_id',
'grid': {
'grid... |
# ext/turbogears.py
# Copyright (C) 2006-2011 the Mako authors and contributors <see AUTHORS file>
#
# This module is part of Mako and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
import re, inspect
from mako.lookup import TemplateLookup
from mako.template import Template
cl... |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE in the project root
# for license information.
from __future__ import absolute_import, division, print_function, unicode_literals
# The actual patterns are defined here, so that tests.patterns.some can redefine
#... |
def test_func(context, p1):
return p1 + 1 |
"""Configuration module."""
from contextlib import contextmanager
import logging
import sys
import toml
log = logging.getLogger()
def load_config(filename=None):
"""Load a configuration from a file or stdin.
If `filename` is `None` or "-", then configuration gets read from stdin.
Returns: A `ConfigDic... |
import os
import sys
import re
allFiles = os.listdir(sys.argv[1])
allFiles.sort()
allFiles = [ sys.argv[1] + "/" + a for a in allFiles]
listStr = "var videoArray = " + str(allFiles);
f = open("src/videolist.js", "w+")
f.write( listStr )
f.close() |
"""
LC 111
Find the minimum depth of a binary tree. The minimum depth is the number of nodes along the shortest path from the root node to the nearest leaf node.
"""
from collections import deque
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
def find_minimum_de... |
# -*- coding: utf-8 -*-
"""
pyvisa-sim.common
~~~~~~~~~~~~~~~~~
This code is currently taken from PyVISA-py.
Do not edit here.
:copyright: 2014 by PyVISA-sim Authors, see AUTHORS for more details.
:license: MIT, see LICENSE for more details.
"""
from __future__ import absolute_import
import s... |
### Modifications due to changes in the coinbase website
import sys, os, time
import numpy as np
import pickle
import tkinter.messagebox
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import config
from coinbase_api.encryption import Coinbase_cryption
from algorithms.lib_trade.tra... |
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def getVal(self,l):
val = ""
while l != None:
val += str(l.val)
l = l.next
return int(val[::-1])
def toList(self,num):
arrayN = []
... |
"""Sample Webots controller for the visual tracking benchmark."""
from controller import Robot, Node
import base64
import os
import sys
import tempfile
try:
import numpy as np
except ImportError:
sys.exit("Warning: 'numpy' module not found. Please check the Python modules installation instructions " +
... |
import unittest
import shlex
import gg
""" assert that override is optional """
class OverrideFailed(Exception):
pass
def vsys(cmd):
raise OverrideFailed()
gg.vsys = vsys
try:
gg.vsys('test')
raise Exception('method override not working')
except OverrideFailed:
pass
""" override vsys """
def vsys... |
import matplotlib.pyplot as plt
# import pandas as pd
import numpy as np
from sko.GA import GA_TSP
import time
import setting
from ryu.base.app_manager import lookup_service_brick
import SRrouting as shortest_forwarding
import network_awareness as awareness
def _GA_Fit(routine):
j=-1
sf = lookup_service_brick(... |
from options import Options
options = Options()
options.add_option('order', 2, 'Order n of linear program (aka number of equations)')
options.add_option('mu', 3.0, 'Determines `shape` of constraint region (Must be >= 3.0; Epsilon = 1/mu)')
options.add_option('pivot_type', 'largest_coefficient', 'Choice of pivot rule',... |
#!/usr/bin/env python
INDEX_DIR = "IndexFiles.index"
import sys
import os
import lucene
import threading
import time
import jieba
from datetime import datetime
from bs4 import BeautifulSoup
from java.nio.file import Paths
from org.apache.lucene.analysis.miscellaneous import LimitTokenCountAnalyzer
from org.apache.lu... |
import collections
from collections.abc import Iterable, Collection
from typing import Union
import torch
from pytorch_nn_tools.convert.sized_map import sized_map
def apply_recursively(func, x):
"""
Apply `func` recursively to `x`.
>>> result = apply_recursively(\
lambda val: val+1, {'a': 10... |
'''
provide web interface to users
'''
import re
import sys
import time
import json
import types
import datetime
import traceback
import pandaserver.jobdispatcher.Protocol as Protocol
import pandaserver.taskbuffer.ProcessGroups
from pandaserver.taskbuffer.WrappedPickle import WrappedPickle
from pandaserver.brokerage... |
from datetime import timedelta
import os
from urllib.parse import urlparse
from google.cloud import storage
# Ref: https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/storage/cloud-client/snippets.py
class GCS:
def __init__(self):
self.client = storage.Client('nogi-backup')
@sta... |
from biothings.utils.common import loadobj
import biothings.hub.databuild.mapper as mapper
class EntrezRetired2Current(mapper.IDBaseMapper):
def __init__(self, db_provider, *args, **kwargs):
super(EntrezRetired2Current,self).__init__(*args,**kwargs)
self.db_provider = db_provider
def load(sel... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon May 6 14:05:30 2019
@author: avanetten
"""
import osmnx_funcs
import numpy as np
from osgeo import gdal, ogr, osr
import scipy.spatial
import geopandas as gpd
import rasterio as rio
import affine as af
import shapely
import time
import os
import sys
i... |
"""
Experiment testing various regularisations on the Sequence UNET model
"""
import os
import sys
import utils
from tensorflow.keras import optimizers
from proteinnetpy.data import ProteinNetDataset, ProteinNetMap
from proteinnetpy.data import make_length_filter
import metrics
import pn_maps
from seq_unet import se... |
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt,numpy as np
plt.clf()
fig = plt.figure(1)
ax = fig.gca(projection='3d')
X, Y, Z = axes3d.get_test_data(0.05)
ax.plot_surface(X, Y, Z, rstride=8, cstride=8, alpha=0.3)
cset = ax.contourf(X, Y, Z, zdir='z', offset=-100,
levels=np.linspace(-10... |
from model.group import Group
from timeit import timeit
def test_group_list(app, db):
ui_list = app.group.get_group_list()
def clean(group):
return Group(id=group.id, groupname=group.groupname.strip())
db_list = map(clean, db.get_group_list())
assert sorted(ui_list, key=Group.id_or_max) == sor... |
""" Hierarchical Sampling for Active Learning (HS)
This module contains a class that implements Hierarchical Sampling for Active
Learning (HS).
"""
from __future__ import division
import numpy as np
from sklearn.cluster import AgglomerativeClustering
from libact.base.interfaces import QueryStrategy
from libact.util... |
# Takes the value of an output in the XML code and calls insert_out()
#def out_processer(root, index, multiple, source, writer, date):
def out_processer(root, index, multiple):
# Index is needed for the research in the file, source is the primary key used to write in the database.
# Multiple is 0 by default, ch... |
# Copyright (C) 2019-2020 Intel Corporation
#
# SPDX-License-Identifier: MIT
from collections import defaultdict
from glob import glob
import logging as log
import os.path as osp
from datumaro.components.extractor import Importer
from datumaro.util.log_utils import logging_disabled
from .format import CocoTask
cla... |
#!/usr/bin/env python3
import socket
import os
import sys
import collections
import re
'''
This script calls the program in its arguments, but replaces any tags (substrings that
begin and end with '@') with a valid port number. The child program can bind to this
port as long as it sets the SO_REUSEPORT sock option. D... |
# Generated by Django 2.2.2 on 2019-06-24 14:52
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
ope... |
from promise import Promise, is_thenable
import six
from graphql.error import format_error as format_graphql_error
from graphql.error import GraphQLError
from graphene.types.schema import Schema
def default_format_error(error):
if isinstance(error, GraphQLError):
return format_graphql_error(error)
r... |
from checkov.terraform.checks.resource.base_resource_value_check import BaseResourceValueCheck
from checkov.common.models.enums import CheckCategories
class S3BlockPublicPolicy(BaseResourceValueCheck):
def __init__(self):
name = "Ensure S3 bucket has block public policy enabled"
id = "CKV_AWS_54"
... |
# Copyright 2017-2020 TensorHub, 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... |
from flask import Blueprint
main = Blueprint("main", __name__)
from ..models import Permission
from . import errors, views
@main.app_context_processor
def inject_permissions():
return dict(Permission=Permission) |
from uuid import UUID
from app.models.customer import Customer
from app.schemas.customer import CustomerInSchema
async def create(payload: CustomerInSchema) -> Customer:
customer = await Customer.create(**payload.dict())
return customer
async def get(customer_id: UUID) -> Customer:
customer = await Cus... |
"""pytest configuration."""
import io
import pathlib
import time
from unittest import mock
import numpy as np
import pytest
from astropy import units as u
from astropy.coordinates import SkyCoord
from typer.testing import CliRunner
import imephu
from imephu.annotation.general import TextAnnotation
from imephu.cli imp... |
# 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 ... |
from .base import ENDPOINT, any_required_kwargs, process_response
class ListsMixin:
@process_response
def get_list_details(self, list_id, **kwargs):
"""
GET /list/{list_id}
"""
url = f"{ENDPOINT}/3/list/{list_id}"
return self.make_request("GET", url, kwargs)
@any_... |
"""
Test suite for the short (<= 8 bytes) input case.
"""
from hypothesis import given
import hypothesis.strategies as st
from umash import C, FFI
from umash_reference import vec_to_u64, umash, UmashKey
U64S = st.integers(min_value=0, max_value=2 ** 64 - 1)
@given(data=st.binary(min_size=0, max_size=8),)
def test_v... |
import numpy as np
import statsmodels.api as sm
import pandas as pd
mdatagen = sm.datasets.macrodata.load().data
mdata = mdatagen[['realgdp','realcons','realinv']]
names = mdata.dtype.names
start = pd.datetime(1959, 3, 31)
end = pd.datetime(2009, 9, 30)
#qtr = pd.DatetimeIndex(start=start, end=end, freq=pd.datetools.B... |
# -*- coding: utf-8 -*-
#
# This file is part of pyfesom2
# Original code by Dmitry Sidorenko, 2013
#
import numpy as np
import matplotlib.pyplot as plt
try:
from mpl_toolkits.basemap import Basemap
except KeyError:
# dirty hack to avoid KeyError: 'PROJ_LIB' problem with basemap
import conda
import os... |
# The MIT License
#
# Copyright (c) 2017 OpenAI (http://openai.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 rights
# to u... |
# -*- coding: utf-8 -*-
###########################################################################
# Copyright (c), The AiiDA team. All rights reserved. #
# This file is part of the AiiDA code. #
# ... |
from appdirs import user_config_dir
import logging
import configparser
import os
from dodo.default_conf import default_conf
conf_dir = user_config_dir("dodo")
conf_file = os.path.join(conf_dir, "dodo.conf")
logfile = os.path.join(conf_dir, "dodo.log")
def write_default_config(conf_file=None):
print("writing defa... |
from security_communication.secure_communication_protocol import SecureCommunicationProtocol
class SecurityProtocol(SecureCommunicationProtocol):
communication_protocol = None
def __init__(self, config, communication_protocol, send_callback = None, receive_callback = None):
super(SecurityProtocol, self).__init... |
#!/usr/bin/env python
from pyzotero import zotero
import bibtexparser
zot = zotero.Zotero('1732893', 'group')
zot.add_parameters(style='mla', format='bibtex', linkwrap="1", tag=">UseGalaxy.eu")
items = zot.everything(zot.top())
with open('_bibliography/citations-eu.bib', 'w') as bibtex_file:
bibtexparser.dump(ite... |
# coding: utf-8
#
# Copyright 2022 :Barry-Thomas-Paul: Moss
#
# 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 applicab... |
# third party
import torch
# syft absolute
import syft as sy
from syft.core.pointer.garbage_collection import GCBatched
from syft.core.pointer.garbage_collection import GCSimple
from syft.core.pointer.garbage_collection import GarbageCollection
from syft.core.pointer.garbage_collection import gc_get_default_strategy
f... |
import numpy as np
sigmoid = lambda x: 1/(1 +np.exp(-x))
def perceptron_sigmoid(weights, inputvect):
return sigmoid(np.dot(np.append(inputvect,[1]), weights))
def gen_network(size):
weights= [np.array([[np.random.randn() for _ in range(size[n-1]+1)]
for _ in range(size[n])]) for n in range(len... |
from .base import *
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['*',]
# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': os.getenv(... |
import operator as op
from manimlib.animation.composition import LaggedStart
from manimlib.animation.transform import ApplyMethod
from manimlib.animation.transform import Restore
from manimlib.constants import BLACK
from manimlib.constants import BLACK
from manimlib.mobject.geometry import Circle
from manimlib.mobject... |
#!/usr/bin/env python
# coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
"""
Script to plot density of states (DOS) generated by an FEFF run
either by site, element, or orbital
"""
__author__ = "Alan Dozier"
__credits__ = "Anubhav Jain, Shyue Ping Ong"
__copy... |
import torch
import torch.nn as nn
import torch.nn.functional as F
class QNetwork(nn.Module):
"""Actor (Policy) Model."""
def __init__(self, state_size, action_size, seed, fc1_units=64, fc2_units=64):
"""Initialize parameters and build model.
Params
======
state_size (int):... |
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making BK-BASE 蓝鲸基础平台 available.
Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
BK-BASE 蓝鲸基础平台 is licensed under the MIT License.
License for BK-BASE 蓝鲸基础平台:
---------------------------------------------... |
# 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... |
"""
WSGI config for register project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SET... |
import pgzrun
TITLE = "Quiz"
WIDTH = 870
HEIGHT = 650
TEMPO_DOMANDA = 10
# Disegna componenti della GUI progettata
scorrevole_box = Rect(0,0,880,80)
domanda_box = Rect(0,0,650,150)
timer_box = Rect(0,0,150,150)
risposta_box1 = Rect(0,0,300,150)
risposta_box2 = Rect(0,0,300,150)
risposta_box3 = Rect(0,0,300,150)
risp... |
from __future__ import unicode_literals
from ..utils import (determine_ext, find_xpath_attr, int_or_none, js_to_json,
unescapeHTML)
from .common import InfoExtractor
class HowStuffWorksIE(InfoExtractor):
_VALID_URL = r"https?://[\da-z-]+\.(?:howstuffworks|stuff(?:(?:youshould|theydontwantyou... |
import numpy as np
from unittest.mock import patch
from pyquil import Program
from pyquil.gates import H, CPHASE, SWAP, MEASURE
from grove.alpha.phaseestimation.phase_estimation import controlled
from grove.alpha.jordan_gradient.jordan_gradient import gradient_program, estimate_gradient
def test_gradient_program():
... |
#!/usr/bin/env python3
"""Module containing the ClassificationPredict class and the command line interface."""
import argparse
import pandas as pd
import joblib
from biobb_common.generic.biobb_object import BiobbObject
from sklearn.preprocessing import StandardScaler
from sklearn import linear_model
from sklearn.neigh... |
import pytest
import logging
from pydm.widgets.timeplot import PyDMTimePlot
from pydm.widgets.waveformplot import WaveformCurveItem
from qtpy.QtGui import QColor
from qtpy.QtCore import QTimer, Qt
from collections import OrderedDict
from ...widgets.baseplot import BasePlotCurveItem, BasePlot
logger = logging.getLogg... |
__author__ = 'chrisprobst'
import unittest
import time
import traceback
import asyncio
HOST = '127.0.0.1'
PORT = 1337
ADDRESS = (HOST, PORT)
class UdpProtocol(asyncio.DatagramProtocol):
def datagram_received(self, data, addr):
print('Datagram received')
def error_received(self, exc):
trace... |
import sqlite3
import pytest
from gsrest.db.user_db import get_db
def test_get_close_db(app):
with app.app_context():
db = get_db()
assert db is get_db()
with pytest.raises(sqlite3.ProgrammingError) as e:
db.execute('SELECT 1')
assert 'closed' in str(e.value)
def test_init_db_... |
# 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 ... |
from django.core import exceptions as django_exceptions
from django.core.exceptions import PermissionDenied
from django.http import Http404
from django.test import TestCase
from misago.core import exceptionhandler
from misago.core.exceptions import Banned
from misago.users.models import Ban
INVALID_EXCEPTIONS = [
... |
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... |
"""
This file provides fallback data for info attributes
that are required for building OTFs. There are two main
functions that are important:
* :func:`~getAttrWithFallback`
* :func:`~preflightInfo`
There are a set of other functions that are used internally
for synthesizing values for specific attributes. These can ... |
import sys, struct
def read_entry(f):
header = f.read(8)
if not header: return (None, None)
typ = header[0:2] # 2 bytes of type
dlen = struct.unpack("<q", header[2:8] + b"\0\0")[0] # 6 bytes of little-endian length
data = f.read(dlen)
return (typ, data)
def read_slot_index(f):
# Read a slot index, as... |
import torch
from utils.data_util import char_list
from utils.train_util import data_init, model_init
def eval_total_acc(config):
# initialize data loaders
test_loader = data_init(mode='test', use_velocity=config.use_velocity,
t_scale=config.t_scale, batch_s=config.batch_s,
... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.10 on 2017-02-24 15:27
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('user', '0007_auto_20170112_1456'),
]
operations = [
migrations.AddField(
... |
#-*- coding: utf-8 -*-
import os
PRJ_PATH = os.path.abspath(os.path.curdir)
DEBUG = True
TEMPLATE_DEBUG = DEBUG
THUMBNAIL_DEBUG = DEBUG
ADMINS = (
("Alice Bloggs", "alice@example.com"),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': "django.db.backends.sqlite3",
'NAME': "wy... |
from fanstatic import Library, Resource
library = Library('moment.js', 'resources')
moment = Resource(library, 'moment.js', minified='moment.min.js')
moment_timezone = Resource(
library, 'moment-timezone.js',
minified='moment-timezone.min.js',
depends=[moment])
moment_timezone_with_data = Resource(
... |
# Copyright (c) Open-MMLab. All rights reserved.
import logging
import os.path as osp
import warnings
from abc import ABCMeta, abstractmethod
import torch
from torch.optim import Optimizer
import mmcv
from mmcv.parallel import is_module_wrapper
from .checkpoint import load_checkpoint
from .dist_utils import get_dist_... |
from flask_restful import Resource, fields, marshal_with
from flask_jwt_extended import jwt_required, get_jwt_identity
from mini_gplus.daos.user import find_user
from mini_gplus.daos.notification import get_notifications, mark_notification_as_read, mark_all_notifications_as_read
from .users import user_fields
from .pag... |
# Generated by Django 2.1.15 on 2022-01-20 22:51
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0009_alter_user_last_name_max_length'),
]
operations = [
migrations.CreateModel(
name='User',
... |
#!/usr/bin/env python3
# Copyright (c) 2014-2019 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test the wallet."""
from decimal import Decimal
import time
from test_framework.test_framework import ... |
import torch
from mmcv.runner import force_fp32
from torch import nn as nn
from typing import List
from .furthest_point_sample import (furthest_point_sample,
furthest_point_sample_with_dist)
from .utils import calc_square_dist
def get_sampler_type(sampler_type):
"""Get the typ... |
import contextlib
import functools
import os
import random
import shutil
import tempfile
import numpy as np
import torch
from PIL import Image
from torchvision import io
import __main__ # noqa: 401
IN_CIRCLE_CI = os.getenv("CIRCLECI", False) == "true"
IN_RE_WORKER = os.environ.get("INSIDE_RE_WORKER") is not None
I... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Word list originally created by dabura667 and released under The MIT License (MIT)
#
# The MIT License (MIT)
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to dea... |
def to_snake_case(name: str) -> str:
return name.lower().replace("-", "_")
def to_camel_case(name: str) -> str:
words = to_snake_case(name).split("_")
title_cased = map(lambda word: word.title(), words)
return "".join(title_cased)
def strip(c: str) -> str:
return c.strip()
def non_blank(c: str... |
#!/usr/bin/env python3
from setuptools import setup
setup(
name='objectstore',
verison='0.0.1',
author='Joshinux',
description='A simple observer pattern implementation in Python.',
license='Apache 2.0',
url='',
packages=['objectstore'],
extras_requires={
'test': [
'... |
from __future__ import absolute_import
from unittest import TestCase, skip
from ccdproc.core import slice_from_string
class TestCcdprocMethods(TestCase):
def test_slice_from_string(self):
string = '[1:100,15:85]'
result = tuple([slice(14, 85, None), slice(0, 100, None)])
python_slice = sl... |
from insights_analytics_collector import register
@register('config', '1.0', description='CONFIG', config=True)
def config(since, **kwargs):
return {
'version': '1.0'
}
@register('json1', '1.1', description='json1')
def json1(**kwargs):
return {'json1': 'True'}
@register('json2', '1.2', descri... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
import abc
from pathlib import Path
import numpy as np
from astropy import units as u
from astropy.io import fits
from astropy.table import Table
from gammapy.data import GTI
from gammapy.utils.scripts import make_path
from gammapy.maps import RegionNDMap
... |
# Copyright (c) 2016 SUSE Linux Products GmbH
# 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
#
# Unl... |
"""
Tests that test the value of individual items
"""
from unittest import TestCase
import re
import validictory
class TestEnum(TestCase):
schema = {"enum": ["test", True, 123, ["???"]]}
schema2 = {"enum": ("test", True, 123, ["???"])}
def test_enum_pass(self):
data = ["test", True, 123, ["?... |
import time
import uuid
from datetime import datetime
from notion.block.basic import (
TextBlock,
ToDoBlock,
HeaderBlock,
SubHeaderBlock,
PageBlock,
QuoteBlock,
BulletedListBlock,
CalloutBlock,
ColumnBlock,
ColumnListBlock,
)
from notion.block.collection.media import CollectionV... |
# Kavya Ravikanti
# kr8nq
datafile = open("tvshows.csv","r")
tv_shows = []
for line in datafile:
new_line = line.strip().split(",")
tv_shows.append(new_line)
print(tv_shows) |
import numpy as np
import h5py
from sklearn import metrics
from sklearn.metrics import accuracy_score
from sklearn import svm
# path variables
score_path = '../../temp_files/scores.mat'
label_path = '../../temp_files/labels.mat'
with h5py.File(score_path, 'r') as f:
test_features = f['scores'][()]
with h5py.File... |
import copy
visited_states = []
# heuristic fn - number of misplaced blocks as compared to goal state
def heuristic(curr_state,goal_state):
goal_=goal_state[3]
val=0
for i in range(len(curr_state)):
check_val=curr_state[i]
if len(check_val)>0:
for j in range(len(check_val)):
... |
import base64
import copy
import json
import unittest
import uuid
import six
from medallion import (application_instance, init_backend, register_blueprints,
set_config, test)
from medallion.test.data.initialize_mongodb import reset_db
from medallion.utils import common
from medallion.views impo... |
"""This module contains the general information for FirmwareStatus ManagedObject."""
from ...ucscentralmo import ManagedObject
from ...ucscentralcoremeta import UcsCentralVersion, MoPropertyMeta, MoMeta
from ...ucscentralmeta import VersionMeta
class FirmwareStatusConsts():
OPER_STATE_ACTIVATING = "activating"
... |
import setuptools
from xxh_xxh import __version__
with open("README.md", "r", encoding="utf8") as fh:
long_description = fh.read()
setuptools.setup(
name="offsh-xxh",
version=__version__,
description="Bring your favorite shell wherever you go through the ssh. This is a fork from https://github.com/xxh... |
import openpyxl,os
filepath = os.path.join(os.path.dirname(__file__),'shopee.xlsx')
wb = openpyxl.load_workbook(filepath)
#切换到目标数据表
#ws = wb[]
ws = wb['Sheet1']
#待填充数据
data = [[1,2,3],[4,5,6]]
for x in data:
ws.append(x)
savename = 'update_excel.xlsx'
wb.save(savename) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.