filename
stringlengths
13
19
text
stringlengths
134
1.04M
the-stack_0_14825
#!/usr/bin/env python3 # Copyright (c) 2017 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 mempool acceptance of raw transactions.""" from io import BytesIO from test_framework.test_framework i...
the-stack_0_14826
from collections import Counter from collections import OrderedDict players = ['Mike', 'Chris', 'Arnold'] standings = OrderedDict([(player, Counter()) for player in players]) print('standings:', standings) standings['Mike']['game_played'] += 1 standings['Mike']['score'] = 2 standings['Mike']['game_played'] += 1 s...
the-stack_0_14829
import io import re import six from boto3.session import Session from botocore.config import Config AWS_ACCESS_KEY = 'AKIAJXFC3JRVYNIHX2UA' AWS_ACCESS_SECRET_KEY = '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' S3_BUCKET_NAME_PATTERN = re.compile(r'^[a-z0-9][a-z0-9\-]{1,61}[a-z0-9]$') S3_KEY_PATTERN = re.compile(r'^[a-z...
the-stack_0_14830
"""Declarative scaffolding for frameworks""" import collections import uuid import warnings __all__ = ["ModelMetaclass", "Field", "TypeDefinition", "TypeEngine", "DeclareException"] __version__ = "0.9.12" missing = object() # These engines can't be cleared _fixed_engines = collections.ChainMap() class Dec...
the-stack_0_14831
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2011 OpenStack LLC. # Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # no...
the-stack_0_14832
#import dependencies from bs4 import BeautifulSoup as bs from splinter import Browser import os import pandas as pd import time import requests import urllib from urllib.request import urlopen, urlretrieve from urllib.parse import urljoin from urllib.parse import urlsplit from splinter import Browser from s...
the-stack_0_14834
# -*- coding: utf-8 -*- """ flask-rstblog ~~~~~~~~~~~~~ :copyright: (c) 2011 by Christoph Heer. :license: BSD, see LICENSE for more details. """ import os from datetime import date from jinja2 import FileSystemLoader from flask import Flask, render_template from flaskrst.modules import manager from ...
the-stack_0_14836
from copy import deepcopy from typing import Optional from warnings import warn import numpy from catsim import cat from catsim.simulation import Estimator, Selector from sklearn.linear_model import LogisticRegression def _fit_log_reg( items, administered_items, response_vector, use_discriminations=T...
the-stack_0_14837
# weather.py ''' # Configuration The weather module reads from the weather.yaml file stored in bobbit's configuration directory and expects the following values: default: This is the default zip code ''' import logging import re import aiohttp.client_exceptions # Metadata NAME = 'weather' ENABLE = Tru...
the-stack_0_14841
''' The actual saltkey functional code ''' # Import python modules import os import shutil import sys import logging # Import salt modules import salt.crypt import salt.utils import salt.utils.event log = logging.getLogger(__name__) class Key(object): ''' The object that encapsulates saltkey actions '''...
the-stack_0_14842
# Copyright (c) AIRBUS and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from __future__ import annotations import random from enum import Enum from typing import Any, Dict, List, Optional, Union import numpy as np from sk...
the-stack_0_14843
#!/usr/bin/python # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed...
the-stack_0_14844
import os import keywords as kw import mechanism_names as mn import mechanism from util import ParseUtil, make_readable_list_of_strings # All parameters and their defaults. PD = {kw.BEHAVIORS: set(), # set of (restricted) strings , REQ kw.STIMULUS_ELEMENTS: set(), # set of (...
the-stack_0_14845
import socket import threading import codecs from scapy.all import * contentTable = ['porn', 'guns', 'torrent', 'skype'] firstIface = 'eth0' firstIfaceFlows = ['52:54:00:42:84:65'] secondIface = 'eth1' secondIfaceFlows = ['52:54:00:a1:54:c0'] def inOutServer(): global contentTable global firstIface ...
the-stack_0_14848
# coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import os import re ...
the-stack_0_14850
#!/usr/bin/env python # -*- coding: utf-8 -*- # SPDX-License-Identifier: Apache-2.0 # Copyright 2021 RT 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...
the-stack_0_14856
# qubit number=3 # total number=12 import numpy as np from qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ import networkx as nx from qiskit.visualization import plot_histogram from typing import * from pprint import pprint from math import log2 from collectio...
the-stack_0_14858
# Copyright 2019 The TensorTrade 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...
the-stack_0_14860
import _plotly_utils.basevalidators class HighlightcolorValidator(_plotly_utils.basevalidators.ColorValidator): def __init__( self, plotly_name="highlightcolor", parent_name="surface.contours.y", **kwargs ): super(HighlightcolorValidator, self).__init__( plotly_name=plotly_name, ...
the-stack_0_14866
from pathlib import Path import requests from lxml import etree headers = { 'user-agent': "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36" } meta_url = "https://pypi.org/" search_url = "https://pypi.org/search/?q" def init_save_path(save_path...
the-stack_0_14867
from seleniumbase import BaseCase from ..page_objects.main_page import MainPage as PageObjects class HappyPathTest(BaseCase): def common_actions(self): # Preenche valor para aplicar com 20,00 self.update_text(PageObjects.input_valor_aplicar, '20,00') # Preenche valor que você quer poupar ...
the-stack_0_14868
import sys import csv_data import my_perceptron # TWEAKING VARIABLES max_perceptron_iterations = 100 def printResults( data_name, result_unrounded ): print( "RESULTS FOR", data_name.upper() ) print( "{:.2f}% correct prediction on {}\n".format( round( result_unrounded, 2 ), data_name.lower() ) ) def main( arg...
the-stack_0_14871
# Copyright The PyTorch Lightning team. # # 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 i...
the-stack_0_14872
#!/usr/bin/python3 #import time import random import imp modl = imp.load_source('ppFunctions', '../00/ppFunctions.py') import os from ppFunctions import * from termcolor import colored, cprint #sleep becouse of loading midi modules print("Are you ready?") time.sleep(1) print_status = lambda x: cprint(x, 'white', 'on_b...
the-stack_0_14873
# # This source file is part of the EdgeDB open source project. # # Copyright 2008-present MagicStack Inc. and the EdgeDB 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...
the-stack_0_14875
# code is borrowed from the original repo and fit into our training framework # https://github.com/HuCaoFighting/Swin-Unet/tree/4375a8d6fa7d9c38184c5d3194db990a00a3e912 from __future__ import absolute_import from __future__ import division from __future__ import print_function import torch import torch.nn as nn ...
the-stack_0_14877
#!/usr/bin/env python3 import unittest from unittest.mock import patch import numpy as np import pandas as pd from tmc import points from tmc.utils import load, get_stdout, patch_helper module_name="src.subsetting_by_positions" subsetting_by_positions = load(module_name, "subsetting_by_positions") main = load(modul...
the-stack_0_14878
# Import python libs import new import sys # Import Salt Testing libs from salttesting import skipIf, TestCase from salttesting.helpers import ensure_in_syspath ensure_in_syspath('../../') # wmi and pythoncom modules are platform specific... wmi = new.module('wmi') sys.modules['wmi'] = wmi pythoncom = new.module('py...
the-stack_0_14880
from PyQt5 import QtWidgets from PyQt5.QtCore import qWarning, Qt from PyQt5.QtWidgets import QWidget, QSplitter from candy_editor.qt.controls.ToolWindowManager.ToolWindowManagerArea import ToolWindowManagerArea class ToolWindowManagerWrapper ( QWidget ): def __init__ ( self, manager ): super ( ToolWindowManagerW...
the-stack_0_14881
#Claire Williams & Matthew Rasmussen #1/26/2021 #Moves info from one CSV file to other CSV files #dictionary full of info import csv def make_athletes_table(): '''SOMETHING ''' athlete_dict = {} with open('athlete_events.csv') as csv_file: csv_reader = csv.reader(csv_file, delimit...
the-stack_0_14883
# Copyright 2017 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_14884
# Copyright 2019 Kyoto University (Hirofumi Inaguma) # Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0) """Training/decoding definition for the speech translation task.""" import itertools import json import logging import os from chainer import training from chainer.training import extensions import numpy ...
the-stack_0_14886
import os import os.path as osp import argparse import pickle import numpy as np from operator import itemgetter import re def parse_args(): parser = argparse.ArgumentParser() parser.add_argument('-appstr', type=str, default='unknown') parser.add_argument('-ntask', type=int, default=1, help='number of task...
the-stack_0_14887
from api.models.base import Base db = Base.db class Activity(Base): """Model activities available for points.""" __tablename__ = 'activities' activity_type_id = db.Column( db.String, db.ForeignKey('activity_types.uuid'), nullable=False ) added_by_id = db.Column( ...
the-stack_0_14890
import cv2 from time import sleep cap = cv2.VideoCapture(0) while True: ret,frame = cap.read() # Our operations on the frame come here gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # Display the resulting frame cv2.imshow('frame',gray) if cv2.waitKey(1) & 0xFF == ord('q'): break sleep(1) cap.re...
the-stack_0_14893
# gpl author: Ryan Inch (Imaginer) import bpy from bpy.types import Menu from . import utils_core class DynTopoMenu(Menu): bl_label = "Dyntopo" bl_idname = "VIEW3D_MT_sv3_dyntopo" @classmethod def poll(self, context): return utils_core.get_mode() == 'SCULPT' def draw(self, context): ...
the-stack_0_14894
# # Copyright (c) 2021, Neptune Labs Sp. z o.o. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agr...
the-stack_0_14898
# Copyright 2016 Mycroft AI, Inc. # # This file is part of Mycroft Core. # # Mycroft Core is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later versio...
the-stack_0_14899
# Copyright 2018 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
the-stack_0_14900
# -*- coding:utf-8 -*- # Copyright (c) 2015, Roger Duran. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights #...
the-stack_0_14901
# pylint: disable=no-self-use,invalid-name from __future__ import with_statement from __future__ import absolute_import from __future__ import print_function from collections import defaultdict import pytest import numpy from allennlp.common.checks import ConfigurationError from allennlp.common.testing import Allen...
the-stack_0_14903
from __future__ import annotations from collections import Counter import re import string import numpy as np import pandas as pd import torch from torch.nn.init import xavier_uniform_ from torch.nn import Module, Embedding, Sequential, ELU, Conv1d, Linear, CrossEntropyLoss from torch.nn.functional import avg_pool1d,...
the-stack_0_14904
import os import logging logging.basicConfig(level=logging.DEBUG, format='[%(asctime)s] - %(message)s') ld = logging.debug class PartialObservabilityProblem: def __init__(self, dataset_path, num_nodes, T, num_examples_to_generate, ...
the-stack_0_14907
import sys import uuid from dataclasses import dataclass from dataclasses import field from dataclasses import fields from dataclasses import make_dataclass from typing import Dict from typing import get_type_hints from typing import Iterator from typing import List from typing import Union from unittest import mock fr...
the-stack_0_14908
import flask import git import local_system import update api_blueprint = flask.Blueprint('api', __name__, url_prefix='/api') @api_blueprint.route('/shutdown', methods=['POST']) def shutdown_post(): try: local_system.shutdown() return _json_success() except local_system.Error as e: r...
the-stack_0_14910
# -*- coding: utf-8 -*- import os import types import logging from socket import AF_INET from socket import AF_INET6 from socket import AF_UNSPEC from itertools import chain from functools import partial from pr2modules import config from pr2modules.config import AF_BRIDGE from pr2modules.netlink import NLMSG_ERROR fro...
the-stack_0_14912
import numpy as np import time from rllab.misc import logger def rollout(env, policy, path_length, render=False, speedup=None): Da = env.action_space.flat_dim Do = env.observation_space.flat_dim observation = env.reset() policy.reset() observations = np.zeros((path_length + 1, Do)) actions ...
the-stack_0_14913
import os from flask import Flask, request, abort, jsonify, json from flask_sqlalchemy import SQLAlchemy from sqlalchemy import exc from flask_cors import CORS import random from flask_migrate import Migrate from models import setup_db, Movies, Actors, db from auth.auth import AuthError, requires_auth def create_app...
the-stack_0_14915
import os import pytest from pyinsights.cli import run CONFIG_FILEPATH_FOR_TEST = os.getenv('CONFIG_FILEPATH_FOR_TEST') PROFILE_FOR_TEST = os.getenv('PROFILE_FOR_TEST') REGION_FOR_TEST = os.getenv('REGION_FOR_TEST') @pytest.mark.skipif( CONFIG_FILEPATH_FOR_TEST is None, reason='Use AWS Resource' ) class T...
the-stack_0_14916
"""EESG.py Created by Latha Sethuraman, Katherine Dykes. Copyright (c) NREL. All rights reserved. Electromagnetic design based on conventional magnetic circuit laws Structural design based on McDonald's thesis """ from openmdao.api import Group, Problem, ExplicitComponent,ExecComp,IndepVarComp,ScipyOptimizeDriver impo...
the-stack_0_14917
from jinja2 import Environment, PackageLoader templates = { 'drawing': 'drawing.xml', 'hyperlink': 'hyperlink.xml', 'insert': 'insert.xml', 'main': 'base.xml', 'p': 'p.xml', 'pict': 'pict.xml', 'r': 'r.xml', 'sectPr': 'sectPr.xml', 'smartTag': 'smart_tag.xml', 'style': 'style.xm...
the-stack_0_14919
from discord.ext import commands from cassiopeia import riotapi config: dict = {} def init(bot: commands.Bot, cfg: dict): global config config = cfg[__name__] riotapi.set_region(config["api_region"]) riotapi.set_api_key(config["api_key"]) from .trivia import LoLTrivia bot.add_cog(LoLTrivia...
the-stack_0_14920
from JumpScale9Portal.portal import exceptions import re INT = r"""(?:[+-]?(?:[0-9]+))""" BASE10NUM = r"""(?<![0-9.+-])(?>[+-]?(?:(?:[0-9]+(?:\.[0-9]+)?)|(?:\.[0-9]+)))""" NUMBER = r"""(?<![0-9.+-])(?>[+-]?(?:(?:[0-9]+(?:\.[0-9]+)?)|(?:\.[0-9]+)))""" BASE16NUM = r"""(?<![0-9A-Fa-f])(?:[+-]?(?:0x)?(?:[0-9A-Fa-f]+))""" ...
the-stack_0_14922
#!/usr/bin/env python # coding: utf-8 import logging import os from timeit import default_timer as timer import emmental import torch from emmental.data import EmmentalDataLoader from emmental.learner import EmmentalLearner from emmental.model import EmmentalModel from fonduer import Meta, init_logging from fonduer.c...
the-stack_0_14923
import os import unittest from livestreamer import Livestreamer, PluginError, NoPluginError from livestreamer.plugins import Plugin from livestreamer.stream import * class TestPluginStream(unittest.TestCase): def setUp(self): self.session = Livestreamer() def assertDictHas(self, a, b): for ke...
the-stack_0_14926
# -*- coding: iso-8859-15 -*- # ================================================================= # # Authors: Tom Kralidis <tomkralidis@gmail.com> # Angelos Tzotsos <tzotsos@gmail.com> # # Copyright (c) 2015 Tom Kralidis # Copyright (c) 2015 Angelos Tzotsos # # Permission is hereby granted, free of charge, to...
the-stack_0_14927
# model settings norm_cfg = dict(type='SyncBN', requires_grad=True) model = dict( type='CascadeEncoderDecoder', num_stages=2, pretrained='open-mmlab://resnet50_v1c', backbone=dict( type='ResNetV1c', depth=50, num_stages=4, out_indices=(0, 1, 2, 3), dilations=(1, 1...
the-stack_0_14930
#!/usr/bin/env python3 # Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import numpy as np from ax.exceptions.model import ModelError from ax.models.discrete.thompson import ThompsonSample...
the-stack_0_14931
"""Basic tests of the Misty VM SCL <scott@rerobots.net> Copyright (c) 2020 rerobots, Inc. """ import pytest import mistygrind @pytest.fixture def client(loop, aiohttp_client): yield loop.run_until_complete( aiohttp_client(mistygrind.vm.create_vm()) ) async def test_api_battery(client): resp =...
the-stack_0_14932
#! /usr/bin/env python import sys from aubio import source, sink, pvoc, tss if __name__ == '__main__': if len(sys.argv) < 2: print('usage: %s <inputfile> <outputfile_transient> <outputfile_steady>' % sys.argv[0]) sys.exit(1) samplerate = 44100 win_s = 1024 # fft size hop_s = win...
the-stack_0_14933
import re from urllib.parse import urlencode import collections from directory_api_client.client import api_client from directory_constants import choices import directory_components.helpers from ipware import get_client_ip from django.http import Http404 from django.utils import translation from django.urls import r...
the-stack_0_14934
import functools import logging def catch_exception(func): """ A decorator that wraps the passed in function and logs exceptions should one occur """ @functools.wraps(func) def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except: # log the...
the-stack_0_14936
import pygame import os import random CAR = pygame.image.load("Car.png") BACKGROUND = pygame.image.load("Road.png") BG_CARS = [ pygame.transform.scale(pygame.image.load("cars/" + vehicle), (100, 100)) for vehicle in os.listdir("cars") ] MAX_CARS = 5 class Game: RANDOM_CARS_COUNT = 0 def __init__(sel...
the-stack_0_14940
#!/usr/bin/env python3 ''' Author: Tom McLaughlin Email: tom@serverlessops.io Description: DynamoDB tables ''' import os import boto3 from boto3.dynamodb.conditions import Key from .errors import ApiAuthSvcBaseError from . import logging _logger = logging.get_logger(__name__) DDB_TABLE_NAME = os.environ.get('DDB_T...
the-stack_0_14941
#!/usr/bin/env pnpython4 # -*- coding: iso-8859-15 -*- # # Read Fairfield SEG-D (Version 1.6) from the Sweetwater experiment. # Write PH5 # # Steve Azevedo, May 2014 # Modified to read SEG-D from 3C's, July 2016 # import os import sys import logging import time import json import re from math import modf impor...
the-stack_0_14944
import os import sys def ProcessFile(fileObj): result = "" line = fileObj.readline() #skip to related materials section while not("=Related Material" in line or "= Related Material" in line or "=Manual" in line or "==Manual" in line or "= Manual" in line or "== Manual" in line or line == ""): ...
the-stack_0_14945
from django.http import Http404 from django.conf import settings from django.shortcuts import get_list_or_404 from rest_framework.generics import RetrieveAPIView, DestroyAPIView, GenericAPIView from rest_framework.response import Response from client.authentication import ClientSenderIdAuthentication from submission.m...
the-stack_0_14948
# code adpated from https://github.com/m-lundberg/simple-pid import time import warnings def _clamp(value, limits): lower, upper = limits if value is None: return None elif (upper is not None) and (value > upper): return upper elif (lower is not None) and (value < lower): retu...
the-stack_0_14950
""" sphinx.builders.texinfo ~~~~~~~~~~~~~~~~~~~~~~~ Texinfo builder. :copyright: Copyright 2007-2021 by the Sphinx team, see AUTHORS. :license: BSD, see LICENSE for details. """ import os from os import path from typing import Any, Dict, Iterable, List, Tuple, Union from docutils import nodes fr...
the-stack_0_14951
import re, textwrap import z3 from .utils import logger from .z3api import z3utils ############################################################################### # Serialize Declarations ############################################################################### def smt_sort_str(sort): assert isinstance(so...
the-stack_0_14954
""" Defines different methods to configure a connection to a Kubernetes cluster. """ import asyncio import base64 import contextlib import copy import datetime import json import logging import os import kubernetes import kubernetes_asyncio from kubernetes_asyncio.client import Configuration from kubernetes_asyncio.c...
the-stack_0_14960
#!/usr/bin/env python # coding: utf-8 # # Tutoriel complet Regression lineaire # ## Utilisation de l'intégration continue # ## Collect data using pandas # In[59]: # modules nécessaires pour le notebook import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from sklearn.linear_model import Linear...
the-stack_0_14962
# This software may be modified and distributed under the terms # of the MIT license. See the LICENSE file for details. # # PanDA authors: # - Aleksandr Alekseev, aleksandr.alekseev@cern.ch, 2022 # - Paul Nilsson, paul.nilsson@cern.ch, 2022 from abc import ABC, abstractmethod from typing import Iterator, Union import...
the-stack_0_14965
# Copyright 2016-2020 The Matrix.org Foundation C.I.C. # Copyright 2020 Sorunome # # 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_14966
import argparse import asyncio from pybecker.becker import Becker async def main(): """Main function""" parser = argparse.ArgumentParser() parser.add_argument('-c', '--channel', required=True, help='channel') parser.add_argument('-a', '--action', required=True, help='Command to execute (UP, DOWN, HAL...
the-stack_0_14967
"""Adapted from: @longcw faster_rcnn_pytorch: https://github.com/longcw/faster_rcnn_pytorch @rbgirshick py-faster-rcnn https://github.com/rbgirshick/py-faster-rcnn Licensed under The MIT License [see LICENSE for details] """ from __future__ import print_function import torch import torch.nn as nn import to...
the-stack_0_14968
import torch.nn as nn from mmcv.cnn import ConvModule from mmcv.cnn import constant_init, kaiming_init from ..builder import BACKBONES import os from mmdet.ops.CSPOSAModule import CSPOSAModule class ConvStride2(nn.Module): def __init__(self, in_ch, out_ch, kernel_size=3, exp=1, norm_cfg=dict(type='BN', requires_gr...
the-stack_0_14969
import Eva from collections import defaultdict from cdlib import AttrNodeClustering import networkx as nx from cdlib.utils import convert_graph_formats from cdlib.algorithms.internal.ILouvain import ML2 __all__ = ["eva", "ilouvain"] def eva( g_original: object, labels: dict, weight: str = "weight", ...
the-stack_0_14973
total = 0 line = input() while line != "NoMoreMoney": current = float(line) if current < 0: print("Invalid operation!") break total += current print(f"Increase: {current:.2f}") line = input() print(f"Total: {total:.2f}")
the-stack_0_14974
import logging from concurrent.futures import ProcessPoolExecutor from functools import partial from typing import Iterable, List import pandas as pd from pyarrow import parquet as pq from feast.constants import DATETIME_COLUMN from feast.feature_set import FeatureSet from feast.type_map import ( pa_column_to_pro...
the-stack_0_14976
#!/usr/bin/env python # -*- coding: utf-8 -*- # SPDX-License-Identifier: AMPAS # Copyright Academy of Motion Picture Arts and Sciences """ Defines unit tests for *ACES* configuration. """ from __future__ import division import hashlib import os import re import shutil import sys import tempfile import unittest sys....
the-stack_0_14977
from plotly.basedatatypes import BaseTraceHierarchyType import copy class Titlefont(BaseTraceHierarchyType): # color # ----- @property def color(self): """ The 'color' property is a color and may be specified as: - A hex string (e.g. '#ff0000') - An rgb/rgba string...
the-stack_0_14978
import config import telebot bot = telebot.TeleBot(config.token) @bot.message_handler(commands=['start']) def start_message(message): keyboard = telebot.types.ReplyKeyboardMarkup(True) keyboard.row('Добавить вещь', 'Найти вещь') bot.send_message(message.chat.id, '''Привет! Я помогу тебе обменять что-...
the-stack_0_14979
import Backends import random import numpy as np from .theano_helpers import floatX def create_dropout_masks(route, fname, dimensionality, ks=1000): """ route = path where to create a file fname = filename ks = thousand of masks to create (1e6 masks by default) """ hdf5_backend = Backends.HDF5...
the-stack_0_14981
# -*- coding: utf-8 -*- import numpy as np import pandas as pd from pandas.api.types import is_string_dtype from pandas.api.types import is_numeric_dtype import re import warnings import multiprocessing as mp import matplotlib.pyplot as plt import time import os import platform from .condition_fun import * from .info_...
the-stack_0_14984
# -*- coding: utf-8 -*- from jqdatasdk import auth, query, indicator, get_fundamentals, logout from zvdata.api import get_data from zvdata.utils.pd_utils import df_is_not_null from zvt.api.api import get_finance_factors from zvt.api.common import to_jq_entity_id, to_jq_report_period from zvt.domain import FinanceFacto...
the-stack_0_14985
import numpy as np import pytest from devito.logger import info from devito import norm, configuration from examples.seismic.viscoacoustic import ViscoacousticWaveSolver from examples.seismic import demo_model, setup_geometry, seismic_args def viscoacoustic_setup(shape=(50, 50), spacing=(15.0, 15.0), tn=500., space_...
the-stack_0_14987
import traceback from urllib.parse import urlparse import click import timeago from metaflowbot.cli import action from metaflowbot.message_templates.templates import error_message from metaflowbot.state import MFBState MAX_ARTIFACT_SIZE = 1000 import json import requests def random_joke(): ENDPOINT = r"https:...
the-stack_0_14988
""" Network tools to run from the Master """ import logging import socket import salt.utils.files import salt.utils.network import salt.utils.stringutils log = logging.getLogger(__name__) def wollist(maclist, bcast="255.255.255.255", destport=9): """ Send a "Magic Packet" to wake up a list of Minions. ...
the-stack_0_14989
#!/usr/bin/python # Copyright 2014 Google. # # 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...
the-stack_0_14990
"""StudentHomepage URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Cla...
the-stack_0_14991
# This code gives back JSON file for: # --> only in the documents where this word appears: how many time does the word appears on average import os import json count_file = 0 word_count = 0 word_dic = {} result_dic = {} # This is path of data folder path = '/media/neel/Extra/gigaword_eng_5/data/afp_eng/' # This is p...
the-stack_0_14993
import discord from discord.ext import commands from asyncdagpi import ImageFeatures class Image(commands.Cog): def __init__(self, bot): self.bot = bot @commands.command() async def colors(self, ctx, member:discord.Member=None): if member is None: member = ctx.author ...
the-stack_0_14994
import json from argparse import ArgumentParser from ibm_watson import AssistantV1 from ibm_cloud_sdk_core.authenticators import IAMAuthenticator import dateutil.parser import datetime import time DEFAULT_WCS_VERSION='2018-09-20' DEFAULT_PAGE_SIZE=500 DEFAULT_NUMBER_OF_PAGES=20 def getAssistant(iam_apikey, url, versi...
the-stack_0_14996
from __future__ import division import numpy as np import seaborn as sns import sys from sys import platform as sys_pf if sys_pf == 'Darwin': import matplotlib matplotlib.use("TkAgg") from mpl_toolkits.mplot3d import Axes3D from matplotlib import pyplot as plt def normalize(v): norm=np.linalg.norm(v) ...
the-stack_0_14998
import random import numpy as np import sys from domain.make_env import make_env from domain.task_gym import GymTask from neat_src import * class WannGymTask(GymTask): """Problem domain to be solved by neural network. Uses OpenAI Gym patterns. """ def __init__(self, game, paramOnly=False, nReps=1): """Ini...
the-stack_0_15000
from socket import * import threading class RecvThread(threading.Thread): def __init__(self, s, bufsize): if not isinstance(s, socket): raise TypeError super(RecvThread, self).__init__() self.s = s self.bufsize = bufsize def run(self): while Tr...
the-stack_0_15001
from typing import List, Any, Sequence from .util import MLP, ThreadedIterator, SMALL_NUMBER import tensorflow as tf import numpy as np import time import pickle import os import shutil class GGNN(object): @classmethod def default_params(cls): return { 'num_epochs': 1, 'patien...
the-stack_0_15003
import os import logging import boto3 from botocore.exceptions import ClientError from datetime import datetime as dt import json logger = logging.getLogger() logger.setLevel(logging.INFO) TABLE_NAME = "aqa_scores" VIDEO_NAME_KEY = 'videoName' VIDEO_SCORE_KEY = 'videoScore' def handler(event, context): try: ...
the-stack_0_15004
import ast import re from abc import ABC, abstractmethod from dataclasses import dataclass from enum import Enum from pathlib import PurePath from typing import Callable, Dict, List, Optional, Sequence, TypeVar, Union from .logging import log from .utils import fmt_path, str_path class ArrowHead(Enum): NORMAL = ...