text stringlengths 1 927k |
|---|
#!/usr/bin/env python3
#
# This file is part of Magnum.
#
# Copyright © 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019,
# 2020, 2021 Vladimír Vondruš <mosra@centrum.cz>
# Copyright © 2021 Pablo Escobar <mail@rvrs.in>
#
# Permission is hereby granted, free of charge, to any person obta... |
# input() reads a string with a line of input, stripping the ' ' (newline) at the end.
# This is all you need for most problems.
import os
os.system('cls')
file = open('shuffled_anagrams_sample_ts1_input.txt', 'r')
#overwrite input to mimic google input
def input():
line = file.readline()
return line
import ... |
# Copyright 2015 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 © 2021 Province of British Columbia
#
# 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... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import os
import mock
import pytest
from .validate_spec_url_test import make_mock_responses
from .validate_spec_url_test import read_contents
fr... |
# This script creates the competition intensity values for the weighted total trade networks
# Importing required modules
import numpy as np
import pandas as pd
# Reading in the data
main_data = pd.read_csv('C:/Users/User/Documents/Data/Pollution/pollution_data.csv')
# Creating a list of all nations
nations = sor... |
#!/usr/bin/env python
# coding=utf-8
import json
from threading import Lock
import warnings
from sacred.commandline_options import cli_option
from sacred.observers.base import RunObserver
from sacred.serializer import flatten
DEFAULT_SQL_PRIORITY = 40
# ############################# Observer ######################... |
import numpy as np
import random
import math
from PIL import Image
import cv2
cv2.setNumThreads(0)
cv2.ocl.setUseOpenCL(False)
import torch
from torchvision.transforms import ColorJitter
import torch.nn.functional as F
class FlowAugmentor:
def __init__(self, crop_size, min_scale=-0.2, max_scale=0.5, do_flip=Tru... |
"""main_info.py
This file contains private functions for scraping the review pages
This file requires no packages.
This file contains the following functions:
* _get_critic_reviews_from_page - scrapes info per critic page
* _get_num_pages - finds number of pages to scrape
* get_critic_reviews - scrapes ... |
import logging
import os
import subprocess
import sys
import tempfile
import time
import yaml
from datetime import datetime
from teuthology import setup_log_file, install_except_hook
from . import beanstalk
from . import report
from . import safepath
from .config import config as teuth_config
from .config import set_... |
#!/usr/bin/python3
""" Implementation of the interactive DriveInspector using the DriveFile
class implemented in drivefile.py
Started 2018-05-12 by Marc Donner
Copyright (C) 2018 Marc Donner
"""
import sys
from drivefilecached import DriveFileCached
from drivefilecached import canonicalize_path
from drivefile... |
import os
import cv2
import numpy as np
import multiprocessing
class SiftExtractor:
def __init__(self, feature_data, collection_data):
""" Creates a SiftExtractor.
:param feature_data: Feature data set.
:param collection_data: Collection data set.
"""
self.__feature_dat... |
'''
calc_vg_sim_fragment_length_stats.py
Calculates fragment length mean and standard deviation
from vg sim path position output.
'''
import sys
import gzip
import numpy
from utils import *
printScriptHeader()
if len(sys.argv) != 3:
print("Usage: python calc_vg_sim_fragment_length_stats.py <input_name> <read_len... |
"""
CEASIOMpy: Conceptual Aircraft Design Software
Developed for CFS ENGINEERING, 1015 Lausanne, Switzerland
The script evaluate the wings geometry from cpacs file for an
unconventional aircraft with fuselage.
Python version: >=3.6
| Author : Stefano Piccini
| Date of creation: 2018-09-27
| Last modifiction: 2020-0... |
"""Support for Ebusd sensors."""
import logging
import datetime
from homeassistant.helpers.entity import Entity
from .const import DOMAIN
TIME_FRAME1_BEGIN = 'time_frame1_begin'
TIME_FRAME1_END = 'time_frame1_end'
TIME_FRAME2_BEGIN = 'time_frame2_begin'
TIME_FRAME2_END = 'time_frame2_end'
TIME_FRAME3_BEGIN = 'time_f... |
'''
This Module is One to Make Your Code Shorter.
High API Will Make You Feel You're Ordering And Machine Is Doing!
Also There is Collection of most usefull function and methods from popular modules of python.
(Read Help of Functions)
Official Documention Will Be Added Soon.
'''
'''
Written By RX
Last Update: 1-15-2021... |
import socket
import time
# import logging
import tornado.ioloop
import tornado.iostream
from tornado import gen
from . import constants
from . import exceptions
class Host(object):
def __init__(self, host, conn, debug=0):
self.debug = debug
self.host = host
self.port = 11211
self... |
# model settings
evidence_loss = dict(type='EvidenceLoss',
num_classes=101,
evidence='exp',
loss_type='log',
with_kldiv=False,
with_avuloss=True,
annealing_method='exp')
model = dict(
... |
"""
ScrapeService API Tests
"""
# pylint: disable=protected-access,missing-class-docstring,unidiomatic-typecheck
# stdlib
import unittest
# library
import pytest
# module
from avwx import exceptions, service
# tests
from .test_base import BaseTestService
class TestStationScrape(BaseTestService):
service_cla... |
from django.contrib import admin
from .models import Post
from .models import PostComment
# Register your models here.
admin.site.register(Post)
admin.site.register(PostComment) |
import taichi as ti
class Atom:
def __init__(self, radius, dim=3):
self.radius = radius
self.dim = dim
self.color = ti.Vector.field(dim, ti.f32, shape=1)
self.pos = ti.Vector.field(dim, ti.f32, shape=1)
def display(self, scene):
scene.particles(self.pos, self.radius, p... |
import hashlib
import json
import os
import shutil
import tempfile
import textwrap
import time
from six.moves import shlex_quote, urllib
from mlflow.entities import RunStatus
from mlflow.projects import _fetch_project
from mlflow.projects.submitted_run import SubmittedRun
from mlflow.utils import rest_utils, file_uti... |
# Copyright 2021 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 required by applicable law or a... |
from map import map_canvas
from maps_utils import Node, resolution, map_size, border_size, Obstacles
from maps_utils import cost
def compareNodes(node_1, node_2):
"""
Compares two nodes to check if they are equal
:param node_1: The first node to check
:type node_1: Node type
:par... |
"""
Python Interchangeable Virtual Instrument Library
Copyright (c) 2012-2014 Alex Forencich
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... |
import signal
import unittest
import time
from . import website as w
class EulerProblem(unittest.TestCase):
problem_id = None
def solver(self, input_val):
raise NotImplementedError()
simple_input = None
simple_output = None
real_input = None
def solve_real(self):
"""
... |
# 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 ... |
import numpy as np
def compute_cost_with_regularization_test_case():
np.random.seed(1)
Y_assess = np.array([[1, 1, 0, 1, 0]])
W1 = np.random.randn(2, 3)
b1 = np.random.randn(2, 1)
W2 = np.random.randn(3, 2)
b2 = np.random.randn(3, 1)
W3 = np.random.randn(1, 3)
b3 = np.random.randn(1, 1... |
import collections
from supriya import CalculationRate
from supriya.synthdefs import UGen
class MulAdd(UGen):
"""
An Optimized multiplication / addition ugen.
::
>>> source = supriya.ugens.SinOsc.ar()
>>> mul_add = supriya.ugens.MulAdd.new(
... addend=0.5,
... mu... |
from django.test import TestCase
import datetime as dt
# Create your tests here.
from .models import Photos, categories, Location
class LocationTestClass(TestCase):
def setUp(self):
self.location = Location(name = 'Nairobi')
def test_instance(self):
self.assertTrue(isinstance(self.location, Lo... |
# Copyright (c) 2012 OpenStack 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 ... |
import os
from shutil import rmtree
from tempfile import mkdtemp
import filecmp
import tools.pdf2txt as pdf2txt
from helpers import absolute_sample_path
from tempfilepath import TemporaryFilePath
def run(sample_path, options=None):
absolute_path = absolute_sample_path(sample_path)
with TemporaryFilePath() as... |
from binascii import hexlify, unhexlify
import logging
import threading
from electrumsv.util import bfh, bh2u
from electrumsv.bitcoin import (xpub_from_pubkey, TYPE_ADDRESS, TYPE_SCRIPT)
from electrumsv.i18n import _
from electrumsv.transaction import deserialize
from electrumsv.keystore import Hardware_KeyStore, is_x... |
# -*- coding: utf-8 -*-
# *****************************************************************************
# NICOS, the Networked Instrument Control System of the MLZ
# Copyright (c) 2009-2021 by the NICOS contributors (see AUTHORS)
#
# This program is free software; you can redistribute it and/or modify it under
# the t... |
class FabricLocation(Enum,IComparable,IFormattable,IConvertible):
"""
Fabric location in the host
enum FabricLocation,values: BottomOrInternal (1),TopOrExternal (0)
"""
def __eq__(self,*args):
""" x.__eq__(y) <==> x==yx.__eq__(y) <==> x==yx.__eq__(y) <==> x==y """
pass
def __format__(self,*args):
""" __... |
# -*- coding: utf-8 -*-
# @Time : 2021/8/10 17:00
# @Author : zc
# @Desc : 使用用户永久授权码获取token返回值实体
from chanjet_openapi_python_sdk.chanjet_response import ChanjetResponse
class GetTokenByPermanentCodeResponse(ChanjetResponse):
def __init__(self, data=None):
# 错误码,200为成功,其余均为失败
self.code = ''... |
import unittest
from botlang import BotlangSystem, BotlangErrorException
class StackTraceTestCase(unittest.TestCase):
def test_stack_trace(self):
code = """
(begin
(define f
(fun (n)
(fun (x) (n x))
)
... |
import erdos
class WaypointsMessage(erdos.Message):
"""Message class to be used to send waypoints.
Optionally can also send a target speed for each waypoint.
Args:
timestamp (:py:class:`erdos.timestamp.Timestamp`): The timestamp of
the message.
waypoints (:py:class:`~pylot.pl... |
# Licensed to Elasticsearch under one or more contributor
# license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright
# ownership. Elasticsearch licenses this file to you under
# the Apache License, Version 2.0 (the "License"); you may
# not use this file except... |
# Copyright (C) 2020 GreenWaves Technologies, SAS
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
# This progr... |
from os.path import dirname, basename, isfile, join, abspath
import glob
import sys
sys.path.append(abspath(join(dirname(__file__), "../python_src/")))
modules = glob.glob(join(dirname(__file__), "*.py"))
__all__ = [ basename(f)[:-3] for f in modules if isfile(f) and not f.endswith('__init__.py')]
from . import * |
from src.Car import Car
from src.CarImpl import CarImpl
from unittest.mock import *
from unittest import TestCase, main
class test_Car(TestCase):
def test_needsfuel_true(self):
car = Car()
car.needsFuel = Mock(name='needsFuel')
car.needsFuel.return_value = True
carImpl = CarImpl(ca... |
# Copyright 2017 Neural Networks and Deep Learning lab, MIPT
#
# 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... |
import pytest
import numpy as np
import numpy.testing as npt
from simupy.systems import (SwitchedSystem, need_state_equation_function_msg,
need_output_equation_function_msg,
zero_dim_output_msg, full_state_output)
max_n_condition = 4
bounds_min = -1
bounds_max = ... |
r"""Initiate an acquisition and fetch a waveform for each specified channel.
The gRPC API is built from the C API. NI-SCOPE documentation is installed with the driver at:
C:\Program Files (x86)\IVI Foundation\IVI\Drivers\niScope\Documentation\English\Digitizers.chm
A version of this .chm is available online at:
h... |
"""
Django settings for base demoapp.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
from os.path import abspath, dirname, join
from django.conf import global_set... |
"""
.. module:: trend
:synopsis: Trend Indicators.
.. moduleauthor:: Dario Lopez Padial (Bukosabino)
"""
import numpy as np
import pandas as pd
from ta.utils import IndicatorMixin, ema, get_min_max, sma
class AroonIndicator(IndicatorMixin):
"""Aroon Indicator
Identify when trends are likely to change d... |
from sqlalchemy import MetaData, Table, Column, Boolean
meta = MetaData()
def upgrade(migrate_engine):
meta = MetaData(bind=migrate_engine)
batch = Table("batch", meta, autoload=True)
deleted = Column("deleted", Boolean())
deleted.create(batch)
def downgrade(migrate_engine):
meta = MetaData(bi... |
from torch.nn import Module
class AbstractSearch(Module):
"""
AbstractSearch is search algorithm on original neural model to perform special inference.
"""
def __init__(self):
super().__init__()
self._mode = 'infer'
def build(self, *args, **kwargs):
"""
Build sear... |
from decimal import Decimal
from typing import Optional, Union
from ..asset import Asset
from ..exceptions import ValueError, TypeError
from ..keypair import Keypair
from ..muxed_account import MuxedAccount
from ..price import Price
from ..strkey import StrKey
_LOWER_LIMIT = "0"
_UPPER_LIMIT = "922337203685.4775807"
... |
# --------------------------------------------------------
# Face Datasets
# Licensed under The MIT License [see LICENSE for details]
# Copyright 2019 smarsu. All Rights Reserved.
# --------------------------------------------------------
import os.path as osp
import numpy as np
class Dataset(object):
"""The bas... |
import random
def random_nums():
random_float = random.random()
random_int = random.randint(1, 100)
random_elem = random.choice(['heads', 'tails']) |
"""Learning embedding of graph using Poincare Ball Model."""
import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
import geomstats.backend as gs
import geomstats.visualization as visualization
from geomstats.datasets.prepare_graph_data import HyperbolicEmbedding
from geomstats.datasets.utils import l... |
__author__ = 'Mandar Patil (mandarons@pm.me)'
import os
import unittest
from src import config_parser, constants
class TestConfigParser(unittest.TestCase):
def setUp(self) -> None:
pass
def tearDown(self) -> None:
pass
def test_read_config_valids(self):
# Default config path
... |
# © 2020 Nokia
#
# Licensed under the BSD 3 Clause license
#
# SPDX-License-Identifier: BSD-3-Clause
# ============================================
import functools
import sys
import numpy as np
from codesearch.utils import Saveable
from codesearch.data_config import DESCRIPTION_FIELD, CODE_FIELD
class Retrie... |
# Use slow pointer, fast pointer approach
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def middleNode(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
... |
import os
import json
import unittest
import pytest
from app import create_app
from app.api.v2.models.user_models import UserRegistration
from app.api.v2.views.user_views import myuser
from app.api.v2.utils.validators import validate_users
from app.api.v2.models.database_test import QuestionerTestDatabase
connector ... |
# 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 ... |
import numpy as np
import random
import pickle
num_train = 60000
num_val = 10000
num_test = 10000
step_num = 4
elem_num = 26 + 10 + 1
x_train = np.zeros([num_train, step_num * 2 + 3, elem_num], dtype=np.float32)
x_val = np.zeros([num_val, step_num * 2 + 3, elem_num], dtype=np.float32)
x_test = np.zeros([num_test, st... |
from __future__ import print_function
import config
from config import *
from utils import *
# INPUT:
# VGG16 - block5_pool (MaxPooling2D) (None, 7, 7, 512)
# OUTPUT:
# Branch1 - Class Prediction
# Branch2 - IOU Prediction
# NOTE: Both models in create_model_train() and create_model_p... |
from abc import ABC
class Simulator(ABC):
def __init__(self):
self.stats = {}
self.stats['dataInFlight'] = []
self.stats['dataInQueue'] = []
self.stats['packetsInFlight'] = []
self.stats['packetsInQueue'] = []
self.stats['queueSize'] = []
self.stats['packet... |
# Package placeholder
import threading
import functools
import collections
CacheInfo = collections.namedtuple(
'CacheInfo', 'type hits misses maxsize currsize')
def make_key(obj, typed=True):
args, kwargs = obj
key = (tuple(args), tuple(sorted(kwargs.items())))
if typed:
key += tuple(type(v... |
# Copyright 2020 Uber Technologies, 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 applica... |
from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
class ProxyGenericForeignKey(GenericForeignKey):
def __init__(self, *args, **kwargs):
kwargs['for_concrete_model'] = False
super(ProxyGenericForeignKey, self).__init__(*args, **kwargs)
class ProxyGenericRelation(Ge... |
from tests.base_test_case import FlightBaseTestCase
class TestFlight(FlightBaseTestCase):
def test_create_flight(self):
login_uri = "/fbs-api/users/login/"
params_user = {
"email": "test@testadminuser.com",
"password": "Testadminuser12344#",
}
self.set_autho... |
# Copyright 2019 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
# ___INFO__MARK_BEGIN__
#######################################################################################
# Copyright 2008-2021 Univa Corporation (acquired and owned by Altair Engineering Inc.)
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file exce... |
from abc import ABC, abstractmethod
import copy
import numpy as np
from typing import Dict
DEFAULT_META = {
"name": None,
"detector_type": None, # online or offline
"data_type": None # tabular, image or time-series
} # type: Dict
def outlier_prediction_dict():
data = {
'instance_score': No... |
import sys
input_file = open(sys.argv[1])
def parse_line( input_file ):
line = input_file.readline()
if len(line) > 0:
if line[0] == '(':
output = line.replace("\n","").replace(" ","")
while output.find(')') == -1:
line = input_file.readline()
o... |
import io
from setuptools import setup
from setuptools_rust import Binding, RustExtension
long_description = "See https://github.com/OvalMoney/celery-exporter"
with io.open("README.md", encoding="utf-8") as fp:
long_description = fp.read()
with open("README.md", "r") as fh:
long_description = fh.read()
setu... |
from crossref_commons.retrieval import get_entity
from crossref_commons.types import EntityType, OutputType
class PullData: #transform this function as a class
def __init__(self, doi):
self.doi = doi
def getInitials(self, str): #Put getInitials brfore as a alone function instead of part of pullData
allNames = s... |
# 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... |
'''
Excited States software: qFit 3.0
Contributors: Saulo H. P. de Oliveira, Gydo van Zundert, and Henry van den Bedem.
Contact: vdbedem@stanford.edu
Copyright (C) 2009-2019 Stanford University
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation f... |
import os
import time
import threading
import logging
import json
from selfdrive.swaglog import cloudlog
import selfdrive.loggerd.uploader as uploader
from common.timeout import Timeout
from selfdrive.loggerd.tests.loggerd_tests_common import UploaderTestCase
class TestLogHandler(logging.Handler):
def __init__(se... |
from eve import Eve
app = Eve()
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5001, debug=True) |
from pycococreator import PyCocoCreator
from pycococreatortools import PyCocoCreatorTools
from coco_dataset import CocoDataset
from coco_json_utils import CocoJsonCreator
from args import Args
import os
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="Generate")
par... |
"""
CAS authentication protocol
Contact: Steven Gregory <sgregory@iplantcollaborative.org>
"""
from datetime import timedelta
import time
from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.urlresolvers import reverse
from django.http import HttpResponse, HttpRespon... |
"""
Conan tools: classes and function in this module are intended to be used out of the box
with the Conan configuration already currified into them. This configuration refers
mainly to two items:
- requester: on network calls, this will include proxy definition.
- output: the output configuration... |
"""Module with functions which are supposed to be as fast as possible"""
from stat import S_ISDIR
__all__ = ('tree_to_stream', 'tree_entries_from_data', 'traverse_trees_recursive',
'traverse_tree_recursive')
def tree_to_stream(entries, write):
"""Write the give list of entries into ... |
import logging as log
import cfnresponse
import boto3
import hashlib
import time
log.getLogger().setLevel(log.INFO)
client = boto3.client('elbv2')
def main(event, context):
fqn = event['StackId'] + event['LogicalResourceId']
physical_id = hashlib.md5(fqn.encode('utf-8')).hexdigest()
log.info(physical_id)
t... |
import torch
import torch.nn as nn
import models
import os
import pickle
import glob
import json
import numpy as np
backend = 'fbgemm'
def split_path(path):
_, path = os.path.splitdrive(path)
folders = []
while 1:
path, folder = os.path.split(path)
if folder != "":
folders.append(folder)
elif path == "\\" ... |
# Copyright 2022, Kay Hayen, mailto:kay.hayen@gmail.com
#
# Part of "Nuitka", an optimizing Python compiler that is compatible and
# integrates with CPython, but also works on its own.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in complianc... |
from jsonrpc import ServiceProxy
access = ServiceProxy("http://127.0.0.1:4354")
pwd = raw_input("Enter wallet passphrase: ")
access.walletpassphrase(pwd, 60) |
# 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 ... |
#%matplotlib inline
import matplotlib.pyplot as plt
import netCDF4
plt.switch_backend('agg')
from map_plot import MapPlot
import numpy as np
data_folder = '/nobackup/rossby26/users/sm_fuxwa/AI/standard_data/'
fig_out_path = '/home/sm_fuxwa/Figures/AI/'
# 3km: tas, pr
# 12km: ta500, ta700, ta850, ta950,
# hus500... |
import requests
import pandas as pd
import datetime
import io
from bs4 import BeautifulSoup
def validate_datestring(date_text):
try:
datetime.datetime.strptime(date_text, '%Y-%m-%d')
except ValueError:
raise ValueError("Incorrect data format, should be YYYY-MM-DD")
def sanitize_input(start_dt... |
import datetime
import pytest
from django.utils import translation
from hours.enums import FrequencyModifier, RuleContext, RuleSubject, State, Weekday
from hours.models import Rule
from hours.tests.conftest import (
DatePeriodFactory,
RuleFactory,
TimeSpanFactory,
TimeSpanGroupFactory,
)
@pytest.mar... |
from hopeit.app.context import EventContext
__steps__ = ['test_app_call']
async def test_app_call(payload: None, context: EventContext) -> str:
raise NotImplementedError() |
import os
import sys
script="""
from cx_Freeze import setup, Executable
import sys
base = None
if sys.platform == "win32":
base = "Win32GUI"
setup(
name = "$FILENOTPY$",
version = "1.0",
description = "$FILENOTPY$",
executables = [Executable("$FILENAME$",appendScriptToExe = False,appendScriptToLibr... |
# -*- coding: utf-8 -*-
"""
TencentBlueKing is pleased to support the open source community by making 蓝鲸智云-用户管理(Bk-User) available.
Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in compliance with the Lic... |
import json,sys,os,re
# Linares Vasquez
red_apis_file=os.getenv("ANADROID_PATH")+"/resources/redAPIS.json"
sec_apis_file=os.getenv("ANADROID_PATH")+"/resources/secAPIS.json"
# only needed fot tests executed before 27/08/2020
# created to undo error that caused malformed methoddefinitions in instrumentation phase
# ... |
import collections
import caffe2.python.hypothesis_test_util as hu
import hypothesis.strategies as st
import numpy as np
from caffe2.python import core, dyndep, workspace
from hypothesis import given, settings
dyndep.InitOpsLibrary("//caffe2/caffe2/quantization/server:dnnlowp_ops")
workspace.GlobalInit(["caffe2", "-... |
# ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# ------------------------------------
from collections import namedtuple
from six.moves.urllib_parse import urlparse
from .challenge_auth_policy import ChallengeAuthPolicy, ChallengeAuthPolicyBase
from .cl... |
# -*- coding: utf-8 -*-
import time
from DriverInit import initAppiumDriver
def change2app(driver, package, activity):
driver.quit()
driver = initAppiumDriver.initAppiumWithInfo(package=package, activity=activity)
time.sleep(10)
driver.get_screenshot_as_file('./img/%s.png' % time.strftime('%Y-%m-%d_%H... |
import torch
from torch import nn
from torchsparse.nn.functional import spcrop
__all__ = ['SparseCrop']
class SparseCrop(nn.Module):
def __init__(self, loc_min, loc_max):
super().__init__()
self.loc_min = torch.cuda.IntTensor([list(loc_min)])
self.loc_max = torch.cuda.IntTensor([list(loc_... |
# Copyright 2019 DeepMind Technologies Limited. 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 ... |
from .models import *
from .views import *
from .templatetags import * |
import os
import os.path
from time import perf_counter as clock
import numpy
import random
# in order to always generate the same random sequence
random.seed(19)
def fill_arrays(start, stop):
col_i = numpy.arange(start, stop, dtype=numpy.int32)
if userandom:
col_j = numpy.random.uniform(0, nrows, sto... |
for i in range(int(input())):
b, p = list(map(float, input().split()))
t = 60 / p
tt = t * b
print("{:.4f} {:.4f} {:.4f}".format(tt - t, tt, tt + t)) |
from fractions import Fraction
from unittest import SkipTest
import errno
import numpy as np
from av import AudioFrame, VideoFrame
from av.audio.frame import format_dtypes
from av.filter import Filter, Graph
import av
from .common import Image, TestCase, fate_suite
def generate_audio_frame(
frame_num, input_fo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.