text
stringlengths
2
999k
#!/usr/bin/env python """Planner class that derives from search based planner. It defines festure calculation, normalization and heuristic calculation. The train and test planner derive from this planner""" from collections import defaultdict from math import atan2, pi import numpy as np import time from planning_py...
#!/usr/bin/env python3 # 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. r"""Registry is central source of truth in Habitat. Taken from Pythia, it is inspired from Redux's concept of global st...
import numpy as np import scipy.misc import IPython logsumexp = scipy.misc.logsumexp class GoalPredictor(object): max_prob_any_goal = 0.99 log_max_prob_any_goal = np.log(max_prob_any_goal) def __init__(self, goals): self.goals = goals self.log_goal_distribution = np.log((1./len(self.goals))*np.ones(len(...
import os def onoff(v): if v in ["yes", "1", "on"]: return True elif v in ["no", "0", "off"]: return False raise ValueError(f"invalid {v}") def argparser(parser): """Default argument parser for regressions. """ parser.add_argument("--local", action="store_true", ...
from .. import Provider as PhoneNumberProvider class Provider(PhoneNumberProvider): formats = ( '69########', '69## ######', '69## ### ###', '210#######', '210 #######', '210 ### ####', '2##0######', '2##0 ######', '2##0 ### ###', ...
# # Here we define common geometric primitives along with utilities # allowing to find distance from point to the line, to find intersection point # of two lines, and to find the length of the line in two dimensional Euclidean # space. # import math def deg_to_rad(degrees): """ The function to convert degrees...
""" Copyright (c) 2008-2020, Jesus Cea Avion <jcea@jcea.es> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of...
import boto3 from uuid import uuid4 from collections import defaultdict import time from pandas import DataFrame import datetime import numpy as np import pandas import requests pandas.set_option( "display.max_rows", None, "display.max_columns", None, "display.width", 1000, "display.max_colwidth", None ) def get...
from os.path import dirname, join from setuptools import find_packages, setup KEYWORDS = [] CLASSIFIERS = [ 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: Implementation :: CPython', 'Program...
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: inertial.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _refl...
from ledger.accounts.models import EmailUser from rest_framework import serializers from rest_framework_gis.serializers import GeoFeatureModelSerializer from disturbance.components.approvals.models import ApiarySiteOnApproval from disturbance.components.main.utils import get_category, get_tenure, get_region_district, ...
# Need to import path to test/fixtures and test/scripts/ # Ex : export PYTHONPATH='$PATH:/root/test/fixtures/:/root/test/scripts/' # # To run tests, you can do 'python -m testtools.run tests'. To run specific tests, # You can do 'python -m testtools.run -l tests' # Set the env variable PARAMS_FILE to point to your ini ...
# -*- coding: utf-8 -*- ################################################################################ # _____ _ _____ _ # # / ____(_) / ____| | | # # | | _ ___ ___ ___ | (___ _ _ ___...
""" Mask R-CNN The main Mask R-CNN model implemenetation. Copyright (c) 2017 Matterport, Inc. Licensed under the MIT License (see LICENSE for details) Written by Waleed Abdulla """ import os import random import datetime import re import math import logging from collections import OrderedDict import multiprocessing i...
import program.program as program if __name__ == "__main__": # Entry point for Robomaster S1 programs. Actual code should be # in the program directory. program.start()
"""Applies a LUT to a GeoTIFF""" import argparse import os import numpy as np from osgeo import gdal, osr def geotiff_lut(geotiff, lutFile, outFile): # Suppress GDAL warnings gdal.UseExceptions() gdal.PushErrorHandler('CPLQuietErrorHandler') # Read GeoTIFF and normalize it (if needed) inRaster = gdal.Op...
#!/usr/bin/env python # # Electrum - lightweight Bitcoin client # Copyright (C) 2015 Thomas Voegtlin # # 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...
# Time: O(n), per operation # Space: O(1) # # Implement a trie with insert, search, and startsWith methods. # # Note: # You may assume that all inputs are consist of lowercase letters a-z. # class TrieNode: # Initialize your data structure here. def __init__(self): self.is_string = False self....
import copy import logging import random import time import numpy as np import torch import wandb from .utils import transform_list_to_tensor class FedAVGAggregator(object): def __init__(self, train_global, test_global, all_train_data_num, train_data_local_dict, test_data_local_dict, train_data...
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union from ... import _utilities, _tables from...
import numpy as np import urllib.request, json, time, os, copy, sys from scipy.optimize import linprog from collections import defaultdict as ddict global penguin_url, headers penguin_url = 'https://penguin-stats.io/PenguinStats/api/' headers = {'User-Agent':'ArkPlanner'} Price = dict() with open('price.txt', 'r', en...
# Copyright (C) 2020 Google Inc. # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> """Tests export functionality.""" from integration.ggrc import generator from integration.ggrc import TestCase from integration.ggrc.models import factories class TestBasicExport(TestCase): """Test basic ...
def answer_type(request, json_list, nested): for question in json_list: if question['payload']['object_type'] == 'task_instance': question['answer_class'] = 'task_answer'
# -*- coding: utf-8 -*- __version__ = '0.4.0'
from dataclasses import dataclass, field import sphinxcontrib.bibtex.plugin from sphinxcontrib.bibtex.style.referencing import BracketStyle from sphinxcontrib.bibtex.style.referencing.author_year \ import AuthorYearReferenceStyle def bracket_style() -> BracketStyle: return BracketStyle( left='(', ...
#!/usr/bin/env python # -*- coding: utf8 -*- import setuptools from setuptools.command.develop import develop from setuptools.command.install import install class DevelopScript(develop): def run(self): develop.run(self) ntlk_install_packages() class InstallScript(install): def run(self): ...
import pandas as pd import random from math import floor def train_val_split(df, perc): random.seed(966) pop = int(df.shape[0]) k = floor(pop*perc) sample = random.sample(list(range(pop)), k) train = df[df.index.isin(sample)] val = df[~df.index.isin(sample)] return train, val if __na...
''' Script to migrate users to the ESGF database. Rules: 1) non-local users (i.e. users that logged onto CoG with an external openid) are ignored 2) if a user is local but has no local openid, look for ESGF users with that same email: a) if found, try to associate that openid to the CoG user, if possible b) if...
import os os.environ["CUDA_VISIBLE_DEVICES"] = "-1" import json import time from nas_big_data.covertype.problem_ae import Problem from nas_big_data.covertype.load_data import load_data _, (X_test, y_test) = load_data(use_test=True) arch_seq = [ 9, 1, 30, 1, 1, 28, 1, 1, 0, 2...
""" Support for DLNA DMR (Device Media Renderer). For more details about this platform, please refer to the documentation at https://home-assistant.io/components/media_player.dlna_dmr/ """ import asyncio from datetime import datetime from datetime import timedelta import functools import logging import aiohttp import...
"""Implementation for dbus.Bus. Not to be imported directly.""" # Copyright (C) 2003, 2004, 2005, 2006 Red Hat Inc. <http://www.redhat.com/> # Copyright (C) 2003 David Zeuthen # Copyright (C) 2004 Rob Taylor # Copyright (C) 2005, 2006 Collabora Ltd. <http://www.collabora.co.uk/> # # Permission is hereby granted, free ...
"""[Node for all modules, Takes all funstions here for the main file] """ from SetNoti import * from Speech import * # imports speech_recognition as sr from BOOT import * # imports pandas as pd, os, PasswordGenerator from Mails.BootMails import * # imports SendmMails from Authentication.FaceDetection import * # im...
# Copyright 2013-2019 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class SpectrumMpi(Package): """IBM MPI implementation from Spectrum MPI.""" homepage = "htt...
from anygraph import Many class Node(object): nexts = Many('prevs') prevs = Many('nexts') if __name__ == '__main__': node_1 = Node() node_2 = Node() node_3 = Node() node_1.nexts = [node_2, node_3] node_2.nexts.include(node_3) node_3.nexts.include(node_1) visited = [] def on...
API_KEY = "myapikey" SECRET_KEY = "mysecretkey"
""" Function lesson """ def is_even(number): if number%2 == 0: return True else: return False def hello(name='Ada', age='15'): print('Hello,', name) print('You are {} years old'.format(age)) hello(name='Baiboon', age=17) number = 21 print('is {} an even? {}'.format(number, is_e...
# Copyright 2019 Nokia # 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, softwar...
# Copyright 2022 Huawei Technologies 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 # # Unless required by applicable law or agreed to...
import logging import os import structlog def get_logger(log_name: str = __name__) -> structlog._config.BoundLoggerLazyProxy: """Just stubbed out in case we want later configuration.""" stagename = os.environ.get("STAGE", "user") processors = [ # This performs the initial filtering, so we don't ...
import requests from openstates import metadata def coords_to_divisions(lat, lng): url = f"https://v3.openstates.org/divisions.geo?lat={lat}&lng={lng}" divisions = [] try: data = requests.get(url).json() for d in data["divisions"]: divisions.append(d["id"]) divisions.ap...
""" Functions for preparing various inputs passed to the DataFrame or Series constructors before passing them to a BlockManager. """ from __future__ import annotations from collections import abc from typing import ( TYPE_CHECKING, Any, Hashable, Sequence, cast, ) import warnings import numpy as n...
import torch from ca_particles import ParticleSimulation, CAModel, CASimulation, CATrainer if __name__ == '__main__': env_size = 24 cell_dim = 16 hidden_dim = 512 batch_size = 32#128 wall_pad = 2 train_steps = 4096*4 seed = 55 device = torch.device('cuda') pretrain_path = 'checkpoin...
""" https://portswigger.net/web-security/csrf/lab-token-validation-depends-on-request-method """ import sys import requests from bs4 import BeautifulSoup site = sys.argv[1] if 'https://' in site: site = site.rstrip('/').lstrip('https://') s = requests.Session() url = f'https://{site}/' resp = s.get(url) soup = ...
# import os import pytest import tempfile from stl import stl def _test_conversion(from_, to, mode, speedups): for name in from_.listdir(): source_file = from_.join(name) expected_file = to.join(name) if not expected_file.exists(): continue mesh = stl.StlMesh(source_...
from __future__ import absolute_import, division, print_function from tornado.concurrent import Future from tornado import gen from tornado import netutil from tornado.iostream import IOStream, SSLIOStream, PipeIOStream, StreamClosedError from tornado.httputil import HTTPHeaders from tornado.log import gen_log, app_log...
#!/usr/bin/env python3 # # Copyright 2018-2019 PSB # # 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 ...
from .. import * from ..getterdone_gpu import * import cupy as cp import cudf, cuml, xgboost # import dask_cudf import cuxfilter, cusignal from ..measures.bootstrap import * # from ..viewer.PlotBootstrap import * def comp_square_displacement_rapids(df,t_col='t',pos_col_lst=['x','y']): '''computes the squared disp...
import sqlite3 as sqlite from history import get_history import numpy as np import math from collections import defaultdict DBNAME = 'data.db' N = 20 n = 5 rate = 0.8 num = 5 cache = {} cats = {} def query(statement): conn = sqlite.connect(DBNAME) cur = conn.cursor() cur.execute(statement) res = cur....
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. import time from gaiatest import GaiaTestCase from gaiatest.apps.music.app import Music class TestMusic(GaiaTestCase):...
''' default settings for publication app override in main settings ''' from datetime import timedelta PUBLICATION_NOTIFICATION_SENDER_EMAIL = 'emailsender@mytardisserver' PUBLICATION_OWNER_GROUP = 'publication-admin' PUBLICATION_SCHEMA_ROOT = 'http://www.tardis.edu.au/schemas/publication/' # This schema holds biblio...
from django.contrib import admin from .models import * from django.contrib.auth.models import User from django.contrib.auth.admin import UserAdmin as BaseUserAdmin # Register your models here. class RadioItemsInline(admin.StackedInline): model = RadioItems class PickerItemsInline(admin.StackedInline): model = ...
raise Exception('Bad') # equivalent of 'throws' in Java # can extend this class to adjust the behaviour raise FileExistsError('File Exist error oh no!')
# MIT No Attribution # Copyright 2021 Amazon.com, Inc. or its affiliates. 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 limitatio...
import pyaf.Bench.TS_datasets as tsds import tests.artificial.process_artificial_dataset as art art.process_dataset(N = 1024 , FREQ = 'D', seed = 0, trendtype = "PolyTrend", cycle_length = 0, transform = "Anscombe", sigma = 0.0, exog_count = 20, ar_order = 0);
from pymongo import MongoClient import pprint client = MongoClient() db = client['NoSQL'] EPL = db["match"] def getTeamDetails(teamName): result = EPL.aggregate([ {"$match": {"$or": [{"AwayTeam": teamName}, {"HomeTeam": teamName}]}}, {"$group": { "_id": "null", "Matches": {...
# -*- coding: utf-8 -*- """ TencentBlueKing is pleased to support the open source community by making 蓝鲸智云-权限中心(BlueKing-IAM) available. Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved. Licensed under the MIT License (the "License"); you may not use this file except in compliance with th...
from unittest.case import TestCase from oo.carro import Motor, Direcao, Carro class CarroTestCase(TestCase): def test_velocidade_inicial(self): motor = Motor() self.assertEqual(0,motor.velocidade) def test_acelerar_first(self): motor = Motor() motor.acelerar() self.ass...
import os import tensorflow as tf import numpy as np import random import math class Simulator(): def __init__(self, type) -> None: if type == 'D': # deuteranope self.color_matrix = tf.convert_to_tensor([[1, 0, 0], [0.494207, 0, 1.24827], [0, 0, 1]]) elif type == 'P': ...
# -*- coding: utf-8 -*- import libvirt, time import virtinst.util as util from django.utils.translation import ugettext_lazy as _ from django.shortcuts import render_to_response from django.http import HttpResponseRedirect from virtmgr.model.models import * def index(request, host_id): if not request.user.is_authent...
#!/bin/env python import argparse import os import sys sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), "../")) from pmg.search import Search, Transforms from pmg import app if __name__ == "__main__": data_types = Transforms.data_types() + ["all"] parser = argparse.ArgumentParser(de...
import base64 from urllib import parse import rsa from reqs.login import LoginReq from .base_class import Forced, Wait, Multi class LoginTask(Forced, Wait, Multi): TASK_NAME = 'null' @staticmethod async def check(_): return (-2, None), @staticmethod async def work(user): # 搞两层的...
# coding=utf-8 # Copyright 2018 The OpenAI Team Authors and HuggingFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. 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...
# -*- coding: utf-8 -*- # # Copyright 2015 Benjamin Kiessling # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable ...
import first
# -*- coding: utf-8 -*- # # Copyright 2015-2020 BigML # # 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 ...
from morion.filewriter import register_writer from .writer_templates import standard_experiment_write, standard_component_write from .models import IV, Wafer, Die from pathlib import Path def get_header(header_name: str): filepath: Path = Path(__file__).parent / 'headers' / header_name return str(filepath) ...
from PIL import Image og_image = Image.open("img/pikachu.png") image = Image.new(og_image.mode, og_image.size) for col in range(image.width): for row in range(image.height): coords = (col, row,) flip_coords = (image.width - col - 1, row,) pixel = og_image.getpixel(flip_coords) ima...
from sys import maxsize class Group: def __init__(self, name=None, header=None, footer=None, id=None): self.name = name self.header = header self.footer = footer self.id = id def __repr__(self): return "%s:%s;%s;%s" % (self.id, self.name, self.header, self.footer) ...
import operator, random from twisted.trial.unittest import TestCase from axiom.iaxiom import IComparison, IColumn from axiom.store import Store, ItemQuery, MultipleItemQuery from axiom.item import Item, Placeholder from axiom import errors from axiom.attributes import ( reference, text, bytes, integer, AND, OR,...
# Copyright Contributors to the Pyro project. # SPDX-License-Identifier: Apache-2.0 from numpyro.infer.barker import BarkerMH from numpyro.infer.elbo import ( ELBO, RenyiELBO, Trace_ELBO, TraceGraph_ELBO, TraceMeanField_ELBO, ) from numpyro.infer.hmc import HMC, NUTS from numpyro.infer.hmc_gibbs im...
import pytest import responses from sparkpost import SparkPost from sparkpost.exceptions import SparkPostAPIException @responses.activate def test_success_campaigns(): responses.add( responses.GET, 'https://api.sparkpost.com/api/v1/metrics/campaigns', status=200, content_type='app...
#!/usr/bin/env python import sys import os import libtorrent if len(sys.argv) < 3: print('usage make_torrent.py file tracker-url') sys.exit(1) input = os.path.abspath(sys.argv[1]) fs = libtorrent.file_storage() #def predicate(f): # print f # return True #libtorrent.add_files(fs, input, predicate) parent_input =...
""" Assignment6 """ ''' This exercise builds on assignment 5 and explores sending mail programatically using smtplib Assuming that you have imported the data into the database in previous assignment, write a click script (collegereport.py) which will take a college acronym (say gvp) and sends out a class report to a ...
# https://open.kattis.com/problems/problemclassification import sys, collections, functools def main(a, b): for _ in range(int(input())): name, *items = map(str, input().split()); a[name] = items[1:] for l in sys.stdin.readlines(): for k in a: b[k] += sum([l.split().count(c) for c in a[k]]) print(*sorted([k...
#!/usr/bin/env python # coding: utf-8 # # Matrix Plots # # Matrix plots allow you to plot data as color-encoded matrices and can also be used to indicate clusters within the data (later in the machine learning section we will learn how to formally cluster data). # # Let's begin by exploring seaborn's heatmap and clu...
"""Implement the Google Smart Home traits.""" from __future__ import annotations import logging from homeassistant.components import ( alarm_control_panel, binary_sensor, camera, cover, fan, group, input_boolean, input_select, light, lock, media_player, scene, scrip...
#!/usr/bin/env python3 import os import celery.signals import run_p2rank_task prankweb = celery.Celery("prankweb") if "CELERY_BROKER_URL" in os.environ: prankweb.conf.update({ "broker_url": os.environ["CELERY_BROKER_URL"] }) elif "CELERY_BROKER_PATH" in os.environ: prankweb.conf.update...
__author__ = "Radical.Utils Development Team (Andre Merzky, Ole Weidner)" __copyright__ = "Copyright 2013, RADICAL@Rutgers" __license__ = "MIT" import radical.utils.testing as rut # ------------------------------------------------------------------------------ # class TestConfig (rut.TestConfig): #-----...
# ! # * Copyright (c) Microsoft Corporation. All rights reserved. # * Licensed under the MIT License. See LICENSE file in the # * project root for license information. from typing import Optional, Union, List, Callable, Tuple import numpy as np import datetime import time try: from ray import __versio...
"""Retrieve a variable from the variables file or definition.""" # pyright: reportIncompatibleMethodOverride=none from __future__ import annotations import logging from typing import TYPE_CHECKING, Any from typing_extensions import Final, Literal from .base import LookupHandler if TYPE_CHECKING: from ...utils i...
# coding=utf-8 from stash.tests.stashtest import StashTestCase class CompleterTests(StashTestCase): def setUp(self): StashTestCase.setUp(self) self.complete = self.stash.completer.complete def test_completion_01(self): newline, possibilities = self.complete('pw') assert newli...
log_level = 'INFO' load_from = None resume_from = None dist_params = dict(backend='nccl') workflow = [('train', 1)] checkpoint_config = dict(interval=10) evaluation = dict( interval=10, metric=['PCK', 'AUC', 'EPE'], key_indicator='AUC') optimizer = dict( type='Adam', lr=5e-4, ) optimizer_config = dict(grad...
import tensorflow as tf from collections import namedtuple # Model Parameters tf.flags.DEFINE_integer( "vocab_size", 91620 , "The size of the vocabulary. Only change this if you changed the preprocessing") # Model Parameters tf.flags.DEFINE_integer("embedding_dim", 100, "Dimensionality of the embeddings") tf.fl...
# flake8: noqa """ 下载证券宝5分钟bar => vnpy项目目录/bar_data/ """ import os import sys import csv import json from collections import OrderedDict import pandas as pd from datetime import datetime, timedelta vnpy_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..')) if vnpy_root not in sys.path: sys.pa...
# Import packages import matplotlib.pyplot as plt import numpy as np import pylustrator # Use scientific plot style plt.style.use('scientific') # Create dummy data x = np.linspace(0, 4*np.pi, 200) y1 = np.sin(x) y2 = np.cos(x) # Start pylustrator pylustrator.start() # Create panelled figure fig = plt.figure() ax1 =...
import cv2 import numpy as np image = cv2.imread('1.jpg') result = image.copy() gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) thresh = cv2.threshold(gray, 0, 255,cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1] kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5,5)) dilate = cv2.dilate(thresh, kernel, iterations=3) cn...
"""Documentation configuration.""" # Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Path setup ------------------------------------...
# Author # Peter Svenningsson # Email # peter.o.svenningsson@gmail.com ########### # IMPORTS # ########### # Standard import time import csv import json # 3rd party import numpy as np import matplotlib.pyplot as plt # Local from dataset.dataset_QSNMC import QSNMCDataset from models.izencovich_neuron import SimpleIzenco...
# 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...
#!/usr/bin/python3 from datetime import timedelta from io import StringIO import collections import functools import os import string import pytest from hypothesis import given, settings, HealthCheck, assume import hypothesis.strategies as st import srt REGISTER_SETTINGS = lambda name, **kwargs: settings.register_p...
import torch import torch.nn as nn import torch.nn.functional as F from ncc.modules.seq2seq.ncc_incremental_decoder import NccIncrementalDecoder from ncc.modules.embedding import Embedding from ncc.utils import utils from ncc.modules.adaptive_softmax import AdaptiveSoftmax from ncc.modules.common.layers import ( Li...
state = [ # nested list ["*","*","*"],#i0 ["*","*","*"], ["*","*","*"] ] def checkWin(x, y): for i in range(3): if x[i][0] == x[i][1] == x[i][2] == y: return y if x[0][i] == x[1][i] == x[2][i] == y: return y if x[0][0] == x[1][1] == x[2][2] == y: ...
import torch import torch.nn as nn def conv(*a, **kwa): return nn.Conv2d(*a, **kwa) def convlayer(in_c, out_c, kernel_size=3, stride=1, padding=1): return nn.Sequential( conv(in_c, out_c, kernel_size=kernel_size, stride=stride, padding=padding, bias=True), nn.BatchNorm2d(out_c),...
# Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. """ Model interpretability is often very specific to the model and thus TorchX provides examples of how to create...
import discord from datetime import datetime, timedelta import asyncio from discord.ext import commands as bot_commands from discord.ext import tasks class FridayCog(bot_commands.Cog): def __init__(self, bot): self.bot = bot @bot_commands.Cog.listener() async def on_ready(self): aw...
import logging import queue import random import string import time import uuid import asyncio import concurrent.futures import signal import attr logging.basicConfig( level=logging.INFO, format="%(asctime)s,%(msecs)d %(levelname)s: %(message)s", datefmt="%H:%M:%S", ) @attr.s class PubSubMessage: ins...
import math from ray.rllib.agents.a3c.a3c import DEFAULT_CONFIG as A3C_CONFIG, \ validate_config, get_policy_class from ray.rllib.optimizers import SyncSamplesOptimizer, MicrobatchOptimizer from ray.rllib.agents.a3c.a3c_tf_policy import A3CTFPolicy from ray.rllib.agents.trainer_template import build_trainer from r...
# -*- coding: utf-8 -*- """Inception V3 model for Keras. Note that the input image format for this model is different than for the VGG16 and ResNet models (299x299 instead of 224x224), and that the input preprocessing function is also different (same as Xception). # Reference - [Rethinking the Inception Architecture...
import os import re import argparse import subprocess as sp def compress(tag, archieved_dir): for dir_path, _, file_list in os.walk(f'./data_{tag}'): for file_name in file_list: full_path = os.path.join(dir_path, file_name) date = re.findall(r'\d{8}', full_path)[0] fn, e...
import datetime from decimal import Decimal from cypherpunkpay.models.charge import Charge from cypherpunkpay.models.user import User # SQLite3 does not offer strong typing. We do want to make sure the types are exactly what we expect. # Hence, manual type assertions for Python objects that are subject to db CRUD. ...