text
stringlengths
1
927k
# 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...
# Scrapy settings for scrapy project # # For simplicity, this file contains only settings considered important or # commonly used. You can find more settings consulting the documentation: # # https://docs.scrapy.org/en/latest/topics/settings.html # https://docs.scrapy.org/en/latest/topics/downloader-middleware....
from .baseeffect import BaseEffect from .genericeffect import GenericEffect from .endbattleeffect import EndBattleEffect from ..pokefighter import PokeFighter import math STATUS_BONUSES = { "Paralysis": 1.5, "Sleep": 2.5, "Freeze": 2.5, "Burn": 1.5, "Poison": 1.5, "BadPoison": 1.5, } class B...
#!/usr/bin/env python3 """ L2 regularization layer """ import tensorflow as tf def l2_reg_create_layer(prev, n, activation, lambtha): """ l2 regularization layer """ reg = tf.contrib.layers.l2_regularizer(scale=lambtha) w = tf.contrib.layers.variance_scaling_initializer(mode='FAN_AVG') layer...
# Copyright 2017 Intel 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 agreed to in wri...
#-*-encoding:utf-8-*- import os, logging def test_data_loader(root_path): """ 문장을 리턴한다. return: list of sentence """ data_path = os.path.join(root_path, 'test', 'test_data') return _load_data(data_path, is_train=False) def local_test_data_loader(root_path): """ 문장을 리턴한다. return: list of sentence """ data_p...
from django.contrib.syndication.views import Feed from django.urls import reverse_lazy from .models import Job class JobFeed(Feed): """ Python.org Jobs RSS Feed """ title = "Python.org Jobs Feed" description = "Python jobs from Python.org" link = reverse_lazy('jobs:job_list') def items(self): ...
from b2sdk.v1 import InMemoryAccountInfo, B2Api from b2sdk.v1 import Bucket as B2Bucket from b2sdk.exception import InvalidAuthToken from typing import List info = InMemoryAccountInfo() class Account: def __init__(self, name: str, keys: list): self.api = B2Api(info) self.name = name sel...
# coding: utf-8 """ Sunshine Conversations API The version of the OpenAPI document: 9.4.5 Generated by: https://openapi-generator.tech """ import pprint import re # noqa: F401 import six from sunshine_conversations_client.configuration import Configuration from sunshine_conversations_client.undefine...
## proj11: Tests import proj11 from proj11 import addStar from proj11 import harmonicSum from proj11 import isPalindrome from proj11 import replace # from fractions import gcd ## Uncomment tests as you need them! ########### sumList ############### def sumList_test(lst): if proj11.sumList(lst) == sum(lst): ...
import numpy as np from .shape import Shape from .._shapes_utils import find_corners, rectangle_to_box class Rectangle(Shape): """Class for a single rectangle Parameters ---------- data : (4, D) or (2, 2) array Either a (2, 2) array specifying the two corners of an axis aligned rectan...
from data import COCODetection, get_label_map, MEANS, COLORS from yolact import Yolact from utils.augmentations import BaseTransform, FastBaseTransform, Resize from utils.functions import MovingAverage, ProgressBar from layers.box_utils import jaccard, center_size from utils import timer from utils.functions import Sav...
# coding: utf-8 """ Xero Payroll AU This is the Xero Payroll API for orgs in Australia region. # noqa: E501 OpenAPI spec version: 2.3.4 Contact: api@xero.com Generated by: https://openapi-generator.tech """ import re # noqa: F401 from xero_python.models import BaseModel class LeaveType(Bas...
#!/usr/bin/env python3 import rospy from std_msgs.msg import String from geometry_msgs.msg import Twist mag=0.0 dir=0.0 max_linear_speed = 1.0 max_rotational_speed = 2.5 def callback_vector(msg): global mag, dir mag,dir = float(msg.data.split(",")[0]),float(msg.data.split(",")[1]) def obs_avoider(): g...
""" Clean a DataFrame column containing text data. """ import re import string from functools import partial, update_wrapper from typing import Any, Callable, Dict, List, Optional, Set, Union from unicodedata import normalize import dask.dataframe as dd import numpy as np import pandas as pd from ..assets.english_sto...
import dataclasses import json import os import warnings from dataclasses import dataclass, field from enum import Enum from typing import Any, Dict, List, Optional, Tuple from .file_utils import cached_property, is_torch_available, is_torch_tpu_available, torch_required from .trainer_utils import EvaluationStrategy f...
import torch import torch import torch.nn as nn import torch.nn.utils import torch.nn.functional as F from torch.autograd import Variable from torch.nn.utils.rnn import pad_packed_sequence, pack_padded_sequence import torch.nn.functional as F import numpy as np from torch.nn.init import xavier_normal_ from transformers...
def problem263(): pass
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2021 Huawei Device Co., 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 # #...
"""Certbot constants.""" import logging import pkg_resources from acme import challenges from certbot.compat import misc from certbot.compat import os SETUPTOOLS_PLUGINS_ENTRY_POINT = "certbot.plugins" """Setuptools entry point group name for plugins.""" OLD_SETUPTOOLS_PLUGINS_ENTRY_POINT = "letsencrypt.plugins" ""...
# Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd import pickle from sklearn.linear_model import LinearRegression from sklearn.preprocessing import MinMaxScaler as mini from sklearn.model_selection import train_test_split # Importing the libraries import numpy as np import...
import os import cv2 import numpy as np import xml.etree.ElementTree as ET import matplotlib matplotlib.use("TkAgg") from matplotlib import pyplot as plt # cf. nas/repos/cloud-colorizer/projection/... and repos/projection_utils/... class View: """ View class representing the extrinsics and intrinsics of an imag...
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2018, 2019, 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. #...
#!/usr/bin/env python3 import asyncio from pyrevolve import parser from pyrevolve.evolution import fitness from pyrevolve.evolution.selection import multiple_selection, tournament_selection from pyrevolve.evolution.population import Population, PopulationConfig from pyrevolve.evolution.pop_management.steady_state impo...
from typing import List from collections import deque # Definition for a Node. class Node: def __init__(self, val=None, children=None): self.val = val self.children = children class Solution: # This is a spin-off of my third solution to LeetCode #589. Once I had # that one working, this...
from typing import Any, Callable, Dict, List, Optional import torch from PIL import Image class ImageDataset(torch.utils.data.Dataset): def __init__( self, imgs: List[str], transform: Optional[Callable[[Image.Image], Any]] = None ): assert isinstance(imgs, (list, tuple)) super().__ini...
# -*- coding: utf-8 -*- # Copyright 2021-2022 CERN # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
# Copyright 2015 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed ...
# Pyrogram - Telegram MTProto API Client Library for Python # Copyright (C) 2017-2018 Dan Tès <https://github.com/delivrance> # # This file is part of Pyrogram. # # Pyrogram is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published # by the Free S...
import re from datetime import datetime from uuid import UUID from enum import Enum, auto from graphql.language.source import Source from graphql.language.parser import parse from graphql.language.ast import ( ObjectTypeDefinition, NamedType, NonNullType, ListType, InputObjectTypeDefinition, E...
#!/usr/bin/env python # Description: If you need enable debug mode use this script to allow that the # Adafruit HUZZAH ESP8266 prints messages in the serial port of the activity # that it is executed # Author: Edward U. Benitez Rendon # Date: 11-07-17 import paho.mqtt.client as mqtt import time import argparse parse...
"""Indy SDK verifier implementation.""" import json import logging import indy.anoncreds from indy.error import IndyError from ...core.profile import Profile from ..verifier import IndyVerifier LOGGER = logging.getLogger(__name__) class IndySdkVerifier(IndyVerifier): """Indy-SDK verifier implementation.""" ...
# Processes the ticket deletion confirmation from Script.import_emojis import Emojis from Script.import_functions import create_embed async def reaction_add_close_ticket(self, reaction, member): if (reaction.emoji in [Emojis["Yes"], Emojis["No"]]) and (reaction.message.embeds[0].title == "Close this ticket"): ...
import section import pytest # 作成 class Test_2つの整数を引数に閉区間オブジェクトをつくる: def test_3から8の閉区間を作れる(self): x=section.Section(3,8) assert x.lower==3 and x.upper==8 def test_3から8の閉区間を作れる(self): x=section.Section(3,3) assert x.lower==3 and x.upper==3 # 作成(例外処理) class Test_整数以外では閉区間オブジェクトをつ...
#!/usr/bin/env python # This file is part of ObjectPath released under MIT license. # Copyright (C) 2010-2014 Adrian Kalbarczyk import sys, re from .parser import parse from objectpath.core import * import objectpath.utils.colorify as color # pylint: disable=W0614 from objectpath.utils import flatten, filter_dict, t...
"""Module with Kytos Events.""" from kytos.core.helpers import now class KytosEvent: """Base Event class. The event data will be passed in the `content` attribute, which should be a dictionary. """ def __init__(self, name=None, content=None): """Create an event to be published. ...
import pytest import matplotlib.pyplot as plt import numpy as np from py_wake.deficit_models import SelfSimilarityDeficit from py_wake.deficit_models.no_wake import NoWakeDeficit from py_wake.deficit_models.noj import NOJDeficit from py_wake.examples.data import hornsrev1 from py_wake.examples.data.hornsrev1 import Ho...
from pydantic import BaseSettings, Field, PositiveInt _MINUTE = 60 _HOUR = 60 * _MINUTE class ServicesCommonSettings(BaseSettings): # set this interval to 1 hour director_dynamic_service_save_timeout: PositiveInt = Field( _HOUR, description=( "When stopping a dynamic service, if i...
# count() # Number of elements in the RDD is returned. from pyspark import SparkContext sc = SparkContext("local", "count app") words = sc.parallelize ( ["scala", "java", "hadoop", "spark", "akka", "spark vs hadoop", "pyspark", "pyspark and spark"] ) counts = words.count() print "Number of ...
import hashlib import random from datetime import timedelta from typing import Any, Dict, List, Mapping, Optional, Sequence, Set, Union from unittest import mock import orjson from django.conf import settings from django.core.exceptions import ValidationError from django.http import HttpResponse from django.utils.time...
class MyClass: def my_function(self, n): return n
import unittest from collections import OrderedDict from fractions import Fraction from searches.binary_search import find_lower class MyTestCase(unittest.TestCase): def test_binary_search(self): lisst = [1, 7, 9, 14, 23, 80] lisst[find_lower(lisst, 80)] for i in range(1, 81): ...
import asyncio import pytest import aioodbc from aioodbc import Pool, Connection from pyodbc import Error @pytest.mark.asyncio async def test_create_pool(loop, pool_maker, dsn): pool = await pool_maker(loop, dsn=dsn) assert isinstance(pool, Pool) assert 10 == pool.minsize assert 10 == pool.maxsize ...
""" Lupe: The CLI helper you need lupe(help_message, options?) Example: ```python import lupe cli = lupe('usage: foo [options]') # display help cli.show_help() ``` Read more on the [documentation](https://github.com/abranhe/lupe) """ import sys from lupe.core import Lupe __version__ = '0.1.12' sys.modules[__n...
""" Faça um programa que tenha uma função chamada escreva(), que recebe um texto qualquer como parâmetro e mostre uma mensa- gem com tamanho adaptável. ex: escreva('Olá, Mundo!') saída: ---------- Olá Mundo! ---------- """ def escreva(msg): tam = len(msg) + 5 print('~'*tam) print(f'{msg:^{tam}}') prin...
# -*- coding: utf-8 -*- # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved from detectron2.config import CfgNode as CN def add_detr_config(cfg): """ Add config for DETR. """ cfg.MODEL.DETR = CN() cfg.MODEL.DETR.NUM_CLASSES = 2 # For Segmentation cfg.MODEL.DETR.FROZEN_W...
import struct import logging import asyncio from bitarray import bitarray from migen import * from migen.genlib.cdc import MultiReg from ....support.pyrepl import * from ....gateware.pads import * from ....database.jedec import * from ....arch.jtag import * from ... import * class JTAGProbeBus(Module): def __ini...
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import json from threading import Event import time from odoo.http import request class EventManager(object): def __init__(self): self.events = [] self.sessions = {} def _delete_expired_session...
import sqlite3 import os class DB: def __init__(self): path= os.path.dirname(os.path.abspath(__file__)) self.filename = path + "/database.db" self.dbfile = sqlite3.connect(self.filename) self.dbcursor = self.dbfile.cursor() self.create_db() def create_db(self): ...
# 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 u...
from social_core.backends.oauth import BaseOAuth2 class AtlassianOAuth2(BaseOAuth2): name = 'atlassian' AUTHORIZATION_URL = 'https://auth.atlassian.com/authorize' ACCESS_TOKEN_METHOD = 'POST' ACCESS_TOKEN_URL = 'https://auth.atlassian.com/oauth/token' DEFAULT_SCOPE = ['read:jira-user', 'offline_ac...
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.FileItem import FileItem from alipay.aop.api.constant.ParamConstants import * from alipay.aop.api.domain.AlipayFundAuthOrderFreezeModel import AlipayFundAuthOrderFreezeModel class AlipayFundAuthOrderFreezeRequest(object): def __init...
from torchtools import * from data import MiniImagenetLoader, TieredImagenetLoader, TieredImagenetLoaderCustom from model import EmbeddingImagenet, GraphNetwork, ConvNet import shutil import os import random #import seaborn as sns class ModelTrainer(object): def __init__(self, enc_module, ...
import skimage.io as io import numpy as np import os def to_0_255_format_img(in_img): max_val = in_img[:,:].max() if max_val <= 1: out_img = np.round(in_img * 255) return out_img.astype(np.uint8) else: return in_img def to_0_1_format_img(in_img): max_val = in_img[:,:].max() i...
import flask
import argparse import random from copy import deepcopy import torch import torch.backends from torch import optim from torch.hub import load_state_dict_from_url from torch.nn import CrossEntropyLoss from torchvision import datasets from torchvision.models import vgg16 from torchvision.transforms import transforms fro...
import setuptools with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name="json-graph-lite", version="0.8a0", author="Roman Suzi", author_email="roman.suzi@gmail.com", description="Lightweight graph implementation with JSON serialization", long_description=lo...
import numpy as np from ..base.mixins import RandomStateMixin from ..policies.base import BasePolicy from ..utils import argmax __all__ = ( 'EpsilonGreedy', # 'BoltzmannPolicy', #TODO: implement ) class EpsilonGreedy(BasePolicy, RandomStateMixin): """ Value-based policy to select actions using eps...
#!/usr/bin/env python # Copyright (c) Facebook, Inc. 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. import unittest import parlai.utils.testing as testing_utils """ Integration tests for the Controllable Dialogue project...
#!/usr/bin/env python # vim: ai ts=4 sts=4 et sw=4 from django.urls import path from . import views urlpatterns = ( path('', views.registration, name="registration"), path('contact/add/', views.contact, name="registration_contact_add"), path('contact/bulk_add/', views.contact_bulk_add, name="registration...
# -*- coding: utf-8 -*- #BEGIN_HEADER import logging import os import copy import traceback import json from biokbase.workspace.client import Workspace from installed_clients.DataFileUtilClient import DataFileUtil from installed_clients.KBaseReportClient import KBaseReport #END_HEADER class Coveringarray: ''' ...
import os import shutil from hummingbot.client.config.config_var import ConfigVar from hummingbot.core.utils.async_utils import safe_ensure_future from hummingbot.client.config.config_helpers import ( get_strategy_config_map, parse_cvar_value, default_strategy_file_path, save_to_yml, get_strategy_t...
import fileinput, math ### ### # utility func # ### ### dbug = True def pd(s, label=''): global dbug if dbug: header = 'debug:' if label != '': header += ' (%s)\t' % label print header, s def stoi(s): return([ int(x) for x in s.split() ]) def perm(n, k, wheels=True): if wheels: ass...
"""Script to play the allocation game based on the previously trained policies """ # external imports import os import random import copy import numpy as np import sys from numpy.random import permutation import rl_setup def play(patient_list, doc_stats, folder_name, rounds=10): patients = patient_list doc...
from setuptools import setup, find_packages from setuptools.command.install import install import os import io SETUP_DIR = os.path.dirname(os.path.abspath(__file__)) # List all of your Python package dependencies in the # requirements.txt file def readfile(filename, split=False): with io.open(filename, encoding...
import os import logging from configobj import ConfigObj, ConfigObjError from iredis import project_data # TODO verbose logger to print to stdout logger = logging.getLogger(__name__) system_config_file = "/etc/iredisrc" default_config_file = os.path.join(project_data, "iredisrc") pwd_config_file = os.path.join(os.g...
num = int(input('Enter a number: ')) def find_divisors(num): divisors = [] for i in range(1, num + 1): if num % i == 0: divisors.append(i) return divisors print('Divisors: ', find_divisors(num)) print('Divisors Sum: ', sum(find_divisors(num))) print('Divisors Count: ', len(find_divis...
'''OpenGL extension APPLE.vertex_array_object This module customises the behaviour of the OpenGL.raw.GL.APPLE.vertex_array_object to provide a more Python-friendly API Overview (from the spec) This extension introduces named vertex array objects which encapsulate vertex array state on the client side. The main ...
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: google/protobuf/duration.proto from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_data...
import logging from contextlib import contextmanager import requests from flask_babel import lazy_gettext as _ from requests import HTTPError, Request from core.exceptions import BaseError from core.model import DeliveryMechanism from core.model.configuration import ( ConfigurationAttributeType, Configuration...
# # Copyright (c) 2009-2015, Jack Poulson # All rights reserved. # # This file is part of Elemental and is under the BSD 2-Clause License, # which can be found in the LICENSE file in the root directory, or at # http://opensource.org/licenses/BSD-2-Clause # import El, time n0=20 n1=20 output = False display = Tr...
import collections import cProfile import csv from pathlib import Path profiler = cProfile.Profile() profiler.disable() Record = collections.namedtuple( 'Record', 'airline, fatal_accidents_85_99, fatalities_85_99, ' 'fatal_accidents_00_14, fatalities_00_14' ) def parse_row(row): record = Record( ...
import http.cookiejar import secrets import tempfile import time from unittest.mock import MagicMock import pytest import requests import requests_mock from requests.utils import CaseInsensitiveDict from ansys.openapi.common import SessionConfiguration from ansys.openapi.common._session import _RequestsTimeoutAdapter...
## Mocking Bot - Task 1.1: Note Detection # Instructions # ------------ # # This file contains Main function and note_detect function. Main Function helps you to check your output # for practice audio files provided. Do not make any changes in the Main Function. # You have to complete only the note_detect functio...
from django.apps import apps from organizational_area.models import OrganizationalStructure from uni_ticket.utils import user_is_in_default_office def chat_operator(user, structure_slug): if not structure_slug: return False if not user: return False structure = OrganizationalStructure.objects.filter(slug...
import pandas as pd # type: ignore import numpy as np
from __future__ import absolute_import from __future__ import division from __future__ import print_function import math import numpy as np import scipy as sp from sklearn import metrics class Evaluation(object): """ Assumes: predicted: matrix of label prediction confidence [trial, tag] eval_...
from ..core import WesternCalendar, FRI from ..registry_tools import iso_register @iso_register('MH') class MarshallIslands(WesternCalendar): "Marshall Islands" FIXED_HOLIDAYS = WesternCalendar.FIXED_HOLIDAYS + ( (3, 3, "Remembrance Day"), (5, 1, "Constitution Day"), (11, 17, "Presiden...
import argparse import sys from pathlib import Path # from ml_volatility.algos.extractor import Extractor # from ml_volatility.algos.extractor import ExtractorWithJumps from ml_volatility.algos.extractor import FinalExtractor # Default paths for intermediate output files, meta paths DATA_PATH: Path = Path(__file__).p...
"""Define RNN-based decoders.""" import inspect import tensorflow as tf from tensorflow.python.estimator.util import fn_args from opennmt.decoders.decoder import Decoder, logits_to_cum_log_probs, build_output_layer from opennmt.utils.cell import build_cell class RNNDecoder(Decoder): """A basic RNN decoder.""" ...
from reportlab.pdfgen import canvas from reportlab.lib.pagesizes import LETTER class FooterCanvas(canvas.Canvas): def __init__(self, *args, is_booklet=False, font_name='Times-Roman', **kwargs): canvas.Canvas.__init__(self, *args, **kwargs) self.pages = [] self.is_booklet = is_booklet ...
from PyQuantum.Tools.CSV import * import plotly.graph_objs as go import numpy as np from PyQuantum.Tools.PlotBuilder2D import * # data = [] # data.append(go.Scatter( # x=[1, 2, 3], # y=[4, 5, 6], # name="w_0['title']", # )) # plot_builder = PlotBuilder2D({ # 'title': 'M[p<sub>sink</sub>]<sub>|t<sub>0...
""" Layout blocks are essentially a wrapper around content. e.g. rows, columns, hero units, etc. """ from django.utils.translation import ugettext_lazy as _ from wagtail.core import blocks from wagtail.images.blocks import ImageChooserBlock from coderedcms.settings import cr_settings from .base_blocks import BaseLay...
# # Copyright (c) 2020 Lucas Lehnert <lucas_lehnert@brown.edu> # # This source code is licensed under an MIT license found in the LICENSE file in the root directory of this project. # from itertools import product, combinations import numpy as np import rlutils as rl from rlutils.environment.gridworld import pt_to_idx...
# Generated by Django 2.1.1 on 2018-09-07 21:37 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('shop', '0006_auto_20180907_1837'), ] operations = [ migrations.AlterField( model_name='order', name='ordertoral', ...
#!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'wwttms.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportE...
import sys import numpy as np import pandas as pd def main(): df = pd.read_csv(sys.argv[1], names=["Method", "Time"]) print(df.groupby("Method").describe().to_csv()) if __name__ == "__main__": main()
# # Copyright (c) 2016 GigaSpaces Technologies Ltd. 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 requ...
import rethinkdb as r class BibleCrawlerConnection(object): def __init__(self, version: str, url: str, books): self.connection = r.connect("localhost", 28015) self.DB = r.db("bible") self.table = self.setup_table(version) self.create_books(books) def setup_table(self, bible_v...
from credentials import *
from Pathfinder import PathFinder import numpy as np import winsound def generate_map_collage(): maps_coords = pf.get_maps_coords() maps = [] shape = (abs(end[1] - start[1]) + 1, abs(end[0] - start[0]) + 1) counter = 0 for coord in maps_coords: map_infos = pf.llf.coord_fetch_map(coord, pf....
# -*- coding: utf-8 -*- # PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN: # https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code from ccxt.base.exchange import Exchange import math from ccxt.base.errors import ExchangeError from ccxt.base.errors import AuthenticationE...
# Copyright (C) 2015 KillerInstinct, Updated 2017 for Cuckoo 2.0 # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # T...
from midigen import heightmap map = heightmap.diamond_square(8, 0.5, "Math Center", None) map = heightmap.heightmap_normalize(map) print("Map in memory") heightmap.heightmap_to_png(map, "mathcenter")
import pytest import torch import torch.nn.functional as F from lean_transformer.utils import pad_to_multiple, GELU import numpy as np @pytest.mark.forked def test_pad_to_multiple(): x = torch.randn(3, 3) assert pad_to_multiple(x, multiple=3, dims=0) is x assert pad_to_multiple(x, multiple=3, dims=1) is ...
# Copyright 2021 The Kubeflow 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 applicabl...
# Copyright The Linux Foundation and each contributor to CommunityBridge. # SPDX-License-Identifier: MIT """ The entry point for the CLA service. Lays out all routes and controller functions. """ import hug from falcon import HTTP_401 from hug.middleware import LogMiddleware import cla import cla.auth import cla.con...
import dash from dash.dependencies import Output, Input import dash_core_components as dcc import dash_html_components as html import plotly import random import plotly.graph_objs as go from collections import deque X = deque(maxlen=20) X.append(1) Y = deque(maxlen=20) Y.append(1) app = dash.Dash(__name__) app.layou...
# Copyright (c) ACSONE SA/NV 2018 # Distributed under the MIT License (http://opensource.org/licenses/MIT). import ast import logging import os from functools import wraps from .pypi import MultiDistPublisher, RsyncDistPublisher, TwineDistPublisher _logger = logging.getLogger("oca_gihub_bot.tasks") def switchable(...
# -*- coding: utf-8 -*- ########################################################################### # Copyright (c), The AiiDA team. All rights reserved. # # This file is part of the AiiDA code. # # ...