content stringlengths 5 1.05M |
|---|
from PySide2.QtWidgets import QWidget
from PySide2.QtGui import QMouseEvent
from PySide2.QtCore import QTimer, Qt
from ui.card_ui import Ui_Card
class Card(QWidget, Ui_Card):
def __init__(self, shape, number, parent=None,):
super().__init__(parent=parent, f=Qt.FramelessWindowHint)
self.setupUi(se... |
import os
import sys
import pandas as pd
import math
def GeneCounts(infile2):
in2 = open(infile2)
headline = in2.readline()
GeneDict = {}
for line in in2:
fields = line.strip().split("\t")
gene = fields[0]
GeneDict[gene] = [int(x) for x in fields[1:]]
return GeneDict
def Counts(infile1,outfile,GeneDict):
... |
import sys
import os
import hashlib
from os.path import join, commonprefix, isfile, isdir, dirname, basename
from pyflu.path import sub_path
import bsdiff
import tarfile
import pickle
import struct
import shutil
from StringIO import StringIO
__version__ = "0.1"
class UpdateError(Exception): pass
class InvalidFile(... |
numero1 = int(input('Primeiro número: '))
numero2 = int(input('Segundo número: '))
s = numero1 + numero2
print('A sooma é' , s)
|
# Copyright (c) 2020 HITCON Agent Contributors
# See CONTRIBUTORS file for the list of HITCON Agent Contributors
# 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, includin... |
import collections
from others.utils import cal_date_f1
import pytest # 引入pytest包
def test_count(): # test开头的测试函数
pred_date = ["2017-12-09T20", "2017-12-09", "2017-12-10", "2017-12-12"]
ref_date = [
"2017-12-09 20:10",
"2017-12-09",
"2017-12-09",
"2017-12-11",
"2017-1... |
import torch
from torch import nn
from torch.autograd import Variable
import grassmodel
from draw3dobb import showGenshape
decoder = torch.load('./models/vae_decoder_model.pkl')
for i in range(10):
root_code = Variable(torch.randn(1,80)).cuda()
boxes = grassmodel.decode_structure(decoder, root_code)
sho... |
from ..utils import Object
class SetPinnedChats(Object):
"""
Changes the order of pinned chats
Attributes:
ID (:obj:`str`): ``SetPinnedChats``
Args:
chat_list (:class:`telegram.api.types.ChatList`):
Chat list in which to change the order of pinned chats
chat_i... |
import json
import xmltodict
simple_xml = """<?xml version="1.0" encoding="UTF-8"?>
<library name="Algiers Regional Library">
<books>
<book format="hardcover">
<title>Wise Blood</title>
<author format="First Name Last Name">Flannery O'Connor</author>
</book>
<book format="paperb... |
from importlib import import_module
# For update times
from time import time as unix_timestamp
# Enable custom node function import
import sys, os
dup = os.path.dirname
env_root = dup(dup(dup(__file__)))
sys.path.append(os.path.join(env_root, 'data'))
import get_node
class InvalidNodeError(Exception):
pass
cla... |
import numpy as np
import cv2
import matplotlib.pyplot as plt
image_path = "../assets/img.png"
image = cv2.imread(image_path)
image = cv2.resize(image, (256, 256))
image_shape = image.shape
rows, cols, ch = image.shape
pts1 = np.float32([[50, 50],
[200, 50],
[50, 200]])
pts2 =... |
import math
import time
import pyautogui
from gaze_tracking import GazeTracking
from .gaze import Gaze
from .calibration import Calibration
class MouseControl:
def __init__(self, gaze: GazeTracking, calibration: Calibration):
self.gaze_tracking = gaze
self.last_gaze = Gaze(self.gaze_tracking)
... |
from news import NewsItem
from typing import List, Literal, Optional, Set
from pydantic.main import BaseModel
from requests import get
from datetime import datetime
from time import sleep
import threading
import cachetools
from pydantic import BaseSettings
from candles import *
import news_market_data
import news_mar... |
from flask import redirect, url_for, session
from functools import wraps
def usuario_conectado(f):
@wraps(f)
def wrap(*args, **kwargs):
if 'usuario_conectado' in session:
return f(*args, *kwargs)
else:
return redirect(url_for('autorizar.entrar'))
return wrap
def... |
import os
import datetime
# os.environ["FIRESTORE_EMULATOR_HOST"] = "localhost:8081"
import firebase_admin
from firebase_admin import credentials, firestore
class FBDatabase:
db = None
def __init__(self):
if self.db is None:
cred = credentials.Certificate(
"../../keys/key... |
from typing import Dict
def solution() -> None:
global input
numbers_dictionary: Dict[str, int] = dict()
try:
while (line_in := input()) != "Search":
numbers_dictionary[line_in] = int(input())
while (line_in := input()) != "Remove":
print(numbers_dictionary[line_in... |
from __future__ import unicode_literals
from django.utils.translation import ugettext_lazy as _
from smart_settings import Namespace
from .literals import DEFAULT_LOGIN_METHOD, DEFAULT_MAXIMUM_SESSION_LENGTH
namespace = Namespace(name='authentication', label=_('Authentication'))
setting_login_method = namespace.add... |
import scipy.io
import os
import requests
url='https://www.dropbox.com/s/875u1rkva9iffpj/Gist512CIFAR10.mat?dl=1'
response = requests.get(url)
with open(os.path.join("./", "Gist512CIFAR10.mat"), 'wb') as f:
f.write(response.content)
mat = scipy.io.loadmat('./Gist512CIFAR10.mat')
from sklearn.preprocessing import... |
import unittest
import numpy as np
from pymicro.crystal.lattice import Lattice, HklDirection, HklPlane, Symmetry
from pymicro.crystal.microstructure import Orientation
from pymicro.xray.laue import select_lambda, diffracted_vector, gnomonic_projection_point, gnomonic_projection, index
from pymicro.xray.detectors import... |
print(__doc__)
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import make_multilabel_classification
from sklearn.multiclass import OneVsRestClassifier
from sklearn.svm import SVC
from sklearn.decomposition import PCA
from sklearn.cross_decomposition import CCA
def plot_hyperplane(clf, min_... |
"""
Copyright (c) Facebook, Inc. and its affiliates.
"""
import os
import unittest
import json
from ..nsp_querier import NSPQuerier
from droidlet.shared_data_structs import MockOpt
from prettytable import PrettyTable
class fontcolors:
HEADER = "\033[95m"
OKBLUE = "\033[94m"
OKCYAN = "\033[96m"
OKGREEN... |
class BasicAuth(object):
pass |
from common_files.admin.base import BaseAdmin
from common_files.admin.timestamp import TimestampAdmin
|
from django.shortcuts import render, redirect
from tasks import forms
# Create your views here.
from tasks.models import Task
def create(request):
if request.method == 'POST':
task = forms.TaskForm(request.POST).save(commit=False)
task.save()
return redirect('panel')
else:
re... |
# Imports the Google Cloud client library
import os
from ipware import get_client_ip
from translate import translator
import django_mlcommenting
def google_translate(text, target='en'):
# Instantiates a client
try:
new = translator(source=text, target=target)
except AttributeError as e:
... |
from skimage.transform import resize
import pandas as pd
import cv2, json, os
from skimage.color import rgb2grey
from sklearn.preprocessing import MinMaxScaler
from skimage.exposure import rescale_intensity
from skimage.transform import resize
import numpy as np
from PIL import Image
import tensorflow as tf
from keras... |
import heapq
from typing import Iterable, Tuple
import numpy as np
def normalize(vector):
"""
Returns the normalized vector (same dtype) using the L2 norm (||v||2) for a vector, v.
"""
return vector / np.sqrt(np.dot(vector, vector))
def cosine_similarity(vector1, vector2):
"""
Returns the co... |
"""Setup"""
import os
import sys
import site
from pathlib import Path
from subprocess import call
from setuptools import setup
def readme():
"""Readme"""
with open("README.md") as rhand:
return rhand.read()
setup(name='python-git',
version='2018.01.08',
description='Automate boring git ... |
f=open('C:\\Python Practice\\MyProjects01\\MyProjects01\\20180609\\poem_01.txt')
for k in f.readlines():
print(k.strip().split())
f.close()
|
import os
from types import ModuleType
from typing import Optional, Tuple
from tests.utils.dirutils import file_text
from tests.utils.filters import metadata_filter
from tests.environment import env
def compare_python(expected: str, actual: str, expected_path: Optional[str] = None) -> Optional[str]:
"""
Make... |
# Imports
import discord
from discord.ext import commands
import json
# Initialize bot and set command prefix
QBot = commands.Bot(command_prefix="$")
# Cooking variables
QBot.is_cooking = False
QBot.cooking_step = 0
# Bot startup status event
@QBot.event
async def on_ready():
print("QuesadillaBot up and ready to... |
# Generated by Django 3.1.3 on 2020-11-12 14:01
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('service', '0005_auto_20201112_1355'),
]
operations = [
migrations.AddField(
model_name='appointment... |
# -*- coding: utf-8 -*-
# <nbformat>3.0</nbformat>
# <markdowncell>
# #Extract ESTOFS water levels using NetCDF4-Python and analyze/visualize with Pandas
# <codecell>
# Plot forecast water levels from NECOFS model from list of lon,lat locations
# (uses the nearest point, no interpolation)
%matplotlib inline
import ... |
"""
@file
@brief Shortcuts to *tools*.
"""
from .json_helper import json_loads, json_dumps
|
import matplotlib.pyplot as plt
import numpy as np
from sklearn import datasets, linear_model
from sklearn.metrics import mean_squared_error, r2_score
import matplotlib.pyplot as plt
from math import fabs
def main():
data_set = datasets.load_boston()
features, target = split_features_target(data_set)
split = 0.15
... |
from requests.structures import CaseInsensitiveDict
from six.moves.urllib.parse import quote
from .base_requests import AnymailRequestsBackend, RequestsPayload
from ..exceptions import AnymailRequestsAPIError
from ..message import AnymailRecipientStatus
from ..utils import get_anymail_setting
class EmailBackend(Anym... |
import logging
import pathlib
import webbrowser
from typing import List
from sqlalchemy import Column, ForeignKey, Integer, Table, Text, create_engine, desc
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship, sessionmaker
logger = logging.getLogger(__name__)
Base = declar... |
spotify_client_id = ''
spotify_client_secret = ''
|
from django.urls import path
from tictactoe import views
app_name = 'tictactoe'
urlpatterns = [
# /tictactoe/
path('', views.welcome, name='welcome')
] |
def Load (_Path):
with open (_Path, 'r') as File:
return Loads (File.read ())
def Loads (_Data):
if isinstance (_Data, str):
Data = _Data.split ('\n')
else:
Data = _Data
Contents = {}
LineIndex = 0
for Line in Data:
LineIndex += 1
if Line in ' \n\t':
... |
from django.db import models
from api.models.gcd.image import GCDImage
from api.models.gcd.publisher import GCDPublisher
class GCDBrandGroup(models.Model):
class Meta:
app_label = 'api'
ordering = ('name',)
db_table = 'gcd_brand_groups'
brand_group_id = models.AutoField(primary_ke... |
# Copyright 2015 ETH Zurich
#
# 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, sof... |
Mod = 1000000007
def f(a,x):
if x<1:
return 1
elif x == 1:
return a%Mod
else:
b=f(a,x//2)
if x%2 == 1:
return (b*b*a)%Mod
else:
return (b*b)%Mod
A=int(input())
X=int(input())
print(f(A,X)) |
#
# MIT License
#
# Copyright (c) 2020 Pablo Rodriguez Nava, @pablintino
#
# 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 righ... |
import argparse
import ray
from wiki_search import Dataset, Engine
if __name__ == '__main__':
if not ray.is_initialized():
ray.init()
parser = argparse.ArgumentParser()
parser.add_argument('--data_dir', type=str, default='./data')
parser.add_argument('--ranking', type=str, default='tfidf')
... |
import collections
import os
import re
import networkx as nx
from .traverser import Traverser
class Code(Traverser):
def __init__(self, logger, serializer):
Traverser.__init__(self, logger, serializer, 'code')
def find(self):
print "# Calls"
self.graphChains = nx.DiGraph()
co... |
#!/usr/bin/env python3
#
# dbs_fast_scrape (DBS *Fast* Scraping script)
# Written by zzyzy
#
# This is the faster version of dbs_scrape, also with more currency rates
# compared to dbs_scrape. There will also be some currency missing like
# MYR for some reason. As this is a cheap process, it can run more
# ... |
# method to calculate the factorial of a number
def factorial(num : int) -> int :
fact = 1
for i in range(2, num+1) :
fact*=i
return fact
if __name__ == "__main__":
mylist = [1,2,3,4,5]
for el in mylist :
print("Factorial of {} = {}".format(el, factorial(el)), end="\r\n"... |
from citePy11.citePy11 import CitePy11
from citePy11.citePy11 import parse |
# taken directly from asyncio runners.py module in python 3.7+
# needed for python 3.6
import asyncio
def _cancel_all_tasks(loop):
to_cancel = asyncio.Task.all_tasks(loop)
if not to_cancel:
return
for task in to_cancel:
task.cancel()
loop.run_until_complete(
asyncio.tasks.ga... |
# Base Python
import datetime
import csv
import enum
import os.path
import io
import glob
from collections import Counter
# PIP Packages
import unidecode
import yaml
from sqlalchemy.ext.associationproxy import association_proxy
from sqlalchemy.orm import backref
from sqlalchemy import literal, case
from werkzeug.except... |
# coding=utf-8
import argparse
import csv
import os
import re
import shutil
import sys
import time
import cv2
import numpy as np
import tensorflow as tf
from PIL import Image
from pytesseract import pytesseract
from cropper import cropper
sys.path.append("./crnn/crnn.pytorch")
sys.path.append("./ctpn")
sys.path.appe... |
## @file
# Parse FV image
#
# Copyright (c) 2008 - 2014, Intel Corporation. All rights reserved.<BR>
# This program and the accompanying materials
# are licensed and made available under the terms and conditions of the BSD License
# which accompanies this distribution. The full text of the license may be found a... |
#!/usr/bin/python3
#-*-coding:utf-8-*-
import os
import socket
import time
import threading
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
import utils
from worker import FileWorker
from worker import SockWorker
from worker import DataWorker
from authority import AuthClient... |
# Generated by Django 2.1 on 2020-04-28 14:59
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('test_app', '0002_foomodel_extra'),
]
operations = [
migrations.AddField(
model_name='foomodel',
name='pre_serializer',... |
def test():
assert [(ent.text, ent.label_) for ent in doc1.ents] == [
("amsterdem", "GPE")
], "Double-check the entities in the first example."
assert [(ent.text, ent.label_) for ent in doc2.ents] == [
("Paris", "GPE")
], "Double-check the entities in the second example."
assert [(en... |
import cv2
import config
import platform
import os
if(config.imageType == "Video"):
if(platform.system() == "Linux" and config.callOS == 1):
print("Calling OS Script")
os.system(config.osScript)
cap = cv2.VideoCapture(config.imageSource)
if config.imageSource == 0 or config.imag... |
"""Views for Zinnia random entry"""
from django.views.generic.base import RedirectView
from zinnia.models.entry import Entry
class EntryRandom(RedirectView):
"""
View for handling a random entry
simply do a redirection after the random selection
"""
permanent = False
def get_redirect_url(sel... |
"""
Wigner function of a Kerr resonator
"""
from scipy.special import hyp2f1, factorial, gamma
from scipy.misc import comb
import numpy as np
import decimal
def hyper2f1m(m, c1, c1c2, eta):
"""
The Gauss hyper geometric function summing upto m terms. It is given by:
$$\_2F_1(-m, c_1; c_1 + c_2; \eta) = \... |
import numpy as np
import matplotlib.pyplot as plt
import sklearn.metrics as metric
import seaborn as sns
import pydicom
import SimpleITK as sitk
LIST=open('../data/ages.txt','r')
times=LIST.readlines()
tname=[n.split('\t')[0] for n in times]
sex=[n.split('\t')[1] for n in times]
ages=[int(n.split('\t')[2][:-1]) for n ... |
from flask import request, g, current_app, jsonify, url_for
from . import api
from ..models import Post, Permission
from .decorators import permission_required
from .errors import forbidden
from app import db
@api.route('/posts/')
def get_posts():
page = request.args.get('page', 1, type=int)
pagination = Post.query.... |
import json
import logging
import pytest
import sdk_cmd
import sdk_install
import sdk_plan
import sdk_tasks
from tests import config
log = logging.getLogger(__name__)
@pytest.fixture(scope="module", autouse=True)
def configure_package(configure_security):
try:
sdk_install.uninstall(config.PACKAGE_NAME, ... |
import DBTables
True = 1
False = 0
# Get the TTable object associated to
# the delphi table displayed on right
# It is done when you click on Execute
T = DBTables.T
# Display columns
print "Columns: "
for i in T.FieldNamesAsTuple():
print " ", i
T.CancelRange()
# For each record of the table
for ... |
################################################################################
# Copyright (c) 2021 ContinualAI. #
# Copyrights licensed under the MIT License. #
# See the accompanying LICENSE file for terms. ... |
from typing import List
class Internal_Data:
def __init__(self, name, data) -> None:
self.name = name
self.raw_data : List[str] = data
self.pp_data : List[str] = None
self.pruned_data : List[str] = None #without stopwords and punctuation
def add_preprocessed_data(self, pp_data)... |
# Copyright (C) 2013-2017 Internet Systems Consortium.
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET ... |
class Pokemon:
def __init__(self, id, nome, altura, peso, tipo):
self.__id = id
self.__nome = nome
self.__altura = altura
self.__peso = peso
self.__tipo = tipo
@property
def id(self):
return self.__id
@property
def nome(self):
return self.__n... |
"""
py3status
"""
import os
import sys
from setuptools import find_packages, setup
from setuptools.command.develop import develop
from setuptools.command.install import install
from setuptools.command.easy_install import _to_ascii, ScriptWriter
module_path = os.path.join(
os.path.dirname(os.path.realpath(__file__... |
# Generated by Django 2.2.16 on 2020-11-07 01:33
import atlantisbot_api.models
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('atlantisbot_api', '0004_auto_20201107_0019'),
]
operations = [
migrations.AlterField(
model_name='team',
... |
from ...utils.train import linlogcut
from .base import Energy
__all__ = ["LinLogCutEnergy"]
class LinLogCutEnergy(Energy):
"""Cut off energy at singularities.
Parameters
----------
energy : Energy
high_energy : float
Energies beyond this value are replaced by `u = high_energy + log(1 + e... |
import sys
from PySide import QtGui, QtCore
from ui import PreviewWidget, LayerWidget, Toolbar, FunctionsWidget
class MainWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent=parent)
self.m_Preview = PreviewWidget(self)
self.setCent... |
import time
import pytest
from ddtrace.profiling import collector
from ddtrace.profiling import recorder
def _test_collector_collect(collector, event_type, fn=None, **kwargs):
r = recorder.Recorder()
c = collector(r, **kwargs)
c.start()
thread_id = c._worker.ident
while not r.events[event_type]:... |
import unittest
import os
from test_helper import TESTDATA
import numpy as np
import karta
import karta.vector as vector
from karta.vector.geometry import Point, Multipoint, Line, Polygon
class GPXTests(unittest.TestCase):
def setUp(self):
self.points = [vector.gpx.Point((np.random.random(), np.random.ra... |
from flask import Blueprint
from flask_restful import Api
from main.server.resources.Message import MessageListResource, MessageResource
# Api Blueprint
api_bp = Blueprint('api', __name__)
api = Api(api_bp)
# Routes
api.add_resource(MessageListResource, '/messages')
api.add_resource(MessageResource, '/messages/<me... |
#!/usr/bin/env python3
# encoding: utf-8
import json, sys
import pandas as pd
from datetime import date
from datetime import datetime
from models.exchange.coinbase_pro.api import AuthAPI as CBAuthAPI, PublicAPI as CBPublicAPI
def printHelp():
print ('Create a config.json:')
print ('* Add 1 or more portfolios... |
from myapi.extensions import db, pwd_context
class User(db.Model):
"""Basic user model
"""
__tablename__ = "user_v2"
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True, nullable=False)
email = db.Column(db.String(80), unique=True, nullable=False)
p... |
"""Parse network devices' configuration and store in database."""
import sys
import os
from loguru import logger
from faddr.rancid import RancidDir
from faddr.device import Device
from faddr.device import CiscoIOSDevice
__version__ = "0.0.3"
__all__ = (
"RancidDir",
"Device",
"CiscoIOSDevice",
)
if os... |
"""
Inference on webcams: Use a model on webcam input.
Once launched, the script is in background collection mode.
Press B to toggle between background capture mode and matting mode. The frame shown when B is pressed is used as background for matting.
Press Q to exit.
Example:
python inference_webcam.py \
... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import absolute_import, division, print_function, unicode_literals
from collections import Counter
import pytest
from numpy.testing.utils import assert_allclose
from astropy import units as u
from ...utils.testing import assert_quantity_all... |
from __future__ import absolute_import, division
import numpy as np
import scipy.sparse as ss
import warnings
from scipy.linalg import cho_factor, get_lapack_funcs
from sklearn import linear_model
from sklearn.metrics import pairwise_distances
from graphs import Graph
from ..mini_six import range
from .nei... |
#
# Copyright (c) 2018 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... |
#!/usr/bin/env python
from __future__ import absolute_import
from ._helper import AuraTestCase
class TestTrack_ReturnedAudioMimetype(AuraTestCase):
def setUp(self):
super(TestTrack_ReturnedAudioMimetype,self).setUp()
def test_mime_mpeg(self):
for item in self.items_all_formats():
... |
# Copyright 2018-2020 Descartes Labs.
#
# 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 ... |
# PROBLEM 52
# It can be seen that the number, 125874, and its double, 251748,
# contain exactly the same digits, but in a different order.
# Find the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, contain the same digits.
def compare_digits(num1, num2):
digist1 = list(str(num1))
digist2 = li... |
# Copyright 2014-2016 Insight Software Consortium.
# Copyright 2004-2008 Roman Yakovenko.
# Distributed under the Boost Software License, Version 1.0.
# See http://www.boost.org/LICENSE_1_0.txt
"""Parser sub-package.
"""
from .config import gccxml_configuration_t
from .config import xml_generator_configurati... |
import sys, json
import torch
import os
import numpy as np
import opennre
from opennre import encoder, model, framework
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--bag_size', type=int, default=0)
parser.add_argument('--ckpt', type=str, default='nyt10_pcnn_att')
parser.add_argument('--only... |
import pytest
from aoc_cqkh42.year_2015 import day_10
@pytest.mark.parametrize(
'data, answer',
[('1', 2), ('11', 2), ('21', 4), ('1211', 6), ('111221', 6)]
)
def test_part_a(data, answer):
assert day_10.part_a(data, iters=1) == answer
|
'''
File name: Test Segmentation
Author: minhnc
Date created(MM/DD/YYYY): 10/2/2018
Last modified(MM/DD/YYYY HH:MM): 10/2/2018 5:22 AM
Python Version: 3.6
Other modules: [None]
Copyright = Copyright (C) 2017 of NGUYEN CONG MINH
Credits = [None] # people who reported bug fixes, made sugg... |
import os
import sys
import time
import pymogilefs
from google.cloud import pubsub_v1, storage
from shared import (
BATCH_SETTINGS,
MIGRATE,
MogileFile,
copy_object,
encode_json,
make_bucket_map,
make_db_connection,
)
BUCKET_MAP = make_bucket_map(os.environ["BUCKETS"])
TOPIC_ID = os.envir... |
class FilterError(Exception):
"""
Raised when filter is malformed
"""
pass
class JSONEncodingValueError(Exception):
"""
Raised when data cannot be encoded into json
"""
pass
class MimeTypeError(Exception):
"""
Raised when incompatible MIME type selected
"""
pass
... |
# 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
fro... |
# dirbrowser v0.1.0
|
# -*- coding: utf-8 -*-
import math
a = float(input())
b = float(input())
print('%d°' % int(round(math.degrees(math.atan(a/b)))))
|
import tensorflow as tf
import numpy as np
import math
# tensorflow 2.3.1
# numpy 1.18.5
interpreter = tf.lite.Interpreter(model_path="pilot2.tflite")
interpreter.allocate_tensors()
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()
input_shape0 = input_details[0]['sha... |
from webcamlib.Config import Config, ConfigTemperature
import logging
from pathlib import PosixPath
from abc import ABC, abstractproperty
from webcamlib.Exceptions import DeviceError, ConfigError
class AbstractLightSensor(ABC):
""" Base class for the light sensor """
def __init__(self, lightsensor_config):
... |
import asyncio
import json
from django.contrib.auth import get_user_model
from channels.consumer import AsyncConsumer
from channels.db import database_sync_to_async
from .models import Thread, ChatMessage
class ChatConsumer(AsyncConsumer):
async def websocket_connect(self, event):
print("connected", event... |
# Copyright 2021 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... |
from flask import Flask
from flask_script import Manager
from flask_sqlalchemy import SQLAlchemy
class DatabaseSetup(object):
"""Database administration logic."""
@classmethod
def set_up_db(cls, app: Flask, db: SQLAlchemy):
"""
Create all db tables.
:param app: main Flask app.
... |
import json
from .errors import GhostException
class Model(dict):
"""
Wrapper around the response objects
to allow accessing fields as properties.
"""
def __getattr__(self, item):
return self.get(item)
def __setattr__(self, key, value):
self[key] = value
class Post(Model):... |
import time
from functools import wraps
def retry(
ExceptionToCheck,
tries=4,
delay=3,
backoff=2,
):
"""Retry calling the decorated function using an exponential backoff.
http://www.saltycrane.com/blog/2009/11/trying-out-retry-decorator-python/
original from: http://wiki.python.org/moin/Py... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.