text stringlengths 2 999k |
|---|
#name_scan "d/yourdomain" 1
import sys, os
#sys.path.append('/home/khal/sources/nmcontrol/lib/')
import DNS
import rpcClient
import struct, listdns, base64, types, json, random
#from jsonrpc import ServiceProxy
from utils import *
from common import *
class Source(object):
#def __init__(self):
#self.server... |
"""Tests for the :mod:`~polymatheia.data.writer` package."""
import json
import os
from shutil import rmtree
from polymatheia.data import NavigableDict
from polymatheia.data.writer import JSONWriter
DOCUMENTS = [NavigableDict(r) for r in [
{
'id': '1',
'name': {
'first': 'A',
... |
# -*- coding: utf-8; -*-
from __future__ import unicode_literals, absolute_import
import json
import requests
import six
from tests import unittest, mock
from freight_forwarder.registry import Registry, V1, V2
from freight_forwarder.registry.registry_base import RegistryBase, RegistryException
from ..fa... |
__all__ = ["loss_fn"]
from icevision.imports import *
def loss_fn(preds, targets) -> torch.Tensor:
return preds["loss"]
|
# Generated by Django 3.2.4 on 2021-09-11 12:44
import ckeditor_uploader.fields
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('blog', '0007_subscriber'),
]
operations = [
migrations.AlterField(
model_name='post',
name='... |
import unittest
from numpy.testing import assert_allclose
from qspectra import polarization
from qspectra.simulate import decorators
class TestGetCallArgs(unittest.TestCase):
def test(self):
self.assertEqual(
decorators._get_call_args(lambda a: None, 1),
{'a': 1})
self.ass... |
# proxy module
from traitsui.editors.check_list_editor import *
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed May 29 16:16:57 2019
@author: rakshit
"""
import os
import cv2
import argparse
import matplotlib
import numpy as np
import deepdish as dd
import scipy.io as scio
print('Extracting Santini')
parser = argparse.ArgumentParser()
parser.add_argument('--noD... |
from django.http import HttpResponse
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login, logout
from django.shortcuts import redirect
from django.core.validators import URLValidator # https://stackoverflow.com/questions/7160737/python-how-to-validate-a-url-in-python-malf... |
"""
The arraypad module contains a group of functions to pad values onto the edges
of an n-dimensional array.
"""
from __future__ import division, absolute_import, print_function
import numpy as np
__all__ = ['pad']
###############################################################################
# Private utility ... |
import copy
import json
import logging
import pytest
import burn_lock_functions
import test_utilities
from integration_env_credentials import sifchain_cli_credentials_for_test
from pytest_utilities import generate_minimal_test_account
from test_utilities import EthereumToSifchainTransferRequest, SifchaincliCredential... |
"""Build Environment used for isolation during sdist building
"""
import logging
import os
import sys
import textwrap
from distutils.sysconfig import get_python_lib
from sysconfig import get_paths
from pip._vendor.pkg_resources import Requirement, VersionConflict, WorkingSet
from pip import __file__ as pip_location
... |
import logging
from random import randint
import traceback
from typing import cast, Dict, List, Set, Collection
from geniusweb.actions.Accept import Accept
from geniusweb.actions.Action import Action
from geniusweb.actions.LearningDone import LearningDone
from geniusweb.actions.Offer import Offer
from geniusweb.action... |
METER_TO_KM = 1e-3
ONE_TO_KILO = 1e3
KM_TO_METER = 1e3
KILO_TO_ONE = 1e3
# Average earth radius, see https://en.wikipedia.org/wiki/Earth_radius
EARTH_RADIUS_KM = 6371.0088
# in reality air density varies between 1.14 and 1.42 in kg/m^3
AIR_DENSITY_RHO = 1.225
# of course this introduces a small mistake due to leap ... |
# Time: O(n)
# Space: O(1)
class Solution(object):
# @param a, a string
# @param b, a string
# @return a string
def addBinary(self, a, b):
result, carry, val = "", 0, 0
for i in range(max(len(a), len(b))):
val = carry
if i < len(a):
val += int(a[... |
"""Test whether all elements of cls.args are instances of Basic. """
# NOTE: keep tests sorted by (module, class name) key. If a class can't
# be instantiated, add it here anyway with @SKIP("abstract class) (see
# e.g. Function).
import os
import re
import warnings
import io
from sympy import Basic, S, symbols, sqrt... |
#ARC076e
def main():
import sys
input=sys.stdin.readline
sys.setrecursionlimit(10**6)
if __name__ == '__main__':
main() |
from django.core.management.base import BaseCommand
from django.utils.timezone import now
class Command(BaseCommand):
args = '[event_slug...]'
help = 'Create missing email aliases'
def handle(*args, **opts):
from access.models import InternalEmailAlias
InternalEmailAlias.ensure_internal_... |
from django.contrib.auth.models import User
from rest_framework.test import APITestCase
class FVHAPITestCase(APITestCase):
def assert_dict_contains(self, superset, subset, path=''):
for key, expected in subset.items():
full_path = path + key
received = superset.get(key, None)
... |
"ts_project rule"
load("@build_bazel_rules_nodejs//:providers.bzl", "DeclarationInfo", "NpmPackageInfo", "declaration_info", "js_module_info", "run_node")
_DEFAULT_TSC = (
# BEGIN-INTERNAL
"@npm" +
# END-INTERNAL
"//typescript/bin:tsc"
)
_ATTRS = {
"args": attr.string_list(),
"declaration_dir... |
# encoding: utf-8
from __future__ import unicode_literals
class TranslationError(Exception):
"""Failure to translate source."""
pass
|
# Write a Python program to get execution time for a Python method.
import time
def sum_of_n_numbers(x):
start_time = time.time()
s = 0
for i in range(1, x + 1):
s = s + i
end_time = time.time()
return s, end_time - start_time
n = 5
print("\nTime to sum of 1 to ", n, " and required time... |
'''
Native support for Multitouch devices on Linux, using libmtdev.
===============================================================
The Mtdev project is a part of the Ubuntu Maverick multitouch architecture.
You can read more on http://wiki.ubuntu.com/Multitouch
To configure MTDev, it's preferable to use probesysfs p... |
import unittest
from unittest.mock import MagicMock
import pandas as pd
from pandas.testing import assert_frame_equal
from data_export.pipeline.dataset import Dataset
class TestDataset(unittest.TestCase):
def setUp(self):
example = MagicMock()
example.to_dict.return_value = {"data": "example"}
... |
# Copyright 2018 The gRPC 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 in writ... |
from ..proto import *
from ..graph_io import *
import paddle.fluid as fluid
import numpy as np
from paddle.fluid.core import VarDesc, AttrType
def union(list_a, list_b):
return list(set(list_a).union(set(list_b)))
def difference(list_a, list_b):
return list(set(list_a).difference(set(list_b)))
class Edge_for_flu... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2018, Abhijeet Kasurde <akasurde@redhat.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata... |
import logging
from django.core.mail import EmailMultiAlternatives, EmailMessage
from django.utils.encoding import smart_text
from django.core.urlresolvers import reverse
from django.conf import settings
from disturbance.components.emails.emails import TemplateEmailBase
from ledger.accounts.models import EmailUser
l... |
# -*- coding: utf-8 -
from iso8601 import parse_date
from datetime import datetime, date, time, timedelta
import dateutil.parser
from pytz import timezone
import os
from decimal import Decimal
import re
TZ = timezone(os.environ['TZ'] if 'TZ' in os.environ else 'Europe/Kiev')
def get_all_etender_dates(initial_tender... |
import os
import pytest
import sys
import random
import tempfile
import requests
from pathlib import Path
import ray
from ray.test_utils import (run_string_as_driver,
run_string_as_driver_nonblocking)
from ray._private.utils import (get_wheel_filename, get_master_wheel_url,
... |
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///posts.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
# app.config['FLASK_RUN_PORT'] = 5002
db = SQLAlchemy(app)
|
# coding: utf-8
"""
SendinBlue API
SendinBlue provide a RESTFul API that can be used with any languages. With this API, you will be able to : - Manage your campaigns and get the statistics - Manage your contacts - Send transactional Emails and SMS - and much more... You can download our wrappers at h... |
# coding: utf-8
import math
import numpy as np
import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.nn.functional as F
def conv3x3(in_planes, out_planes, stride=1):
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
padding=1, bias=False)
... |
# Tweepy
# Copyright 2009-2010 Joshua Roesslein
# See LICENSE for details.
"""
Tweepy Twitter API library
"""
__version__ = '3.2.0'
__author__ = 'Joshua Roesslein'
__license__ = 'MIT'
from tweepy.models import Status, User, DirectMessage, Friendship, SavedSearch, SearchResults, ModelFactory, Category
from tweepy.erro... |
#!/Users/julian/.local/share/virtualenvs/great/bin/pypy
import json
import sys
from great.models import music
from great.web import engine_from_config
from pyperclip import copy
from sqlalchemy import sql
from titlecase import titlecase
e = engine_from_config()
def canonicalize(artist):
if artist.isupper():
... |
# Copyright (c) 2017 OpenStack Foundation
#
# 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 ... |
#!/usr/bin/env python
#########################################################################
# Author: Andy Ohlin (debian.user@gmx.com)
# Modified by: Andrew Palmer (palmer@embl.de)
# Artem Tarasov (lomereiter@gmail.com)
#
# Example usage:
# pyisocalc('Fe(ClO3)5',plot=false,gauss=0.25,charge=-2,resoluti... |
import unittest
from code.google_search import get_people_also_ask_links
class TestGoogleSearch(unittest.TestCase):
def setUp(self) -> None:
pass
def test_get_people_also_ask_links(self):
"""Test the get_people_also_ask_links method"""
test = "principal components"
result = get... |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 OpenStack Foundation
#
# 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... |
from datetime import datetime
from typing import List, Dict, Optional
from pydantic import BaseModel, validator, root_validator
class ItemModel(BaseModel):
cve: Dict
configurations: Optional[Dict]
impact: Optional[Dict]
publishedDate: datetime
lastModifiedDate: datetime
class ResultModel(BaseMod... |
import easygui as g
user_info=g.multenterbox(title='账号中心',msg='【*用户名】为必填项\t【*真实姓名】为必填项\t【*手机号码】为必填项\t【*E-mail】为必填项',
fields=['*用户名','*真实姓名','固定电话','*手机号码','QQ','*E-mail']
) |
import re
import os
__location__ = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))
""" Holds all the custom exceptions raised by the api """
class OrderNotFound(StandardError):
"""Error raised when an order is not found"""
def __init__(self, orderid):
"""Create new OrderNotF... |
#Import modules and libraries
from random import randint
from string import ascii_uppercase, ascii_lowercase
from itertools import permutations
from copy import deepcopy
from tail_recursion import tail_recursive, recurse
#Define board mapping function
def mapBoard(col, row, value):
board = [[value for x in range(c... |
import os
import argparse
import json
import pandas as pd
import bilby
from bilby_pipe.create_injections import InjectionCreator
def main():
parser = argparse.ArgumentParser(description="Slurm files from nmma injection file")
parser.add_argument(
"--prior-file",
type=str,
required=Tr... |
from functools import partial
from typing import NamedTuple, Union
from flake8_annotations import Argument, Function
from flake8_annotations.enums import AnnotationType
class FormatTestCase(NamedTuple):
"""Named tuple for representing our test cases."""
test_object: Union[Argument, Function]
str_output:... |
# coding: utf-8
import sys
import os
sys.path.insert(0, os.path.join(os.path.dirname(__file__),'../..'))
import suzu.matdb.srim_compounddb as compounddb
air = compounddb.Compound()
air.desc = 'Air, Dry near sea level (ICRU-104) 0.00120484 O-23.2, N-75.5, Ar-1.3'
air.name = '%Air, Dry (ICRU-104)'
air.density = 0.0... |
import numpy as np
from sklearn import metrics
from PIL import Image
def get_metrics(pred, logits, gt):
if isinstance(logits, list):
logits = logits[-1]
result = {'confusion_matrix': metrics.confusion_matrix(gt.flatten(), pred.flatten(), labels=[1, 0]),
'auc': roc(gt, logits)}
return ... |
from pysys.constants import *
from apama.basetest import ApamaBaseTest
from apama.correlator import CorrelatorHelper
from GAPDemoConnected import GAPDemoConnectedHelper
class PySysTest(ApamaBaseTest):
def __init__(self, descriptor, outsubdir, runner):
super(PySysTest, self).__init__(descriptor, outsubdir, ru... |
"""youtubesearch URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.0/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')
Class... |
from cereal import car
from selfdrive.car import dbc_dict
Ecu = car.CarParams.Ecu
class CarControllerParams:
ACCEL_MAX = 2.0
ACCEL_MIN = -3.7
STEER_MAX = 384 # 409 is the max, 255 is stock
STEER_DELTA_UP = 3
STEER_DELTA_DOWN = 7
STEER_DRIVER_ALLOWANCE = 50
STEER_DRIVER_MULTIPLIER = 2
STEER_DRIVER_FA... |
# -*-coding:Utf-8 -*
# Copyright (c) 2010 LE GOFF Vincent
# 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
# l... |
from __future__ import absolute_import, division, print_function
import numbers
import warnings
import torch
from torch.autograd import Variable
import pyro
import pyro.poutine as poutine
from pyro.distributions.util import is_identically_zero
from pyro.infer.elbo import ELBO
from pyro.infer.enum import iter_discret... |
# -*- coding: utf-8 -*-
"""HydroMT workflows"""
from .basin_mask import *
from .forcing import *
from .rivers import *
|
"""
To trace the falcon web framework, install the trace middleware::
import falcon
from ddtrace import tracer
from ddtrace.contrib.falcon import TraceMiddleware
mw = TraceMiddleware(tracer, 'my-falcon-app')
falcon.API(middleware=[mw])
You can also use the autopatching functionality::
import... |
# coding: utf-8
# @author octopoulo <polluxyz@gmail.com>
# @version 2020-05-01
"""
Sync
"""
import gzip
from logging import getLogger
import os
import re
import shutil
from subprocess import run
from time import time
from typing import Any
from PIL import Image, ImageFile
from common import makedirs_safe, read_text... |
"""Tests for the main module."""
import unittest
from unittest.mock import Mock, patch
from yala.main import LinterRunner
class TestLinterRunner(unittest.TestCase):
"""Test the LinterRunner class."""
@patch('yala.main.Config')
def test_chosen_not_found(self, mock_config):
"""Should print an erro... |
"""Platform for sensor integration."""
from __future__ import annotations
import homeassistant.helpers.config_validation as cv
import requests
import voluptuous as vol
from homeassistant.components.sensor import SensorEntity, PLATFORM_SCHEMA, SensorStateClass, SensorDeviceClass
from homeassistant.const import CONF_USE... |
import torch
import numpy as np
def get_sigmas(config):
if config.model.sigma_dist == 'geometric':
sigmas = torch.tensor(
np.exp(np.linspace(np.log(config.model.sigma_begin), np.log(config.model.sigma_end),
config.model.num_classes))).float().to(config.device)
... |
"""
User Animation Card
===================
Copyright (c) 2019 Ivanov Yuri
For suggestions and questions:
<kivydevelopment@gmail.com>
This file is distributed under the terms of the same license,
as the Kivy framework.
Example
-------
from kivymd.app import MDApp
from kivy.lang import Builder
from kivy.factory imp... |
# Moduł definiujący walidatory API
from marshmallow import Schema, fields, validate
fields.Email.default_error_messages['required'] = 'Email jest wymagany'
fields.Email.default_error_messages['invalid'] = 'Niepoprawny adres email'
class VUser(Schema):
# Walidator rejestracji
nick = fields.String(
r... |
class Option:
def __init__(self, option_info):
self.option_info = option_info
self.flag = option_info['flag']
def mkdir(self):
if self.flag == False:
return False
return self.option_info['mkdir']
def dir_name(self, problem):
if self.flag == False:
... |
import copy
import torch.nn as nn
from torch.quantization.fuser_method_mappings import get_fuser_method
# for backward compatiblity
from torch.quantization.fuser_method_mappings import fuse_conv_bn # noqa: F401
from torch.quantization.fuser_method_mappings import fuse_conv_bn_relu # noqa: F401
from typing import ... |
#################################################################################
# The Institute for the Design of Advanced Energy Systems Integrated Platform
# Framework (IDAES IP) was produced under the DOE Institute for the
# Design of Advanced Energy Systems (IDAES), and is copyright (c) 2018-2021
# by the softwar... |
"""Test component helpers."""
# pylint: disable=protected-access
from collections import OrderedDict
import unittest
from homeassistant import helpers
from tests.common import get_test_home_assistant
class TestHelpers(unittest.TestCase):
"""Tests homeassistant.helpers module."""
# pylint: disable=invalid-n... |
import pandas as pd
import numpy as np
def top_time(ind=None, gs=None):
"""
Selects the location (by coordinates) which was visited for the longest period during given time interval
:param ind: user id
:param gs: GeoDataFrame from groupby execution containing all the data in the given time interval
:return: user... |
import numpy as np
np.show_config() |
from PIL import Image as im
import numpy as np
from io import BytesIO
import csv
class outputResponse():
def __init__(self,reponse):
self.response = reponse
def retrieveResult(response, returntype):
if (returntype == "image/png" or returntype == "image/jpeg"):
img_arr = np.array(i... |
import pytest
import os
from machaon.types.file import TextFile
from machaon.types.shell import Path
from machaon.core.invocation import instant_return_test, instant_context
def test_construct(tmp_path):
FILEPATH = Path(__file__)
context = instant_context()
context.define_type(TextFile)
f = instant_re... |
import re
# match whole string
data1 = "aaab"
data2 = "aaaba"
pattern = r"\Aa+b\Z"
match1 = re.match(pattern, data1)
print(match1)
match2 = re.match(pattern, data2)
print(match2)
# regular expression options
data = "AaaA\n\raaaA"
pattern = r"^(a+)$"
match = re.match(pattern, data, re.I | re.M)
print(match)
print(m... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Rate',
fields=[
('id', models.AutoField(verbose... |
DEBUG = True
ALLOWED_HOSTS = ['*', ]
|
# coding: utf-8
# # python 爬虫相关
# ## 1. class 定义和使用
# In[11]:
import os
import requests
import time
import random
from lxml import etree
class Spider(object):
def __init__(self, savePath, keyWord):
self.headers = {
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 1... |
import logging
import logging.handlers
import sys
import os
import json
import sqlite3
import signal
import threading
import time
import difflib
import vk_api
from vk_api.longpoll import VkLongPoll, VkEventType
import requests.exceptions
cwd = os.path.dirname(os.path.abspath(__file__))
logging.basicConfig(
format=... |
"""
Definition of events.
"""
from abc import ABC
EVENT_LOG = 'eLog' #Log Event
EVENT_MARKETDATA = 'eMarketData' #Pushing MarketData Event
EVENT_TRADE = 'eTrade' #Trade Event
EVENT_BUY = 'eBuy' #Buy Event
EVENT_SELL = 'eSell' ... |
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Business Applications
# Copyright (C) 2004-2012 OpenERP S.A. (<http://openerp.com>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms o... |
import pytest
import io
from cite_seq_count import preprocessing
@pytest.fixture
def data():
from collections import OrderedDict
from itertools import islice
# Test file paths
pytest.correct_whitelist_path = 'tests/test_data/whitelists/correct.csv'
pytest.correct_tags_path = 'tests/test_data/... |
from game_data import *
from hosting import ServerHandler, ClientHandler
import json
board = [
["R", "K", "B", "Q", "E", "B", "K", "R"],
["P", "P", "P", "P", "P", "P", "P", "P"],
[" ", " ", " ", " ", " ", " ", " ", " "],
[" ", " ", " ", " ", " ", " ", " ", " "],
[" ", " ", " ", " ", " ", " ", " ", "... |
# Pydifact - a python edifact library
#
# Copyright (c) 2019 Christian González
#
# 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 ... |
"""Utilities for reading real time clocks and keeping soft real time constraints."""
import gc
import os
import time
import multiprocessing
from common.clock import sec_since_boot # pylint: disable=no-name-in-module, import-error
from selfdrive.hardware import PC, TICI
# time step for each process
DT_CTRL = 0.01 #... |
import os, json
import shutil, logging
import click
from pyspark.sql.functions import lit, udf, explode, array, to_json
from pyspark.sql.types import ArrayType, StringType, IntegerType, MapType, StructType, StructField
from luna.common.CodeTimer import CodeTimer
from luna.common.config import ConfigSet
from luna.com... |
# Copyright 2021 Supun Nakandala. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... |
# labplus mPython-box library
# MIT license; Copyright (c) 2018 labplus
# mpython-box buildin periphers drivers
# history:
# V1.0 zhaohuijiang
from machine import Pin, UART
import time
import ujson
from time import sleep_ms, sleep_us, sleep
# touchpad
class BS8112A(object):
""" """
def __init__(self, i2c)... |
import fodmc
# output_mode: PyFLOSIC, NRLMOL
# output_name: NameOfMolecule.xyz (for PyFLOSIC only)
output_mode = ['NRLMOL','PyFLOSIC'][1]
output_name = ['', 'test.xyz'][1]
fodmc.fodmc_mod.get_guess(output_mode,output_name)
|
# -*- coding: utf-8 -*-
#
# 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
#... |
# Generated by Django 3.1.1 on 2020-10-19 16:09
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('maps', '0011_auto_20201019_1839'),
]
operations = [
migrations.AlterField(
model_name='trafficsignal',
... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.1 on 2016-07-25 13:13
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('band', '0002_auto_20160725_1313'),
]
operations = [... |
"""
Augmenters that somehow change the size of the images.
List of augmenters:
* :class:`Resize`
* :class:`CropAndPad`
* :class:`Crop`
* :class:`Pad`
* :class:`PadToFixedSize`
* :class:`CenterPadToFixedSize`
* :class:`CropToFixedSize`
* :class:`CenterCropToFixedSize`
* :class:`Crop... |
from .common import *
__all__ = ["TestReadWriteMemory"]
class TestReadWriteMemory(MCPTestCase):
def test_read_flash_ok(self):
self.mcp.dev.read.return_value = self.xb0_00
self.assertEqual(self.mcp._read_flash(FlashDataSubcode.ChipSettings), self.xb0_00[4:14])
def test_read_sram_ok(self):
... |
#!/usr/bin/env python
from decimal import Decimal, getcontext
from fractions import Fraction
digits = 500
getcontext().prec = digits
def leibnitz(n):
"""
Parameters
----------
n : int
Returns
-------
Fraction
Approximation of pi.
"""
pi = Fraction(0)
sign = 1
for... |
import os.path
from app.data.database import init_db, db_path, get_expected_pathname, set_path
def db_exists():
return os.path.isfile(db_path)
def check_db():
global db_path
if (db_path != get_expected_pathname()):
print('DB Check: Running backup')
backup_database_to(get_expected_pathname... |
# 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, overload
from .. import _utilities
from... |
import numpy as np
def partition(arr, low, high):
i = (low-1) # index of smaller element
pivot = arr[high] # pivot
for j in range(low, high):
# If current element is smaller than the pivot
if arr[j] < pivot:
# increment index of smaller element
i = i+... |
#!/bin/env python3
# Steps requried to use
# install requried libraries
# (root)# dnf install python3-ldap3
#
# Create python virtual environment directory
# (user)$ python3 -m venv ./venv3
#
# Enable virtual environment
# (user)$ source ./venv3/bin/activate
#
# Update pip and then install needed libary
# (user-venv3)... |
"""Test UPnP/IGD config flow."""
from datetime import timedelta
from unittest.mock import AsyncMock, patch
from homeassistant import config_entries, data_entry_flow
from homeassistant.components import ssdp
from homeassistant.components.upnp.const import (
CONFIG_ENTRY_SCAN_INTERVAL,
CONFIG_ENTRY_ST,
CONF... |
from .BSD500 import BSD500
__all__ = ('BSD500')
|
week = ["SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT"]
print(7-week.index(input())) |
"""
priorityqueue.py
Priority Queue Implementation with a O(log n) Remove Method
This file implements min- amd max-oriented priority queues based on binary
heaps. I found the need for a priority queue with a O(log n) remove method.
This can't be achieved with any of Python's built in collections including
the heapq m... |
from selenium import webdriver
from fixture.session import SessionHelper
from fixture.group import GroupHelper
from fixture.contact import ContactHelper
class Application:
def __init__(self, browser, base_url):
if browser == "firefox":
self.wd = webdriver.Firefox()
elif browser == "ch... |
import matplotlib.pyplot as plt
from shapely.geometry import MultiLineString
from .route_iterator import RouteIterator
from .graphconverter import GraphConverter
class TramLine(object):
"""Class represents single tram line for example '33: from Pilczyce to Sępolno' """
def __init__(self, number, direction_to... |
"""Hermes MQTT service for Rhasspy wakeword with snowboy"""
import argparse
import asyncio
import dataclasses
import itertools
import json
import logging
import os
import sys
import typing
from pathlib import Path
import paho.mqtt.client as mqtt
import rhasspyhermes.cli as hermes_cli
from . import SnowboyModel, Wake... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.