content
stringlengths
5
1.05M
from radiacode.bytes_buffer import BytesBuffer from radiacode.radiacode import spectrum_channel_to_energy, RadiaCode from radiacode.types import *
class GameActuator: filename = None mode = None
import codecs import re import sys def warn(s): sys.stderr.write(s) sys.stderr.flush() class CfgParserError(Exception): pass _name_pat = re.compile("[a-z][a-z0-9]*", re.UNICODE) class CfgParser: """Important note: parser related methods and attributes are capitalized. You can access (get an...
from setuptools import setup, find_packages # read the contents of your README file from pathlib import Path this_directory = Path(__file__).parent long_description = (this_directory / "README.md").read_text() setup( name='jkx', version='1.0.4', license='MIT', author="Andrew Heaney", author_email=...
#Crie um algoritimo que leia um numero e mostre o seu dobro # o seu triplo e a raiz quadrada n = float(input('Digite um numero: ')) print('Seu dobro é {}'.format(n * 2)) print('Seu triplo é {}'.format(n * 3)) print('Sua raiz quadrada é: {}'.format(n**(1/2)))
# -*- coding: utf-8 -*- """ flask_babelplus.domain ~~~~~~~~~~~~~~~~~~~~~~ Localization domain. :copyright: (c) 2013 by Armin Ronacher, Daniel Neuhäuser and contributors. :license: BSD, see LICENSE for more details. """ import os from babel import support from .utils import get_state, get_locale f...
from __future__ import print_function from botocore.exceptions import ClientError import json import datetime import boto3 import os def handler(event, context): print("log -- Event: %s " % json.dumps(event)) response = "Error auto-remediating the finding." try: # Set Clients ec2 = boto3.clien...
import pytest from whatlies.language import BytePairLang @pytest.fixture() def lang(): return BytePairLang("en", vs=1000, dim=25, cache_dir="tests/cache") def test_single_token_words(lang): assert lang["red"].vector.shape == (25,) assert len(lang[["red", "blue"]]) == 2 def test_similar_retreival(lang...
class Solution: @staticmethod def addBinary(a: str, b: str) -> str: length = max(len(a), len(b)) answer = '' rem = 0 answer, rem = Solution.calculate(a.zfill(length), answer, b.zfill(length), length, rem) if rem != 0: answer = '1' + answer return answe...
import sys sys.path.append('/root/csdc3/src/sensors') import unittest import time from sensor_manager import SensorManager from sensor_constants import * class Tests(unittest.TestCase): def setUp(self): pass def test_ds1624(self): ds1624 = [TEMP_PAYLOAD_A, TEMP_BAT_1] for sensor in ds1...
import sys sys.dont_write_bytecode = True import json from PyQt5.QtWidgets import QApplication from models.Authenticate import Dialog from models.Base import MainWindow if __name__ == "__main__": try: cfg_file = open("config.json","r") config = json.loads(cfg_file.read()) ip = config['server_ip'] p...
from logging import getLogger from threading import Thread from time import sleep from signalrc.ws_transport import WebSocketsTransport logger = getLogger('signalr.client') class SignalRClient: def __init__(self, url, hub, session=None): self.url = url self._invokes_counter = -1 self.tok...
import shutil from fastapi import APIRouter, File, HTTPException, UploadFile from models.migration_models import ChowdownURL from services.migrations.chowdown import chowdown_migrate as chowdow_migrate from services.migrations.nextcloud import migrate as nextcloud_migrate from app_config import MIGRATION_DIR from util...
"""Top-level package for django-extra-field-validation.""" __author__ = """Tonye Jack""" __email__ = "jtonye@ymail.com" __version__ = "1.1.1" from .field_validation import FieldValidationMixin __all__ = ["FieldValidationMixin"]
#!/usr/bin/env python import random import rospy from std_msgs.msg import UInt32 if __name__ == '__main__': random.seed() rospy.init_node('random') pub = rospy.Publisher('rand_int', UInt32, queue_size = 1) rate = rospy.Rate(10) while not rospy.is_shutdown(): pub.publish(random.randint(0,...
# Generated by Django 3.0.5 on 2021-04-23 10:02 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ('cse', '0011_delete_dev'), ] operations = [ migrations.CreateModel( name='semester', fields=[ ...
# Generated by Django 2.1 on 2018-08-18 02:03 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('users', '0001_initial'), ('inventories', '0001_initial'), ] operations = [ migrations.RenameModel( old_name='ItemInventory', ...
# -*- coding: utf-8 -*- """ The view ports widget @author: Chris Scott """ from __future__ import absolute_import from __future__ import unicode_literals from __future__ import division import logging from PySide2 import QtWidgets from . import rendererSubWindow class ViewPortsWidget(QtWidgets.QWidget): """ ...
from .views import SearchContact, markSpam, detailView from django.urls import path urlpatterns = [ path('Search/', SearchContact.as_view()), path('mark/<int:id>', markSpam, ), path('Detail/<int:id>', detailView), ]
from . import data from . import datasets from . import layers from . import losses from . import metrics from . import models from . import optimizers from . import utils
"""! @brief Unit-test runner for core wrapper. @authors Andrei Novikov (pyclustering@yandex.ru) @date 2014-2020 @copyright BSD-3-Clause """ import unittest from pyclustering.tests.suite_holder import suite_holder # Generate images without having a window appear. import matplotlib matplotlib.use('Agg') from pyclu...
#!/usr/bin/python3 # -*- coding: utf-8 -*- #===============================================================================# #title :MangaPark.py # #description :contains the MangaPark class # #author :August B. San...
__all__ = ['HttpCacheControlMixin'] class HttpCacheControlMixin: http_cache_control_max_age = None def get_http_cache_control_max_age(self): return self.http_cache_control_max_age def dispatch(self, *args, **kwargs): response = super().dispatch(*args, **kwargs) if response.status...
from __future__ import annotations # python import logging import os import random import importlib import json import datetime from halo_app.classes import AbsBaseClass from halo_app.app.context import HaloContext, InitCtxFactory from halo_app.infra.providers.providers import get_provider,ONPREM from halo_app.app.re...
"""A helper rule for testing detect_root function.""" load("@rules_foreign_cc//tools/build_defs:detect_root.bzl", "detect_root") def _impl(ctx): detected_root = detect_root(ctx.attr.srcs) out = ctx.actions.declare_file(ctx.attr.out) ctx.actions.write( output = out, content = detected_root,...
import sys import json from .kafka import Consumer from .postgres import PGClient from .model import URLStatus if __name__ == '__main__': try: with PGClient() as pg_client, Consumer() as kafka_consumer: # TODO: change to subscript # TODO: try https://github.com/aio-libs/aiokafka ...
import os import neat import pygame from bird import Bird from pipe import Pipe from base import Base from background import Background class Game: WIN_WIDTH = 500 WIN_HEIGHT = 800 def __init__(self): self.isRunning = True self.score = 0 self.birds = [] self.nets = [] ...
import FWCore.ParameterSet.Config as cms process = cms.Process("ANALYSIS") process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(10) ) process.source = cms.Source("PoolSource", fileNames = cms.untracked.vstring('file:clustering.root') ) process.pfClusterAnalyzer = cms.EDAnalyzer("PFClusterAnalyz...
#!/usr/bin/env python # David Prihoda # Calculate coverage of BGCs by a DataFrame of BGC Candidates import pandas as pd import matplotlib.pyplot as plt import numpy as np import argparse def get_single_contig_coverage(a_cands, b_cands): """ Get coverage of each BGC candidate in a_cands by BGC candidates in b_...
import tensorflow as tf class Generator(object): def __init__(self, n_node, node_emd_init, config): self.n_node = n_node self.node_emd_init = node_emd_init self.motif_size = config.motif_size self.max_value = config.max_value with tf.compat.v1.variable_scope('generator'): ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals, print_function from django.conf import settings FRAME_FORMATTER = getattr(settings, 'FRAME_FORMATTER', None) FRAME_SEPARATOR = getattr(settings, 'FRAME_SEPARATOR', None) if FRAME_FORMATTER is None: raise ValueError('Improperly Configured FRAME_FORMA...
from __future__ import division from utils.utils import * from utils.datasets import * from utils.parse_config import * from models.darknet import * from models.yolo_nano_helper import YoloNano from torch.nn.parallel import DataParallel import os import sys import time import datetime import argparse import tqdm imp...
"""A module to generate OpenAPI and JSONSchemas.""" import json import os from pkg_resources import get_distribution from pydantic_openapi_helper.core import get_openapi from pydantic_openapi_helper.inheritance import class_mapper from queenbee.repository import RepositoryIndex from queenbee.job import Job, JobStat...
import unittest from time import sleep from random import randint import requests from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.common.keys imp...
#!/usr/bin/env python import sys for line in sys.stdin: # extract data key, val = line.strip().split('\t', 1) s_val = val.split(',') # day day = key.split(',')[3][:10] # revenue try: revenue = float(s_val[11]) + float(s_val[12]) + float(s_val[14]) except ValueError: co...
from typing import TypeVar T = TypeVar("T") class Node: def __init__(self, item: T): self.item = item self.next = None
import re from File import * from Base import * from subprocess import call class Animation_Html(): ##! ##! Animation main HTML path ##! def Animation_HTML_Path(self): return "/".join( [ self.Path,self.FileName,self.Curve_Parms_Path ] ) ##! ##! Animation main HTML file...
from django.contrib.postgres.fields import ArrayField from django.db import models from osf.models import Node from osf.models import OSFUser from osf.models.base import BaseModel, ObjectIDMixin from osf.models.validators import validate_subscription_type from osf.utils.fields import NonNaiveDateTimeField from website....
import logging log = logging.getLogger(__name__) from dogpile.cache import make_region from dogpile.cache.api import NO_VALUE import os, errno CACHE_FAILS = (NO_VALUE,) def mkdir_p(path): try: os.makedirs(path) except OSError as exc: # Python >2.5 if exc.errno == errno.EEXIST: ...
#!/usr/bin/python # -*- coding: UTF-8 import sys import os import math import statistics import matplotlib matplotlib.use('Agg') import numpy as np import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap from matplotlib.backends.backend_pdf import PdfPages from datetime import datetime import col...
r""" ``cotk.metrics`` provides classes and functions evaluating results of models. It provides a fair metric for every model. """ import random import multiprocessing from multiprocessing import Pool import numpy as np from nltk.translate.bleu_score import corpus_bleu, sentence_bleu, SmoothingFunction from .._utils.un...
from re import search from requests import get, post from requests.exceptions import ConnectionError, MissingSchema, ReadTimeout from sqlalchemy import Boolean, case, ForeignKey, Integer from sqlalchemy.ext.associationproxy import association_proxy from sqlalchemy.ext.hybrid import hybrid_property from sqlalchemy...
# Generated by Django 2.1 on 2020-08-04 10:43 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('encounterapp', '0032_auto_20200801_1914'), ('encounterapp', '0032_auto_20200801_1758'), ] operations = [ ]
import os #BASE_DIR = os.path.abspath('.') BASE_DIR = os.path.dirname(os.path.abspath(__file__)) #os.path.abspath('.') ROUGE_DIR = os.path.join(BASE_DIR,'summariser','rouge','ROUGE-RELEASE-1.5.5/') #do not delete the '/' at the end PROCESSED_PATH = os.path.join(BASE_DIR,'data','summaries_processed_data') SUMMARY_DB_DI...
""""Utilities for Diffie-Hellman key exchange.""" from __future__ import unicode_literals import base64 import warnings import six from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.asymmetric.dh import DHParameterNumbers, DHP...
import imp import astropy.units as un import astropy.coordinates as coord import matplotlib.pyplot as plt import gala.coordinates as gal_coord from astropy.table import Table from vector_plane_calculations import * from velocity_transformations import * imp.load_source('helper', '../tSNE_test/helper_functions.py') f...
#import needed packages import os, json, sys #creates functions global commands = {} #import modules modules = os.listdir(path='modules') print('Importing modules') count_mod = 0 count_ok_mod = 0 for module in modules: try: with open('modules/' + module + '/index.json') as read_modules: mod_da...
from django.urls import path, include from management import views from rest_framework_simplejwt import views as jwt_views urlpatterns = [ # Used to signup as a teacher or a student path('signup/', views.SignUpView.as_view(), name = 'signup'), # Used to obtain refresh and access token path('login/acc...
from __future__ import annotations import numpy as np import pandas as pd from sklearn import datasets from IMLearn.metrics import mean_square_error from IMLearn.utils import split_train_test from IMLearn.model_selection import cross_validate from IMLearn.learners.regressors import PolynomialFitting, LinearRegression, ...
import chardet import codecs def WriteFile(filePath, lines, encoding="utf-8"): with codecs.open(filePath, "w", encoding) as f: actionR = '' #定位到[Events]区域的标记 for sline in lines: if '[Events]' in sline: actionR = 'ok' f.write(sline) continu...
from screenplay import Action, Actor from screenplay.actions import fail_with_message class _if_nothing_is_found_fail_with_message(Action): def __init__(self, action: Action, fail_actions: list, message: str): super().__init__() self.action = action self.fail_actions = fail_actions ...
# 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, software # distributed unde...
from .base import * BOOST_PER_SECOND = 80 * 1 / .93 # boost used per second out of 255 REPLICATED_PICKUP_KEY = 'TAGame.VehiclePickup_TA:ReplicatedPickupData' REPLICATED_PICKUP_KEY_168 = 'TAGame.VehiclePickup_TA:NewReplicatedPickupData' def get_boost_actor_data(actor: dict): if REPLICATED_PICKUP_KEY in actor: ...
#!/usr/bin/env python3 # Copyright (c) 2019 The Unit-e Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. from test_framework.mininode import sha256 from test_framework.regtest_mnemonics import regtest_mnemonics from t...
from sanic import Sanic from sanic.blueprints import Blueprint from sanic.response import stream, text from sanic.views import HTTPMethodView from sanic.views import stream as stream_decorator bp = Blueprint("bp_example") app = Sanic("Example") class SimpleView(HTTPMethodView): @stream_decorator async def p...
import argparse class ArgumentParser(argparse.ArgumentParser): def __init__(self): self.parser = argparse.ArgumentParser(description="Robyn, a fast async web framework with a rust runtime.") self.parser.add_argument('--processes', type=int, default=1, required=False) self.parser.add_argumen...
r = 's' while r == 's': n1 = int(input('Digite o 1º valor: ')) n2 = int(input('Digite o 2º valor: ')) print(' [ 1 ] SOMAR') print(' [ 2 ] Multiplicar') print(' [ 3 ] Maior') print(' [ 4 ] Novos Números') print(' [ 5 ] Sair do Programa') opcao = int(input('Escolha uma operação: ')) ...
# -*- coding: utf-8 -*- """ Created on Sat Oct 28 10:00:06 2017 @author: ldn """ EndPointCoordinate=((-3.6,0.0,7.355),(123.6,0.0,7.355)) #west & east end point rGirderRigidarmCoordinate=((10,8.13,0),(15,8.3675,0),(20,8.58,0), (25,8.7675,0),(30,8.93,0),(35,9.0675,0),(40,9.18,0),(45,9.2675,0),(50,9.33,0),(55,9.36...
# # PySNMP MIB module SGTE-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SGTE-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 20:53:51 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:1...
from django import forms from django.contrib.auth.models import User from .models import Profile class UserCreationForm(forms.ModelForm): username = forms.CharField(label='اسم المستخدم', max_length=30, help_text='اسم المستخدم يجب ألا يحتوي على مسافات.') email = forms.EmailField(...
class Seat: """Seat contains features of the seat""" def __init__(self): self.left_handed = False self.special_needs = False self.broken = False # Describes sid of person sitting there self.sid = -1 # Used for ChunkIncrease # True to use the seat, False ...
nJoints = 16 accIdxs = [0, 1, 2, 3, 4, 5, 10, 11, 14, 15] shuffleRef = [[0, 5], [1, 4], [2, 3], [10, 15], [11, 14], [12, 13]] edges = [[0, 1], [1, 2], [2, 6], [6, 3], [3, 4], [4, 5], [10, 11], [11, 12], [12, 8], [8, 13], [13, 14], [14, 15], [6, 8], [8, 9]] ntuImgSize = 224 h36mImgSize...
# -*- coding: utf-8 -*- from ConfigParser import NoOptionError import calendar import datetime from taxi import remote from taxi.exceptions import CancelException, UsageError from taxi.projects import Project from taxi.timesheet import ( NoActivityInProgressError, Timesheet, TimesheetCollection, TimesheetFile ) fr...
"""This module will contain everything needed to train a neural Network. Authors: - Johannes Cartus, QCIEP, TU Graz """ from os.path import join from uuid import uuid4 import tensorflow as tf import numpy as np from SCFInitialGuess.utilities.usermessages import Messenger as msg from SCFInitialGuess.nn.cost_functio...
from django.contrib import admin from . import models from django.conf import settings admin.site.register(models.OfferCategory) class OfferAdmin(admin.ModelAdmin): if settings.MULTI_VENDOR: list_display = ['title', 'total_vendors', 'starts_from', 'ends_at'] list_filter = ('vendor',) else: ...
from __future__ import annotations from amulet.world_interface.chunk.interfaces.leveldb.base_leveldb_interface import ( BaseLevelDBInterface, ) class LevelDB4Interface(BaseLevelDBInterface): def __init__(self): BaseLevelDBInterface.__init__(self) self.features["chunk_version"] = 4 se...
import unittest from ui.stub_io import StubIO class StubIOTest(unittest.TestCase): def setUp(self): self.io = StubIO() def test_method_write_adds_argument_to_output_list(self): self.io.write("test") self.assertEqual(self.io.output, ["test"]) def test_method_set_input_add...
import unittest from kafka_influxdb.encoder import heapster_event_json_encoder class TestHeapsterEventJsonEncoder(unittest.TestCase): def setUp(self): self.encoder = heapster_event_json_encoder.Encoder() def testEncoder(self): msg = b'{"EventValue":"{\\n \\"metadata\\": {\\n \\"name\\": \\...
import os import numpy as np from PIL import Image import subprocess import cv2 def vision(): output = False # False: Disable display output & True: Enable display output # subprocess.run(["sudo fswebcam --no-banner -r 2048x1536 image3.jpg"], capture_output=True) # subprocess.run("sudo fswebcam /home/pi/...
# 生成矩形的周长上的坐标 import numpy as np from skimage.draw import rectangle_perimeter img = np.zeros((5, 6), dtype=np.uint8) start = (2, 3) end = (3, 4) rr, cc = rectangle_perimeter(start, end=end, shape=img.shape) img[rr, cc] = 1 print(img)
# -*- coding: utf-8 -*- import logging from openstack import exceptions as openstack_exception from cinderclient import client as volume_client from cinderclient import exceptions as cinder_exception import oslo_messaging from oslo_config import cfg from BareMetalControllerBackend.conf.env import env_config from comm...
class nodo_error: def __init__(self, linea, columna, valor, descripcion): self.line = str(linea) self.column = str(columna) self.valor = str(valor) self.descripcion = str(descripcion) errores = []
import pytest from telliot_core.apps.core import TelliotCore from telliot_core.queries.price.spot_price import SpotPrice from telliot_core.utils.response import ResponseStatus from telliot_core.utils.timestamp import TimeStamp @pytest.mark.asyncio async def test_main(mumbai_cfg): async with TelliotCore(config=mu...
from swockets import swockets, SwocketError, SwocketClientSocket, SwocketHandler handle = SwocketHandler() server = swockets(swockets.ISSERVER, handle) handle.sock = server while(True): user_input = {"message":raw_input("")} if len(server.clients) > 0: server.send(user_input, server.clients[0], server.clients[0]...
from tkinter import * root = Tk() root.geometry('800x800') root.title('Rythmic Auditory Device') root.configure(background="#ececec") f = ("Times bold", 54) def next_page(): """Go to next page of GUI Function destroys current calibration page and moves on to next main page. """ root.destroy() i...
from functools import lru_cache import requests from six import u from unidecode import unidecode _synset_sparql_query = """ SELECT ?item ?itemLabel WHERE {{ ?item wdt:P2888 <http://wordnet-rdf.princeton.edu/wn30/{}-n> SERVICE wikibase:label {{ bd:serviceParam wikibase:language "{}". }} }} """ _wikidata_url = 'h...
#!/usr/bin/env python # encoding: utf-8 import sys if sys.version_info.major > 2: import http.server as http_server import socketserver else: import SimpleHTTPServer as http_server import SocketServer as socketserver Handler = http_server.SimpleHTTPRequestHandler # python -c "import SimpleHTTPServer;...
# -*- coding: utf-8 -*- """ Authors: Tim Hessels Contact: t.hessels@un-ihe.org Repository: https://github.com/TimHessels/SEBAL Module: SEBAL Description: This module contains a compilation of scripts and functions to run pySEBAL """ from SEBAL import pySEBAL __all__ = ['pySEBAL'] __version__ = '0.1'
import unittest import smartphone from parameterized import parameterized, parameterized_class TEST_PHONE_NUMBER = '123' class SmartPhoneTest(unittest.TestCase): def setUp(self): super().setUp() self.phone = smartphone.SmartPhone() @parameterized.expand([ ('idle', smartphone.CallState.IDLE, f'Has ca...
#!/usr/bin/env python import Bio; from Bio import SeqIO from Bio.SeqRecord import SeqRecord import urllib2 import sys import StringIO import os base = os.path.expanduser('~') prot_folder = base + '/biotools/uniprot_proteomes/' fasta_records = [] if len(sys.argv) == 1: accession = input('Enter UNIPROT proteome acces...
import os import math import cereal.messaging as messaging import cereal.messaging_arne as messaging_arne from selfdrive.swaglog import cloudlog from common.realtime import sec_since_boot from selfdrive.controls.lib.radar_helpers import _LEAD_ACCEL_TAU from selfdrive.controls.lib.longitudinal_mpc import libmpc_py from...
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2011 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Copyright 2011 Fourth Paradigm Development, Inc. # # Licensed under the Apache License, Version 2.0 (the "Licen...
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # --------------------------------------------------------------------...
""" This file is part of genofunc (https://github.com/xiaoyu518/genofunc). Copyright 2020 Xiaoyu Yu (xiaoyu.yu@ed.ac.uk) & Rachel Colquhoun (rachel.colquhoun@ed.ac.uk). """ import os import unittest from genofunc.extract_metadata import * this_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) data_di...
from .atmosphere import Atmosphere from .generalized_atmosphere import GeneralizedAtmosphere from .generalized_matching import GeneralizedMatching from .psycop import PSYCOP from .illicit_conversion import IllicitConversion from .logically_valid_lookup import LogicallyValidLookup from .matching import Matching f...
import demistomock as demisto from CommonServerPython import * # noqa # pylint: disable=unused-wildcard-import from CommonServerUserPython import * # noqa import requests import traceback from typing import Dict, Any # Disable insecure warnings requests.packages.urllib3.disable_warnings() TYPES = { 'threatType...
from typing import Optional from odmantic import Model class Person(Model): name: str age: Optional[int] john = Person(name="John") print(john.age) #> None
""" Implementation of DRO models """ import gurobipy as grb import numpy as np from time import time def train_classifier(Kernel, labels_raw, all_epsilon, all_kappa, nc): print('Train class ', nc + 1, '...') t = time() n_samples = Kernel.shape[0] alpha = np.zeros((n_samples, len(al...
import sys if len(sys.argv) != 2: print("Usage: python buildcml.py <cml file>") exit(1) infile = sys.argv[1] # file names outfile_md = "docs/" + infile.split(".")[0] + ".md" outfile_txt = infile.split(".")[0] + ".txt" # file buffers md_buffer = "# Controller Layouts\n" txt_buffer = "" with open(infile, "r") as ...
from dataclasses import field from datetime import datetime from typing import List, Optional from pydantic.dataclasses import dataclass @dataclass class TypeA: one: str two: float @dataclass class TypeB(TypeA): one: str three: bool = field(default=True) @dataclass class TypeC(TypeB): four: ...
import requests import unittest class TestStringMethods(unittest.TestCase): '''def test_000_operacoes_ola1(self): r = requests.get('http://localhost:5000/ola/marcio') self.assertEqual(r.text,'ola marcio') r = requests.get('http://localhost:5000/ola/mario') self.assertEqual(r....
from pytest import (fixture, mark) from wrdpzl import(Board, Solver) @fixture(scope='module') def words(): with open('words.txt') as file: return list(map(str.strip, file.readlines())) @fixture(scope='module') def solver(words): return Solver(words) @mark.timeout(0.5) @mark.parametrize('board', [ ...
# Copyright (c) 2017-2021 Analog Devices Inc. # All rights reserved. # www.analog.com # # SPDX-License-Identifier: Apache-2.0 # import PMBus_I2C from encodings import hex_codec import codecs from time import * from array import array import math import sys if sys.version_info.major < 3: input = ...
# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- """Url Ent...
import queue import time from threading import Thread import cv2 from scripts import centerface_utils TARGET_WIDTH = 640 TARGET_HEIGHT = 640 TARGET_FPS = 30 class CameraDemo: """Multi-threaded python centerface detection demo.""" def __init__(self, runner: centerface_utils.CenterFaceNoDetection) -> None: ...
#!/usr/bin/env python ''' ASMO Configuration Author: Rony Novianto (rony@ronynovianto.com) ''' # Run web to support any programming language via RESTful web service # Run local if a higher performance is required (e.g. using ASMO with machine learning) is_running_local = False host = 'http://localhost...
def double_first(vec): try: first = vec[0] parsed = int(first) return parsed * 2 except IndexError: print("no first item") except ValueError: print("invalid first item") if __name__ == '__main__': numbers = ["42", "93", "18"] empty = [] strings = ["tofu"...
import numpy as np # initial values ARRAY = [] with open("xoData.txt") as f: for line in f: ARRAY.append([int(x) for x in line.split()]) # step function (activation function) def step_function(sum): if sum >= 0: return 1 return -1 # calculateing output def calculate_outpu...
from yargy.utils import Record
import networkx as nx import numpy as np from copy import deepcopy from collections import defaultdict from ylearn.utils import to_repr from . import prob from .utils import (check_nodes, ancestors_of_iter, descendents_of_iter) class CausalGraph: """ A class for representing DAGs of causal structures. A...