content
stringlengths
0
894k
type
stringclasses
2 values
import pandas as pd import networkx as nx import numpy as np from typing import Union from pymarket.transactions import TransactionManager from pymarket.bids import BidManager from pymarket.mechanisms import Mechanism, MechanismReturn RandomState = Union[np.random.RandomState, None] def p2p_random(bids: pd.DataFrame...
python
SEP = "/" def _splitnode(nodeid): """Split a nodeid into constituent 'parts'. Node IDs are strings, and can be things like: '' 'testing/code' 'testing/code/test_excinfo.py' 'testing/code/test_excinfo.py::TestFormattedExcinfo::()' Return values are lists e.g. [] ...
python
print("Hell o' world.")
python
"""test_rest_api URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.10/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Cl...
python
from typing import Dict, List, Optional, Pattern, Type, TypedDict # CONFIG ALIASES from pyVmomi import vim ResourceFilterConfig = TypedDict( 'ResourceFilterConfig', {'resource': str, 'property': str, 'type': str, 'patterns': List[str]} ) MetricFilterConfig = Dict[str, List[str]] InstanceConfig = TypedDict( '...
python
#!/usr/bin/env python3 from setuptools import setup, find_packages setup( name = "ascii_py", version = "2.0", description = "Make ascii art", # This is because shutil.get_terminal_size() was added in 3.3 python_requires=">=3.5", author = "ProfOak", author_email = "OpenProfOak@gmail.com", ...
python
# Use Modern Python from __future__ import unicode_literals, absolute_import, print_function # System imports # Django imports from django.forms import ValidationError, Field, TextInput # External libraries import six # Local imports import django_prbac.csv class StringListInput(TextInput): def render(self, n...
python
import os import shutil import tempfile import unittest import numpy as np import cwepr.dataset import cwepr.exceptions import cwepr.io.magnettech import cwepr.processing ROOTPATH = os.path.split(os.path.abspath(__file__))[0] class TestMagnettechXmlImporter(unittest.TestCase): def setUp(self): source =...
python
from django.apps import AppConfig class BillingsConfig(AppConfig): name = 'billings' def ready(self): import billings.signals # noqa
python
from utils import parsing, mysql_module config = parsing.parse_json('config.json') mysql = mysql_module.Mysql() def is_owner(ctx): return ctx.message.author.id in config["owners"] def is_server_owner(ctx): return ctx.message.author.id == ctx.message.server.owner def in_server(ctx): return ctx.message....
python
import jedi from jedi.evaluate.recursion import ExecutionRecursionDetector try: from queue import Queue except ImportError: # Python 2 shim from Queue import Queue stop_execution_signal_queue = Queue(maxsize=1) """ Allows a controller thread to cause Jedi to abort execution. `ExecutionRecursionDetector.pu...
python
# -*- coding: utf-8 -*- from enum import Enum, auto class TokenType(Enum): """ Types (categories) of tokens such as "number", "symbol" or "word". """ Unknown = 0, Eof = auto() Eol = auto() Float = auto() Integer = auto() HexDecimal = auto() Number = auto() Symbol = auto() ...
python
from __future__ import absolute_import default_app_config = 'project.jass.apps.JASSAppConfig'
python
import pytest @pytest.mark.functions def test_fill_empty(null_df): df = null_df.fill_empty(columns=["2"], value=3) assert set(df.loc[:, "2"]) == set([3]) @pytest.mark.functions def test_fill_empty_column_string(null_df): df = null_df.fill_empty(columns="2", value=3) assert set(df.loc[:, "2"]) == set...
python
# By Soham Koradia as a project for Khan Academy ''' The process to user this is similar as that described at the top of the total_infection module, and the onyl difference is that instead of running the total_infection algorithm, you would use this one, like so (continuing from the example users given in that module)...
python
import numpy as np import matplotlib.pyplot as plt data = np.loadtxt("intento.dat") n_points = int(np.sqrt(len(data))) grid = np.reshape(data.T, (201, 201)) plt.figure(figsize=(15,5)) plt.subplot(1,2,1) plt.imshow(grid) plt.xlabel("Indice X") plt.ylabel("Indice T") plt.colorbar(label="Temperatura") T1=data[:,0] T2...
python
from operator import attrgetter import pyangbind.lib.xpathhelper as xpathhelper from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType, RestrictedClassType, TypedListType from pyangbind.lib.yangtypes import YANGBool, YANGListType, YANGDynClass, ReferenceType from pyangbind.lib.base import PybindBase from d...
python
#!/usr/bin/env python3 class DSHead(): def printTemplateHead(self): templateHeader = "".join(open('tjgwebservices/views/static/dsheader.tpl','r').readlines()) templateHeader = templateHeader.replace("{website.title}","II Data School") templateHeader = templateHeader.replace("{website.v...
python
class AverageMeter(object): """Computes and stores the average and current value""" def __init__(self): self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 def update(self, val, n=1): self.val = val self.sum += val...
python
a= int(input('Digite um numero: ')) print(f'{a*1}\n{a*2}\n{a*3}\n{a*4}\n{a*5}\n{a*6}\n{a*7}\n{a*8}\n{a*9}\n{a*10}')
python
class User(object): def __init__(self, **args): self.id = args.get('id') self.name = args.get('name') self.username = args.get('username') self.email = args.get('email') self.street = args.get('street') self.suite = args.get('suite') self.city = args.get('city...
python
# -*- coding: utf-8 -*- from torchvision.models.resnet import BasicBlock, Bottleneck, ResNet, model_urls as imagenet_urls from torchvision.models.utils import load_state_dict_from_url from .utils import cnn_model __all__ = ['resnet18', 'resnet34', 'resnet50', 'resnet101', 'resnet152', 'resnext50_32x4d', '...
python
def cockroach_speed(s): return int(s * 27.7778)
python
from .dataset_processing import apply_mask, roi_array
python
""" real_estate_in_korea trade check command line tool.""" from real_estate_in_korea.main import main main(None)
python
# 公主连接Re:Dive会战管理插件 # clan == クラン == 戰隊(直译为氏族)(CLANNAD的CLAN(笑)) from nonebot import on_command from hoshino import R, Service, util from hoshino.typing import * from .argparse import ArgParser from .exception import * sv = Service('clanbattle') SORRY = 'ごめんなさい!嘤嘤嘤(〒︿〒)' _registry:Dict[str, Tuple[Callable, ArgParse...
python
# # Copyright 2018 Analytics Zoo 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...
python
""" Code is generated by ucloud-model, DO NOT EDIT IT. """ import pytest import logging from ucloud.core import exc from ucloud.testing import env, funcs, op, utest logger = logging.getLogger(__name__) scenario = utest.Scenario(279) @pytest.mark.skipif(env.is_ut(), reason=env.get_skip_reason()) def test_set_279(...
python
# deliverable_spec.py # This file is auto-generated from the same code that generates # https://docs.patreon.com. Community pull requests against this # file may not be accepted. import pytest from patreon.schemas import deliverable @pytest.fixture def attributes(): return [ 'completed_at', 'deli...
python
from base_automation import BaseAutomation from lib.core.monitored_callback import monitored_callback HOME_ZONE = "home" AWAY = "not_home" MESSAGE_LEFT_ZONE = "{} left {}" MESSAGE_ARRIVED_ZONE = "{} arrived {}" class ZoneChangeNotificationAutomation(BaseAutomation): def initialize(self): # args ...
python
"""All widgets related to editing channels are here.""" from PyQt4 import QtGui, QtCore from ..ramps import Channel from CommonWidgets import QMultipleSpinBoxEdit, QNamedPushButton import rampage.format as fmt class QEditChannelInfoDialog(QtGui.QDialog): """Dialog to edit channel info. This dialog is called...
python
import os import bpy import bpy_extras from ... import ops, plugin, plugin_prefs, registry, utils from ...version_utils import assign_props, IS_28 from .. import imp from . import utils as imp_utils, props op_import_object_props = { 'filter_glob': bpy.props.StringProperty( default='*.object', options={'...
python
# Copyright (c) 2011-2020 Eric Froemling # # 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 # to use, copy, modify, merge, publish,...
python
import shutil import optparse from os import listdir, mkdir from os.path import abspath, join, exists from codecs import open from lxml import etree from math import floor def voc2yolo(output_p, imgs_p, labels_p, split_ratios = None): img_filetype = ['.jpg', '.jpeg', '.png', '.tiff', '.tif'] classes_name = {}...
python
from flask_wtf import FlaskForm from wtforms import SelectMultipleField, StringField, SubmitField, \ TextAreaField, ValidationError from wtforms.validators import DataRequired, Optional class GroupForm(FlaskForm): """Main form for Group GUI""" name = StringField('Name', validators=[DataRequired()]) de...
python
from face_api.views import FaceApi from django.urls import path,include urlpatterns = [ path('',FaceApi.as_view()) ]
python
from time import sleep print('CONTAGEM REGRESSIVA') for c in range(10, -1, -1): print(c) sleep(1) print('KABUM!!!')
python
# -*- coding: utf-8 -*- from .didtx import ItemFromConfirmationId, ItemFromDid, Create, RecentItemsFromDid from .did_document import GetDidDocumentsFromDid, GetDidDocumentsFromCryptoname from .servicecount import GetServiceCountSpecificDidAndService, GetServiceCountAllServices
python
import sys import argparse import collections from os import remove, path from subprocess import call def _compress_png(source_path, destination_path, is_quantization_allowed): PNG_CRUSH_TOOL = "./lib/pngcrush_1_8_11_w64.exe" PNG_QUANT_TOOL = "./lib/pngquant.exe" png_crush_source = source_path tempora...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- import numpy as np from dehazer.core.DarkChannel import getDarkChannel def getTransmission(I, A, w=0.95, patchSize=15): """ Get the transmission t of the RGB image data from a numpy array # Arguments - I: 3 * M * N numpy array of the input image, whe...
python
import telebot TOKEN = None with open("token.txt") as f: TOKEN = f.read().strip() bot = telebot.TeleBot(TOKEN) @bot.message_handler(commands=['help']) def send_welcome(message): bot.reply_to(message, "sorry. v1.1 it's not finish") bot.polling()
python
# Copyright 2017 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...
python
n = float(input('A number: ')) if n%2 == 0: print ('Even') else: print ('Odd')
python
from machine import UART, Pin import time from httpParser import HttpParser ESP8266_OK_STATUS = "OK\r\n" ESP8266_ERROR_STATUS = "ERROR\r\n" ESP8266_FAIL_STATUS = "FAIL\r\n" ESP8266_WIFI_CONNECTED="WIFI CONNECTED\r\n" ESP8266_WIFI_GOT_IP_CONNECTED="WIFI GOT IP\r\n" ESP8266_WIFI_DISCONNECTED="WIFI DISCONNECT\r\n" ESP826...
python
from easydict import EasyDict from copy import deepcopy hopper_dt_config = dict( exp_name='hopper_medium_expert_dt_seed0', env=dict( env_id='Hopper-v3', norm_obs=dict(use_norm=False, ), norm_reward=dict(use_norm=False, ), collector_env_num=1, evaluator_env_num=8, ...
python
# import libraries import urllib2 import json #retrieve the information of a character an parse it into an character object name.data def getCharacter(name): Char = [] name = name.replace(' ', '+') charUrl = 'https://api.tibiadata.com/v2/characters/' + name + '.json' charPage = urllib2.urlopen(charUrl)...
python
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. import logging import typing from collections import defaultdict import torch.nn as nn from .jit_handles import ( addmm_flop_jit, conv_flop_jit, einsum_flop_jit, get_jit_model_analysis, matmul_flop_jit, ) # A dictionary that ...
python
from direct.directnotify import DirectNotifyGlobal from otp.chat.TalkAssistant import TalkAssistant from otp.chat.ChatGlobals import * class TTTalkAssistant(TalkAssistant): notify = DirectNotifyGlobal.directNotify.newCategory('TTTalkAssistant') def sendToonTaskSpeedChat(self, taskId, toNpcId, toonProgress, ms...
python
import logging from aiocron import crontab @crontab("*/1 * * * *") def test_task(): logging.debug("Example task")
python
#!/usr/bin/env python ''' Project: Geothon (https://github.com/MBoustani/Geothon) File: Vector/shp_info.py Description: This code gives shapefile information. Author: Maziyar Boustani (github.com/MBoustani) ''' try: import ogr except ImportError: from osgeo import ogr #example shapefi...
python
import tkinter as Tk import sys sys.path.append("/Users/PeterLevett/Documents/My Actual Documents/SideProjects/ORDERM8/ORDERM8_V2/SQL_functions") import editentry class CustomerpageWindow(Tk.Frame): def __init__(self, parent): Tk.Frame.__init__(self, parent) self.parent = parent self.basic...
python
from fractions import Fraction as fr, gcd def cancel_digits(num, den): is_cancelled = False numstr, denstr = str(num), str(den) for i in range(len(numstr)): for j in range(len(denstr)): if numstr[i] == denstr[j] and numstr[i] != '0': is_cancelled = True n...
python
#!/usr/bin/python3 # -*- coding: utf-8 -*- ''' Layer ''' import poller class Layer(poller.Callback): ''' Classe abstrata herdeira de poller.Calback para acrescentar camadas ao protocolo ''' def __init__(self): self._top = None self._bottom = None def setBottom(self, bottom)...
python
""" Orkut OAuth support. This contribution adds support for Orkut OAuth service. The scope is limited to http://orkut.gmodules.com/social/ by default, but can be extended with ORKUT_EXTRA_SCOPE on project settings. Also name, display name and emails are the default requested user data, but extra values can be specifie...
python
import os.path import tempfile from youtube_dl import YoutubeDL def download_subtitles(video_id, lang): temp_dir = tempfile.gettempdir() file_name = f'{temp_dir}/{video_id}.{lang}.vtt' def read_file(): with open(file_name) as file: return file.read() if os.path.isfile(file_name)...
python
"""MongoDB related commands for dhutil's CLI.""" import click from dhutil.drive_ops import ( sync_google_drive_acceptance_status_to_mongo, sync_uptodate_teams_from_mongo, send_conf_confirm_emails, ) @click.group(help="Google Drive related commands.") def drive(): """Google Drive related commands."""...
python
from battleship.interface.tty import TTY from battleship.player.player import Player __author__ = 'jitrixis' class BattleShip: def __init__(self): self.__players = (Player(), Player()) TTY.cls() TTY.player_show_turn('PLAYER 1') self.__players[0].view_set_name() self.__pla...
python
# various Amiga Math utils import struct import math def int32(x): st = struct.pack("I", x) return struct.unpack("i", st)[0] def int16(x): st = struct.pack("H", x) return struct.unpack("h", st)[0] def int8(x): st = struct.pack("B", x) return struct.unpack("b", st)[0] def signext16(x): ...
python
from .consts import ActionType, ClaimingType, TILE_SET from .player_data import Action, Claiming str2act_dict = { 'PASS': ActionType.PASS, 'DRAW': ActionType.DRAW, 'PLAY': ActionType.PLAY, 'CHI': ActionType.CHOW, 'PENG': ActionType.PUNG, 'GANG': ActionType.KONG, 'BUGANG': ActionType.MELD_KO...
python
import logging import requests from collections import namedtuple from contextlib import suppress from getpass import getuser from re import DOTALL, IGNORECASE, MULTILINE, compile as Regex from time import time, ctime from tkinter import _default_root,...
python
"""Tests API to manage moderators.""" import json from django.contrib.auth import get_user_model from django.test import TestCase from machina.apps.forum_permission.shortcuts import assign_perm from ashley import SESSION_LTI_CONTEXT_ID from ashley.defaults import _FORUM_ROLE_MODERATOR from ashley.factories import For...
python
""" 33. How to import only every nth row from a csv file to create a dataframe? """ """ Difficiulty Level: L2 """ """ Import every 50th row of BostonHousing dataset as a dataframe. """ """ """
python
""" Example prediction file. """ import os import torch import csv import logging import hydra from tmb.data import AcclerationDataSetSchmutter from tmb.model import FC_FFT from sklearn.preprocessing import MaxAbsScaler from hydra.core.config_store import ConfigStore from config import tmbConfig from pathlib import ...
python
from django.apps import AppConfig class SerialConfig(AppConfig): name = "controllers.serial"
python
from typing import NamedTuple, Dict, List, Tuple import re from collections import defaultdict class Bag(NamedTuple): color: str contains: Dict[str, int] def parse_line(line: str) -> Bag: part1, part2 = line.split(" contain ") color = part1[:-5] part2 = part2.rstrip(".") if part2 == "no oth...
python
import torchvision import os # 通过压缩包格式获得训练集和测试集的图片和相应标签 # 训练集图片在data\train_pic中,标签在data\train_label.txt # 测试集图片在data\test_pic中,标签在data\test_label.txt # 其中,标签数据用‘,’分隔,图片以i.jpg的方式进行存储,它代表标签文件的第i个数据就是这张图片的标签 def data_visual(): mnist_train=torchvision.datasets.MNIST('./data',train=True,download=True)#首先下载数据集,并数据分割成训练集...
python
""" Python utilities to use it from ein.el Copyright (C) 2012- Takafumi Arakaki Author: Takafumi Arakaki <aka.tkf at gmail.com> ein.py is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the Lic...
python
#!/usr/bin/env python import os import sys if __name__ == "__main__": if "DJANGO_SETTINGS_MODULE" not in os.environ: sys.exit("Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined") try: from django.core.management import execute_from_command_line ex...
python
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('mapApp', '0006_auto_20150820_1631'), ] operations = [ migrations.RenameField( model_name='weather', ...
python
from __future__ import unicode_literals from .quicksectx import Interval, IntervalNode, IntervalTree, distancex from .version import __version__
python
from pydantic.dataclasses import dataclass from typing import List from .cost_center import CostCenter @dataclass class CostCenters: offset: int limit: int cost_centers: List[CostCenter]
python
from contextlib import contextmanager import logging @contextmanager def all_logging_disabled(highest_level=logging.CRITICAL): """ A context manager that will prevent any logging messages triggered during the body from being processed. :param highest_level: the maximum logging level in use. This...
python
# -*- coding: utf-8 -*- """ Created on Wed Jun 26 14:24:59 2019 @author: chalbeisen This program is used for saving filenames of .wav files which are already downloaded into a numpy file """ import numpy as np import os import re #global variables #audio_src defines directory where .wav files are saved...
python
import common.networking as networking from tqdm import tqdm from multiprocessing import Process, Manager, Semaphore from pymongo import MongoClient import os import zlib import re import Levenshtein from datetime import datetime # Compare the levenshtein distance difference percentage with threshold def compare_diff...
python
import torch.nn as nn import torch.utils.model_zoo as model_zoo from utils import utils __all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101', 'resnet152'] model_urls = { 'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth', 'resnet34': 'https://download.pytorch....
python
#----------------------------------------------------------------------------- # Copyright (c) 2012 - 2020, Anaconda, Inc., and Bokeh Contributors. # All rights reserved. # # The full license is in the file LICENSE.txt, distributed with this software. #-------------------------------------------------------------------...
python
name = "aoc_utils"
python
import random import torch from collections import namedtuple Transition = namedtuple('Transition', ('state', 'action', 'next_state', 'reward')) class ReplayMemory(object): def __init__(self, args, capacity): self.device = args.device self.capacity = capacity self.transitions = [] ...
python
import argparse import json import pandas as pd from detoxify.bias_metrics import ( IDENTITY_COLUMNS, MODEL_NAME, TOXICITY_COLUMN, calculate_overall_auc, compute_bias_metrics_for_model, convert_dataframe_to_bool, get_final_metric, ) def main(): with open(TEST) as f: results = ...
python
#%% import pandas as pd from pandas.core.frame import DataFrame import requests from bs4 import BeautifulSoup import Levenshtein as lev # %% # 검색 결과 불러오기 search_result = pd.read_csv("Web Crawling Data/메뉴검색결과.csv", index_col=0) search_result # %% # 정규 표현식을 통한 한글 외 문자 제거 search_result['검색결과'] = search_result['검색결과'].st...
python
from discord import TextChannel, Role, User, utils from discord.ext.commands import Cog, Context, group, check, guild_only from bot.core.bot import Bot class Dungeon(Cog): """Quarantine the users with an account less than specified days of creation.""" def __init__(self, bot: Bot) -> None: self.bot =...
python
import numpy import perfplot def test(): kernels = [lambda a: numpy.c_[a, a]] r = [2**k for k in range(4)] out = perfplot.bench( setup=numpy.random.rand, kernels=kernels, labels=['c_'], n_range=r, xlabel='len(a)' ) out.show() out = perfplot.bench( setup=numpy.rando...
python
from sympy import I, Matrix, symbols, conjugate, Expr, Integer from sympy.physics.quantum.dagger import Dagger def test_scalars(): x = symbols('x',complex=True) assert Dagger(x) == conjugate(x) assert Dagger(I*x) == -I*conjugate(x) i = symbols('i',real=True) assert Dagger(i) == i p = symbol...
python
import handler.handler as handler class ScalingHandler(handler.TemplateHandler): """ ScalingHandler inherits from the hander.TemplateHandler class. It displays an information page about scaling up a web application. """ def get(self): self.render("scaling.html")
python
""" Database description. Session is performed by a subject. Session has multiple blocks. Block has multiple trials. Sessions, blocks, and trials have events of certain event type at certain time. Trial has parameters. """ import os import sys from sqlalchemy import Column, ForeignKey, Integer, String, Float, DateTi...
python
import client new_client = client.Client(observations='Billy/#nHello Billy') print(new_client.encode_observations()) print(new_client.decode_observations(new_client.observations)) print(new_client.observations)
python
import tkinter as tk from tkinter import * from tkinter.ttk import * from datetime import datetime, timedelta, date from app.models import session from app.models.booking import Booking from app.models.returns import Returns from app.models.tools import Tools from app.models.users import Users class Bookings(tk.Fram...
python
#coding:utf-8 """DjangoAdmin URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name...
python
""" Encountering some difficulties getting pytest to generate standard logging files. Exploring here """ import logging def test_logfile(): logging.log(logging.INFO, 'whattup test')
python
# coding=utf-8 from mxnet.gluon import nn from .base import SegBaseResNet from mxnetseg.nn import FCNHead, PPModule from mxnetseg.utils import MODELS @MODELS.add_component class PSPNet(SegBaseResNet): """ Dilated ResNet50/101/152 based PSPNet. Reference: Zhao, H., Shi, J., Qi, X., Wang, X., &...
python
#!/usr/bin/env python """ Write a Python script in a different directory (not the one containing mytest). a. Verify that you can import mytest and call the three functions func1(), func2(), and func3(). b. Create an object that uses MyClass. Verify that you call the hello() and not_hello() methods. """ impor...
python
from django.contrib import admin from api.models import Category, Comment, Genre, Review, Title admin.site.register(Category) admin.site.register(Genre) admin.site.register(Title) admin.site.register(Comment) admin.site.register(Review)
python
class Temperature: def __init__(self, value, scale): self.value = value self.scale = scale if scale == "C": self.value_kelvin = value + 273.15 elif scale == "F": self.value_kelvin = (value - 32) * 5 / 9 + 273.15 def __repr__(self): return f"Temper...
python
import numpy as np from scipy.sparse.linalg import svds from numpy_groupies import aggregate # for accumarray type functionality import sparse def sparse_unfold(data, mode): ''' Unfolding of a sparse tensor ''' data = data.copy() # first step: swap axis with first if mode != 0: row_mode...
python
import os import math import json import shutil import tempfile import subprocess import numpy as np from celery import shared_task from PIL import Image, ImageDraw from imagekit.utils import open_image, save_image from pilkit.utils import extension_to_format from pilkit.processors import ResizeToFit from django.db.m...
python
from collections import namedtuple from unittest.mock import MagicMock, patch, PropertyMock from onap_data_provider.resources.esr_system_info_resource import ( CloudRegion, EsrSystemInfoResource, ) ESR_RESOURCE_DATA = { "esr-system-info-id": "Test ID", "user-name": "Test name", "password": "testp...
python
import urwid class UserInfoBar(urwid.Text): PARTS = ( ('name', '{u.name}'), ('level', '{s.level} level'), ('hp', '{s.hp}/{s.max_hp} hp'), ('exp', '{s.exp}/{s.max_exp} exp'), ('mp', '{s.mp}/{s.max_mp} mp'), ('gold', '{s.gold:.2f} gold'), ) @classme...
python
import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import json; from pprint import pprint Settings = json.load(open('settings.txt')) import matplotlib.pyplot as plt import numpy as np import sys sys.path.insert(0,'../') from os.path import isdir root = Settings['data_root'] from pak.datasets.CAD_...
python
class Counter: def __init__(self): self.count = 0 def count_up(self, channel): self.count += 1 print('GPIO%02d count=%d' % (channel, self.count)) def __eq__(self, other): return self.count == other def __lt__(self, other): return self.count < other def main()...
python
import cv2 as cv import time import datetime import requests import json import pathlib import re API_ROUTE_URL = "http://localhost:5000/sendEmail" SECONDS_TO_RECORD_AFTER_DETECTION = 15 SECONDS_BETWEEN_RECORDINGS = 60 def drawRectangle(obj, frame): for (x, y, width, heigth) in obj: cv.rectangle(frame, (x...
python