text stringlengths 2 999k |
|---|
class JsonRes:
craftplan = 'json/craftplan.json'
category_to_icon_en = 'json/en/category_to_icon_en.json'
words_en = 'json/en/words_en.json'
items_en = 'json/en/items_en.json'
material_to_icon_en = 'json/en/material_to_icon_en.json'
plans_en = 'json/en/plans_en.json'
materials_en = 'json/en/... |
"""
WSGI config for hc 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.8/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
from django.contrib.staticfiles.handlers ... |
# _ __
# | |/ /___ ___ _ __ ___ _ _ ®
# | ' </ -_) -_) '_ \/ -_) '_|
# |_|\_\___\___| .__/\___|_|
# |_|
#
# Keeper Commander
# Copyright 2021 Keeper Security Inc.
# Contact: ops@keepersecurity.com
#
import calendar
import datetime
import getpass
import json
import logging
from typing import Optional, Li... |
# Copyright (c) 2014 Red Hat, Inc.
# 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 require... |
import serial
import time
from datetime import datetime
import sys
import os
import yaml
import csv
import re
from validate_commands import CommandValidator
def build_cmd_string(command, values=None, format="%0.3f"):
txt = command
if values is not None:
#print("%s \t %s"%(command, values))
i... |
# ##### BEGIN GPL LICENSE BLOCK #####
#
# 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 the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distrib... |
from .base import Block, GenesisBlock, BlockChain
|
"""
This module contains pdsolve() and different helper functions that it
uses. It is heavily inspired by the ode module and hence the basic
infrastructure remains the same.
**Functions in this module**
These are the user functions in this module:
- pdsolve() - Solves PDE's
- classify_pde() - Classif... |
import demistomock as demisto
from CommonServerPython import *
from CommonServerUserPython import *
""" IMPORTS """
from typing import Dict, Generator, List, Optional, Tuple, Union
import dateparser
import urllib3
# Disable insecure warnings
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
''' CON... |
#!/usr/bin/env python
import numpy as np
import matplotlib.pyplot as plt
import scipy.io.netcdf as netcdf
plt.ion()
flag_mov = 0
flag_traj = 0
dir0 = '../run/'
file1 = 'diags.0000000000.t001.nc'
file2 = 'grid.t001.nc'
f1 = netcdf.netcdf_file(dir0 + file1)
f2 = netcdf.netcdf_file(dir0 + file2)
x = f2.variables['... |
from xml.dom import minidom
from urllib import request
import xmltodict, json
def get_informacoes_clima_7_dias(latitude, longitude):
endpoint_lat_lng = "http://servicos.cptec.inpe.br/XML/cidade/7dias/" + latitude + "/" + longitude + "/previsaoLatLon.xml"
response = request.urlopen(endpoint_lat_lng)
data =... |
import logging
import time
import pytest
from helpers.cluster import ClickHouseCluster
logging.getLogger().setLevel(logging.INFO)
logging.getLogger().addHandler(logging.StreamHandler())
@pytest.fixture(scope="module")
def cluster():
try:
cluster = ClickHouseCluster(__file__)
cluster.add_instance... |
#!/usr/bin/python
# SPDX-License-Identifier: MIT
import math
with open("input", "r") as file:
horizontal_positions = list(map(int, file.readline().split(",")))
cheapest = math.inf
for align in range(min(horizontal_positions), max(horizontal_positions) + 1):
fuel = sum(abs(p - align) for p in horizontal_posit... |
from Util import *
def controls(s):
s.throttle = curve1((s.y - .63 * s.brakes * s.pyv / ((1 - s.pyv / 2300) * 3 + 1)) / 999)
s.steer = curve1(Range180(s.a - s.av / 55, 1))
s.pitch = regress(-s.i - s.iv / 17)
s.yaw = regress(Range180(s.a - s.av / 12, 1))
s.roll = regress(Range180(- s.r + s.rv / 2... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# bittrex_websocket/summary_state.py
# Stanislav Lazarov
from time import sleep
from bittrex_websocket.websocket_client import BittrexSocket
if __name__ == "__main__":
class MyBittrexSocket(BittrexSocket):
def on_open(self):
self.client_callbacks = [... |
import os
import pytest
import sys
import numpy as np
try:
import pymake
except:
msg = "Error. Pymake package is not available.\n"
msg += "Try installing using the following command:\n"
msg += " pip install https://github.com/modflowpy/pymake/zipball/master"
raise Exception(msg)
try:
import fl... |
import os
import time
from cereal import car
from common.kalman.simple_kalman import KF1D
from common.realtime import DT_CTRL
from selfdrive.car import gen_empty_fingerprint
from selfdrive.config import Conversions as CV
from selfdrive.controls.lib.events import Events
from selfdrive.controls.lib.vehicle_model import V... |
import operator
def main():
print ('Compute algorithm rank')
f = open('../data/join_results/sj.12_30.log.csv')
output_f = open('../data/join_results/sj.12_30.log.ranked.csv', 'w')
header = f.readline()
header = header.strip()
header += ',1st time,2nd time,3rd time,4th time, 1st #splits,2nd #sp... |
import sys
import hashlib
def check(args):
if len(args) != 2:
print("usage hashme.py <phrase>")
return False
return True
def main(phrase):
salt ='Km5d5ivMy8iexuHcZrsD'
hash_obj = hashlib.pbkdf2_hmac('sha512', phrase.encode(), salt.encode(), 200000)
print(hash_obj.hex())
if check(sys.argv): main(sys.argv[1])... |
# -*- coding: utf-8 -*-
#
# MongoDB documentation build configuration file, created by
# sphinx-quickstart on Mon Oct 3 09:58:40 2011.
#
# This file is execfile()d with the current directory set to its containing dir.
import sys
import os
import datetime
from sphinx.errors import SphinxError
try:
tags
except Na... |
from unittest.mock import patch
from pydragonfly.sdk.const import ANALYZED, MALICIOUS
from tests.mock_utils import MockAPIResponse
from tests.resources import APIResourceBaseTestCase
from tests.resources.test_analysis import AnalysisResultTestCase
class DragonflyTestCase(APIResourceBaseTestCase):
@property
d... |
from email import generator
from os import listdir
from os.path import isfile, join
import numpy as np
import random
import string
from pymongo import MongoClient
from models.user import User
from models.channel import *
from models.workspace import Workspace
from models.settings import *
# Setup Mongo client
class M... |
# Copyright 2017 The Forseti Security Authors. 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 ap... |
import unittest
from os.path import abspath, join
from robot import api, model, parsing, reporting, result, running
from robot.utils.asserts import assert_equals
class TestExposedApi(unittest.TestCase):
def test_test_case_file(self):
assert_equals(api.TestCaseFile, parsing.TestCaseFile)
def test_... |
from PIL import Image
import os
percent = 0.5
for file_name in os.listdir("../foto/"):
if file_name == "pic8.jpg":
img = Image.open("../foto/"+str(file_name))
if img.size[0] > img.size[1]:
#foto orizzontale
hsize = int((float(img.size[0]) * float(percent)))
vsize = int((float(img.size[1]) * float(perce... |
import sqlite3
from contextlib import closing
with closing(sqlite3.connect('sample.db')) as conn:
c = conn.cursor()
c.execute('create table users (id integer primary key, name varchar, age integer, gender varchar)')
c.executemany('insert into users (name, age, gender) values (?, ?, ?)', [
('Alex', ... |
"""
Here come the tests for attention types and their compatibility
"""
import unittest
import torch
from torch.autograd import Variable
import onmt
class TestAttention(unittest.TestCase):
def test_masked_global_attention(self):
source_lengths = torch.IntTensor([7, 3, 5, 2])
# illegal_weights_m... |
"""Environment wrapper class for logging episodes.
This can be used to record data from a subject playing the task. See
../../moog_demos/restore_logged_data.py for an example of how to read log files.
Note: This logger records everything about the environment, which can be a lot
of data (depending on the task). If yo... |
# -*- coding: utf-8 -*-
'''
Management of the Salt beacons
==============================
.. versionadded:: 2015.8.0
.. code-block:: yaml
ps:
beacon.present:
- save: True
- enable: False
- services:
salt-master: running
apache2: stopped
sh:
beacon.... |
import json
import re
from email import message_from_bytes
from email.message import Message
from office365.runtime.client_request import ClientRequest
from office365.runtime.http.http_method import HttpMethod
from office365.runtime.http.request_options import RequestOptions
from office365.runtime.queries.batch_query ... |
from setuptools import setup, find_packages
from setuptools.command.test import test as TestCommand
import os, sys
# From here: http://pytest.org/2.2.4/goodpractises.html
class RunTests(TestCommand):
DIRECTORY = 'test'
def finalize_options(self):
TestCommand.finalize_options(self)
self.test_a... |
voxel_size = [0.05, 0.05, 0.1]
model = dict(
type='VoxelNet',
voxel_layer=dict(max_num_points=5,
point_cloud_range=[0, -40, -3, 70.4, 40, 1],
voxel_size=voxel_size,
max_voxels=(16000, 40000)),
voxel_encoder=dict(type='HardSimpleVFE'),
middl... |
import time
from pycspr.api.get_block import execute as get_block
def execute(
polling_interval_seconds: float = 1.0,
max_polling_time_seconds: float = 120.0
) -> dict:
"""Returns last finialised block in current era.
:param polling_interval_seconds: Time interval time (in seconds) before polli... |
# -*- coding: utf-8 -*-
#
"""
Unit tests for data related operations.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import os
import sys
import copy
import shutil
import tempfile
import ssl
import tensorflow as ... |
people = int(input())
presentation = ""
total_score = 0
total_average = 0
count_presentation = 0
while True:
command = input()
if command == "Finish":
break
presentation = command
score = 0
count_presentation += 1
for i in range(0, people):
score += float(input())
... |
import os
from django.contrib.gis.utils import LayerMapping
from liveapp.models import Town
town_mapping = {
'town_name': 'Town_Name',
'town_type': 'Town_Type',
'geom': 'MULTIPOINT',
}
town_shp = os.path.abspath(os.path.join(os.path.dirname(__file__), 'data/subcounty', 'towns.shp'),)
def run(verbose=Tru... |
"""
Python <= 3.4 compat for singledispatch.
"""
from sys import version_info
if (version_info.major, version_info.minor) < (3, 4): # pragma: no cover
from singledispatch import singledispatch
else: # pragma: no cover
from functools import singledispatch
__all__ = ['singledispatch']
|
# vim: expandtab:ts=4:sw=4
from __future__ import absolute_import
import numpy as np
from . import kalman_filter
from . import linear_assignment
from . import iou_matching
from .track import Track
class Tracker:
"""
This is the multi-target tracker.
Parameters
----------
metric : nn_matching.Near... |
"""
To understand why this file is here, please read:
http://cookiecutter-django.readthedocs.io/en/latest/faq.html#why-is-there-a-django-contrib-sites-directory-in-cookiecutter-django
"""
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations... |
from django.test import TestCase, Client
from django.contrib.auth import get_user_model
from django.urls import reverse
class AdminSiteTests(TestCase):
def setUp(self):
self.client = Client()
self.admin_user = get_user_model().objects.create_superuser(
email="admin@test.com",
... |
from django.shortcuts import render
# Create your views here.
from django.http import HttpResponse
def index(request):
# return HttpResponse("Hello, world. You're at the polls index.")
return render(request, 'login/index.html') |
import logging
class BaseResponseHandler:
def on_execution(self, event):
logging.debug(event)
return event
def on_exception(self, ex):
logging.exception(str(ex))
raise
def on_response(self, response):
logging.debug(response)
return response
|
from pyspark import SparkContext
import sys
import time
# Put node with smaller id as src of edge and node with bigger id as dst.
def reOrderingSrcAndDstOfEgde(x:list)-> tuple:
src = x[0]
dst = x[1]
probability = x[2]
if src < dst:
return (src,(dst,probability))
else:
return (dst... |
from __future__ import unicode_literals
from wtforms.form import Form
from wtforms.validators import ValidationError
from .fields import CSRFTokenField
class SecureForm(Form):
"""
Form that enables CSRF processing via subclassing hooks.
"""
csrf_token = CSRFTokenField()
def __init__(self, form... |
import csv
import json
import os
import shutil
from collections import defaultdict
import numpy as np
import torch
import torchvision
from termcolor import colored
from torch.utils.tensorboard import SummaryWriter
COMMON_TRAIN_FORMAT = [('episode', 'E', 'int'), ('step', 'S', 'int'),
('episode_... |
'''
Level order binary tree traversal
'''
from collections import deque
class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
n1 = Node(1)
n2 = Node(2)
n3 = Node(3)
n4 = Node(None)
n5 = Node(2)
n6 = Node(None)
n7 = Node(3)
'''
1
... |
# MIT LICENSE
#
# Copyright 1997 - 2020 by IXIA Keysight
#
# 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,... |
# -*- coding: utf-8 -*-
import scipy
from manimlib.imports import *
from from_3b1b.old.fourier import *
import warnings
warnings.warn("""
Warning: This file makes use of
ContinualAnimation, which has since
been deprecated
""")
FREQUENCY_COLOR = RED
USE_ALMOST_FOURIER_BY_DEFAULT = False
class GaussianDis... |
# Generated by Django 2.0.1 on 2018-01-28 04:36
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0004_auto_20180128_1003'),
]
operations = [
migrations.AlterField(
model_name='letter',
name='subject',
... |
"""
Custom demographic model for our example.
"""
import numpy
import dadi
def prior_onegrow_mig((nu1F, nu2B, nu2F, m, Tp, T), (n1,n2), pts):
"""
Model with growth, split, bottleneck in pop2, exp recovery, migration
nu1F: The ancestral population size after growth. (Its initial size is
defined t... |
"""
pygame-menu
https://github.com/ppizarror/pygame-menu
TEST WIDGET SELECTION.
Test widget selection effects.
License:
-------------------------------------------------------------------------------
The MIT License (MIT)
Copyright 2017-2021 Pablo Pizarro R. @ppizarror
Permission is hereby granted, free of charge, t... |
n = int(input("Enter a number : "))
s = 0
num =n
while(n>0):
r = n % 10
s = s + r* r* r
n = n//10
if(s==num):
print("The number is Armstrong")
else:
print("The number is not Armstrong")
|
XX XXXXXXXXXXXXXXXXXXXXXXXXXXXX
|
# Generated by Django 3.1.6 on 2021-04-14 15:18
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
("websites", "0016_remove_site_content_type_constraint"),
]
operations = [
migrations.RenameField(
model_name="websitecontent",
... |
COLOR = ((1, 0, 0), (0, 1, 0), (1, 0, 1), (1, 1, 0), (0, 162 / 255, 232 / 255), (0.5, 0.5, 0.5), (0, 0, 1), (0, 1, 1),
(136 / 255, 0, 21 / 255), (255 / 255, 127 / 255, 39 / 255), (0, 0, 0))
LINE_STYLE = ['-', '--', ':', '-', '--', ':', '-', '--', ':', '-']
MARKER_STYLE = ['o', 'v', '<', '*', 'D', 'x', '.', '... |
import unittest
from fqfa.validator.create import create_validator
class TestCreateValidator(unittest.TestCase):
def test_create_from_string(self) -> None:
# case sensitive
validator = create_validator("ACGT")
# test valid strings
self.assertIsNotNone(validator("ACGT"))
s... |
from rpip.output import Output
exit0 = {'exit_code': 0, 'stdout': 'yes', 'stderr': ''}
exit1 = {'exit_code': 1, 'stdout': '', 'stderr': 'ERROR'}
o0 = {'host1': exit0, 'host2': exit0, 'host3': exit0}
o1 = {'host1': exit0, 'host2': exit1, 'host3': exit0}
o2 = {'host1': exit0, 'host2': exit1, 'host3': exit1}
def test_... |
import json
import struct
import base64
import subprocess
import random
import time
import datetime
import os
import sys
import zlib
import threading
import http.server
import zipfile
import io
import types
import re
import shutil
import pwd
import socket
import math
import stat
import grp
import numbers
from os.path i... |
# -*- coding: utf-8 -*-
"""
AMPLPY
------
AMPL API is an interface that allows developers to access the features of the
AMPL interpreter from within a programming language. All model generation and
solver interaction is handled directly by AMPL, which leads to great stability
and speed; the library just acts as an int... |
# Copyright 2008-2018 pydicom authors. See LICENSE file for details.
"""Benchmarks for the numpy_handler module.
Requires asv and numpy.
"""
from platform import python_implementation
from tempfile import TemporaryFile
import numpy as np
from pydicom import dcmread
from pydicom.data import get_testdata_file
from py... |
# Copyright 2018 Cisco Systems, Inc.
# 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 requi... |
import pyaf.Bench.TS_datasets as tsds
import pyaf.tests.artificial.process_artificial_dataset as art
art.process_dataset(N = 128 , FREQ = 'D', seed = 0, trendtype = "Lag1Trend", cycle_length = 12, transform = "RelativeDifference", sigma = 0.0, exog_count = 0, ar_order = 12); |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from whats import whats
def test_tellme():
assert whats.tellme('美妙的新世界')
|
# pylint: disable=redefined-builtin
# pylint: disable=too-many-arguments
"""Test related method and functionality of Context."""
import pytest
import responses
from decanter.core import Context
from decanter.core.core_api import TrainInput
from decanter.core.extra import CoreStatus
from decanter.core.jobs import DataU... |
# -*- coding: utf-8 -*-
# cython: language_level=3
# Copyright (c) 2020 Nekokatt
# Copyright (c) 2021-present davfsa
#
# 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, inc... |
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community
Edition) available.
Copyright (C) 2017-2019 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in co... |
logging = False
def log(string):
if logging:
print(string)
|
"""
Consul API Endpoints
"""
from consulate.api.acl import ACL
from consulate.api.agent import Agent
from consulate.api.base import Response
from consulate.api.catalog import Catalog
from consulate.api.coordinate import Coordinate
from consulate.api.event import Event
from consulate.api.health import Health
from consu... |
################################################################################
# The Neural Network (NN) based Speech Synthesis System
# https://svn.ecdf.ed.ac.uk/repo/inf/dnn_tts/
#
# Centre for Speech Technology Research
# University of Edinburgh, UK
# ... |
# -*- coding: utf-8 -*-
"""
Model Parallel Best Practices
*************************************************************
**Author**: `Shen Li <https://mrshenli.github.io/>`_
Data parallel and model parallel are widely-used in distributed training
techniques. Previous posts have explained how to use
`DataParallel <https... |
# -*- coding: utf-8 -*-
from celery import Celery
import config
if config.REDIS_PASSWD:
redis_url = "redis://:{0}@{1}:{2}/{3}".format(
config.REDIS_PASSWD,
config.REDIS_HOST,
config.REDIS_PORT,
config.REDIS_DB
)
else:
redis_url = "redis://{0}:{1}/{2}".format(
config... |
# Copyright 2018 The TensorFlow Authors. 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 applica... |
#!/usr/bin/python3
from brownie import AdvancedCollectible, accounts, network, config
from scripts.helpful_scripts import fund_advanced_collectible
def main():
print(config["wallets"]["from_key"])
dev = accounts.add(config["wallets"]["from_key"])
print(network.show_active())
# publish_source = True if... |
###############################################################################
#
# The MIT License (MIT)
#
# Copyright (c) Tavendo GmbH
#
# 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 with... |
#!/usr/bin/env python3
#******************************************************************************
#
#"Distribution A: Approved for public release; distribution unlimited. OPSEC #4046"
#
#PROJECT: DDR
#
# PACKAGE :
# ORIGINAL AUTHOR :
# MODIFIED DATE :
# MODIFIED BY :
# REVISION :
#
# Copyrigh... |
""" Test utilities for testing
:Author: Arthur Goldberg <Arthur.Goldberg@mssm.edu>
:Date: 2019-10-31
:Copyright: 2019, Karr Lab
:License: MIT
"""
from scipy.constants import Avogadro
import os
import shutil
import tempfile
import unittest
from de_sim.simulation_config import SimulationConfig
from wc_sim.multialgorit... |
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'WatchInSGE.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise Imp... |
import numpy
from chainer.backends import cuda
from chainer import configuration
from chainer import function_node
from chainer.utils import argument
from chainer.utils import type_check
class Zoneout(function_node.FunctionNode):
"""Zoneout regularization."""
def __init__(self, zoneout_ratio):
self... |
#!/usr/bin/env python
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
# basic
name='tool-registry-client',
version='0.1.0',
# packages=setuptools.find_packages(exclude=["tests", "tests.*"]),
# py_modules=['hello'],
# scripts=['bin/nlp-eva... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.12 on 2018-04-20 18:17
from __future__ import unicode_literals
from django.db import migrations
import mep.accounts.models
class Migration(migrations.Migration):
dependencies = [
('accounts', '0018_merge_20180418_1607'),
]
operations = [
... |
from unittest.mock import patch
from m.ci.config import Config, GitFlowConfig, MFlowConfig, Workflow
from m.ci.git_env import GitEnv, get_git_env
from m.core import issue
from m.core.fp import Good
from m.core.io import EnvVars
from ..util import FpTestCase
class GitEnvTest(FpTestCase):
config = Config(
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 5/15/20 4:49 PM
# @File : grover.py
# qubit number=4
# total number=37
import cirq
import cirq.google as cg
from typing import Optional
import sys
from math import log2
import numpy as np
#thatsNoCode
from cirq.contrib.svg import SVGCircuit
# Symbols for... |
# -*- coding: utf-8 -*-
"""Region office topology.
Office has tro floors
_________terminate_switch_____________________
| | |
switch-1-floor switch-2-floor
| | |
hosts switchF2 hosts
... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import argparse
import glob
import multiprocessing as mp
import os
import time
import cv2
import tqdm
import numpy as np
from detectron2.config import get_cfg
from detectron2.data.detection_utils import read_image
from detectron2.utils.logger impor... |
from typing import Generic, TypeVar, List, Optional
T = TypeVar('T')
class Stack(Generic[T]):
def __init__(self):
self.items: List[T] = []
def empty(self) -> bool:
return len(self.items) == 0
def push(self, item: T):
self.items.append(item)
def pop(self) -> T:
retu... |
"""Custom url shortener backend for testing Zinnia"""
from django.core.exceptions import ImproperlyConfigured
raise ImproperlyConfigured('This backend only exists for testing')
def backend(entry):
"""Custom url shortener backend for testing Zinnia"""
return ''
|
#
# Copyright (c) 2020, Neptune Labs Sp. z o.o.
#
# 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 agr... |
import unittest
from unittest.mock import patch, Mock
import discord
import datetime
from commands import ChangePrefixCommand
from serverobjects.server import DiscordServer
class TestChangePrefixCommand(unittest.TestCase):
def setUp(self):
self.command = ChangePrefixCommand()
self.time = datetime.datetime.now()
... |
#!/usr/bin/env python
''' Python DB API 2.0 driver compliance unit test suite.
This software is Public Domain and may be used without restrictions.
"Now we have booze and barflies entering the discussion, plus rumours of
DBAs on drugs... and I won't tell you what flashes through my mind each
time I read... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
from .box_head import ROI_BOX_HEAD_REGISTRY, build_box_head
from .keypoint_head import ROI_KEYPOINT_HEAD_REGISTRY, build_keypoint_head, BaseKeypointRCNNHead
from .mask_head import ROI_MASK_HEAD_REGISTRY, build_mask_head, BaseMaskRCNNHead
from .r... |
import os.path
import tkinter as tk
import tkinter.filedialog as fd
import tkinter.messagebox as mb
def main():
text_editor = TextEditor()
text_editor.mainloop()
class TextEditor(tk.Tk):
def __init__(self):
super(TextEditor, self).__init__()
self.title('Ugly Text Editor')
self.... |
import pydantic
import pytest
from jina.peapods.runtimes.gateway.http.models import (
PROTO_TO_PYDANTIC_MODELS,
JinaRequestModel,
)
from jina.types.document import Document
from tests import random_docs
def test_schema_invocation():
for v in vars(PROTO_TO_PYDANTIC_MODELS).values():
v.schema()
... |
#!/usr/bin/env python
"""
This file defines a class for controlling the scope and heterogeneity of
parameters involved in a maximum-likelihood based tree analysis.
"""
import pickle
import warnings
import numpy
from cogent3.align import dp_calculation
from cogent3.align.pairwise import AlignableSeq
from cogent3.cor... |
# Generated by Django 3.2.4 on 2021-07-05 08:34
import django.contrib.postgres.fields
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = []
operations = [
migrations.CreateModel(
name="MusicalWork",
fields=[
... |
# -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2015-2018 CERN.
#
# cds-migrator-kit is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Test example app."""
import os
import signal
import subprocess
import ti... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.8 on 2018-03-20 06:22
from __future__ import unicode_literals
from django.db import migrations, models
import uuid
class Migration(migrations.Migration):
dependencies = [
('flowcells', '0005_auto_20180319_0947'),
]
operations = [
migrat... |
import pygubu
import os
from interpreter import imageFunctions as imageWrapper
from interpreter import lexer as lexer
from interpreter import executeFunctions as main
from interpreter.dataStructures import programState, direction, position
from GUI import infoManager
from GUI import canvasManager
class GUI:
def... |
#!/usr/bin/python3
from ctypes import *
import cv2
import numpy as np
import sys
import os
import time
from ipdb import set_trace as dbg
from enum import IntEnum
class CPoint(Structure):
_fields_ = [("x", c_int),
("y", c_int)]
FEAT_POINTS = 14
class CWindow(Structure):
_fields_ = [("x", c_int)... |
# -*- coding: utf-8 -*-
#
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... |
#*#*#*./examples/evaluate.py
"""Official evaluation script for SQuAD version 2.0.
In addition to basic functionality, we also compute additional statistics and
plot precision-recall curves if an additional na_prob.json file is provided.
This file is expected to map question ID's to the model's predicted probability
th... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.