content
stringlengths
5
1.05M
import argparse from bus import Bus from cpu import CPU from frame import Frame from io_registers import IO_Registers from ram import RAM from ppu.ppu import PPU from rom import ROM from ui import UI def main(): # set up command line argument parser parser = argparse.ArgumentParser(description='NES Emulator.')...
"""\ wxSpinButton objects based on wxGlade/widgets/spin_ctrl/ @copyright: 2004 D.H. aka crazyinsomniac at users.sourceforge.net @copyright: 2014-2016 Carsten Grohmann @copyright: 2016-2017 Dietmar Schwertberger @license: MIT (see LICENSE.txt) - THIS PROGRAM COMES WITH NO WARRANTY """ import wx from edit_windows impo...
#!/usr/bin/env python # -*- coding: UTF-8 -*- """ RESTful endpoints for createing/showing/deleting a user's Jumpbox in vLab """ from setuptools import setup, find_packages setup(name="vlab-jumpbox-api", author="Nicholas Willhite,", author_email='willnx84@gmail.com', version='2018.07.25', packa...
""" An object-oriented high-level wrapper for training InceptionV3 CNNs. """ from keras.applications.inception_v3 import InceptionV3 from keras.preprocessing import image from keras.models import Model from keras.models import load_model from keras.layers import Dense, GlobalAveragePooling2D, Dropout from keras import...
# flake8: noqa from .moxa import MoxaHTTP_2_2
from .app import create_database, delete_database # Delete any previous # data in the database along with # its tables delete_database() # Create the database create_database()
import json import zipfile import numpy as np import pandas as pd import time from dtw import dtw ### Control the number of closest trips used to calculate trip duration N_trips = 20000 ### Get Haversine distance def get_dist(lonlat1, lonlat2): lon_diff = np.abs(lonlat1[0]-lonlat2[0])*np.pi/360.0 ...
import ssz from eth2.beacon.types.attester_slashings import AttesterSlashing def test_defaults(sample_attester_slashing_params): attester_slashing = AttesterSlashing(**sample_attester_slashing_params) assert ( attester_slashing.slashable_attestation_1.validator_indices == sample_attester_sla...
import sys import lib import zipfile import getpass from sys import exit from zipfile import ZipFile if input("R : Run \nE : Exit\n::: ").upper() != "R" : exit() user = getpass.getpass("enter username ::: ") password = getpass.getpass("enter password ::: ") result = lib.checkDB(".") # checks if there exist a fir...
from __future__ import absolute_import from builtins import range from functools import partial import numpy as npo try: import scipy except: from warnings import warn warn('Skipping scipy tests.') else: import autograd.numpy as np import autograd.numpy.random as npr import autograd.scipy.misc ...
import parse import audit import utils import sys import argparse import os def main(): # Definition of Help Text # Argument Parsing parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter, description='''\ This script takes a Cisco ACL definition and parses it into a sea...
# -*- coding: utf-8 -*- from django.test import TestCase from djorm_core.postgresql import server_side_cursors from .models import TestModel class ServerSideCursorsTest(TestCase): @classmethod def setUpClass(cls): TestModel.objects.bulk_create([TestModel(num=x) for x in range(200)]) @classmetho...
#!/usr/bin/python3 # -*- coding: utf-8 -*- """ Utility module for the workflow.""" import logging import os import pprint import yaml from colorlog import ColoredFormatter from tabulate import tabulate # Classes --------------------------------------------------------------------- class DataManager(object): """...
from sagemaker_rl.coach_launcher import SageMakerCoachPresetLauncher class MyLauncher(SageMakerCoachPresetLauncher): def default_preset_name(self): """This points to a .py file that configures everything about the RL job. It can be overridden at runtime by specifying the RLCOACH_PRESET hyperparame...
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright: (c) 2017, Gaudenz Steinlin <gaudenz.steinlin@cloudscale.ch> # Copyright: (c) 2019, René Moser <mail@renemoser.net> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, prin...
''' 高级特性 1. 切片 2. 迭代 3. 列表生成式 4. 生成器 5. 迭代器 ''' #%% 切片 # 类似于 Matlab 的冒号表达式,区别在于 # 开始 : 结束 : 间隔 # 同时支持负数索引 # 可以省略任意元素 L = list(range(100)) print(L[0:10]) print(L[90:-1]) print(L[95:]) print(L[:10]) print(L[:10:2]) print(L[:]) #%% 迭代 # 普通迭代 L = {'a': 1, 'b': 2, 3: 3} for k in L: print(k, L[k]) # 键值迭代 for k, v in...
''' Given an array of characters chars, compress it using the following algorithm: Begin with an empty string s. For each group of consecutive repeating characters in chars: If the group's length is 1, append the character to s. Otherwise, append the character followed by the group's length. The compressed string s s...
import torch from torch.autograd import Function from torch.autograd import Variable from ..build.lib import SpaVar class SpaVarFunction(Function) : @staticmethod def forward(ctx, ref_feas, tar_feas, ref_mask, tar_mask, disparity, max_disp) : """sparse matching while forwarding Args:...
#Crie um algoritmo que leia um número e mostre o seu dobro, triplo e a raiz quadrada . print("==========Exercicio 6 ==========") numero = int(input("Digite um número: ")) dobro = numero * 2 triplo = numero * 3 raiz = numero**(0.5) print(f"O dobro de {numero} é {dobro} \n o triplo de {numero} é {triplo} \n a raiz qu...
""" Hand Tracker on Depth Image based on https://www.learnopencv.com/object-tracking-using-opencv-cpp-python/ """ import os import PIL import glob import numpy as np from matplotlib import pyplot as plt import cv2 import json import configparser import csv DATASET_BASE_DIR_NAME = r"D:\git\HandPointer\dataset" def ...
from openmdao.recorders.case_reader import CaseReader cr = CaseReader('propulsor.db') print(cr.system_cases.list_cases())
# -*- coding: utf-8 -*- """ @Time : 2022/1/14 3:34 下午 @Author : hcai @Email : hua.cai@unidt.com """ import os import time file_root = os.path.dirname(__file__) import sys sys.path.append(file_root) from nlg.run import Service class Summarization(object): def __init__(self, model_name, mode='predict', **kwar...
from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import permissions from rodan.celery import app class TaskQueueActiveView(APIView): """ Returns the list of active Celery tasks. """ permission_classes = (permissions.IsAdminUser,) def get(s...
# Generated by Django 2.2.9 on 2020-01-21 01:27 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('users', '0003_auto_20200121_1017'), ] operations = [ migrations.RenameField( model_name='user', old_name='avartar', ...
import json import logging from functools import wraps from django.http import HttpResponse from rest_framework_auth0.settings import ( auth0_api_settings, ) from rest_framework_auth0.utils import ( get_auth_token, get_roles_from_payload, ) logger = logging.getLogger(__name__) def json_response(response...
import unittest import logging as l from astroutilities.logger import * class BaseLoggerTest(unittest.TestCase): @classmethod def setUpClass(cls): setup_applevel_logger(log_level=l.DEBUG) def test_simple_info_log(self): log = get_logger("test1") with self.assertLogs() as captured...
from django.shortcuts import render from django.views.generic.list import ListView from django.views.generic.detail import DetailView from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.urls import reverse_lazy from django.views.generic import TemplateView from persona.models import P...
import src.bpmnextract import src.data import src.capabilities
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...
import time from ops import * from utils import * from tensorflow.python.client import timeline from graphviz import Digraph import json def profile(run_metadata, epoch=0): with open('profs/timeline_step' + str(epoch) + '.json', 'w') as f: # Create the Timeline object, and write it to a json file ...
import csv import time from matplotlib import pyplot as plt from matplotlib.axes import Axes import numpy as np from planner.drone import DroneState from planner.flyZone import MOCAP_FLY_ZONE, FlyZone from planner.plotting import plotDroneState, plotFlyZone, plotlive from plotUtils import saveFig Z_HEIGHT = 1.5 clas...
# # PySNMP MIB module WWP-LEOS-PING-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/WWP-LEOS-PING-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 21:31:26 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Ma...
import numpy as np from netCDF4 import Dataset from matplotlib import pyplot as plt from PIL import Image # Both datasets use an evenly spaced grid with a 2.5 deg. resolution. # Relative humidity, expressed as a percentage, indicates a present state of absolute humidity relative to a maximum humidity given the same te...
""" # MULTI-LOSS WEIGHTING WITH COEFFICIENT OF VARIATIONS ## https://arxiv.org/pdf/2009.01717.pdf In other words, this hypothesis says that a loss with a constant value should not be optimised any further. Variance alone, however, is not sufficient, given that it can be expected that a loss which has a larger (mean) m...
"""043 - DESENVOLVA UMA LÓGICA QUE LEIA O PESO E A ALTURA DE UMA PESSOA, CALCULO SEU IMC E MOSTRE SEU STATUS, DE ACORDO COM A TABELA ABAIXO: - ABAIXO DE 18,5: ABAIXO DO PESO - ENTRE 18,5 E 25: PESO IDEAL - ENTRE 25 E 30: SOBREPESO - ENTRE 30 E 40: OBESIDADE MORBIDA""" print('-' * 20, 'DESAFIO 043', '-' * 20) ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals import logging # from django.db import connection #引入数据库的列表 from django.core.cache import cache from django.views.generic import ListView, DetailView # from silk.profiling.profiler import silk_profile from .models import Post, Tag, Category from config.m...
# -*- coding: utf-8 -*- # (c) 2018 The PosterKit developers <developers@posterkit.org> import os import logging import requests from glob import glob from docopt import docopt, DocoptExit from posterkit import __version__ from posterkit.util import boot_logging, normalize_options, read_list from gafam.poster import ren...
import numpy as np import collections from random import randint from core.evaluation.labels import PositiveLabel, NegativeLabel, NeutralLabel from sample import Sample from extracted_relations import ExtractedRelation class BagsCollection: def __init__(self, relations, bag_size...
# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import unicode_literals import codecs import sys import warnings from itertools import chain try: from django.urls import Resolver404, resolve except ImportError: from django.core.urlresolvers import Resolver404, resolve try: f...
import argparse from pyannote.database.util import load_rttm import numpy as np import tqdm def segment_load(seg_path): segment = np.load(seg_path, allow_pickle=True).item() return segment if __name__ == "__main__": parser = argparse.ArgumentParser(description="convert segment file to rttm file") par...
import os import numpy as np import scipy.misc import h5py import imageio from PIL import Image # Loading data from disk class DataLoaderDisk(object): def __init__(self, **kwargs): self.load_size = int(kwargs['load_size']) self.fine_size = int(kwargs['fine_size']) self.data_mean = np.array...
#!/usr/bin/env python3 # Copyright (C) 2020 The Android Open Source Project # # 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 requ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('icekit_plugins_image', '0006_auto_20160309_0453'), ] operations = [ migrations.AddField( model_name='imageitem',...
import numpy as np import rasterio def write_raster(filename, data, transform, crs, nodata, **kwargs): """Write data to a GeoTIFF. Parameters ---------- filename : str data : d ndarray transform : rasterio transform object crs : rasterio.crs object nodata : int """ count = 1 ...
import warnings warnings.filterwarnings("ignore") import sys import pandas as pd import numpy as np from sklearn.model_selection import train_test_split from sklearn.preprocessing import MinMaxScaler from sklearn.ensemble import RandomForestClassifier from sklearn.neighbors import KNeighborsClassifier from sklearn.svm...
import random import operator import tkinter import matplotlib matplotlib.use('TkAgg') import matplotlib.pyplot import matplotlib.animation import agentframework import csv import requests import bs4 import time start_time = time.time() # We set the random seed so we can see repeatable patterns random.seed(0) #Func...
#!/usr/bin/env python """Tests for grr.parsers.wmi_parser.""" from grr.lib import flags from grr.lib import test_lib from grr.lib.rdfvalues import client as rdf_client from grr.lib.rdfvalues import protodict as rdf_protodict from grr.parsers import wmi_parser from grr.test_data import client_fixture class WMIParserT...
import pandas as pd import utils import torch from config import * from model import * import matplotlib.pyplot as plt def predict(): # test_loader = utils.data_loader('Dig-MNIST') data = utils.load_data('test') data = torch.from_numpy(data).to(Config.device) num_sample = data.size(0) idx = torch....
from flask_wtf.csrf import CSRFProtect from dotenv import load_dotenv import os csrf = CSRFProtect() class Configurate: def __init__(self, app, config, option="config"): self.app = app self.config = config self.SQLALCHEMY_DATABASE_URI = 'SQLALCHEMY_DATABASE_URI' if option == "c...
# -*- coding: utf-8 -*- # # File : examples/timeserie_prediction/switch_attractor_esn # Description : NARMA 30 prediction with ESN. # Date : 26th of January, 2018 # # This file is part of EchoTorch. EchoTorch is free software: you can # redistribute it and/or modify it under the terms of the GNU General Public # Licen...
from pyparsing import (CharsNotIn, Word, Literal, OneOrMore, alphanums, delimitedList, printables, alphas, alphas8bit, ...
# ==================================================================== # Author : swc21 # Date : 2018-03-14 09:42:27 # Project : ClusterFiles # File Name : parallel_IO_test # Last Modified by : swc21 # Last Modified time : 2018-03-14 12:03:25 # =========...
name="MatricesM" __package__="MatricesM" __path__='./MatricesM'
#!/usr/bin/python # -*- coding: UTF-8 -*- import sys import os pchars = u"abcdefghijklmnopqrstuvwxyz,.?!'()[]{}" fchars = u"ɐqɔpǝɟƃɥıɾʞlɯuodbɹsʇnʌʍxʎz'˙¿¡,)(][}{" flipper = dict(zip(pchars, fchars)) def flip(s): charList = [ flipper.get(x, x) for x in s.lower() ] charList.reverse() return u"\n(╯°□°)╯︵ " + "".j...
from cython.cimports.cpython.ref import PyObject def main(): python_string = "foo" # Note that the variables below are automatically inferred # as the correct pointer type that is assigned to them. # They do not need to be typed explicitly. ptr = cython.cast(cython.p_void, python_string) adr...
""" Select a Shortlist of Applicants Based on Isotonic Regression Calibration. Reference: Accurate Uncertainties for Deep Learning Using Calibrated Regression Volodymyr Kuleshov et al. """ import argparse import pickle import numpy as np from sklearn.isotonic import IsotonicRegression from utils import calculate_expect...
from setuptools import setup setup (name='pyscarab', version='0.1.1', description='Python wrapper and abstractions for libscarab FHE library', author='Bogdan Kulynych, Benjamin Lipp, Davide Kirchner', author_email='hello@hidden-markov.com, mail@benjaminlipp.de, davide.kirchner@yahoo.it', ...
import difflib import logging import pathlib from abc import abstractmethod from typing import Iterable, List, Optional, Sequence, Set from . import git_utils from .command import CommandBase from .error_lines import parse_error_diffs from .reporter import Reporter from .source import FilePredicateType, Source class...
from django.http import HttpResponse from django.shortcuts import render_to_response from django.template import Context, loader from django.http import HttpResponseRedirect from django.core.urlresolvers import reverse from siptracklib.utils import object_by_attribute import siptracklib.errors from siptrackweb.views im...
# # PySNMP MIB module CXFrameRelayInterfaceModule-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CXFrameRelayInterfaceModule-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 18:17:14 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Pytho...
class HashTable: ''' Hashable reperesents a custom dictionary implementation where we use two private list to achieve storing and hashing of key-value pairs. ''' def __init__(self): self.max_capacity = 4 self.__keys = [None] * self.max_capacity self.__values = [None] * s...
import falcon from ebl.context import Context from ebl.corpus.application.corpus import Corpus from ebl.corpus.web.alignments import AlignmentResource from ebl.corpus.web.chapters import ChaptersDisplayResource, ChaptersResource from ebl.corpus.web.colophons import ColophonsResource from ebl.corpus.web.extant_lines im...
class perro(): nombre = 'solovino' raza = 'cruza' edad = 5 color = 'Negro' def setnombre(self): self.nombre = input("Ingresa el nombre de tu perro: ") def getnombre(self):#Getter o método que obtiene propiedad return self.nombre def cr...
CONTEXT_ALL = 0 CONTEXT_CHANNEL = 1 CONTEXT_QUERY = 2
from src.config import hiv_config from hiv_domain.fittedQiter import FittedQIteration from sklearn.externals import joblib import pickle import matplotlib.pyplot as plt import numpy as np if __name__ == "__main__": ep_reward = [] config = hiv_config rewards = [] """ Load hiv environment - th...
import re from model.address import Address def test_address_on_home_page(app): # info o kontakcie ze str glownej address_from_home_page = app.address.get_address_list()[0] # info o kontakcie z formy edytowania address_from_edit_page = app.address.get_address_info_from_edit_page(0) assert address_...
from rlib.jit import promote from som.interpreter.ast.frame import is_on_stack from som.vmobjects.abstract_object import AbstractObject from som.vmobjects.block_ast import VALUE_SIGNATURE from som.vmobjects.primitive import ( UnaryPrimitive, BinaryPrimitive, TernaryPrimitive, ) class BcBlock(AbstractObje...
class Util: def __init__(self, bot): self.bot = bot def update_channels(self): conversations = self.bot.slack_client.api_call("conversations.list") for channel in conversations.get("channels"): self.bot.redis.hset("channels:cid_name", channel["id"], channel["name"]) ...
"""The following code will cause various Python Exceptions to occur""" def name_error(): """This function will raise a NameError.""" no_function() def type_error(): """This function will raise a TypeError.""" "hello world" + 7 def attribute_error(): """This function will raise a AttributeError....
#!/usr/bin/env python # Copyright (c) 2021, Microsoft from threading import Lock import numpy as np import rospy from std_msgs.msg import Float64 from vesc_msgs.msg import VescStateStamped from nav_msgs.msg import Odometry import utils # Tune these Values! KM_V_NOISE = 0.4 # Kinematic car velocity noise std dev KM...
import pytest @pytest.mark.parametrize( "file, result, expected", ( ("src/dafny/utils/MathHelpers.dfy", "passed", "passed"), ("src/dafny/utils/Helpers.dfy", "failed", "failed"), ), ) def test_proof_result(file, result, expected): assert file.endswith(".dfy") assert result == expec...
""" @Project: BeautifulReport @Author: Mocobk @Data: 2019/03/18 @File: test_demo_report.py @License: MIT """ import unittest from BeautifulReport import BeautifulReport if __name__ == '__main__': test_suite = unittest.defaultTestLoader.discover('./tests', pattern='test_demo*.py') result = BeautifulReport(test_...
def convert(String): list1 = list(String.split(" ")) return list1 if __name__=="__main__": String = (input()) print(convert(String)) list2 = ["Anuja", "pritee"] print(str(list2)) def list_to_String(list): str1 =" " for item in list: str1+=item return...
from dataclasses import dataclass @dataclass class Event: type: str # TODO: enum? user_id: str output = 'slack' @dataclass class MessageEvent(Event): message: str channel: str @dataclass class ErrorEvent(Event): error: str code: str message: str @dataclass class OutputEvent: ...
import os import pytest from flask import render_template_string, url_for from flask_rollup import Bundle, Rollup def test_create_simple(app): rv = Rollup(app) assert rv.app == app assert app.extensions['rollup'] == rv def test_init_app(app): r = Rollup() r.init_app(app) assert r.app is No...
import torch from SDE_CG import layers from torch_scatter import scatter_add import numpy as np import torch.nn as nn from .SDE_builder import GaussianFourierProjection class ScoreNet(torch.nn.Module): def __init__(self,config, marginal_prob_std, hidden_dim=256,device='cuda'): super().__init__()...
"""run the linters and formatters""" import sys import doit import shutil from . import DOIT_CONFIG, Task, main, needs, Param, get_name def task_lint(): """lint and format the project with pre-commit""" def lint(raises): needs("pre_commit") # do not fail this unless explicit action...
#!/usr/bin/env python # -*- encoding: utf-8 -*- import math from loguru import logger import pulp from .benchmarker import ModelBenchmarker, DeviceBenchmarker from .worker_manager import WorkerManager class Allocator(object): def __init__( self, model_cfg: dict, worker_manager: WorkerMan...
""" Copyright (c) 2015-2021 Ad Schellevis <ad@opnsense.org> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, ...
import typer import git from InquirerPy import inquirer try: repo = git.Repo('.') except git.exc.InvalidGitRepositoryError as err: typer.echo("This is not a Git repository") exit() def get_branches(): """Return the list of local branches except the active.""" branches = [] for ref in repo.head...
""" MIT License Copyright (c) 2017 Zeke Barge 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, di...
from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from endpoints.utils.decorators import room_required, pk_required from music.serializers import PlaylistSerializer from music.models import PlaylistTrack class PlaylistView(APIView): """ Pl...
#!/usr/bin/python3 ADT_PATH = "~/MGLTools/MGLToolsPckgs/AutoDockTools/Utilities24/" PDBAA_PATH = "~/GASSER/database/pdbaa/pdbaa" MODELLER_PATH = "/opt/modeller923/bin/mod9.23" BRENDA_PATH = "../database/enzyme/brenda-90"
from __future__ import absolute_import import json import os from datetime import datetime, timedelta import pytest from app import db from app.models import ( DATETIME_FORMAT, Framework, User, Lot, Brief, Supplier, ContactInformation, Service, BriefClarificationQuestion ) from app.models.direct_award import Dir...
# -*- coding: utf-8 -*- """ (c) 2017 - Copyright Red Hat Inc Authors: Pierre-Yves Chibon <pingou@pingoured.fr> """ from __future__ import unicode_literals, absolute_import import json import unittest import sys import os import pygit2 from mock import patch, MagicMock sys.path.insert( 0, os.path.join(os...
#!/usr/bin/python import os,sys if False: for stateCode in os.listdir('.'): if len(stateCode) != 2: continue for districtCode in os.listdir(stateCode): if districtCode == 'index.txt': continue if districtCode == 'district.court': #print "%s: %s" % (stateCode...
#!/usr/bin/env python # -*- mode: python; encoding: utf-8 -*- """Test the hunt_view interface.""" from __future__ import unicode_literals import os import traceback import unittest from grr_response_core.lib import flags from grr_response_server import aff4 from grr_response_server import data_store from grr_respon...
"""User constraints predicates.""" import warnings import collections import dateutil.tz import dateutil.parser from jacquard.utils import check_keys ConstraintContext = collections.namedtuple("ConstraintContext", ("era_start_date",)) ConstraintContext.__doc__ = """Context for evaluating constraints.""" Constrai...
import pandas as pd def check_template(df_json, df_annotation, df_activity, df_json_exp): # omit '_Test.xaml', 'Test_Framework/RunAllTests.xaml' df_json_dup = df_json.loc[:, ['index', 'mainFolder', 'subfiles', 'mainFile']] df_json_dup.subfiles = df_json_dup.apply(lambda x: [subfile.replace(str(x['mainFolde...
import os import numpy as np from tqdm import tqdm import torch from libyana.evalutils.avgmeter import AverageMeters from libyana.evalutils.zimeval import EvalUtil from meshreg.visualize import samplevis from meshreg.netscripts import evaluate from meshreg.datasets.queries import BaseQueries from meshreg.datasets im...
from flask_mail import Message from backend.tasks import send_mail_async_task class TestTasks: def test_send_mail_task(self, outbox): msg = Message(subject='hello world', recipients=['foobar@example.com'], sender='noreply@example.com', htm...
#!/usr/bin/env python # -*- coding: utf-8 -*- """Display an iterative method for determining the greatest common denominator. Jan 17, 2019: Just added in :mod:`sys` so that we accept input from the user. """ import logging import sys def gcd_iter(a, b): """Find the greatest common denominator with 2 arbit...
import textwrap from mako.template import Template __all__ = ['DependencyGraph'] class DependencyGraph: def __init__(self, generator=None): self.node_indices = {} self.cnt = 0 if generator is not None: self.add_node(generator) def add_node(self, node): if node n...
import argparse #from PIL import Image, ImageTk import sqlite3 from max30102 import MAX30102 import hrcalc import threading import time import numpy as np import Adafruit_DHT dht_sensor = Adafruit_DHT.DHT11 pin = 5 humidity, temperature = Adafruit_DHT.read_retry(dht_sensor, pin) class HeartRateMonitor(object): ...
""" loading widgets """ # Copyright (c) 2021 ipyradiant contributors. # Distributed under the terms of the Modified BSD License. import ipywidgets as W import traitlets as T from rdflib import BNode, Graph from .base import BaseLoader from .upload import UpLoader class FileManager(W.HBox): """Wraps a file selec...
import ckan.logic as logic from ckan.common import c def scheming_get_user_dict(): context = None data_dict = {'id': c.user} user_dict = logic.get_action('user_show')(context, data_dict) return user_dict
#!/usr/bin/env python from __future__ import print_function from itertools import groupby import sys import random mut = {'A': 'C','C': 'G','G': 'T','T': 'A'} hdr = ('##fileformat=VCFv4.2\n' '##FILTER=<ID=PASS,Description="All filters passed">\n' '##fileDate=20151014\n' '##FORMAT=<ID=GT,Number=1...
from django.test import TestCase from django.contrib.auth.models import User class AnonymousUserTestCase(TestCase): '''Test cases for anonymous (non-authenticated) users''' def test_anon_user_can_visit_home(self): '''Ensure the anonymous user is redirected to /login when visiting the root''' re...
# Copyright (c) 2015 Microsoft Corporation from z3 import * ctx1 = Context(relevancy=0) ctx2 = Context(':model', False, ':pp-decimal', True, relevancy=2, pp_decimal_precision=50) x = Int('x', ctx1) _x = x.translate(ctx2) print(_x == (x + 1).translate(ctx2)) print(simplify(Sqrt(2, ctx2))) # pp_params is a global varia...
from azure.cosmosdb.table.tableservice import TableService from azure.cosmosdb.table.models import Entity, EntityProperty, EdmType from string import Template from database.models.Listing import Listing class ListingRepository: def __init__(self): self.tableService = TableService(connection_string='DefaultEndpoints...