text
stringlengths
2
999k
""" process_handling.py This is a collection of utility functions that are useful for handling processes. They include the tools necessary to determine which processes are subprocesses of the current Joshua process by looking at the appropriate environment variables. """ # This source file is part ...
import math from typing import Optional, List, Tuple, Sequence, Union, cast, TypeVar from typing import Iterator, overload import numpy import itertools from .. import registry from ..types import Xp, Shape, DTypes, DTypesInt, DTypesFloat, List2d, ArrayXd from ..types import Array3d, Floats1d, Floats2d, Floats3d, Flo...
#!/usr/bin/env python3 # Copyright (c) Meta Platforms, Inc. and affiliates. # # 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 requi...
# Generated by Django 3.1.5 on 2021-01-28 05:12 from django.conf import settings from django.db import migrations, models import django.db.models.deletion import tinymce.models class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_...
# coding=utf-8 from __future__ import absolute_import from collections import Iterable from colorama import Fore import numpy as np import re from colorama import Fore import sys import json import os from enum import Enum import torch from torch import multiprocessing as mp from tensorboardX import SummaryWriter base...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Copyright (C) 2017-2020 The Project X-Ray Authors. # # Use of this source code is governed by a ISC-style # license that can be found in the LICENSE file or at # https://opensource.org/licenses/ISC # # SPDX-License-Identifier: ISC """ Python 3 removed the 'cmp' functi...
from pypy.conftest import gettestobjspace class AppTest_make_proxy: def setup_class(cls): cls.space = gettestobjspace(**{"objspace.std.withtproxy": True}) def test_errors(self): from tputil import make_proxy raises(TypeError, "make_proxy(None)") raises(TypeError, "make_proxy(N...
import logging from abc import ABC, abstractmethod from fritzconnection.core.exceptions import ActionError, ServiceError, FritzInternalError from prometheus_client.core import CounterMetricFamily, GaugeMetricFamily logger = logging.getLogger(__name__) logger.setLevel(logging.WARN) class FritzCapability(ABC): ca...
import scipy from scipy import ndimage import matplotlib.pyplot as plt l = scipy.misc.lena() blurred_l = ndimage.gaussian_filter(l, 3) filter_blurred_l = ndimage.gaussian_filter(blurred_l, 1) alpha = 30 sharpened = blurred_l + alpha * (blurred_l - filter_blurred_l) plt.figure(figsize=(12, 4)) plt.subplot(131) plt....
# -*- coding: utf-8 -*- # -------------------------------------------------------------------------------- # file :main.py.py # target : # # output : # author :Miller # date :18.7.2 12:00 # log :包含修改时间、修改人、修改line及原因 # ----------------------------------------------------------------------------...
from tqdm import tqdm import os import argparse from parseAnnotatedXML import * import turicreate as tc from tqdm import tqdm import numpy as np try: import xml.etree.cElementTree as et except ImportError: import xml.etree.ElementTree as et class EvaluationSFrame(object): def getSFrame(xml_file, image_fo...
""" Dependencies of Tink base. """ load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive", "http_file") def tink_base_deps(): """ Loads dependencies of Tink base. """ # ----- Go # Release from 2021-01-20 http_archive( name = "io_bazel_rules_go", sha256 = "dbf5a9ef855...
# -*- mode: python; coding: utf-8 -*- # Copyright 2019 the AAS WorldWide Telescope project # Licensed under the MIT License. import numpy as np import pytest from .. import pyramid from ..pyramid import Pos def test_next_highest_power_of_2(): assert pyramid.next_highest_power_of_2(1) == 256 assert pyramid.n...
import time from board import SCL, SDA import busio from micropython import const from adafruit_seesaw.seesaw import Seesaw # pylint: disable=bad-whitespace BUTTON_RIGHT = const(6) BUTTON_DOWN = const(7) BUTTON_LEFT = const(9) BUTTON_UP = const(10) BUTTON_SEL = const(14) # pylint: enable=bad-whi...
#!/usr/bin/env python2 #-*- coding: utf-8 -*- # This file is used to generate config file for LIEF test # Basically it parse it parse the output of readelf import re import yaml import subprocess import sys import hashlib p = subprocess.Popen(["readelf", "-a", sys.argv[1]], stdout=subprocess.PIPE) (output, err) = p....
# encoding: utf-8 import os import os.path as osp import time import torch import torch.distributed as dist from collections import OrderedDict from utils.pyt_utils import ( parse_torch_devices, ensure_dir) from utils.logger import get_logger from utils.checkpoint import load_model from utils.misc import save_hd...
# -*- coding: utf-8 -*- # # Copyright 2019 SoloKeys Developers # # Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or # http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or # http://opensource.org/licenses/MIT>, at your option. This file may not be # copied, modified, or distribute...
from autoballs.utils import get_img_from_seg import cv2 from PIL import Image import numpy as np import albumentations as albu from torch.utils.data import DataLoader from torch.utils.data import Dataset as BaseDataset class Dataset(BaseDataset): """Read images, apply augmentation and preprocessing tr...
""" Unit tests for CMake script creation """ load("@bazel_skylib//lib:unittest.bzl", "asserts", "unittest") load("//tools/build_defs:cmake_script.bzl", "create_cmake_script", "export_for_test") load("//tools/build_defs:cc_toolchain_util.bzl", "CxxFlagsInfo", "CxxToolsInfo") load("@foreign_cc_platform_utils//:os_info.b...
from contextlib import contextmanager import io import os import shutil import stat def get_repo(path, search_parent_directories=True): repo = None try: import git repo = git.Repo( path, search_parent_directories=search_parent_directories ) except ImportError: ...
from core.config import *
# WebDriver specification ID: dfn-error-response-data errors = { "element click intercepted": 400, "element not selectable": 400, "element not interactable": 400, "insecure certificate": 400, "invalid argument": 400, "invalid cookie domain": 400, "invalid coordinates": 400, "invalid elem...
# import time from django.db import connections from django.db.utils import OperationalError from django.core.management.base import BaseCommand class Command(BaseCommand): """Django commands to pause execution until database is available""" def handle(self, *args, **options): self.stdout.write('Wait...
from typing import List, Any def transform( data: List[dict] ) -> List[tuple]: return [ (key, value) for dict_item in data for key, value in dict_item.items() ] def main(): data = [ {"key": "value", "123": 123}, {"another_key": "another_value", "key": "value"}...
from django.contrib.auth.models import User from django.contrib.messages import get_messages from django.test import TestCase from examples.models import MyStocks class MixinsTest(TestCase): def setUp(self): self.MyStocks = MyStocks.objects.create( title='Life of Jane Doe', publi...
# Copyright notice: # Copyright Members of the EMI Collaboration, 2013. # # See www.eu-emi.eu for details on the copyright holders # # 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...
"""Faça um programa que leia três números e mostre qual é o maior e qual é o menor.""" """ Pode ser feito dessa maneira n1 = int(input('Digite um Valor')) n2 = int(input('Digite Outro Valor')) n3 = int(input('Digite Outro Valor')) maior = max(n1,n2,n3) menor = min(n1,n2,n3) print(f'O maior numero é {maior}') print(f'...
"""Top-level package for {{ cookiecutter.project_name }}.""" __author__ = """{{ cookiecutter.full_name }}""" __version__ = '{{ cookiecutter.version }}'
#!/usr/bin/env python # -*- coding: utf-8 -*- try: from setuptools import setup except ImportError: from distutils.core import setup with open("README.rst") as readme_file: readme = readme_file.read() with open("HISTORY.rst") as history_file: history = history_file.read().replace(".. :changelog:", ...
# Importing modules import datetime import smtplib import webbrowser import pyttsx3 import speech_recognition as sr import wikipedia import os engine = pyttsx3.init('sapi5') voices = engine.getProperty('voices') engine.setProperty('voices',voices[0].id) # Speak function def speak(audio): engine...
# Copyright 2019 NEC 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 writi...
from setuptools import setup, find_packages from codecs import open from os import path __version__ = '1.0.0' here = path.abspath(path.dirname(__file__)) # Get the long description from the README file with open(path.join(here, 'README.md'), encoding='utf-8') as f: long_description = f.read() # get the dependen...
from typing import Optional, Callable, List import os import os.path as osp import glob import pickle import torch import torch.nn.functional as F import networkx as nx from torch_geometric.data import (InMemoryDataset, Data, download_url, extract_zip, extract_tar) from torch_geometr...
import traceback import argparse import numpy as np from src import NeuralNetwork from typing import * def get_args() -> argparse.Namespace: """Set-up the argument parser Returns: argparse.Namespace: """ parser = argparse.ArgumentParser( description='Project 1 for the Deep Learning cl...
""" This file offers the methods to automatically retrieve the graph Listeria monocytogenes Scott. The graph is automatically retrieved from the STRING repository. Report --------------------- At the time of rendering these methods (please see datetime below), the graph had the following characteristics: Datetime...
class AuthError(ValueError): def __init__(self, message, code=None): if code: self.code = code super().__init__(message) class PermissionDenied(AuthError): def __init__(self, message, code=None): if code: self.code = code super().__init__(message)
# -*- coding:utf-8 -*- """ Huobi 模块使用演示 为了在订单薄买盘提前埋伏订单,在 `BTC/USDT` 订单薄盘口距离10美金的位置挂买单,数量量为1。 随着订单薄盘口价格不断变化,需要将价格已经偏离的订单取消,再重新挂单,使订单始终保持距离盘口价差为 `10 ± 1` 美金。 这里设置了缓冲价差为 `1` 美金,即只要盘口价格变化在 `± 1` 内,都不必撤单之后重新挂单,这样设置的目的是尽量减少挂撤单的次数, 因为交易所开放的交易接口有调用频率的限制,如果调用太过频繁超过了限制可能会报错。 """ import sys from quant import const from quant....
from utilidadesCeV import moeda preco = float(input('Digite o preco em: R$')) moeda.resumo(preco, 80, 35)
from languages.predicate import Predicate class Path(Predicate): predicate_name = "path" def __init__(self, source=None, destination=None, weight=None): Predicate.__init__(self, [("source"),("destination")]) self.source = source self.destination = destination def get_source(self):...
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import json import os import re from shutil import rmtree import urllib from urllib.parse import urlparse, quote as urlquote from urllib.request import build_opener, HTTPCookieProcessor, HTTPError from http import cookiejar from bs4 import BeautifulSoup from Py...
""" Check serialization of PyJavaInstance subclasses. (from Lib). #unitcheck """ import support support.compileJava("test117j.java") import java, org pi = java.io.PipedInputStream() po = java.io.PipedOutputStream(pi) oo = java.io.ObjectOutputStream(po) oi = org.python.util.PythonObjectInputStream(pi) import test117...
# Copyright 2013-2021 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 Grpc(CMakePackage): """A high performance, open-source universal RPC framework.""" mai...
from __future__ import with_statement import os from alembic import context from sqlalchemy import engine_from_config, pool from logging.config import fileConfig # this is the Alembic Config object, which provides # access to the values within the .ini file in use. config = context.config if not 'BAUBLE_DB_URL' in o...
# Copyright 2018 Max Shinn <max@maxshinnpotential.com> # # This file is part of Paranoid Scientist, and is available under the # MIT license. Please see LICENSE.txt in the root directory for more # information. __all__ = ['Numeric', 'ExtendedReal', 'Number', 'Integer', 'Natural0', 'Natural1', 'Range', 'RangeClosedOp...
import pytest def test_home(client, auth): # log in as teacher and see teacher home Page # with list of courses auth.login() response = client.get('/home') assert b'Teacher Home Page' in response.data # course not owned by teacher assert b'ENG 101' in response.data # course owned by te...
import sys from enum import Enum from typing import Any, Callable, ClassVar, Dict, List, Mapping, Optional, Type, get_type_hints from uuid import UUID, uuid4 import pytest from pydantic import ( BaseModel, ConfigError, Extra, Field, NoneBytes, NoneStr, Required, ValidationError, co...
from data import * from utils.augmentations import SSDAugmentation from layers.modules import MultiBoxLoss from ssd import build_ssd import os import sys import time import torch from torch.autograd import Variable import torch.nn as nn import torch.optim as optim import torch.backends.cudnn as cudnn import torch.nn.in...
"""Gaussian Elimination""" import numpy as np def gaussian_elimination(matrix: np.ndarray): return matrix def main(): matrix = np.array([[4, 8, -4, 4], [3, 8, 5, -11], [-2, 1, 12, -17]]) values = gaussian_elimination(matrix) print(values) if __name__...
from django.contrib import admin from grandprix.models import Tournament, Player, PlayerScore, TournamentType,\ Season, Points class PointInline(admin.TabularInline): model = Points @admin.register(TournamentType) class TournamentTypeAdmin(admin.ModelAdmin): list_display = ['name'] inlines = [Point...
from __future__ import absolute_import, unicode_literals import string from jaraco.text import FoldedCase class IRCFoldedCase(FoldedCase): """ A version of FoldedCase that honors the IRC specification for lowercased strings (RFC 1459). >>> IRCFoldedCase('Foo^').lower() 'foo~' >>> IRCFolded...
# ============================================================================= # Copyright 2020 NVIDIA. 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://ww...
# Copyright 2013 - Mirantis, Inc. # Copyright 2015 - StackStorm, 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 # # Unl...
# encoding: utf-8 import json if __name__ == "__main__": with open("original/districts.csv", "r", encoding="utf-8") as f: lines = f.readlines() json_data = { "name": "korean-admin-districts", "version": "20170824", "url": "https://github.com/kaniblu/korean-adm...
# Generated by Django 3.1.6 on 2021-08-14 00:55 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("scheduler", "0010_auto_20210814_0030"), ] operations = [ migrations.AlterField( model_name="taskinfo", name="modifie...
from __future__ import absolute_import import collections as _collections import os as _os import pytest as _pytest import pandas as _pd import uuid as _uuid import datetime as _datetime from flytekit.common.types.impl import schema as _schema_impl from flytekit.common.types import primitives as _primitives, blobs as ...
def validate(*validations): """ Checks if all `validations` are correct before executing. """ def message_validation(func): def func_wrapper(*args, **kwargs): if all(validations): func(*args, **kwargs) return func_wrapper return message_validation
#!/usr/bin/env python3 # encoding: utf-8 import sys import os import time import cfsmt_expr_write as mte_wr import cfs_test_common as tc def print_usage(): print( 'Usage: {} <ext4 | fsp> [append] [share] [numapp=]'.format( sys.argv[0])) if len(sys.argv) < 2: print_usage() sys.exit(...
# coding: utf-8 """ Copyright 2016 SmartBear Software 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...
# 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 __a...
from django import template from django.template.defaultfilters import stringfilter import re #code patterns class patterns(): def __init__(self): # Regex pattern core_patterns = { "heading" :"^#+\s", #heading "se_text_h1":"^\s*[=]+(?<=$)", # setext h1 "se_text...
from abc import ABCMeta, abstractmethod import torch import torch.nn as nn from mmcv.cnn import normal_init from mmcv.runner import auto_fp16, force_fp32 from mmseg.core import build_pixel_sampler from mmseg.ops import resize from ..builder import build_loss from ..losses import accuracy class BaseDeco...
import unittest from nose.tools import raises from . import ci from . import ti class AnalysisTest(unittest.TestCase): def test_add_analysis(self): name = "analysis x" program = "Magic" programversion = "1.0" algorithm = "mind" sourcename = "src" sourceversion =...
import matplotlib.pyplot as plt import numpy as np feat_x2_0_inter = np.array([0.34256017, 0.31460512, 0.27144957, 0.24856855, 0.22719437]) feat_x2_0_inter_ste = np.array([0.004312400818, 0.003773893416, 0.002982698083, 0.00233306855, 0.002138502002]) feat_x2_1_inter = np.array([0.35977444, 0.3302486, 0.2858478, 0.262...
import os os.system('cd .. \n bash ./scripts/metrics_shapenet_lm.sh')
#! /usr/bin/env python3 import logging import sys def analyze(fin): result = [] for line in fin.readlines(): line = line.strip() if line == "": continue parts = line.split() if len(parts) != 3: logging.error("skipping unexpected line '%s'", line) continue if parts[2] != "s": logging.error("...
''' Driver to start BigLambda Job Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: MIT-0 ''' import boto3 import json import math import random import re from io import StringIO import sys import time import lambdautils import glob import subprocess from multip...
import unittest from unittest import TestCase from bitsnpieces import torrent class TestTorrentFile(TestCase): def test_torrent_load_ubuntu(self): torfile = torrent.load("test/data/ubuntu-20.04.1-desktop-amd64.iso.torrent") self.assertEqual(torfile.announce, "https://torrent.ubuntu.com/announce") ...
############################################################################## # # Copyright (c) 2001, 2002 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # TH...
from opentera.services.ServiceConfigManager import ServiceConfigManager, DBConfig class ConfigManager(ServiceConfigManager, DBConfig): def validate_config(self, config_json): return super().validate_config(config_json) and self.validate_database_config(config_json)
""" Exceptive is a Python library that makes exception handling more programmatic and debuggable. """ __author__ = "Eray Erdin" __copyright__ = "Copyright 2018, Eray Erdin" __license__ = "Apache License 2.0" __maintainer__ = "Eray Erdin" __email__ = "eraygezer.94@gmail.com" __status__ = "Prototype" __version__ = "0.1....
""" Created by Epic at 8/18/20 """ import logging from discord.ext import commands import discord class Sponsor(commands.Cog): def __init__(self, bot): self.bot = bot self.logger = logging.getLogger("salbot.cogs.sponsor") @commands.Cog.listener() async def on_member_update(self, before: ...
""" WSGI config for testsite project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATION``...
#!/usr/bin/env python # # Copyright (c) 2009 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list...
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
"""Helpers to help coordinate updates.""" from __future__ import annotations import asyncio from collections.abc import Awaitable, Callable from datetime import datetime, timedelta import logging from time import monotonic from typing import Any, Generic, TypeVar # pylint: disable=unused-import import urllib.error i...
""" Django settings for gestionairweb project. Generated by 'django-admin startproject' using Django 1.8.1. For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ """ # Buil...
import numpy as np import cv2 as cv from psnr import psnr_numpy def create_low_res_images(images: np.ndarray) -> np.ndarray: images_low_res = tuple(create_low_res_image(image) for image in images) return np.array(images_low_res) def create_low_res_image(image: np.ndarray) -> np.ndarray: return resize_up(resize_do...
""" mbed SDK Copyright (c) 2016 ARM Limited 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, so...
# Tencent is pleased to support the open source community by making ncnn available. # # Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved. # # Licensed under the BSD 3-Clause License (the "License"); you may not use this file except # in compliance with the License. You may obtain a copy of the...
import tweepy cred = {} f = open("./guest_credentials.txt") for line in f: name, value = line.split(":") cred[name] = value.strip() f.close() auth = tweepy.OAuthHandler(cred["key"], cred["key_secret"]) auth.set_access_token(cred["token"], cred["token_secret"]) api = tweepy.API(auth) public_tweets = api.home...
#!/usr/bin/env python # # Copyright 2016 Cisco Systems, 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 applicab...
# Note: The information criteria add 1 to the number of parameters # whenever the model has an AR or MA term since, in principle, # the variance could be treated as a free parameter and restricted # This code does not allow this, but it adds consistency with other # packages such as gretl and X1...
""" Django settings for cwProject project. Generated by 'django-admin startproject' using Django 2.0.6. For more information on this file, see https://docs.djangoproject.com/en/2.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.0/ref/settings/ """ import os ...
from core.module import Module from core.moduleexception import ProbeException from core.argparse import ArgumentParser import datetime WARN_INVALID_VALUE = 'Invalid returned value' class Check(Module): '''Check remote files type, md5 and permission''' def _set_vectors(self): self.support_vectors.a...
# Generated by Django 3.2.6 on 2021-12-01 14:43 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('users', '0008_auto_20211201_1530'), ] operations = [ migrations.CreateModel( name='AboutUs', fields=[ ...
import os import stat import json import zipfile from plynx.constants import NodeResources from plynx.plugins.base import BaseResource from plynx.utils.common import zipdir from plynx.utils.config import get_web_config WEB_CONFIG = get_web_config() class File(BaseResource): NAME = 'file' ALIAS = 'File' I...
import json import os import platform import threading from functools import partial import dask.array as da import numpy import pytest import rasterio import xarray from affine import Affine from dask.delayed import Delayed from numpy.testing import assert_almost_equal, assert_array_equal from packaging import versio...
""" This file tests the ability for serde.py to convert complex types into simple python types which are serializable by standard serialization tools. For more on how/why this works, see serde.py directly. """ import warnings from syft.serde import ( _simplify, apply_lz4_compression, apply_no_compression, ...
# The term broadcasting refers to the ability of NumPy to treat arrays of different shapes during # arithmetic operations. Arithmetic operations on arrays are usually done on corresponding elements. # If two arrays are of exactly the same shape, then these operations are smoothly performed. import numpy as np a = ...
""" Checker functions """ import numpy as np import torch PI = 3.1415 DIM = 64.0 SCALE = 255.0 FIXED_CIRCLE = False class CentroidFunction(torch.nn.Module): def __init__(self, bs, ch, sx, sy): super(CentroidFunction, self).__init__() self.x_lin = torch.nn.Parameter(torch.linspace(0, sx, sx).expa...
from scrapy.linkextractors import LinkExtractor from scrapy.spiders import CrawlSpider, Rule class DmozSpider(CrawlSpider): """Follow categories and extract links.""" name = 'dmoz' allowed_domains = ['dmoztools.net'] start_urls = ['http://dmoztools.net/'] rules = [ Rule(LinkExtractor( ...
import sys from typing import ( Tuple, ) import pywintypes # noqa: E402 import win32file # noqa: E402 if sys.platform != "win32": raise ImportError("This module should not be imported on non `win32` platforms") class NamedPipe: def __init__(self, ipc_path: str) -> None: try: self.h...
import rpi_ws281x from .segment import Segment class Strip(rpi_ws281x.PixelStrip): ''' Strip This class extends the PixelStrip and allows segmentating and controlling the different segments on their own. Keyword argument: num -- The number of leds the strip has pin -- The pin in which the data...
from django.contrib import admin from .models import BillingProfile, Card, Charge # Register your models here. admin.site.register(BillingProfile) admin.site.register(Card) admin.site.register(Charge)
# This file is automatically generated by the rmf-codegen project. # # The Python code generator is maintained by Lab Digital. If you want to # contribute to this project then please do not edit this file directly # but send a pull request to the Lab Digital fork of rmf-codegen at # https://github.com/labd/rmf-codegen ...
""" This is a wrapper for a JSON http response specific to the massenergize API. It ensures that the data retrieved is in a json format and adds all possible errors to the caller of a particular route """ from django.http import JsonResponse from collections.abc import Iterable import json class MassenergizeResponse...
''' URL: https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/description/ Time complexity: O(logn) Space complexity: O(1) ''' class Solution(object): def findMin(self, nums): """ :type nums: List[int] :rtype: int """ start = 0 end = len(nums) - 1 ...
#!/usr/bin/env python import argparse import json import numpy import pandas import seaborn from matplotlib import pyplot seaborn.set() seaborn.set_style("white") seaborn.despine() scpb = seaborn.color_palette("Blues") scpr = seaborn.color_palette("Reds") scpg = seaborn.cubehelix_palette(rot=-.4) base_resolution = 1...
from random import sample class ReplayMemory: def __init__(self, max_size): # deque object that we've used for 'episodic_memory' is not suitable for random sampling # here, we instead use a fix-size array to implement 'buffer' self.buffer = [None] * max_size self.max_size = max_siz...
from plntter.utils.attitude import AttitudeSolver, AttitudeTransform from plntter.utils.vector import Vector import numpy as np def test_QMethod() -> None: r1,r2,r3 = Vector.random(), Vector.random(), Vector.random() b1,b2,b3 = Vector.random(), Vector.random(), Vector.random() R,B = np.vstack((r1,r2,r3))...