text stringlengths 1 927k |
|---|
#!/usr/bin/env python3
# encoding: utf-8
"""
release_vars.py
Created by Jonathan Burke on 2013-02-05.
Copyright (c) 2014 University of Washington. All rights reserved.
"""
# See release_development.html for an explanation of how the release process works
# it will be invaluable when trying to understand the scripts ... |
import celery as celery_module
import mock
import pytest
from celery import Celery
from celery.signals import (
before_task_publish, after_task_publish, task_postrun
)
from celery.states import SUCCESS, FAILURE
from celery.worker import state as celery_worker_state
from kombu import Connection
from opentracing.ext... |
_base_ = [
'../_base_/models/cascade_rcnn_r50_fpn.py',
'../_base_/datasets/coco_detection.py',
'../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py'
]
model = dict(
backbone=dict(
type='DetectoRS_ResNet',
conv_cfg=dict(type='ConvAWS'),
sac=dict(type='SAC', use_def... |
import numpy as np
import pandas.util.testing as tm
from pandas import (Series, date_range, DatetimeIndex, Index, RangeIndex,
Float64Index)
class SetOperations(object):
params = (['datetime', 'date_string', 'int', 'strings'],
['intersection', 'union', 'symmetric_difference'])
... |
from django.db import models
from models.models import compare_version
from django.dispatch import receiver
from django.db.models.signals import pre_delete, pre_save
from django.utils.module_loading import import_string
from django.conf import settings
from functools import cmp_to_key
class ModelManager(models.Manager... |
import torch
import yaml
import numpy as np
import pandas as pd
import os
import sys
from dp_datagen import double_pendulum_data
from dp_pidnn import pidnn_driver
from dp_dataloader import testloader
from dp_ff import ff_driver
if len(sys.argv) > 2:
config_filename = sys.argv[2]
else:
config_filename = "dp_con... |
from django.db import models
from django.urls import reverse
# Create your models here.
class Zoo(models.Model):
name = models.CharField(max_length=200, help_text="Enter Zoo Name")
logoFileName = models.CharField(max_length=200, help_text="Enter logo file name", null=True)
def __str__ (self):
return self.name
... |
import pytest
from .base import TestBase
pytestmark = pytest.mark.asyncio
class TestMailbox(TestBase):
async def test_rename(self, imap_server):
transport = self.new_transport(imap_server)
transport.push_login()
transport.push_readline(
b'status1 STATUS Sent (MESSAGES UIDNEX... |
# Number Of Boomerangs
from collections import defaultdict
class Solution:
def choose(self, n, r):
res = 1
for ri in range(r):
res = res * (n - ri) // (ri + 1)
return res
def numberOfBoomerangs(self, points):
if len(points) <= 2:
return 0
dists... |
# importing libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from statsmodels.tsa.arima_model import ARIMA
import datetime
from datetime import date
import warnings
warnings.filterwarnings('ignore')
plt.style.use('fivethirtyeight')
from pmdarima import auto_arima
confirmed_cases = pd.re... |
# pylint: disable=no-self-use,invalid-name
import numpy
from deep_qa.tensors.backend import hardmax
from deep_qa.testing.test_case import DeepQaTestCase
from keras import backend as K
class TestBackendTensorFunctions(DeepQaTestCase):
def test_hardmax(self):
batch_size = 3
knowledge_length = 5
... |
#### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Tangible()
result.template = "object/tangible/dungeon/shared_cave_stalagmite_ice_style_01.iff"
result.attribute_t... |
import sys
import os
import django.core.handlers.wsgi
sys.path.append(os.path.abspath(os.path.dirname(__file__)))
os.environ['DJANGO_SETTINGS_MODULE'] = 'apps.settings'
application = django.core.handlers.wsgi.WSGIHandler() |
# -*- coding: utf-8 -*-
import os
import yaml
basedir = os.path.abspath(os.path.dirname(__file__))
# Load ACL Action file
_ACL_ACTIONS = None
with open(basedir + '/acl-actions.yaml') as _f:
_ACL_ACTIONS = yaml.load(_f.read())
class Config(object):
ADMIN_USERNAME = os.environ.get('ADMIN_USERNA... |
try:
from urllib.parse import urlencode
except ImportError: # Python 2
from urllib import urlencode
from xml.dom.minidom import parseString
from django.contrib.auth.decorators import login_required, permission_required
from django.core import mail
from django.forms import fields
from django.forms.forms imp... |
def get_part_of_line(line, delimiter=";"):
try:
del_index = line.index(delimiter)
return line[:del_index], line[del_index + 1 :]
except ValueError:
return line, ""
def is_line_valid(line):
parts = line.split(";")
if not parts[-1] or parts[-1] == "0":
# If the last part ... |
#!/usr/bin/env python
## import
import sys
import lanefindlib
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import cv2
import pickle
import os
## argin
if len(sys.argv) < 4 or len(sys.argv) > 5:
print("Syntax error! Usage: ");
print(sys.argv[0], "../test_images/test1.jpg .... |
from flask_assets import Bundle
common_css = Bundle(
'css/vendor/bootstrap.min.css',
'css/vendor/helper.css',
'css/main.css',
filters='cssmin',
output='public/css/common.css'
)
common_js = Bundle(
'js/vendor/jquery.min.js',
'js/vendor/bootstrap.min.js',
Bundle(
'js/main.js',
... |
from checkov.common.models.enums import CheckCategories, CheckResult
from checkov.kubernetes.checks.resource.base_spec_check import BaseK8Check
from checkov.common.util.type_forcers import force_list
class NginxIngressCVE202125742Alias(BaseK8Check):
def __init__(self):
name = "Prevent NGINX Ingress annot... |
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
import os
import json
import boto3
from boto3.dynamodb.conditions import Key
import urllib.parse
import utils
from botocore.exceptions import ClientError
import logger
import metrics_manager
import auth_manager
import... |
"""
Copyright 2020 The OneFlow 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 applicable law or agr... |
#!/usr/bin/env python3
# MIT License
#
# Copyright (c) 2021 Eugenio Parodi <ceccopierangiolieugenio AT googlemail DOT 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 restricti... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 5/15/20 4:49 PM
# @File : grover.py
# qubit number=4
# total number=19
import cirq
import cirq.google as cg
from typing import Optional
import sys
from math import log2
import numpy as np
#thatsNoCode
def make_circuit(n: int, input_qubit):
c = cirq.Ci... |
"""
This file contains some utilities from Neurowatch for visualizing local files of neurons and meshes in FlyBrainLab.
"""
import json
import pandas as pd
def loadJSON(client, file_name, uname=None, mesh_class = 'Neuropil'):
"""Loads a mesh stored in the .json format.
# Arguments
client (FlyBrainLab ... |
import redis
host = "188.131.139.100"
port = 6379
redis_conn = redis.Redis(host=host, port=port, db=0)
redis_pool = redis.ConnectionPool(host=host, port=port, db=0)
redis_conn = redis.Redis(connection_pool=redis_pool)
redis_conn.set(name="student_key", value="student1", ex=100)
value = redis_conn.get(name="student_... |
import httplib, urllib, base64
import sys
pName = sys.argv[1]
personGroup = sys.argv[2]
KEY = sys.argv[3]
headers = {
# Request headers
'Content-Type': 'application/json',
'Ocp-Apim-Subscription-Key': KEY,
}
params = urllib.urlencode({
})
try:
conn = httplib.HTTPSConnection('westus.api.cognitive.mic... |
import logging
import pytest
import yaml
from xmltotabular.sqlite_db import SqliteDB
@pytest.fixture
def empty_db():
return SqliteDB(":memory:")
@pytest.fixture
def simple_config():
config = """
album:
<entity>: album
<fields>:
name: name
artist: artist
released: re... |
import json
import util
def get_temperature():
fields = {}
fields['cputemp'] = util.check_CPU_temp()
fields['gputemp'] = util.check_GPU_temp()
return fields
def get_cpu():
fields = {}
cpused = util.check_CPU_used()
core = 1
for utilization in cpused:
fields['cpu ' + str(core)] ... |
# noinspection PyUnusedLocal
# friend_name = unicode string
def hello(friend_name):
# return "Hello, World!"
return "Hello, {name}!".format(name=friend_name) |
from pxgrid import PxgridControl
from config import Config
import urllib.request
import base64
import time
def query(config, secret, url, payload):
print('query url=' + url)
print(' request=' + payload)
handler = urllib.request.HTTPSHandler(context=config.get_ssl_context())
opener = urllib.request.bu... |
#
# 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... |
# coding=utf-8
# --------------------------------------------------------------------------
# Generated file, DO NOT EDIT
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from msrest.serialization import M... |
"""
Defines functions that are involved in getting some data from the user.
Used for the command line interface variant of RNPFind.
"""
import sys
from hgfind import WrongGeneName, hgfind
from .config import GENOME_VERSION
from .gene_coordinates import Chromosome
def parse_genome_coord(transcript: str) -> dict:
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Benjamin Vial
# License: MIT
import pytest
from gyptis.utils.parallel import *
def f(x, y, a=1, b="b"):
print(f"f called with {x} {y} {a} {b}")
y = x ** 2
print(f"output y = {x}^2 = {y}")
return y
@parloop(n_jobs=4)
def fpar(x, *args, **kwar... |
#!/usr/bin/env python
from string import Template
from os.path import dirname, abspath, join
from codecs import open
import markdown
root = abspath(dirname(__file__))
template_dir = join(root, '..', 'templates')
target_dir = join(root, '..', 'docs')
if __name__ == '__main__':
with open(join(template_dir, 'base.ht... |
'''
Function:
24点小游戏
Author:
Charles
微信公众号:
Charles的皮卡丘
'''
import os
import pygame
from ...utils import QuitGame
from fractions import Fraction
from ..base import PygameBaseGame
from .modules import Card, Button, game24Generator
'''配置类'''
class Config():
# 根目录
rootdir = os.path.split(os.path.absp... |
# # ! DO NOT MANUALLY INVOKE THIS setup.py, USE CATKIN INSTEAD
from distutils.core import setup
from catkin_pkg.python_setup import generate_distutils_setup
# fetch values from package.xml
setup_args = generate_distutils_setup(
packages=['tuw_rqt_ordermanager'],
package_dir={'': 'src'},
requires=['nav_msg... |
from setuptools import find_namespace_packages, setup
setup(
name="rikai-torchhub",
version="0.1.0",
license="Apache License, Version 2.0",
author="Rikai authors",
author_email="rikai-dev@eto.ai",
url="https://github.com/eto-ai/rikai",
python_requires=">=3.7",
install_requires=["rikai>=... |
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 21 00:11:24 2019
@author: Zhou
"""
import os
import re
import pickle
import numpy as np
import pandas as pd
import itertools
import config
def convert_to_orig(s):
"""
Convert string from database to corresponding original text
"""
return s.replace(' ', ... |
"""
urlresolver XBMC Addon
Copyright (C) 2011 t0mm0
Updated by alifrezser (c) 2016
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 3 of the License, or
(at ... |
#!/usr/bin/env python
"""
Using Arista's pyeapi, create a script that allows you to add a VLAN (both the
VLAN ID and the VLAN name). Your script should first check that the VLAN ID is
available and only add the VLAN if it doesn't already exist. Use VLAN IDs
between 100 and 999. You should be able to call the script ... |
# coding=utf-8
# Copyright 2022 The Google Research 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 applicab... |
"""This file can take all files in a directory.
Input list of filenames.
Output is a txt file of all possible combinations of unordered pairs of file input
in the form of a unix command line to analyze with samtools mpileup
and output an Fst file in .gz."""
import sys
import itertools
import os
import datetime
def s... |
# This action will put CORS Configuration information for a Cloud Object Storage bucket.
# If the Cloud Object Storage service is not bound to this action or to the package
# containing this action, then you must provide the service information as argument
# input to this function.
# Cloud Functions actions accept a si... |
# -*- coding: utf-8 -*-
"""
sphinx.environment
~~~~~~~~~~~~~~~~~~
Global creation environment.
:copyright: Copyright 2007-2016 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import re
import os
import sys
import time
import types
import codecs
import fnmatch
from os ... |
# --------------------------------------------------------
# Faster R-CNN
# Copyright (c) 2015 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Ross Girshick and Sean Bell
# --------------------------------------------------------
import caffe
import yaml
import numpy as np
import nump... |
# BOJ 16236 (아기상어)
import heapq
import sys
from collections import deque
sys.stdin = open('../input.txt', 'r')
si = sys.stdin.readline
dy = [-1, 1, 0, 0]
dx = [0, 0, -1, 1]
def bfs(y, x, size):
que = deque()
q = []
visited = [[False for _ in range(n)] for _ in range(n)]
visited[y][x] = True
que.... |
# Copyright 2008-2018 pydicom authors. See LICENSE file for details.
"""Benchmarks for the encaps module."""
from pydicom import dcmread
from pydicom.data import get_testdata_files
from pydicom.encaps import (
fragment_frame,
itemise_frame,
encapsulate,
decode_data_sequence
)
JP2K_10FRAME = get_testd... |
import os
import re
import pytest
from cookiecutter.exceptions import FailedHookException
import sh
import yaml
from binaryornot.check import is_binary
PATTERN = r"{{(\s?cookiecutter)[.](.*?)}}"
RE_OBJ = re.compile(PATTERN)
@pytest.fixture
def context():
return {
"project_name": "My Test Project",
... |
import requests
import pdb
from awsauth import S3Auth
import logging
import os
from logging.handlers import RotatingFileHandler
class FooBar(RotatingFileHandler) :
def __init__(self, filename, mode='a', maxBytes=0,backupCount=0, encoding=None, delay=0) :
RotatingFileHandler.__init__(self, filename, mode... |
# Copyright lowRISC contributors.
# Licensed under the Apache License, Version 2.0, see LICENSE for details.
# SPDX-License-Identifier: Apache-2.0
import logging as log
import threading
from signal import SIGINT, signal
from Launcher import LauncherError
from StatusPrinter import get_status_printer
from Timer import ... |
# -*- coding: utf-8 -*-
"""pytest configuration
Extends output capture as needed by pybind11: ignore constructors, optional unordered lines.
Adds docstring and exceptions message sanitizers: ignore Python 2 vs 3 differences.
"""
import contextlib
import difflib
import gc
import re
import textwrap
import pytest
# Ea... |
import unittest
import sys
sys.path.append('../src')
from MathAlgorithm import *
class MathAlgorithmTest(unittest.TestCase):
"""
eratosthenes(end: int)
[2, end) の区間内の素数をリストに詰める
2以下の入力に対し空リストを返す
"""
def test_eratosthenes(self):
self.assertEqual([], eratosthenes(-1))
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import numpy as np
from tools import mkdir
# 1. Create a random Complex matrix H.
# 2. Make it positive, and normalize to unity.
class Generate_separable_state(object):
def __init__(self, name='sep_train_set', size=10000, sub_dim=2, space_number=2, mix_number=10):
... |
#
# Copyright 2013 Apache Software Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agree... |
import _plotly_utils.basevalidators
class RangemodeValidator(_plotly_utils.basevalidators.EnumeratedValidator):
def __init__(self, plotly_name="rangemode", parent_name="layout.yaxis", **kwargs):
super(RangemodeValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_n... |
import datetime
import json
from collections import namedtuple
from decimal import Decimal
from django.conf import settings
from django.contrib import messages
from django.core.exceptions import ValidationError
from django.core.paginator import Paginator
from django.core.validators import validate_email
from django.db... |
import youtokentome as yttm
import webdataset as wds
from pathlib import Path
import argparse
import shutil
import html
import os
parser = argparse.ArgumentParser("""Generate a custom tokenizer for your WebDataset files.""")
parser.add_argument(
"--source",
type=str,
default="./shards",
help="Specif... |
from sympy import (symbols, Symbol, nan, oo, zoo, I, sinh, sin, pi, atan,
acos, Rational, sqrt, asin, acot, coth, E, S, tan, tanh, cos,
cosh, atan2, exp, log, asinh, acoth, atanh, O, cancel, Matrix, re, im,
Float, Pow, gcd, sec, csc, cot, diff, simplify, Heaviside, arg,
conjugate, series... |
import unittest
from openVulnQuery import advisory
from openVulnQuery import constants
NA = constants.NA_INDICATOR
IPS_SIG = constants.IPS_SIGNATURE_LABEL
mock_advisory_title = "Mock Advisory Title"
adv_cfg = {
'advisory_id': "Cisco-SA-20111107-CVE-2011-0941",
'sir': "Medium",
'first_published': "2011-11-0... |
"""Support for the Netatmo Weather Service."""
import logging
import threading
from datetime import timedelta
from time import time
import pyatmo
import requests
import urllib3
import voluptuous as vol
import homeassistant.helpers.config_validation as cv
from homeassistant.components.sensor import PLATFORM_SCHEMA
fro... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from ... import _utilities, _tables
from... |
from cupyx.scipy.linalg.special_matrices import * # NOQA
from cupyx.scipy.linalg.solve_triangular import solve_triangular # NOQA
from cupyx.scipy.linalg.decomp_lu import lu_factor, lu_solve # NOQA |
from __future__ import annotations
from collections.abc import Sequence
from . import grammars
from .exceptions import FailedSemantics
from .semantics import ModelBuilderSemantics
from .util import eval_escapes, re, warning, flatten
class EBNFGrammarSemantics(ModelBuilderSemantics):
def __init__(self, grammar_n... |
from setuptools import setup, Extension
GraphLib_c_ext = Extension('_GraphLib_c',
sources = ['GraphLib_c.i'],
swig_opts = ['-c++'],
extra_compile_args = ['-std=c++11', '-O2']
)
setup(name='GraphLib_c',
ext_modules=[GraphLib_c_ext]) |
# Copyright 2019 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 or agreed to in writing, ... |
from django.core.management.base import BaseCommand, CommandError
from django.conf import settings
from django.core.mail import EmailMessage
from django.db.models import Q
from django.core.exceptions import ObjectDoesNotExist
from pettycash.models import PettycashBalanceCache, PettycashTransaction
from members.models... |
# Copyright 2017 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
import base64
import itertools
import json
impo... |
numerator = input("Enter the numerator: ")
denominator = input("Enter the denominator: ")
try:
# try = try then catch the error, if something fail during execution of the code indented with try, it executes the code indented with except.
numerator = int(numerator)
denominator = int(denominator)
except:
... |
import sys
from codecs import open
from os import path
from setuptools import setup, find_packages
install_requires = [
'grpcio',
'grpcio-tools',
'googleapis-common-protos'
]
exclude_packages = ['tests']
MAJOR = sys.version_info[0]
MINOR = sys.version_info[1]
# only include the async grpc client for pyth... |
################################################################################
"""
Modification of http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440554
"""
#################################### IMPORTS ###################################
import os
import platform
import subprocess
import errno
import tim... |
# coding: utf-8
# -----------------------------------------------------------------------------------
# <copyright company="Aspose">
# Copyright (c) 2018 Aspose.Slides for Cloud
# </copyright>
# <summary>
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associa... |
# Tai Sakuma <tai.sakuma@gmail.com>
import sys
import pytest
import unittest.mock as mock
from atpbar.presentation.base import Presentation
##__________________________________________________________________||
class MockProgressBar(Presentation):
def _present(self):
pass
##_____________________________... |
# pylint: disable=too-many-lines
# 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) AutoRe... |
# 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 ... |
"""
WORK IN PROGRESS
"""
# Imports
from data.db_interface.read import ReadFromDatabase
from data.db_interface.write import WriteToDatabase
# Syncs the new followers with the DB follower list
class FollowersHelper:
def __init__(self, screen_name, new_followers):
self.new_followers = new_followers
... |
from .cyclesr_trainer import CyclesrTrainer |
import json
from enum import Enum
class ErrorTypes(Enum):
'''
Defines errors that can occur when making calls to the Sleuth API. This makes
it easier for the front-end to handle errors appropriately.
'''
# Occurs when an unexpected error occurs duing the handling of a request
UNEXPECTED_SERVER_... |
import pickle
import openpyxl
wb_obj = openpyxl.load_workbook("layer1.xlsx")
sheet_obj = wb_obj.active
layer = 1
degree = {}
ec = {}
close = {}
harm_close = {}
bet = {}
pg = {}
for i in range(2, sheet_obj.max_row+1):
degree[sheet_obj.cell(i, 1).value] = sheet_obj.cell(i, 2).value
close[sheet_obj.cell(i, 1).... |
# Copyright 2015 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/env python
# Copyright 2016 Google 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 required... |
# Copyright 2017 Google 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 required by applicable law or a... |
# Copyright (c) 2020 vesoft inc. All rights reserved.
#
# This source code is licensed under Apache 2.0 License.
from pytest_bdd import scenarios
scenarios('features', 'openCypher/features') |
from __future__ import absolute_import
# Need to import path to test/fixtures and test/scripts/
# Ex : export PYTHONPATH='$PATH:/root/test/fixtures/:/root/test/scripts/'
#
# To run tests, you can do 'python -m testtools.run mx_tests'. To run specific tests,
# You can do 'python -m testtools.run -l mx_test'
# Set the en... |
#!/usr/bin/env python
# Copyright 2017 Google, 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... |
from ujson import decode as json_decode, encode as json_encode
from twisted.web.resource import Resource
from twisted.web.server import NOT_DONE_YET
from twisted.internet import defer
from twisted.python import log
from twisted.python.failure import Failure
from sitebase.backend.postgres import dbBackend
from sitebase... |
import importlib
import pytest
from helpers import running_on_ci
import janitor.chemistry # noqa: disable=unused-import
# Skip all tests if rdkit not installed
pytestmark = pytest.mark.skipif(
(importlib.util.find_spec("rdkit") is None) & ~running_on_ci(),
reason="rdkit tests only required for CI",
)
@pyt... |
###############################################################################
# Code from
# https://github.com/pytorch/vision/blob/master/torchvision/datasets/folder.py
# Modified the original code so that it also loads images from the current
# directory as well as the subdirectories
################################... |
from django.contrib import admin
from .models import Choice, Question
class ChoiceInline(admin.TabularInline):
model = Choice
extra = 3
class QuestionAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['question_text']}),
('Date information', {'fields': [
'p... |
# Time: O(n)
# Space: O(h), h is height of binary tree
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
# @param root, a tree node
# @return an integer
def maxDepth(self, root):
if root is None:
... |
"""Client library for RTSPtoWebserver."""
from __future__ import annotations
import base64
import enum
import hashlib
import logging
from typing import Any, Dict, List, Mapping, Optional, cast
from urllib.parse import urljoin
import aiohttp
from .diagnostics import WEB_DIAGNOSTICS as DIAGNOSTICS
from .exceptions im... |
#!/usr/bin/python
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import json
import logging
import os
from flask_restful.reqparse import RequestParser
from flask_restful_swagger_2 import swagger, Resource
import common.request_processor as request_processor
from doten... |
import math
from time import perf_counter
def is_prime(num):
if num == 2:
return True
if num <= 1 or not num % 2:
return False
for div in range(3,int(math.sqrt(num)+1),2):
if not num % div:
return False
return True
def benchtest():
... |
# pylint: disable=redefined-outer-name, unused-argument
import json
import warnings
from collections import namedtuple
from contextlib import contextmanager
import boto3
import pytest
from dagster import ExperimentalWarning
from dagster.core.test_utils import in_process_test_workspace, instance_for_test
from dagster.... |
# -*- coding:utf-8 -*-
# Author: RubanSeven
import math
import numpy as np
class WarpMLS:
def __init__(self, src, src_pts, dst_pts, dst_w, dst_h, trans_ratio=1.):
self.src = src
self.src_pts = src_pts
self.dst_pts = dst_pts
self.pt_count = len(self.dst_pts)
self.dst_w = ds... |
from django.db import models
from django.contrib.auth.models import User
# Enforce unique email addresses
User._meta.get_field('email')._unique = True |
from coro.asn1.python import encode, decode
import coro
import struct
# four bytes from os.urandom().
MAGIC = '%\xf1\xbfB'
class Logger:
magic = MAGIC
def __init__ (self, file):
self.encode = encode
self.file = file
def log (self, *data):
data = self.encode ((coro.now_usec, data... |
import unittest, time, sys, random, math
sys.path.extend(['.','..','../..','py'])
import h2o, h2o_cmd, h2o_kmeans, h2o_browse as h2b, h2o_util, h2o_import as h2i
# a truly uniform sphere
# http://stackoverflow.com/questions/5408276/python-uniform-spherical-distribution
# he offers the exact solution: http://stackoverf... |
#
# 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... |
# Copyright 2019 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... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.