content
stringlengths
5
1.05M
#!/usr/bin/env python3 # name: test_character.py # version: 0.0.1 # date: 20210422 # author: Leam Hall # desc: Testing 2d6 OGL Character object import unittest from person import Person from person import Character class TestCharacter(unittest.TestCase): def test_creation(self): # Note that thi...
#!/usr/bin/env python # Copyright (C) 2017 Maeve Automation - All Rights Reserved # Permission to copy and modify is granted under the MIT license import rospy from std_msgs.msg import Bool import ros_parameter_loading import rpi_piezo_buzzer ## @package rpi_piezo_buzzer # ROS node for activating a Piezo buzzer on a...
import platform from colorama import init, Fore, Style init(autoreset=True) class interpreter: def __init__(self): #print ("Hello World") return def help(self): print(Style.BRIGHT + Fore.GREEN + """ show options => Show system options exit or quit => Is to exit the s...
"""services/plotting Logic for data manipulation needed when new call backs are executed """ from typing import Dict, Any from penn_chime.utils import add_date_column import pandas as pd def plot_dataframe(dataframe: pd.DataFrame, max_y_axis: int = None,) -> Dict[str, Any]: """ """ if max_y_axis is Non...
import functools import json import typing from pathlib import Path from typing import Dict, Optional @functools.lru_cache() def get_raw_types() -> Dict[str, typing.Any]: path = Path(__file__).parent.joinpath("dread_types.json") with path.open() as f: return json.load(f) @functools.lru_cache() def a...
# WARNING!!! # DO NOT MODIFY THIS FILE DIRECTLY. # TO GENERATE THIS RUN: ./updateWorkspaceSnapshots.sh BASE_ARCHITECTURES = ["amd64", "arm64"] # Exceptions: # - s390x doesn't have libunwind8. # https://github.com/GoogleContainerTools/distroless/pull/612#issue-500157699 # - ppc64le doesn't have stretch security-chan...
from django.urls import path from .views import ServiceListView, ServiceDetailView app_name = 'service' urlpatterns = ( path('', ServiceListView.as_view(), name='index'), path('<slug>/', ServiceDetailView.as_view(), name='detail'), )
# Nama : Eraraya Morenzo Muten # NIM : 16520002 # Tanggal : 19 Maret 2021 # PROGRAM luastrapesium # menghitung luas trapesium dengan persamaan 0.5*t*(s1+s2) # KAMUS # t, s1, s2 : float # ALGORITMA t = float(input()) # menerima input panjang trapesium s1 = float(input()) s2 = float(input()) l = 0.5*t*(s1+s2)...
""" Tools for working with collections """ import itertools import sys from warnings import warn if sys.version_info < (3, 3): from collections import Iterable else: from collections.abc import Iterable __author__ = "Vince Reuter" __email__ = "vreuter@virginia.edu" __all__ = ["is_collection_like", "powerse...
"""Storage Manager Unit Test.""" import pytest from data_resource.config import ConfigurationFactory from data_resource.storage.aws_s3 import S3Manager from data_resource.storage.storage_manager import StorageManager from unittest.mock import patch # Mock S3Manager class for unit tests class MockS3Manager: def aw...
import time, datetime import sys show_possible = False misses = 0 if(len(sys.argv)<=3): sys.exit("INVALID ARGUMENTS "+str(sys.argv)) #At minimum we require 4 arguments: 'score_finder.py', SCORE, X_COUNT, and SHOTS else: if(len(sys.argv)>4): #Optional fifth argument shows permutations containin...
# uncompyle6 version 3.2.4 # Python bytecode 2.7 (62211) # Decompiled from: Python 2.7.15 (v2.7.15:ca079a3ea3, Apr 30 2018, 16:30:26) [MSC v.1500 64 bit (AMD64)] # Embedded file name: lib.coginvasion.cog.SuitHealBossBehavior from lib.coginvasion.cog.SuitHabitualBehavior import SuitHabitualBehavior from lib.coginvasion....
import unittest import solution class TestQ(unittest.TestCase): def test_case_0(self): self.assertEqual(solution.componentsInGraph([ [1, 6], [2, 7], [3, 8], [4, 9], [2, 6], ]), (2, 4)) if __name__ == '__main__': unittest.main()
"""Various frequently used common utilities.""" import json import logging import os from libmorse import exceptions, settings RES_TEXT = "text" RES_JSON = "json" def get_logger(name, use_logging=settings.LOGGING, debug=settings.DEBUG): """Obtain a logger object given a name.""" log = logging.getLogger(n...
# -*- coding: utf-8 -*- """Implementation of ConvE.""" from typing import Dict, Optional import torch import torch.autograd import torch.optim as optim from pykeen.constants import ( CONV_E_FEATURE_MAP_DROPOUT, CONV_E_HEIGHT, CONV_E_INPUT_CHANNELS, CONV_E_INPUT_DROPOUT, CONV_E_KERNEL_HEIGHT, ...
from train import alexnet_train, siamese_train from evaluate import alexnet_evaluate, siamese_evaluate alexnet = alexnet_train() siamese = siamese_train() alexnet_evaluate() siamese_evaluate(siamese)
from bark_ml.library_wrappers.lib_tf_agents.agents.sac_agent import BehaviorSACAgent from bark_ml.library_wrappers.lib_tf_agents.agents.ppo_agent import BehaviorPPOAgent
import numpy as np import logging import itertools class Moon: def __init__(self, x, y, z): self.position = np.array([x,y,z],dtype=int) self.velocity = np.array([0,0,0],dtype=int) def energy(self): return np.abs(self.position).sum() * np.abs(self.position).sum() @property def x(self): return self.posit...
from huey import crontab from app.core.config import TRAFFIC_INTERVAL_SECONDS from app.db.session import db_session from app.db.models.server import Server from app.db.crud.server import get_server_with_ports_usage, get_servers from .config import huey from tasks.utils.runner import run from tasks.utils.handlers impo...
from chainermn.extensions.allreduce_persistent import AllreducePersistent # NOQA from chainermn.extensions.checkpoint import create_multi_node_checkpointer # NOQA from chainermn.extensions.multi_node_evaluator import create_multi_node_evaluator # NOQA
import json import re import npyscreen from vent.helpers.meta import Dependencies class InstanceSelect(npyscreen.MultiSelect): """ A widget class for selecting an exact amount of instances to perform actions on """ def __init__(self, *args, **kargs): """ Initialize an instance select ob...
from rest_framework import serializers from django.contrib.auth.backends import UserModel from question.models import ( TblQuestion ) class QuestionCreateSerializer(serializers.ModelSerializer): class Meta: model = TblQuestion fields = '__all__' read_only_fields = ['id', 'create_time'...
import gzip import os import re from collections import OrderedDict import filetype import pysam from src.BamInfo import BamInfo from src.logger import logger from src.SpliceRegion import SpliceRegion def clean_star_filename(x): u""" if input file is STAR SJ.out.tab or STAR bam then remove the SJ.out.tab ...
import pymongo from pymongo import MongoClient from bson.objectid import ObjectId connection = MongoClient() db = connection.c3stem_database ip = "X.X.X.X" db.virtualmachine.insert({ "_id": ip, "flavor": "m1.medium", "private_IP": 'X.X.X.X', "public_IP": ip, "key_name": "c3stem_keypair", "type...
#!/usr/bin/env python from time import sleep from sys import exit from AmbP3.config import get_args from AmbP3.decoder import Connection from AmbP3.decoder import p3decode from AmbP3.decoder import bin_data_to_ascii as data_to_ascii from AmbP3.decoder import bin_dict_to_ascii as dict_to_ascii from AmbP3.write import W...
sandwich_orders = ['aaa', 'pastrami', 'bbb', 'pastrami', 'ccc','pastrami'] finished_sandwiches = [] print("\nAll pastrami had been sold!") while 'pastrami' in sandwich_orders: sandwich_orders.remove('pastrami') while sandwich_orders: sandwich_order = sandwich_orders.pop() print("\nI made your tuna sanwichi...
__author__ = 'Ralph' import pandas as pd from arff_utils import ARFF from base import Node from base import InputPort class Exporter(Node): def __init__(self, name): super(Exporter, self).__init__(name) class ExportARFF(Exporter): def __init__(self): super(ExportARFF, self).__init__('...
import setuptools with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name="healthdes", # Replace with your own username version="0.0.2", author="David Plummer", author_email="david.plummer@tanzo.org", license="BSD 3-Clause", keywords="library simulation healt...
import os.path as op from tornado import template LOADER = template.Loader(op.join(op.dirname(op.abspath(__file__)), 'templates'), autoescape=None) TEMPLATES = { 'graphite': { 'html': LOADER.load('graphite/message.html'), 'text': LOADER.load('graphite/message.txt'), 'short': LOADER.load('...
# Copyright 2018 Red Hat 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 applicable law or agreed to in writing, ...
import argparse import re import sys import traceback import memory from state import State, StateSA from strategy import StrategyBFS, StrategyDFS, StrategyBestFirst from heuristic import AStar, WAStar, Greedy class SearchClient: def __init__(self, server_messages): self.initial_state = None...
""" Contains unit tests to ensure bounding boxes are converted correctly from a DICOM annotation to a Pascal VOC compatible format. """ from xml.etree.ElementTree import Element, SubElement import numpy as np from breakdb.io.export.voc import create_bounding_box from tests.helpers.xml import match class TestCreateB...
#! python # -*- coding: utf-8 -*- # ================================================================================ # ACUMOS # ================================================================================ # Copyright © 2017 AT&T Intellectual Property & Tech Mahindra. All rights reserved. # =========================...
''' Truncates a string if the length of the string is greater than the provided length integer. @param str {str} @param to_length {int} @return {str} ''' def truncate_str(str, to_length): return (str[:to_length] + '...') if len(str) > to_length else str
# Copyright (c) 2015 Lightricks. All rights reserved.
from __future__ import print_function from flask import Flask, request from flask_restful import reqparse, abort, Api, Resource import argparse import json import os import random CHARS = "BCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz123456789" # 60 unique characters. UNIQUE_LEN = 6 # 46B unique app = Flask...
""" Pipeline for text processing implementation """ from pathlib import Path import re import pymorphy2 from pymystem3 import Mystem from constants import ASSETS_PATH from core_utils.article import Article, ArtifactType class EmptyDirectoryError(Exception): """ No data to process """ class Inconsisten...
import os # Enables directory search items ## Utility function to get list of the immediate dub dirs in folder # @param aDir - the directory to search for sub directories from # @return an array of sub directories def getImmediateSubDirs(aDir): return [name for name in os.listdir(aDir...
#!/usr/bin/env python # -*- coding: utf-8 -*- from com.alipay.ams.api.model.grant_type import GrantType from com.alipay.ams.api.model.scope_type import ScopeType from com.alipay.ams.api.model.customer_belongs_to import CustomerBelongsTo from com.alipay.ams.api.model.os_type import OsType from com.alipay.ams.api.model....
#!/usr/bin/env python # inst: university of bristol # auth: jeison sosa # mail: j.sosa@bristol.ac.uk / sosa.jeison@gmail.com import os import sys import subprocess import configparser import getopt import numpy as np import gdalutils from lfptools import shapefile from lfptools import misc_utils from osgeo import osr...
import bluetooth import time import threading class BluetoothReceiver(threading.Thread): """ no docs... too bad! oh yeah, here is an example: addr = '98:D3:51:FD:EB:C4' # some device address, whatever port = 1 t = BluetoothReceiver(addr, port) with t: for _ ...
from django.contrib.auth.models import User, Group from django.conf import settings from rest_framework import generics from rest_framework import filters from rest_framework import permissions from rest_framework import status from rest_framework.decorators import api_view,permission_classes from rest_framework.respo...
import unittest from cpuinfo import * import helpers class MockDataSource(object): bits = '64bit' cpu_count = 8 is_windows = False arch_string_raw = 'amd64' uname_string_raw = 'amd64' can_cpuid = False @staticmethod def has_dmesg(): return True @staticmethod def dmesg_a(): retcode = 0 output = '''...
# Copyright (c) 2019, Anders Lervik. # Distributed under the MIT License. See LICENSE for more info. """Create a map using folium.""" from functools import partial import json import pandas as pd import folium import branca.colormap as cm from legend import Legend COLORS = { 'blue': '#1f77b4', 'orange': '#ff7...
import smtplib import imaplib import poplib from email.header import Header from email.mime.text import MIMEText from utils.logger import logger class Pop3Mail(object): def __init__(self, smtpserver='mail.test.com'): self.smtpserver = smtpserver self.timeout = 5 def conn(self,user, ...
import itertools def groupper(iterable, n, fillvalue=None): args = [iter(iterable)] * n return itertools.zip_longest(fillvalue=None, *args) def gen(): for ii in range(10, 32): yield ii for n in groupper(gen(), 5): print(list(n))
import unittest from app.models import Pitch from app import db class PitchTest(unittest.TestCase): """ Test class to test the behaviour of the Pitch """ def setUp(self): """ Set up method that will run before every Test """ self.new_pitch = Pitch(0000, 'name','...
import datetime import re from pathlib import Path from typing import Optional from il2fb.commons.belligerents import BELLIGERENTS from il2fb.ds.events.definitions.mission import MissionLoadedInfo from il2fb.ds.events.definitions.mission import MissionStartedInfo from il2fb.ds.events.definitions.mission import Miss...
#!/usr/bin/env python #! -*- encoding:utf-8 -*- import datetime import qiniu from rest_framework import status from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework.decorators import authentication_classes from rest_framework.decorators import permission_class...
IMAGE_PATH = '/Users/calvindelima/code/weekly-rain-day-predictions/weather-network-7-day-forecast-scraper/tests/screenshot.png' WN_FORECAST_DATA_PATH = '/Users/calvindelima/code/weekly-rain-day-predictions/weather-network-7-day-forecast-scraper/tests/wn_forecast_data.csv' FORECAST_URL = 'https://www.theweathernetwork.c...
from __future__ import print_function import difflib import os import unittest import remove_py_md class TestRemovePy(unittest.TestCase): def test_store_input(self): test_file = 'tests/test.md' test_out = 'tests/test_no_py.md' gold = 'tests/gold.md' remove_py_md.remove_py(test_fi...
from dateutil import parser ''' ctime attribute will be provided within VideoDetector but same as time.ctime(os.path.getctime("filename")) - parsed_time: datetime type ''' class Blacklist: def __init__(self, ctime): self.blacklisted = False self.parsed_time = parser.parse(ctime) self.check...
from __future__ import absolute_import, division, print_function import libtbx.load_env from libtbx.utils import multi_out from optparse import OptionParser from six.moves import cStringIO as StringIO import os.path as op import os import sys # XXX these will be skipped (for various reasons) ignore_modules = set([ ...
#!/usr/bin/python3 # 다음 코드를 실행하기 위해서는 별도 모듈이 필요하지 않습니다. def print_text(text, encoding_type): byte_data = text.encode(encoding_type) hex_data_as_str = ' '.join("{0}".format(hex(c)) for c in byte_data) int_data_as_str = ' '.join("{0}".format(int(c)) for c in byte_data) print('\'' + text + '\' 전체 문자 길이: {0}'.fo...
from opencensus.trace.execution_context import get_opencensus_tracer from python.service.handler import SimpleLeagueHandler from python.service.codegen import feb_stats_pb2, feb_stats_pb2_grpc class FebStatsServiceServicer(feb_stats_pb2_grpc.FebStatsServiceServicer): def __init__(self, league_handler: SimpleLeagu...
#!/usr/bin/python import requests import socket import json from getpass import getpass import sys import os import time from IPython.core.magic import (Magics, magics_class, line_magic, cell_magic, line_cell_magic) from requests.packages.urllib3.exceptions import SubjectAltNameWarning, InsecureRequestWarning from req...
from .BaseEncoder import BaseEncoder # noqa from .BiTransformerCnnEncoder import BiTransformerCnnEncoder # noqa
# Copyright (c) 2014 VMware, 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 applicable law or agreed to in writi...
# -*- coding: utf-8 -*- import unittest from openprocurement.api.tests.base import snitch from openprocurement.tender.belowthreshold.tests.base import test_organization, test_author, test_lots from openprocurement.tender.belowthreshold.tests.bid_blanks import ( # TenderBidDocumentResourceTest not_found, #...
print("dic for person and user will ask about information") person = {"name":"Ajinkya","gender":"Male","address":"Toronto","phone": 5488881681 } key = input("Please enter what information would like to know about: ").lower() result = person.get(key,"Invalid Input") print(result)
from django import forms from .models import Order class OrderForm(forms.ModelForm): class Meta: model = Order fields = ['supplier', 'text', 'department', 'amount'] widgets = { 'supplier': forms.Textarea(attrs={'rows':1, 'cols':100, 'style':'resize:none;'}), 'text': fo...
import re import requests import datetime from bs4 import BeautifulSoup from python_utils import converters def get_parsed_page(url): # This fixes a blocked by cloudflare error i've encountered headers = { "referer": "https://www.hltv.org/stats", "user-agent": "Mozilla/5.0 (Windows NT 10.0; Wi...
# https://codility.com/programmers/task/perm_missing_elem/ def solution(A): greater = 0 lenA = len(A) N = lenA + 1 i = 0 while i < lenA: if A[i] == i + 1 or A[i] == N: i += 1 continue A[A[i]-1], A[i] = A[i],A[A[i]-1] for i in xrange(lenA): i...
from functools import wraps from flask import session, request, flash, redirect def auth_required(fn): @wraps(fn) def wrap(*args, **kwargs): print(session) if 'logged_in' not in session: flash('You need to login first.', 'danger') return redirect('/sign-in') retu...
from dataclasses import dataclass from viewdom import html, VDOM from viewdom_wired import component from .plugins import greeting from .plugins.greeting import Greeting plugins = (greeting,) @component(for_=Greeting) @dataclass class SiteGreeting: name: str = 'Site' def __call__(self) -> VDOM: re...
# -*- coding: utf-8 -*- from crispy_forms import helper as crispy_helper from crispy_forms import layout from crispy_forms import bootstrap import floppyforms from .models import Historia class HistoriaEditForm(floppyforms.ModelForm): def __init__(self, *args, **kwargs): super(HistoriaEditForm, self).__init__(*...
__version__ = '1.0.4.2'
"""ETL step wrapper for delta loading a table based on a date column """ from ..database import SqlScript from ..database import Table from ..utils.helpers import parse_path from .upsert import UpsertStep class DeltaLoadStep(UpsertStep): """DeltaLoadStep Step class that creates the table if needed and loads data ...
# -*-coding:utf-8-*- # Copyright (c) 2020 DJI. # # 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 in the file LICENSE.txt or at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless require...
from rest_framework import serializers from main.models import Sentence class SentenceSerializer(serializers.ModelSerializer): spoken_count = serializers.SerializerMethodField(read_only=True) class Meta: model = Sentence fields = ('content_jp', 'content_en', 'score', 'spoken_count', ) d...
from abc import ABCMeta, abstractmethod class Classifier(metaclass=ABCMeta): ''' An abstract interface for classifier model. ''' def __init__(self, n_class, x_min, x_max, x_shape, x_dtype, y_dtype): ''' Initialize the abstract Classifier with metadata. :param n_class: A ``int`` number. Numbe...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # https://projecteuler.info/problem=5 # 232792560 el = 2520 if __name__ == '__main__': while True: st = True for d in [11, 13, 14, 16, 17, 28, 19, 20]: if el % d != 0: st = False if not st: el += 2520 ...
from django.db import models from members.models import Member class Project(models.Model): """A project worked on by members and containing bugs""" POSSIBLE_STATUS = ['ON-GOING', 'FINISHED', 'PAUSED', 'CLOSED'] STATUS_CLASSES = { 'ON-GOING': 'primary', 'FINISHED': 'success', 'PAU...
from scrapy import Item, Field class V2exLoginItem(Item): # 标题 title = Field() # 节点 node = Field() # 作者 auth = Field()
# -*- coding: utf-8 -*- import time import datetime from itertools import chain, groupby from flask_admin import expose from flask_login import current_user from flask_babel import gettext as _ from application.extensions import admin import application.models as Models from flask import redirect, url_for, request, jso...
# Generated by Django 2.2.7 on 2020-10-01 05:23 import ckeditor_uploader.fields import datetime from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('blog', '0018_auto_20200929_1828'), ] operations = [ migrati...
import math import numpy as np import os import datetime import torch import torch.optim as optim import torch.nn.functional as F # from tqdm import tqdm from torchvision import transforms, datasets from net import Net from itertools import takewhile import matplotlib.pyplot as plt # MAX_SAVEPOINTS = 10 CLASSES = ('pl...
import os import pandas as pd import datetime import numpy as np def import_OR_record_sheet(OR_fname, output_OR_fname): full_path = os.path.expanduser(OR_fname) OR_file = pd.read_excel(full_path) OR_file['Spectrum-OV'] = 'SPECTRUM-OV-' + OR_file['Spectrum-OV'].astype(str) OR_file['Surgery Date'] = OR_...
# The contents of this file is free and unencumbered software released into the # public domain. For more information, please refer to <http://unlicense.org/> character_query = ''' query ($id: Int, $search: String) { Page { characters (id: $id, search: $search) { name { full native ...
# coding: utf-8 from parlaseje.models import * from sklearn.decomposition import PCA from numpy import argpartition all_votes = Vote.objects.all() all_votes_as_list = list(all_votes) all_votes_as_vectors = [(vote.votes_for, vote.against, vote.abstain, vote.not_present) for vote in all_votes_as_list] pca = PCA(n_comp...
import pandas as pd datatrain = pd.read_csv('/home/edvvin/Desktop/mnist/mnist_train.csv') datatrain_array = datatrain.values ytrain = datatrain_array[:,0] temp = datatrain_array[:,1:] xtrain = [] for ar in temp: xic = [] for i in range(28): xic.append(ar[i*28:(i+1)*28]) xtrain.append([xic]) imp...
from django.contrib import admin from django.conf.urls import url from . import views from django.urls import path from django.views.generic import RedirectView urlpatterns = [ path('',views.index, name = 'index'), #url(r'^admin/', admin.site.urls), url(r'^$',views.signIn), url(r'^postsign/',views.post...
# (C) Datadog, Inc. 2020-present # All rights reserved # Licensed under a 3-clause BSD style license (see LICENSE) JVM_E2E_METRICS = [ 'jvm.buffer_pool.direct.capacity', 'jvm.buffer_pool.direct.count', 'jvm.buffer_pool.direct.used', 'jvm.buffer_pool.mapped.capacity', 'jvm.buffer_pool.mapped.count',...
#!/usr/bin/python # (c) 2018 Jim Hawkins. MIT licensed, see https://opensource.org/licenses/MIT # Part of Blender Driver, see https://github.com/sjjhsjjh/blender-driver """Python module for Blender Driver demonstration application. This code illustrates: - Basic use of the Blender Game Engine (BGE) KX_GameObject in...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- if __name__ == '__main__': s = str(input("Put some text: ")) c = 0 if (s[0] == ' ') and (s[len(s) - 1] == ' '): for i in s: if i == ' ': c += 1 print (f"Количество слов в строке = {c - 1}") else: for i i...
#!/usr/bin/env python # # Copyright (c) 2016 10X Genomics, Inc. All rights reserved. # # Support code for Supernova stages # # "Pseudo" Martian API for reporting errors and warnings from C++ # code prior to deployment of a formal adapter. # # Code to plot molecule length histogram and the kmer spectrum import os impor...
# # SPDX-License-Identifier: Apache-2.0 # # Copyright 2020 Andrey Pleshakov # # 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...
from django.views.generic.base import TemplateView from .models import BannerHome from apps.products.models import ShopDepartment from .documents import ProductDocument class HomePageView(TemplateView): template_name = "shop/web/home.html" def get_context_data(self, **kwargs): context = super(HomePa...
import logging import os pretrained_model_path = './pretrained-model/' AUDIO_NAME = 'MOCK CALL_Bank Customer Service_139-284.wav' #'Bdb001_interaction_first60s.wav' AUDIO_PATH = './wav/' AUDIO_FILE = os.path.join(AUDIO_PATH,AUDIO_NAME) SAMPLE_RATE = 44100 STT_SAMPLERATE = 16000 FLG_REDUCE_NOISE:bool = True FLG_SPEECH...
import logging from os import makedirs, path from shutil import rmtree from urllib import urlencode from dulwich.errors import NotGitRepository from dulwich.repo import Repo from tornado.testing import AsyncHTTPTestCase from tornado.web import Application from magpie.server import make_app logging.getLogger('tornado...
# # Solved Problems in Geostatistics # # ------------------------------------------------ # Script for lesson 5.3 # "Variogram Modeling and Volume Variance" # ------------------------------------------------ import sys sys.path.append(r'../shared') from numpy import * from geo import * from matplotlib im...
import os import json import tweepy import logging logger = logging.getLogger() logging.basicConfig(filename='simar_roturas.log', filemode='a', format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',level=logging.INFO) #twitter loggin and api creation def create_api(): consumer_key = os.getenv("CONSUMER_K...
"""Tests the changelog activity.""" import os import json from rever import vcsutils from rever.logger import current_logger from rever.main import env_main REVER_XSH = """ $ACTIVITIES = ['authors'] $PROJECT = "WAKKA" $AUTHORS_FILENAME = "AUTHORS.md" $AUTHORS_METADATA = "authors.yaml" $AUTHORS_MAILMAP = "Mailmap" $A...
import numpy as np import pandas as pd import warnings from sklearn.compose import ColumnTransformer from sklearn.pipeline import make_pipeline from sklearn.impute import SimpleImputer from sklearn.preprocessing import OneHotEncoder, StandardScaler, QuantileTransformer, LabelEncoder, FunctionTransformer from sklearn.pr...
# coding: utf-8 # In[1]: import pandas as pd # In[12]: ufo = pd.read_csv('http://bit.ly/uforeports') # In[13]: type(ufo) # In[14]: ufo.head() # In[19]: type(ufo['City']) # In[20]: ufo['City'].head() # In[23]: ufo.City.head() # sane as ufo['City'].head() # In[26]: ufo['Colors Reported'].head() # ...
from .Event import Event, EventType, EventCategory class MouseEvent(Event): def __init__(self) -> None: pass @property def CategoryFlags(self) -> int: return EventCategory.Mouse | EventCategory.Input class MouseButtonPressedEvent(MouseEvent): __slots__ = "__ButtonCode" def __init...
############################################################################### # Copyright 2014 OCLC # # 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/LICENS...
import json from django.urls import reverse from django_dynamic_fixture import G from guardian.shortcuts import assign_perm from rest_framework import status from rest_framework.test import APIClient, APITestCase from accounts.models import Child, DemographicData, User from studies.models import ConsentRuling, Lab, R...
# This file makes a python package out of the project. # This way you can access other modules in the project import setuptools with open("README.md", "r", encoding="utf-8") as fh: long_description = fh.read() setuptools.setup( name="example-pkg-LoSSeth", version="0.0.1", author="Jimmy Bierenbroodspo...
import logging import math from datetime import datetime, timedelta from custom_components.smappee import DATA_SMAPPEE, DOMAIN from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.helpers.entity import Entity from homeassistant.util import dt as dt_util from homeassistant.util import Throttle...