filename
stringlengths
13
19
text
stringlengths
134
1.04M
the-stack_0_2849
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 """ Unit tests for versioning.py functions. """ from datetime import datetime, timedelta from operator import itemgetter import pytest from botocore.exceptions import ClientError from botocore.stub import ANY ...
the-stack_0_2850
import unittest from io import BytesIO from eth.util.netstring import (header, encode, FileEncoder, decode_file, Decoder) class TestNetstring(unittest.TestCase): def setUp(self): self.test_data = b"Netstring module by Will McGugan" self.encoded_data = b"9:Netstring...
the-stack_0_2854
""" Get the Bots in any chat* Syntax: .get_bot""" from telethon import events from telethon.tl.types import ChannelParticipantAdmin, ChannelParticipantsBots from uniborg.util import admin_cmd @borg.on(admin_cmd(pattern="get_bot ?(.*)")) async def _(event): if event.fwd_from: return mentions = "**Bots ...
the-stack_0_2856
# SPDX-FileCopyrightText: Copyright (c) 2011 LG Electronics Inc. # # SPDX-License-Identifier: GPL-3.0-only import os from fosslight_util.set_log import init_log def main(): output_dir = "tests" logger, _result_log = init_log(os.path.join(output_dir, "test_add_log.txt")) logger.warning("TESTING - add mode...
the-stack_0_2857
# coding: utf-8 from __future__ import annotations from datetime import date, datetime # noqa: F401 import re # noqa: F401 from typing import Any, Dict, List, Optional, Union, Literal # noqa: F401 from pydantic import AnyUrl, BaseModel, EmailStr, validator, Field, Extra # noqa: F401 from aries_cloudcontroller.m...
the-stack_0_2859
#!/usr/bin/env python3 import subprocess import os import sys sys.path.append("../") sys.path.append("../../system/lib/") sys.path.append("../volume/") sys.path.append("../array/") import json_parser import pos import cli import api import json import MOUNT_ARRAY_BASIC SPARE = MOUNT_ARRAY_BASIC.SPARE ARRAYNAME = MOUNT...
the-stack_0_2861
"""Implement models for EFS resources. See AWS docs for details: https://docs.aws.amazon.com/efs/latest/ug/whatisefs.html """ import json import time from copy import deepcopy from hashlib import md5 from moto.core import ACCOUNT_ID, BaseBackend, CloudFormationModel from moto.core.utils import ( camelcase_to_und...
the-stack_0_2862
# -*- coding: utf-8 -*- """ author: zengbin93 email: zeng_bin8888@163.com create_dt: 2021/12/13 17:39 describe: 事件性能分析 """ import os import os.path import traceback import pandas as pd import matplotlib.pyplot as plt from datetime import timedelta, datetime from tqdm import tqdm from typing import Callable, List from c...
the-stack_0_2863
#!/usr/bin/env python3 # encoding: utf-8 """ pyQms ----- Python module for fast and accurate mass spectrometry data quantification :license: MIT, see LICENSE.txt for more details Authors: * Leufken, J. * Niehues, A. * Sarin, L.P. * Hippler, M. * Leidel, S....
the-stack_0_2864
#!/usr/bin/python # # Copyright 2016 Canonical Ltd # # 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...
the-stack_0_2865
from ast import literal_eval from django.shortcuts import render from django.http import HttpResponse from django.template import loader from django.conf import settings from rest_framework import authentication, permissions,\ viewsets, filters, response, status from rest_framework_extensions.cache.mixins import...
the-stack_0_2867
# nuScenes dev-kit. # Code written by Oscar Beijbom, 2018. import copy import os.path as osp import struct from abc import ABC, abstractmethod from functools import reduce from typing import Tuple, List, Dict import cv2 import numpy as np from matplotlib.axes import Axes from pyquaternion import Quaternion from nusc...
the-stack_0_2868
# Copyright 2020 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...
the-stack_0_2869
def findDecision(obj): #obj[0]: Passanger, obj[1]: Time, obj[2]: Coupon, obj[3]: Gender, obj[4]: Age, obj[5]: Children, obj[6]: Education, obj[7]: Occupation, obj[8]: Income, obj[9]: Bar, obj[10]: Coffeehouse, obj[11]: Restaurant20to50, obj[12]: Direction_same, obj[13]: Distance # {"feature": "Occupation", "instances"...
the-stack_0_2871
# -*- coding: utf-8 -*- from __future__ import unicode_literals from __future__ import division from __future__ import absolute_import from __future__ import print_function import numpy as np import pandas as pd from scipy.spatial.distance import cdist from . import AbstractCostFunction from .gap_close import Abs...
the-stack_0_2872
from germanium.impl import _filter_one_for_action def _element(germanium, selector): """ Finds a single element for doing a visual action. :param germanium: :param selector: :return: """ element = None if selector: items = germanium.S(selector).element_list(only_visible=False)...
the-stack_0_2873
#Matt Morrow spcID2412353 COURSE: COP1000 #Statement 1: create random numbers between 1 and 25 #Statement 2: sort the numbers #Statement 3: display in values #Statement 4: display values in order #Statement 5: Determine odds/evens and display import random def main(): nums = [] for value in range(10): ...
the-stack_0_2874
import glymur import os import numpy as np import tempfile class jpeg(object): @staticmethod def name(): '''No Encoding ''' return 'JPEG2000' @staticmethod def compress(data, *args, **kwargs): '''JPEG2000 compression ''' TMPFOLDER = tempfile.mkdtemp(...
the-stack_0_2875
import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import grad import math from itertools import chain from ._deeplab import ASPP # ------------------------------------------- # Multi-Knowledge Aggregation # ------------------------------------------- class Reshape(nn.Mod...
the-stack_0_2877
""" Binary Ninja plugin that imports a capa report, produced via `capa --json /path/to/sample`, into the current database. It will mark up functions with their capa matches, like: ; capa: print debug messages (host-interaction/log/debug/write-event) ; capa: delete service (host-interaction/service/delete) ...
the-stack_0_2879
# Copyright 2017: GoDaddy Inc. import collections import datetime import logging import random import threading import futurist import futurist.rejection import monotonic import requests from netmet.utils import ping from netmet.utils import pusher from netmet.utils import secure LOG = logging.getLogger(__name__) ...
the-stack_0_2881
""" This module provides means of connecting to a QCoDeS database file and initialising it. Note that connecting/initialisation take into account database version and possibly perform database upgrades. """ import io import sqlite3 import sys from contextlib import contextmanager from os.path import expanduser, normpat...
the-stack_0_2882
""" foxtail/clinics/tests/test_models.py """ import pytest from .factories import ClinicFactory pytestmark = pytest.mark.django_db def test_get_organization(): clinic = ClinicFactory() org = clinic.organization assert clinic.get_organization() == org.name
the-stack_0_2883
from itertools import chain import multiprocessing as mp try: from multiprocessing import SimpleQueue as MPQueue except ImportError: from multiprocessing.queues import SimpleQueue as MPQueue import os import threading from ddtrace import Span from ddtrace import tracer from ddtrace.internal import _rand fro...
the-stack_0_2884
import unittest class Test(unittest.TestCase): def test(self): # docs checkpoint 0 import numpy as np import openmdao.api as om from openaerostruct.geometry.utils import generate_mesh from openaerostruct.geometry.geometry_group import Geometry from openaerostruct....
the-stack_0_2886
from unit_test_common import execute_csv2_command, initialize_csv2_request, ut_id, sanity_commands from sys import argv # lno: CV - error code identifier. def main(gvar): if not gvar: gvar = {} if len(argv) > 1: initialize_csv2_request(gvar, selections=argv[1]) else: ...
the-stack_0_2887
""" Support for installing and building the "wheel" binary package format. """ from __future__ import absolute_import import compileall import csv import errno import hashlib import logging import os import os.path import re import shutil import stat import sys import tempfile import warnings from base64 import urlsa...
the-stack_0_2888
# encoding: utf-8 import datetime import logging from sqlalchemy.sql import and_, or_ from sqlalchemy import orm, types, Column, Table, ForeignKey from ckan.common import config from ckan.model import ( meta, core, license as _license, types as _types, domain_object, activity, extension, ...
the-stack_0_2889
# Owner(s): ["oncall: distributed"] import sys import torch import torch.distributed as dist from torch.distributed._sharded_tensor import ( shard_parameter, ) from torch.testing._internal.common_distributed import ( requires_nccl, skip_if_lt_x_gpu, ) from torch.testing._internal.common_utils import ( ...
the-stack_0_2890
#!/usr/bin/env python3 # PYTHON_ARGCOMPLETE_OK # Copyright 2013 Alexey Kardapoltsev # # 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 ...
the-stack_0_2891
import asyncio import json import os import random import unittest from datetime import datetime, timedelta import boto3 import pytest import redislite from mock import MagicMock, Mock, patch from mockredis import mock_strict_redis_client from moto import ( mock_config, mock_dynamodb2, mock_iam, mock_s...
the-stack_0_2892
import unittest import cupy from cupy import testing class TestCArray(unittest.TestCase): def test_size(self): x = cupy.arange(3).astype('i') y = cupy.ElementwiseKernel( 'raw int32 x', 'int32 y', 'y = x.size()', 'test_carray_size', )(x, size=1) self.assertEqual(int(y[...
the-stack_0_2893
from functools import partial from typing import ( AsyncIterator, Callable, Type, ) from async_generator import asynccontextmanager from async_service import background_asyncio_service from p2p.abc import ConnectionAPI from .abc import ExchangeAPI, NormalizerAPI, ValidatorAPI from .candidate_stream impor...
the-stack_0_2894
# coding=utf8 # Copyright 2018 JDCLOUD.COM # # 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 ...
the-stack_0_2896
# -*- coding: utf-8 -*- """Analysis plugin to look up files in nsrlsvr and tag events.""" import socket from plaso.analysis import hash_tagging from plaso.analysis import logger from plaso.analysis import manager class NsrlsvrAnalyzer(hash_tagging.HashAnalyzer): """Analyzes file hashes by consulting an nsrlsvr in...
the-stack_0_2897
# # 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, software # ...
the-stack_0_2899
# # 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 us...
the-stack_0_2900
''' Scratchpad for test-based development. LICENSING ------------------------------------------------- hypergolix: A python Golix client. Copyright (C) 2016 Muterra, Inc. Contributors ------------ Nick Badger badg@muterra.io | badg@nickbadger.com | nickbadger.com This library is free...
the-stack_0_2902
N = int(input()) ans = '' for _ in range(N): p, q, r = input().split() if p == 'BEGINNING': ans += r[0] elif p == 'MIDDLE': ans += r[len(r)//2] else: ans += r[-1] print(ans)
the-stack_0_2903
import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation fig = plt.figure() axes1 = fig.add_subplot(1, 1, 1) line, = axes1.plot(np.random.rand(10)) def update(data): line.set_ydata(data) return line, def data_gen(): while True: yield np.random.rand(10) ani ...
the-stack_0_2904
"""The tests for the device tracker component.""" from datetime import datetime, timedelta import json import logging import os import pytest from homeassistant.components import zone import homeassistant.components.device_tracker as device_tracker from homeassistant.components.device_tracker import const, legacy fro...
the-stack_0_2905
# cta_apply2(test_images{l},model_orient,'padding',0,'precision','single') import numpy as np import scipy.ndimage class Cta_apply2(): def __init__(self, image, model, padding=0, precision='complex64'): self.precision=precision # 'double' self.verbosity=0 self.padding=padding s...
the-stack_0_2906
##script for finding the overlap in the top 100 most significant genes in each cancer and plotting results ##load necessary modules import pylab as plt import numpy as np import math import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) ##I did not write ...
the-stack_0_2907
# Original Code: https://github.com/nrsyed/computer-vision/blob/master/multithread/CountsPerSec.py # Modified for use in PyPotter # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE A...
the-stack_0_2908
""" Shows 20 most important Amino acids, can be used to learn them. """ from setuptools import setup, find_packages dependencies = ["pyqt5", "pandas"] opt_dependencies = [] setup( name="amino-acids-tutor", version="1.0", author="Luka Jeromel", author_email="luka.jeromel1@gmail.com", description="S...
the-stack_0_2909
from fastapi.testclient import TestClient from main import app client = TestClient(app) def test_vowels_post_expected_code(): response = client.post("/vowels/", json={"line": "HOLA"}) assert response.status_code == 200 def test_vowels_post_result(): response = client.post("/vowels/", json={"line": "H...
the-stack_0_2911
import datetime import jwt from app.core import config ''' JWT RFC: https://tools.ietf.org/html/draft-ietf-oauth-json-web-token-25 sub - Subject of the JWT (Volunteer). exp - Expiration time in which the JWT token will be invalid by the server. iat - Issue time, identifies the time at which the JWT as issued. iss - ...
the-stack_0_2912
import os import uuid from mlflow.entities import Experiment, Metric, Param, Run, RunData, RunInfo, RunStatus, RunTag, \ ViewType from mlflow.store.abstract_store import AbstractStore from mlflow.utils.validation import _validate_metric_name, _validate_param_name, _validate_run_id, \ ...
the-stack_0_2913
import logging from pprint import pprint # noqa from followthemoney import model from followthemoney.types import registry from followthemoney.compare import compare from aleph.core import db, es, celery from aleph.model import Match from aleph.index.indexes import entities_read_index from aleph.index.entities import...
the-stack_0_2915
"""Contains UI methods for LE user operations.""" import logging import zope.component from certbot import errors from certbot import interfaces from certbot import util from certbot.compat import misc from certbot.compat import os from certbot.display import util as display_util logger = logging.getLogger(__name__)...
the-stack_0_2916
#!/usr/bin/python import json from random import randint #if any changes are made to this plugin, kindly update the plugin version here. PLUGIN_VERSION = "1" #Setting this to true will alert you when there is a communication problem while posting plugin data to server HEARTBEAT="true" #Mention the units of your ...
the-stack_0_2917
# https://www.codewars.com/kata/5b2e5a02a454c82fb9000048 def get_neighbourhood(n_type, arr, coordinates): x, y = coordinates r, c = len(arr), len(arr[0]) if 0 > x or x >= r or 0 > y or y >= c: return [] if n_type == "moore": return [ arr[i][j] for i in range(x-1 if x > 0 else x, x+2 if x < r-1 ...
the-stack_0_2918
import os import testinfra.utils.ansible_runner testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner( os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all') # check if MongoDB is enabled and running def test_mongo_running_and_enabled(host): mongo = host.service("mongod") assert mongo.is_runnin...
the-stack_0_2920
# -*- coding: utf-8 -*- from socialregister.users.models import User def create_user(strategy, details, user=None, *args, **kwargs): if user: return {'is_new': False} if not details['email']: username = details['username'] else: username = details['email'] user = User.objects...
the-stack_0_2921
import numpy as np from sklearn.decomposition import PCA from sklearn.base import BaseEstimator, OutlierMixin from sklearn.utils.validation import check_is_fitted, check_array, FLOAT_DTYPES class PCAOutlierDetection(BaseEstimator, OutlierMixin): """ Does outlier detection based on the reconstruction error fro...
the-stack_0_2922
# -*- coding: utf-8 -*- ''' :codeauthor: Pedro Algarvio (pedro@algarvio.me) ============= Class Mix-Ins ============= Some reusable class Mixins ''' # pylint: disable=repr-flag-used-in-string # Import python libs from __future__ import absolute_import, print_function import os import sys import t...
the-stack_0_2923
import random import mmcv import numpy as np import torch import torch.nn as nn from mmcv.runner.checkpoint import _load_checkpoint_with_prefix from mmgen.core.runners.fp16_utils import auto_fp16 from mmgen.models.architectures import PixelNorm from mmgen.models.architectures.common import get_module_device from mmge...
the-stack_0_2924
import hashlib import os from shutil import move from tempfile import mkstemp BLOCKSIZE = 65535 def find_hash(hash_file, plan_name): # Try to find the hash in the hash file filename = os.path.normpath(hash_file) if os.path.isfile(filename): plan_hashes = open(filename, 'r').readlines() fo...
the-stack_0_2926
# Copyright 2021 The Kubeflow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in...
the-stack_0_2928
#!/usr/bin/env python3 # # This file is part of LiteX-Boards. # # Copyright (c) 2021 Hans Baier <hansfbaier@gmail.com> # SPDX-License-Identifier: BSD-2-Clause # https://www.aliexpress.com/item/1000006630084.html import os import argparse from migen import * from litex_boards.platforms import qmtech_xc7a35t from li...
the-stack_0_2929
import os import cv2 from PIL import Image import numpy as np import pickle base = os.path.dirname(os.path.abspath(__file__)) image_dir = os.path.join(base, "images") face_cascade = cv2.CascadeClassifier( cv2.data.haarcascades + 'haarcascade_frontalface_alt2.xml') # LBPH is a data algorithm that is u...
the-stack_0_2930
# Source : https://leetcode.com/problems/find-all-anagrams-in-a-string/ # Author : YipingPan # Date : 2020-08-13 ##################################################################################################### # # Given a string s and a non-empty string p, find all the start indices of p's anagrams in s. # # ...
the-stack_0_2931
# Python test set -- part 5, built-in exceptions import copy import gc import os import sys import unittest import pickle import weakref import errno from test.support import (TESTFN, captured_stderr, check_impl_detail, check_warnings, cpython_only, gc_collect, no_t...
the-stack_0_2932
""" buildfarm dependencies that can be imported into other WORKSPACE files """ load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive", "http_file", "http_jar") load("@bazel_tools//tools/build_defs/repo:utils.bzl", "maybe") RULES_JVM_EXTERNAL_TAG = "3.3" RULES_JVM_EXTERNAL_SHA = "d85951a92c0908c80bd855100...
the-stack_0_2933
""" BenchExec is a framework for reliable benchmarking. This file is part of BenchExec. Copyright (C) 2007-2015 Dirk Beyer 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 ...
the-stack_0_2934
############################################################################ # Copyright (C) 2008 by Volker Christian # # Volker.Christian@fh-hagenberg.at # # # # This pr...
the-stack_0_2935
import os def createFolder(directory): try: if not os.path.exists(directory): os.makedirs(directory) except OSError: print ('Error: Creating directory. ' + directory) # Example createFolder('./data/') # Creates a folder in the current directory called data
the-stack_0_2936
import json import sys from urllib import * import argparse from urllib.parse import urlparse, urlencode, parse_qs from urllib.request import urlopen YOUTUBE_COMMENT_URL = 'https://www.googleapis.com/youtube/v3/commentThreads' YOUTUBE_SEARCH_URL = 'https://www.googleapis.com/youtube/v3/search' arr = [] ...
the-stack_0_2937
"""Data processing routines for MongoDB version """ import datetime # import shutil import pathlib from pymongo import MongoClient from pymongo.collection import Collection cl = MongoClient() db = cl.doctree_database # support for older pymongo versions try: test = Collection.update_one except AttributeError: #...
the-stack_0_2938
# -*- coding: utf-8 -*- ''' pytestsalt.utils ~~~~~~~~~~~~~~~~ Some pytest fixtures used in pytest-salt ''' # Import Python libs from __future__ import absolute_import import os import re import sys import json import time import errno import atexit import signal import socket import logging import subprocess import t...
the-stack_0_2941
"""Config flow to configure the Synology DSM integration.""" from __future__ import annotations import logging from typing import Any from urllib.parse import urlparse from synology_dsm import SynologyDSM from synology_dsm.exceptions import ( SynologyDSMException, SynologyDSMLogin2SAFailedException, Synol...
the-stack_0_2942
import pandas as pd import sklearn.model_selection as ms class CrossValidation: def __init__(self, df, shuffle,random_state=None): self.df = df self.random_state = random_state self.shuffle = shuffle if shuffle is True: self.df = df.sample(frac=1, random_state=self.random_state).reset_index(drop=True) ...
the-stack_0_2943
# -*- coding: utf-8 -*- """ Image Augmentation: Make it rain, make it snow. How to modify photos to train self-driving cars by Ujjwal Saxena https://medium.freecodecamp.org/image-augmentation-make-it-rain-make-it-snow-how-to-modify-a-photo-with-machine-learning-163c0cb3843f """ import numpy as np import cv2 # # Sun...
the-stack_0_2945
import torch import torch.nn as nn import torch.optim as optim import numpy as np import misc import argparse import os import model def train(args): if args.dataset.lower() == 'celeba': train_loader, _, _ = misc.load_celebA(args.batch_s, args.img_s) img_c = 3 elif args.dataset.lower() == 'lsu...
the-stack_0_2947
"""Read and write notebooks as regular .py files. Authors: * Brian Granger """ #----------------------------------------------------------------------------- # Copyright (C) 2008-2011 The IPython Development Team # # Distributed under the terms of the BSD License. The full license is in # the file COPYING, dist...
the-stack_0_2949
import torch import torchvision import torchvision.transforms as transforms import torch.nn as nn import matplotlib.pyplot as plt import numpy as np import time # Baseline: VGG-11 finetuning def return_baseline(): net = torchvision.models.vgg11_bn(pretrained=True) for param in net.parameters(): param....
the-stack_0_2950
import numpy as np import matplotlib.pyplot as plt import pandas as pd from sklearn.preprocessing import MinMaxScaler from keras.models import Sequential from keras.layers import Dense from keras.layers import LSTM from keras.layers import Dropout from keras.models import model_from_json import math from sklearn.metric...
the-stack_0_2951
import io import xlsxwriter from . import models from sales import models as s_models, exports as s_exports from datetime import datetime import decimal def date_parse(str, fmt='%Y-%m-%d %H:%M:%S'): if str == None: return None return datetime.strptime(str, fmt) def cell(i, j): char = "A" cha...
the-stack_0_2952
import sys import tarfile from urllib.request import urlretrieve import logging import time from pathlib import Path from collections import defaultdict logger = logging.getLogger(__name__) MODEL_DIRECTORY = Path(__file__).parent / 'models' MODELS = { 'en': ( 'chainer', 'tri_headfirst', ...
the-stack_0_2953
from pytorch_lightning.callbacks import ModelCheckpoint import os from argparse import ArgumentParser import os import gc import datetime import numpy as np import pandas as pd import numpy as np import torch import pytorch_lightning as pl from lightning_module import LightningModel from pytorch_lightning.loggers.ten...
the-stack_0_2954
# -*- coding: utf-8 -*- # file: file_utils.py # time: 2021/7/13 0020 # author: yangheng <yangheng@m.scnu.edu.cn> # github: https://github.com/yangheng95 # Copyright (C) 2021. All Rights Reserved. import copy import json import os import pickle import urllib.request import torch from findfile import find_files, find_...
the-stack_0_2957
# Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich) # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright...
the-stack_0_2958
""" Unit tests for Python ICE-CASCADE hillslope erosion-deposition forward-time centered-space model component References: (1) Holman, J. P. (2002). Heat transfer (pp. 75) """ import unittest import numpy as np from py_ice_cascade import hillslope class ftcs_TestCase(unittest.TestCase): """Tests for hillslope ...
the-stack_0_2959
# -*- coding: utf-8 -*- import copy from pathlib import Path from collections import OrderedDict, namedtuple import numpy as np from parfive import Downloader import astropy.table import astropy.units as u import parfive import sunpy from sunpy import config from sunpy.net.base_client import BaseClient from sunpy.n...
the-stack_0_2960
"""Produce custom labelling for a colorbar. Contributed by Scott Sinclair """ import matplotlib.pyplot as plt import numpy as np from matplotlib import cm from numpy.random import randn # Make plot with vertical (default) colorbar fig, ax = plt.subplots() data = np.clip(randn(250, 250), -1, 1) cax = ax.imshow(data...
the-stack_0_2961
# -*- coding: utf-8 -*- ''' Manage Elasticsearch Domains ================= .. versionadded:: 2016.11.0 Create and destroy Elasticsearch domains. Be aware that this interacts with Amazon's services, and so may incur charges. This module uses ``boto3``, which can be installed via package, or pip. This module accepts ...
the-stack_0_2964
import os from datetime import datetime import pandas as pd import src.config.constants as constants import src.munging as process_data import src.common as common if __name__ == "__main__": RUN_ID = datetime.now().strftime("%m%d_%H%M") MODEL_NAME = os.path.basename(__file__).split(".")[0] logger = comm...
the-stack_0_2966
import ast from typing import Any, List from vyper.parser.context import Context from vyper.parser.expr import Expr from vyper.parser.function_definitions.utils import ( get_default_names_to_set, get_nonreentrant_lock, get_sig_statements, make_unpacker, ) from vyper.parser.lll_node import LLLnode from ...
the-stack_0_2968
#!/usr/bin/env python3 import argparse import socketserver import signal import sys import handlers from util import eprint def get_arguments(): parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument("--port", "-p", help="Local port to bind to", default=...
the-stack_0_2970
import os from sent2vec.vectorizer import Vectorizer from scipy import spatial def compare_two_sentences(sentence_1, sentence_2): sentences = [sentence_1, sentence_2] vectorizer = Vectorizer() vectorizer.bert(sentences) vec_1, vec_2 = vectorizer.vectors dist = spatial.distance.cosine(vec_1, vec_...
the-stack_0_2972
#!/usr/bin/env python3 # Copyright (c) 2014-2016 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 merkleblock fetch/validation # from test_framework.test_framework import BitcoinTestFramework f...
the-stack_0_2973
import itertools import uuid from dataclasses import dataclass, field from typing import ( Generator, Iterator, Dict, Sequence, Optional, TYPE_CHECKING, Union, Tuple, List, ) import numpy as np import weaviate from ..base.backend import BaseBackendMixin from .... import Document fr...
the-stack_0_2974
# coding: utf-8 import pprint import re import six class UpdateDomainLoginPolicyRequest: """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name a...
the-stack_0_2976
import os h, d, aim = 0, 0, 0 def forward(x): global h, d, aim h += x d += aim * x def down(x): global aim aim += x def up(x): global aim aim -= x if __name__ == '__main__': with open(os.path.join('inputs', 'day2.txt')) as f: moves = list(map(lambda x: x.split(' '), f.re...
the-stack_0_2977
import FWCore.ParameterSet.Config as cms from DQMServices.Core.DQMEDHarvester import DQMEDHarvester bphEfficiency = DQMEDHarvester("DQMGenericClient", subDirs = cms.untracked.vstring("HLT/BPH/*"), verbose = cms.untracked.uint32(0), # Set to 2 for all messages resolution = cms.vstring(), ...
the-stack_0_2978
from data.loveda import LoveDALoader from utils.tools import * from skimage.io import imsave import os def predict_test(model, cfg, ckpt_path=None, save_dir='./submit_test'): os.makedirs(save_dir, exist_ok=True) seed_torch(2333) model_state_dict = torch.load(ckpt_path) model.load_state_dict(model_stat...
the-stack_0_2981
import logging import logging.handlers import argparse import sys import os import time from bluetooth import * from . import gpioservice from .powerControllerModule import PowerThread from .configControllerModule import ConfigController from . import stateControllerModule from .libInstaller import LibInstaller from su...
the-stack_0_2982
import requests def esmoneda(cripto): return cripto in monedas def main(): monedas_list=[] data=requests.get("https://api.coinmarketcap.com/v2/listings/").json() for cripto in data["data"]: monedas_list.append(cripto["symbol"]) monedas=tuple(monedas_list) moneda=input("Indique el nombr...
the-stack_0_2983
import frappe def execute(): frappe.reload_doc("contacts", "doctype", "contact_email") frappe.reload_doc("contacts", "doctype", "contact_phone") frappe.reload_doc("contacts", "doctype", "contact") contact_details = frappe.db.sql( """ SELECT `name`, `email_id`, `phone`, `mobile_no`, `modified_by`, `creatio...
the-stack_0_2985
# Copyright 2011 OpenStack 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 agr...