filename
stringlengths
13
19
text
stringlengths
134
1.04M
the-stack_0_12273
#!/usr/bin/env python3 # Copyright (c) 2014-2019 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test the RPC HTTP basics.""" from test_framework.test_framework import MonicoinTestFramework from test...
the-stack_0_12275
"""Views for observations of categories.""" from django.core.exceptions import PermissionDenied from django.views.decorators.gzip import gzip_page from rest_framework import status from rest_framework.response import Response from rest_framework.views import APIView from geokey.core.decorators import handle_exceptio...
the-stack_0_12276
#!/usr/local/bin/python from os import system from sys import argv cl = argv[1] liste = open('/usr/local/share/operator/editor').read() if "sudo" in argv[1:]: print("Can't use sudo with operator") elif ">" in argv[1:]: print("Can't use > with operator") elif cl in liste: print(("Can't use %s with operato...
the-stack_0_12278
import unittest import unittest.mock import re from g1.asyncs import agents from g1.asyncs import kernels from g1.asyncs.bases import locks from g1.asyncs.bases import queues from g1.asyncs.bases import tasks from g1.asyncs.bases import timers class SuperviseAgentsTest(unittest.TestCase): def setUp(self): ...
the-stack_0_12279
# This file helps to compute a version number in source trees obtained from # git-archive tarball (such as those provided by githubs download-from-tag # feature). Distribution tarballs (built by setup.py sdist) and build # directories (produced by setup.py build) will contain a much shorter file # that just contains th...
the-stack_0_12280
#coding=utf-8 from facebook.modules.profile.user.models import TestUser from facebook.graph import GraphAPIError from django.utils import simplejson class TestUsers(object): def __init__(self, graph): self.graph = graph # Friend requests need user access token def update_access_token(self, ac...
the-stack_0_12283
# -*- coding: utf-8 -*- # Copyright (c) Facebook, Inc. and its affiliates. import logging import numpy as np import time import weakref from typing import Dict, List, Optional import torch from torch.nn.parallel import DataParallel, DistributedDataParallel import detectron2.utils.comm as comm from detectron2.utils.ev...
the-stack_0_12285
import asyncio from ...exceptions import NodeJSNotRunning from ...exceptions import NoMtProtoClientSet from ...exceptions import NotInGroupCallError from ...scaffold import Scaffold from ...types import NotInGroupCall from ...types.session import Session class ResumeStream(Scaffold): async def resume_stream( ...
the-stack_0_12286
import functools import operator import os import os.path import sys import numpy as np # Bamboo utilities current_file = os.path.realpath(__file__) print("Current file:",current_file, __file__) current_dir = os.path.dirname(current_file) sys.path.insert(0, os.path.join(os.path.dirname(current_dir), 'common...
the-stack_0_12289
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ ------------------------------------------------- File Name:kerasexa Description: Keras 案例 https://keras.io/getting-started/sequential-model-guide/ Email : autuanliu@163.com Date:2018/1/1 """ import keras import numpy as np from keras.layers import Dens...
the-stack_0_12293
from __future__ import print_function import os import torch from torch.utils.ffi import create_extension sources = ['src/roi_pooling.cpp'] headers = ['src/roi_pooling.h'] defines = [] with_cuda = False if torch.cuda.is_available(): print('Including CUDA code.') sources += ['src/roi_pooling_cuda...
the-stack_0_12294
import os import torch import torch.nn.functional as F import torch.distributed as dist from torch.autograd import Variable import numpy as np # https://github.com/ikostrikov/pytorch-ddpg-naf/blob/master/ddpg.py#L11 def soft_update(target, source, tau): """ Perform DDPG soft update (move target params toward s...
the-stack_0_12296
# -*- coding: utf-8 -*- from __future__ import unicode_literals def csp_protected_view(view, info): """ A view deriver which adds Content-Security-Policy headers to responses. By default, a global policy is applied to every view. Individual views can opt out of CSP altogether by specifying a view o...
the-stack_0_12298
""" This file contains the fundamental BrickBreaker game logic. """ import pygame from pygame.locals import * from GameElements import Paddle, Ball, Brick, Special, SpecialText, \ SpecialType, to_drop_special, choose_random_special, BOUNCE_OFF_VECTORS from Player import Player from LevelGenerator import LevelGenera...
the-stack_0_12299
import asyncio import typing as t from contextlib import asynccontextmanager from nbclient import NotebookClient from nbformat import NotebookNode from nbclient.exceptions import CellExecutionComplete, DeadKernelError, CellControlSignal from nbclient.util import run_hook from appyter.ext.asyncio.event_loop import get_e...
the-stack_0_12300
import pytest from newchain_web3 import ( EthereumTesterProvider, Web3, ) from newchain_web3.providers.eth_tester.main import ( AsyncEthereumTesterProvider, ) from newchain_web3.version import ( AsyncVersion, BlockingVersion, Version, ) @pytest.fixture def blocking_w3(): return Web3( ...
the-stack_0_12301
#imports from splinter import Browser from bs4 import BeautifulSoup as soup from webdriver_manager.chrome import ChromeDriverManager import datetime as dt #scrape all function def scrape_all(): # need to return a json that has data to load into database (MongoDB) # Set up Splinter executable_path...
the-stack_0_12303
# -*- coding: utf-8 -*- # Copyright 2020 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 o...
the-stack_0_12304
import numpy as np import matplotlib.pyplot as plt from scipy.stats import norm import time import bspline import bspline.splinelab as splinelab # The Black-Scholes prices def bs_put(t, S0, K, r, sigma, T): d1 = (np.log(S0 / K) + (r + 1 / 2 * sigma ** 2) * (T - t)) / sigma / np.sqrt(T - t) d2 = (np.log(S0 / K...
the-stack_0_12305
"""empty message Revision ID: 3ca97c203761 Revises: ddc9ab150f3e Create Date: 2021-05-11 14:59:39.803671 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '3ca97c203761' down_revision = 'ddc9ab150f3e' branch_labels = None depends_on = None def upgrade(): # ...
the-stack_0_12306
""" Programa 115 Área de estudos. data 13.12.2020 (Indefinida) Hs @Autor: Abraão A. Silva """ # Abrimos um arquivo para gravação de dados. arquivo = open('/home/abraao/Documentos/testando.txt', 'w') # Modo 'w' sobrescreve o arquivo. while True: nome = str(input('Nome: ')) if nome.isdigit(): pr...
the-stack_0_12307
# -*- coding: utf-8 -*- """ Created on Sun Mar 25 18:47:55 2018 @author: bokorn """ import cv2 import numpy as np import tensorflow as tf def convertSummary(val): if(val.HasField('simple_value')): return val.simple_value elif(val.HasField('obsolete_old_style_histogram')): raise NotImplementedE...
the-stack_0_12311
from .concat_vec_env import ConcatVecEnv from .multiproc_vec import ProcConcatVec class call_wrap: def __init__(self, fn, data): self.fn = fn self.data = data def __call__(self, *args): return self.fn(self.data) def MakeCPUAsyncConstructor(max_num_cpus): if max_num_cpus == 0: ...
the-stack_0_12314
import sys from helpers import api_qradio as q from helpers import MaltegoTransform ############################################################## ## ENRICH Section def ipv4_enrich(mt, ip_address): enrich_list = q.ipv4_enrich(ip_address) for domain in enrich_list['domains']: mt.addEntity("maltego.Dom...
the-stack_0_12315
class Node(): def __init__(self, alphabet): self.char = alphabet self.children = [] self.end_of_word = False self.counter = 1 ''' Create a tree of alphabets like this: + / \ c d / \ a o / \ \ t p g ''' class Trie(): def __init__(self): ...
the-stack_0_12318
# -*- coding: utf-8 -*- # # Copyright 2016 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 requir...
the-stack_0_12321
import pygame from .board import Board from .config import RED, WHITE, BLUE, BLACK, SQUARE_SIZE class Game(): def __init__(self, win): self.win = win self._init() def _init(self): self.selected_piece = None self.board = Board() self.turn = RED self.valid_moves ...
the-stack_0_12323
#!/usr/bin/env python import glob import logging import os import platform import re import shutil import sys import tempfile import time import requests from localstack import config from localstack.config import KINESIS_PROVIDER from localstack.constants import ( DEFAULT_SERVICE_PORTS, DYNAMODB_JAR_URL, ...
the-stack_0_12324
#!/usr/bin/env python # Copyright 2015 The Kubernetes 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 appli...
the-stack_0_12326
from enum import Enum class GenomeBuild(Enum): GRCH37 = 0 GRCH38 = 1 MM9 = 2 MM10 = 3 RN6 = 4 @staticmethod def parse(s: str) -> "GenomeBuild": if s == "GRCh37": return GenomeBuild.GRCH37 elif s == "GRCh38": return GenomeBuild.GRCH38 elif s ...
the-stack_0_12327
import os import cv2 import numpy as np import tqdm from common import my_utils def improve_depth(image, depth, threshold=0.001, threshold_faraway_planes=False): window_size = 20 width = image.shape[0] height = image.shape[1] if threshold_faraway_planes: # NOTE: This could be PERHAPS useful...
the-stack_0_12328
from fireo.fields import ReferenceField, NestedModel, IDField from fireo.queries import errors from fireo.utils import utils from google.cloud import firestore class ModelWrapper: """Convert query result into Model instance""" @classmethod def from_query_result(cls, model, doc, nested_doc=False): ...
the-stack_0_12329
# -*- coding: utf-8 -*- # Copyright: 2009 Nadia Alramli # License: BSD """Draws an animated terminal progress bar Usage: p = ProgressBar("blue") p.render(percentage, message) """ import terminal import sys class ProgressBar(object): """Terminal progress bar class""" TEMPLATE = ( '%(percent)-2s%% ...
the-stack_0_12331
""" Author : James McKain (@jjmckain) Created : 2021-12-10 SCM Repo : https://github.com/Preocts/secretbox """ from __future__ import annotations import logging from typing import Any from secretbox.aws_loader import AWSLoader try: import boto3 from botocore.exceptions import ClientError except I...
the-stack_0_12332
import ctypes from ctypes import c_int from .lib import libmcleece class PublicKey: def __init__(self, data): # check that length matches libmcleece length self.data = data def __bytes__(self): return self.data @classmethod def size(cls): return c_int.in_dll(libmclee...
the-stack_0_12334
#!/usr/bin/python # -*- coding: utf-8 -*- """ Manage featured/good article/list status template. *** This script understands various command-line arguments: *** Task commands: -featured use this script for featured articles. Default task if no task command is specified -good ...
the-stack_0_12335
# -*- coding: utf-8 -*- import urllib3 from dropbox import client, rest import os class DropboxDownloader: def __init__(self, token_path): self.api_client = None urllib3.disable_warnings() self.__oauth2(token_path) def __oauth2(self, token_path): with open(token_path) as f: ...
the-stack_0_12336
import re from nonebot import on_message, on_command from nonebot.adapters import Bot, Event from nonebot.log import logger from nonebot.adapters.cqhttp.permission import GROUP from nonebot.adapters.cqhttp.message import Message from nonebot.rule import regex from .common import START, SEP, CONF from .roll import rol...
the-stack_0_12337
# qubit number=4 # total number=40 import cirq import qiskit from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import BasicAer, execute, transpile from pprint import pprint from qiskit.test.mock import FakeVigo from math import log2 import numpy as np import networkx as nx def bitwise_...
the-stack_0_12340
#coding:latin-1 class CarreMagique : def __init__(self, coef) : self.mat = [ [ coef[i+j*3] for i in range(3) ] for j in range(3) ] def __str__(self) : return "\n".join ( [ ",".join( [ str(n) for n in row ] ) for row in self.mat ] ) def __add__ (self, carre) : coef = [] for i ...
the-stack_0_12341
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import sys sys.path.append('./') import codecs import collections import torch import pickle import utils import torch.nn as nn class Loader(): def __init__(self, target_dir): self.target_dir = target_dir self.char2idx = collections.defaultdict(int)...
the-stack_0_12343
# -*- coding: utf-8 -*- # Copyright 2020 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...
the-stack_0_12345
description = 'FRM II neutron guide line 2b shutter' group = 'lowlevel' includes = ['guidehall'] tango_base = 'tango://ictrlfs.ictrl.frm2:10000/mlz/' devices = dict( NL2b = device('nicos.devices.tango.NamedDigitalInput', description = 'NL2b shutter status', mapping = {'closed': 0, ...
the-stack_0_12346
import natsort import numpy as np import pandas as pd import plotly.io as pio import plotly.express as px import plotly.graph_objects as go import plotly.figure_factory as ff import re import traceback from io import BytesIO from sklearn.decomposition import PCA from sklearn.metrics import pairwise as pw import json im...
the-stack_0_12347
from src.smiles_to_structure import convert_to_structure, MoleculeStructure, Fragment from collections import Counter from termcolor import cprint from src.fragments_library import special_cases, biomolecules, peptide_amino_acids, heterocycles, \ common_aromatic_heterocycles, generalized_heterocycles, arenes, func...
the-stack_0_12348
# # Copyright (c) 2019-2022, NVIDIA CORPORATION. # # 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 ag...
the-stack_0_12349
#!/usr/bin/python # # Currently implemented attacks: # - sniffer - (NOT YET IMPLEMENTED) Sniffer hunting for authentication strings # - ripv1-route - Spoofed RIPv1 Route Announcements # - ripv1-dos - RIPv1 Denial of Service via Null-Routing # - ripv1-ampl - RIPv1 Reflection Amplification DDoS # - ripv...
the-stack_0_12350
import torch import torch.nn as nn from torch.autograd import Variable class RNN(nn.Module): def __init__(self, input_size, hidden_size, output_size, n_layers=1): super(RNN, self).__init__() self.input_size = input_size self.hidden_size = hidden_size self.output_size = output_size ...
the-stack_0_12353
# # 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 # distributed under ...
the-stack_0_12355
#!/usr/bin/python3 def safe_print_list(my_list=[], x=0): i = 0 for j in range(0, x): try: print(my_list[j], end='') i = i + 1 except: break print() return i
the-stack_0_12357
#!/usr/bin/env python # -*- coding:utf-8 -*- # @Author: Jialiang Shi from gerrit.utils.models import BaseModel class Message(BaseModel): def __init__(self, **kwargs): super(Message, self).__init__(**kwargs) self.attributes = [ "id", "_revision_number", "message...
the-stack_0_12358
from __future__ import absolute_import, print_function import typing import gym from core import Action from graphic import CursesSnake class SnakeEnv(gym.Env): """ 0 -> go straight 1 -> turn left 2 -> turn right """ action_space = [0, 1, 2] def __init__(self, shape: [typing.List[int], ...
the-stack_0_12359
# Create your views here. from django import forms, http from django.http import Http404, HttpResponse from django.views.generic import ListView, View, CreateView, FormView, UpdateView from django.views.generic.base import TemplateView from django.http import HttpResponseRedirect from core.views import AuthorizedOrgani...
the-stack_0_12361
# https://www.acmicpc.net/problem/17135 def dfs(cur, depth): if depth == 3: # print(case) check() return if cur == M: return dfs(cur + 1, depth) case.append(cur) dfs(cur + 1, depth + 1) case.pop() def check(): cnt = 0 for _ in range(N): cnt += ...
the-stack_0_12363
import numpy as np import matplotlib.pyplot as plt from PIL import Image from scipy.misc import imresize from operator import itemgetter import cv2 import pdb # actions imshow convenience function def actions_imshow(img,im_size): plt.imshow(img.reshape([im_size,im_size,3])) plt.axis('off') # load Stanford-40 ...
the-stack_0_12365
import setuptools with open("README.md", "r") as f: long_description = f.read() setuptools.setup( name="argtyped", version="0.3.1", url="https://github.com/huzecong/argtyped", author="Zecong Hu", author_email="huzecong@gmail.com", description="Command line arguments, with types", long_...
the-stack_0_12369
"""This package includes all the modules related to data loading and preprocessing To add a custom dataset class called 'dummy', you need to add a file called 'dummy_dataset.py' and define a subclass 'DummyDataset' inherited from BaseDataset. You need to implement four functions: -- <__init__>: ...
the-stack_0_12371
from itertools import chain from typing import Iterable from ground.base import (Context, Location, Orientation, Relation) from ground.hints import (Contour, Multisegment, Point, ...
the-stack_0_12372
from aiohttp import web from tt_web import log from tt_web import postgresql async def on_startup(app): await postgresql.initialize(app['config']['database']) async def on_cleanup(app): await postgresql.deinitialize() def register_routers(app): from . import handlers app.router.add_post('/apply...
the-stack_0_12374
"""Process the raw ShEMO dataset. This assumes the file structure from the original compressed file: /.../ male/ *.wav female/ ... """ from pathlib import Path import click from ertk.dataset import resample_audio, write_annotations, write_filelist from ertk.utils import PathlibPath emotion_map ...
the-stack_0_12376
import torch.nn as nn import torch from modules.lstm_encoder import LSTMEncoder from modules.self_attention import SelfAttention from modules.binary_decoder import BinaryDecoder class BinaryLSTMClassifier(nn.Module): def __init__(self, emb_dim, hidden_dim, vocab_size, num_label, attention_mode, args): sup...
the-stack_0_12377
#!/usr/bin/env python import urllib import json import os from flask import Flask from flask import request from flask import make_response # Flask app should start in global layout app = Flask(__name__) @app.route('/webhook', methods=['POST']) def webhook(): req = request.get_json(silent=True, force=True) ...
the-stack_0_12378
from ast import Continue from astropy.io import fits import numpy as np import matplotlib.pyplot as plt import astropy.units as u from astropy.wcs import WCS from astropy.coordinates import SkyCoord import pandas as pd from photutils.aperture import SkyRectangularAperture, SkyCircularAperture from .imaging import imp...
the-stack_0_12379
# pylint: disable=too-few-public-methods,no-self-use """Tests for datastream generator module""" from builtins import next import unittest import pytest from past.builtins import map, range from mock import mock_open, patch from bcipy.acquisition.datastream.generator import random_data, file_data from bcipy.acquisition...
the-stack_0_12382
# Author: # Adapted from code in Think Complexity, 2nd Edition, by by Allen Downey import sys import numpy as np rule_width = 7 def make_table(rule_num): """Make the table for a given CA rule. rule: int 0-2186 returns: array of 7 0s, 1s, and 2s """ rule_set = [0] * rule_width num = rule_n...
the-stack_0_12383
#!/usr/bin/env python3 import arrow from bs4 import BeautifulSoup from collections import defaultdict import logging from math import isnan import numpy as np from operator import itemgetter import pandas as pd import requests # This parser gets hourly electricity generation data from oc.org.do for the Dominican Rep...
the-stack_0_12388
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.test import TestCase from django.template import Template, Context from django.utils.html import mark_safe from hooks.templatehook import hook from hooks.templatetags.hooks_tags import template_hook_collect from . import utils_hooks class ...
the-stack_0_12389
import os import sys from time import time as timer import gym import torch import numpy as np import numpy.random as rd ''' 2020-0505 ZenJiaHao Github: YonV1943 Compare the running speed of different ReplayBuffer(Memory) implement. ReplayBuffer UsedTime(s) Storage(memories) MemoryList: 24 list() Mem...
the-stack_0_12390
# -*- coding: utf-8 -*- r""" Module for packing and unpacking integers. Simplifies access to the standard ``struct.pack`` and ``struct.unpack`` functions, and also adds support for packing/unpacking arbitrary-width integers. The packers are all context-aware for ``endian`` and ``signed`` arguments, though they can b...
the-stack_0_12391
from __future__ import absolute_import from datetime import datetime, timedelta import six import time import logging from mock import patch, Mock from sentry.event_manager import EventManager from sentry.eventstream.kafka import KafkaEventStream from sentry.testutils import SnubaTestCase from sentry.utils import snu...
the-stack_0_12392
import pytest from .. import base MB = 1 @base.bootstrapped @pytest.mark.asyncio async def test_action(event_loop): async with base.CleanModel() as model: ubuntu_app = await model.deploy( 'mysql', application_name='mysql', series='trusty', channel='stable'...
the-stack_0_12394
from devito.ir.iet import Iteration, List, IterationTree, FindSections, FindSymbols from devito.symbolics import Macro from devito.tools import flatten from devito.types import Array, LocalObject __all__ = ['filter_iterations', 'retrieve_iteration_tree', 'compose_nodes', 'derive_parameters'] def retrieve_...
the-stack_0_12395
def more_even_or_odd(integers): ans = "" even = 0 odd = 0 for i in integers: if i % 2 == 0: even += 1 else: odd += 1 if even > odd: ans += "Even" elif even < odd: ans += "Odd" else: ans += "Equal" return ans
the-stack_0_12396
# Standard imports import pytest import numpy as np # Package imports import pycalib.calibration_methods as calm # General @pytest.fixture(scope='module') def sample_size(): return 1000 @pytest.fixture(scope='module') def p_dist_beta(sample_size, a=1, b=4): # Predicted probabilities (transformed to [0.5, 1...
the-stack_0_12397
# -*- coding: utf-8 -*- # Copyright (c) 2018-2019 The Particl Core developers # Copyright (c) 2020 The Capricoin+ Core developers # Distributed under the MIT software license, see the accompanying # file LICENSE.txt or http://www.opensource.org/licenses/mit-license.php. import os import json import hashlib import thr...
the-stack_0_12398
from xml.etree.ElementTree import register_namespace namespaces = { '': 'http://www.w3.org/2000/svg', 'inkscape': 'http://www.inkscape.org/namespaces/inkscape', 'sodipodi': 'http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd', 'svg': 'http://www.w3.org/2000/svg', 'freecad': 'http://www.freecadweb.o...
the-stack_0_12402
# coding=utf-8 # Copyright 2021 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...
the-stack_0_12403
#!/usr/bin/env python r"""Compute SSP/PCA projections for ECG artifacts. Examples -------- .. code-block:: console $ mne compute_proj_ecg -i sample_audvis_raw.fif -c "MEG 1531" \ --l-freq 1 --h-freq 100 \ --rej-grad 3000 --rej-mag 4000 --rej-eeg 100 """ # Aut...
the-stack_0_12405
"""This module is to declare global objects.""" from datetime import datetime # Configuration Options global moesif_options moesif_options = {} # Debug Flag global DEBUG DEBUG = True # Patch Flag global MOESIF_PATCH MOESIF_PATCH = False # MoesifAPI Client global api_client api_client = None # App Config class glob...
the-stack_0_12407
import glob import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torch.autograd as autograd import torch.optim as optim from torch.autograd import Variable import matplotlib.pyplot as plt import random from tqdm import tqdm import multiprocessing import os.path import csv import ...
the-stack_0_12409
# 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...
the-stack_0_12411
from __future__ import annotations import asyncio import copy import functools import logging import re import typing from typing import Annotated, Awaitable, Callable, Coroutine, Optional, Tuple, Any, TYPE_CHECKING from naff.client.const import MISSING, logger_name from naff.client.errors import CommandOnCooldown, Co...
the-stack_0_12415
import logging from argparse import ArgumentParser from .server import Server logger = logging.getLogger(__name__) def parse_args(): parser = ArgumentParser(prog="contiflowpump_service", description="Start this SiLA 2 server") parser.add_argument("-a", "--ip-address", default="127.0.0.1", help="The IP addre...
the-stack_0_12418
"""Tests for SDEC Plots.""" from tardis.base import run_tardis import pytest import pandas as pd import numpy as np import os from copy import deepcopy from tardis.visualization.tools.sdec_plot import SDECData, SDECPlotter import astropy.units as u from matplotlib.collections import PolyCollection from matplotlib.lines...
the-stack_0_12421
"""A training script of PPO on OpenAI Gym Mujoco environments. This script follows the settings of https://arxiv.org/abs/1709.06560 as much as possible. """ import argparse import functools import chainer from chainer import functions as F from chainer import links as L import gym import gym.spaces import numpy as np...
the-stack_0_12422
from string import punctuation, digits import numpy as np import random # Part I #pragma: coderesponse template def get_order(n_samples): try: with open(str(n_samples) + '.txt') as fp: line = fp.readline() return list(map(int, line.split(','))) except FileNotFoundError: ...
the-stack_0_12423
# # The Python Imaging Library. # $Id$ # # IFUNC IM file handling for PIL # # history: # 1995-09-01 fl Created. # 1997-01-03 fl Save palette images # 1997-01-08 fl Added sequence support # 1997-01-23 fl Added P and RGB save support # 1997-05-31 fl Read floating point images # 1997-06-22 fl Save floating poi...
the-stack_0_12426
from django.contrib import admin # from django.contrib.admin import ModelAdmin from leaflet.admin import LeafletGeoAdmin from .models import ( RainfallEvent, Pixel, Gauge ) # customize admin site info admin.site.site_header = '3RWW API' admin.site.site_title = '3RWW API' admin.site.index_title = '3RWW API...
the-stack_0_12427
# Copyright 2019 The Bazel 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 la...
the-stack_0_12428
# qubit number=4 # total number=43 import cirq import qiskit from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import BasicAer, execute, transpile from pprint import pprint from qiskit.test.mock import FakeVigo from math import log2 import numpy as np import networkx as nx def bitwise_...
the-stack_0_12429
from django.contrib.auth.models import User from rest_framework import serializers from lists.models import Todo, TodoList class UserSerializer(serializers.ModelSerializer): todolists = serializers.PrimaryKeyRelatedField( many=True, queryset=TodoList.objects.all() ) class Meta: model = ...
the-stack_0_12430
# ------------------------------------------------------------------------ # BEAUTY DETR # Copyright (c) 2022 Ayush Jain & Nikolaos Gkanatsios # Licensed under CC-BY-NC [see LICENSE for details] # All Rights Reserved # ------------------------------------------------------------------------ # Parts adapted from Group-F...
the-stack_0_12435
import abc from typing import Dict from typing import Optional from typing import Tuple from typing import Type from typing import Union from winter.core import ComponentMethod from .throws import get_throws NotHandled = object() class ExceptionHandler(abc.ABC): @abc.abstractmethod def handle(self, exceptio...
the-stack_0_12437
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except jin compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appl...
the-stack_0_12439
from pip._internal.cli.base_command import Command from pip._internal.cli.status_codes import SUCCESS from pip._internal.exceptions import CommandError class HelpCommand(Command): """Show help for commands""" name = 'help' usage = """ %prog <command>""" summary = 'Show help for commands.' ...
the-stack_0_12441
""" Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT Test case ID : C14861501 Test Case Title : Verify PxMesh is auto-assigned when Collider component is added after Re...
the-stack_0_12442
import numpy as np class VineyardAnalysis(): def __init__(self): self.name = "Vineyard Suitability Analysis Function" self.description = "This function computes vineyard suitability given elevation, slope, aspect, and soil-type rasters." def getParameterInfo(self): ...
the-stack_0_12443
# -*- coding: utf-8 -*- """ Created on Tue Feb 19 16:54:54 2019 @author: similarities """ import matplotlib.pyplot as plt import numpy as np import os class FwhmImageProcessing: def __init__(self, filename, lambda_fundamental, maximum_harmonic, harmonic_number): self.filename = filename self.fil...
the-stack_0_12445
""" Author: Soubhik Sanyal Copyright (c) 2019, Soubhik Sanyal All rights reserved. Max-Planck-Gesellschaft zur Foerderung der Wissenschaften e.V. (MPG) is holder of all proprietary rights on this computer program. You can only use this computer program if you have closed a license agreement with MPG or you get the ri...
the-stack_0_12446
# This file helps to compute a version number in source trees obtained from # git-archive tarball (such as those provided by githubs download-from-tag # feature). Distribution tarballs (built by setup.py sdist) and build # directories (produced by setup.py build) will contain a much shorter file # that just contains t...