content
stringlengths
5
1.05M
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'Participant' db.create_table(u'precon_participant', ( (u'id', self.gf('django.db...
import pathlib from . import UMRLogging from .UMRType import ChatType, ForwardTypeEnum, DefaultForwardTypeEnum, LogLevel from pydantic import BaseModel, validator from typing import Dict, List, Union, Type, Optional, Generic, AnyStr, DefaultDict from typing_extensions import Literal import importlib import yaml import ...
import torch.nn as nn import torch.nn.functional as F from CGS.gnn.IGNN.IGNNLayer import ImplicitGraph from CGS.gnn.IGNN.utils import get_spectral_rad from CGS.nn.MLP import MLP from CGS.nn.MPNN import AttnMPNN class IGNN(nn.Module): def __init__(self, node_dim: int, edge_dim: ...
def interative_test_xdev_embed(): """ CommandLine: xdoctest -m dev/interactive_embed_tests.py interative_test_xdev_embed Example: >>> interative_test_xdev_embed() """ import xdev with xdev.embed_on_exception_context: raise Exception def interative_test_ipdb_embed(): ...
import unittest from maturin_sample import hello class SampleTestCase(unittest.TestCase): def test_hello(self): self.assertEqual(hello([]), 0) self.assertEqual(hello([5]), 1) self.assertEqual(hello([9, 1, 5, 2, 3]), 5) if __name__ == "__main__": unittest.main()
import pytest from optional import Optional from optional.something import Something class TestSomething(object): def test_can_not_instantiate_with_a_none_value(self): with pytest.raises(ValueError, match='\\AInvalid value for Something: None\\Z'): Something(value=None, optional=Optional) ...
from board import Board,MoveRecommendation from math import inf as infinity import random def __player_turn(board: Board): set_field = input('Enter the number of the field you want to play?[1:' + str(board.size**2) + ']') print('field id', set_field) if(set_field!=''): board.player_set(int(set_fiel...
#!/usr/bin/env python3 import os, re, json import sqlite3 from markov import Markov SQLITE_DATABASE = os.path.join(os.path.dirname(os.path.realpath(__file__)), "chains.db") CHAT_HISTORY_DIRECTORY = os.path.join(os.path.dirname(os.path.realpath(__file__)), "..", "..", "..", "@history") def get_metadata(): with o...
#!/usr/bin/python fichier = open('day6_input.txt') groupes_txt = fichier.read().split('\n\n') compteur = 0 for g in groupes_txt: reponses = set() for q in g.split('\n'): for r in q: reponses.add(r) print(reponses) compteur = compteur + len(reponses) print('fin',compteu...
from cereal import car from common.realtime import DT_CTRL from common.numpy_fast import interp, clip from selfdrive.config import Conversions as CV from selfdrive.car import apply_std_steer_torque_limits, create_gas_command from selfdrive.car.gm import gmcan from selfdrive.car.gm.values import DBC, CanBus, CarControll...
import json import pytest from common.assertions import equal_json_strings from common.methods import anonymize, anonymizers, decrypt @pytest.mark.api def test_given_anonymize_called_with_valid_request_then_expected_valid_response_returned(): request_body = """ { "text": "hello world, my name is Jan...
import sys import maya.OpenMaya as OpenMaya import maya.OpenMayaMPx as OpenMayaMPx import maya.cmds as cmds __author__ = 'Haarm-Pieter Duiker' __copyright__ = 'Copyright (C) 2016 - Duiker Research Corp' __license__ = '' __maintainer__ = 'Haarm-Pieter Duiker' __email__ = 'support@duikerresearch.org' __status__ = 'Produ...
import os import subprocess from multiprocessing import Pool, cpu_count import numpy as np from energy_demand.read_write import read_weather_data def my_function(simulation_number): print('simulation_number ' + str(simulation_number)) # Run smif run_commands = [ "smif run energy_demand_constrain...
'''Netconf implementation for IOSXE devices''' from ncclient import manager from ncclient.transport.errors import TransportError from ncclient.operations.rpc import RPCError import xmltodict def compare_proposed_to_running(proposed_config, running_config): '''Return diff between *proposed_config* and *running_co...
# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/03_model_splits.ipynb (unless otherwise specified). __all__ = ['bert_SeqClassification_split', 'roberta_SeqClassification_split', 'gpt2_lmhead_split', 'distilbert_SeqClassification_split', 'albert_SeqClassification_split'] # Cell #export from fastcore.all imp...
from .main import Wav2Vec2STTTorch
import subprocess import logging from subprocess import PIPE import tempfile import json, os, re from github import Github, GithubException from datetime import datetime """ search-demo-mkdocs-material Submodule Update PR for Uncle Archie Notes: - search-demo is private-www - fake-docs is submodule - install webh...
# # DMG 136 # import os import csv import random import numpy as np from .dice import dice from .utils import csv2dict from .utils import filterDictList data_dir = os.path.join( os.path.dirname( os.path.realpath(__file__) ), "data" ) files = { "ART_AND_GEMSTONES": os.path.join(data_dir, 'ART...
# -*- cpy-indent-level: 4; indent-tabs-mode: nil -*- # ex: set expandtab softtabstop=4 shiftwidth=4: # # Copyright (C) 2019 Contributor # # 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 # # ...
import sys import os.path import subprocess import sublime try: from .sublime_connection import SublimeConnection from .common import msg, shared as G, utils, flooui from .common.exc_fmt import str_e assert G and G and utils and msg except ImportError: from sublime_connection import SublimeConnect...
# Generated by Django 3.2.9 on 2022-02-15 08:57 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('clients', '0026_servicerequest_facility'), ('common', '0015_faq'), ('staff', '0002_alter_staff_default_facility'), ] operations = [ ...
from airflow import DAG from airflow.operators.dummy_operator import DummyOperator from datetime import datetime with DAG('example_dag', start_date=datetime.now()) as dag: op = DummyOperator(task_id='op')
import os from PIL import Image, ImageQt import tkinter as tk import sys from PyQt5 import QtWidgets from PyQt5.QtWidgets import QApplication, QWidget, QMainWindow, QVBoxLayout, QLabel, QSlider, QStackedLayout, QPushButton, QFileDialog from PyQt5.QtGui import QFont, QImage, QPixmap from PyQt5.QtCore import Qt from copy...
from common.remote_execution.SSHConf import sshConfig import socket from Constants import * import json from dataModels.KubeCluster import KubeCluster cluster_management_objects={} def get_cluster_management_object(kube_cluster_name): if kube_cluster_name not in cluster_management_objects: return None ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ build dict interface """ import argparse import os from collections import defaultdict import six def build_dict(input_path, output_path, col_nums, feq_threshold=5, sep=' ', extra_words=None, ...
# Databricks notebook source # MAGIC %md # Python REST Client using Wrapper Module # COMMAND ---------- # MAGIC %md ####Load REST Class # COMMAND ---------- # MAGIC %run ./008-REST_API_Py_Requests_Lib # COMMAND ---------- # MAGIC %md ####Initialize REST Object # COMMAND ---------- import datetime import json #...
#!/usr/bin/python3 import sys import time sys.path.append("./shared") #from sbmloader import SBMObject # location of sbm file format loader from ktxloader import KTXObject # location of ktx file format loader #from sbmath import m3dDegToRad, m3dRadToDeg, m3dTranslateMatrix44, m3dRotationMatrix44, m3...
# -*- coding: utf-8 -*- import numpy as np import pytest from pandas import DataFrame, Index, Series, Timestamp from pandas.util.testing import assert_almost_equal def _assert_almost_equal_both(a, b, **kwargs): """ Check that two objects are approximately equal. This check is performed commutatively. ...
"""Register thermal expansion data.""" import pandas as pd import sqlalchemy.sql.functions as func from setting import session from create_db import * def main(): df = pd.DataFrame({"id":[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], "name":[ "ポンタ", "たぬまる", ...
import requests from datetime import datetime from .get_client_id import get_client_id from ._client_keys import _sign_message_as_client, _ephemeral_mode from ._kachery_cloud_api_url import _kachery_cloud_api_url def _kacherycloud_request(request_payload: dict): client_id = get_client_id() url = f'{_kachery_cl...
from conans import ConanFile, tools, AutoToolsBuildEnvironment, MSBuild import os class YASMConan(ConanFile): name = "yasm" url = "https://github.com/conan-io/conan-center-index" homepage = "https://github.com/yasm/yasm" description = "Yasm is a complete rewrite of the NASM assembler under the 'new' B...
""" Convert a PCF file into a VPR io.place file. """ from __future__ import print_function import argparse import csv import json import sys import os import vpr_io_place from lib.parse_pcf import parse_simple_pcf def main(): parser = argparse.ArgumentParser( description='Convert a PCF file into a VPR io....
''' SOLO TEs are these transcripts that contain intact, or semi intact unspliced transcripts. As we don't trust the short read data to assemble these, we only consider them from the pacbio data: ''' import sys from glbase3 import glload, genelist, config config.draw_mode = 'pdf' sys.path.append('../../') import s...
from KeyHardwareInput import * from time import * from Enderecos import * class keyController(object): def __init__(self): pass def pressionar(self,tecla,tempo): if (tecla==0): self.pressKey(S) sleep(tempo) self.releaseKey(S) if (tecla==1): ...
def insertionsort(lista): tam = len(lista) for i in range(1, tam): proximo = lista[i] atual = i - 1 while proximo < lista[atual] and atual >= 0: lista[atual + 1] = lista[atual] atual -= 1 lista[atual + 1] = proximo # debug if __name__ == "__main__": ...
import time import argparse from helpers.connection import conn import tabulate as tb tb.WIDE_CHARS_MODE = True def parsing_store(parser:argparse.ArgumentParser): sub_parsers = parser.add_subparsers(dest='function') # info parser_info = sub_parsers.add_parser('info') parser_info.add_argument('id', ty...
# Copyright The PyTorch Lightning team. # # 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 i...
# -*- coding: utf-8 -*- """ 定时监控futnn api进程,如果进程crash, 自动重启, 1. 该脚本仅支持windows (目前api也只有windows版本) 2. 构造 FTApiDaemon 需指定ftnn.exe所在的目录 ,一般是'C:\Program Files (x86)\FTNN\\' 3. 对象实现的本地监控, 只能运行在ftnn api 进程所在的机器上 """ import psutil import time import socket import sys import configparser from threading import Thread ...
import os from jinja2 import Environment, FileSystemLoader PATH = os.path.dirname(os.path.abspath(__file__)) TEMPLATE_PATH = os.path.join("/".join(PATH.split("/")[0:-1]),'resources') TEMPLATE_ENVIRONMENT = Environment( autoescape=False, loader=FileSystemLoader(TEMPLATE_PATH), trim_blocks=False) def render...
# Defines projections through a parallel slab. import math import numpy from camera_model import central_projection def polar_normal(elevation, azimuth): # Defines the polar coordinate representation of a normal oriented towards the z-axis per default # # elevation Elevation of the normal vector # a...
from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import UserDetails, HospitalDetails, BankDetails, Address, DoantionLogDetails class UserRegisterForm(UserCreationForm): email = forms.EmailField() first_name = forms.CharFie...
import re from typing import List, TYPE_CHECKING, Union from MFramework import ( Interaction, Application_Command_Option_Type, Interaction_Type, Snowflake, Message, Interaction_Type, ChannelID, RoleID, UserID, User, Guild_Member, GuildID, Groups, ) from .command imp...
from scipy.optimize import linprog import numpy as np import pandas as pd class OptimizationFailedError(Exception): pass def findTaxaAGSVec(proportions, sampleAGS, taxaBounds=True): nsamples, ntaxa = proportions.shape b = np.concatenate([sampleAGS, -1 * sampleAGS]) if taxaBounds: taxaMax = 1...
# coding: utf-8 # In[ ]: from Bio.Blast.Applications import NcbiblastpCommandline from Bio.Blast import NCBIXML import pandas as pd import os # In[ ]: meso_file = "best_hit_org/hit_meso.csv" thermal_file = "best_hit_org/query_thermal.csv" meso_fold = "meso_protein/" thermal_fold = "thermal_protein/" meso_fst_fo...
# coding: utf-8 from .base import Base from .config_auth import ConfigAuth from .config import Config from .user import User from .song import Song from .feedback import Feedback
# Standard import sys # Dependencies import xdg.BaseDirectory as xdg class Config_File_Parse: def __init__(self, project_name, file_name): """ This function creates a diction of configuration keys and values by reading a specified text file passed as an argument. It excludes lines...
import pytoml as toml class TomlConfig(object): def __init__(self, param={}): pass def load_file(self, fn): with open(fn, 'r') as f: return toml.load(f) def load_str(self, s): return toml.loads(s) def dump_file(self, data, fn): with open(fn, 'w') as f: ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import sonnet as snt import tensorflow as tf from ..direction import Direction from ..naive_effect import ShortEffectLayer from ..short_board.black_piece import select_black_gi __author__ = 'Yasuhiro' __date__ = '2018/2/19' class BlackGiEffectLayer(snt.AbstractModule)...
length = int(input()) width = int(input()) height = int(input()) lengths_edges = 4 * (length + width + height) area = 2 * ((length * width) + (width * height) + (length * height)) volume = (length * width) * height print(lengths_edges) print(area) print(volume)
import torch import torch.nn as nn import torch.nn.functional as F class GraphAttentionLayer(nn.Module): """ Simple GAT layer, similar to https://arxiv.org/abs/1710.10903 """ def __init__(self, in_features, out_features, dropout, alpha, concat=True, drop_enc=False): super(GraphAttentionLayer, ...
from FrameLibDocs.utils import read_json, write_json from FrameLibDocs.variables import help_dir, current_version def main(): template_dir = help_dir / "templates" internal_dir = help_dir / "internal_tabs" external_dir = current_version / "FrameLib" / "externals" master_template = help_dir / "help_tem...
# Copyright 2020 Google LLC # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
from mini_gplus.models import Media def get_media(object_name): return Media.objects.get(id=object_name) def create_media(object_name): media = Media() media.id = object_name # have to force save for some reason... # https://github.com/MongoEngine/mongoengine/issues/1246 media.save(force_ins...
# -*- coding: utf-8 -*- """Particle system Constraints objects MIT License Copyright (c) 2020 Mauro Lopez 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 l...
from django.db import models from django.contrib.auth.models import User """Dzien pracy - od zeskanowania kodu do ponownego zeskanowania """ class WorkDay(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) started = models.DateTimeField(auto_now_add=True) finished = models...
import sys import unittest class SC2EnvTests(unittest.TestCase): def test_sc2env_four_towers_hra(self): sys.argv = ['', '--task', 'abp.examples.sc2env.four_towers.hra', '--folder', 'test/tasks/sc2env_four_towers_hra'] from abp.trainer.task_runner import main ...
# Regression test based on detection of carbuncle phenomenon (Odd-Even decoupling) # MHD Riemann solvers # # Modules import logging import scripts.utils.athena as athena import sys import os from shutil import move sys.path.insert(0, '../../vis/python') import athena_read # noqa athena_read...
""" ******** INFO ******** Created by Konrad Wybraniec konrad.wybraniec@gmail.com ********************** """ from mainwindow import MrRoot if __name__ == '__main__': root = MrRoot() root.configure() root.mainloop() # this is testing comment.
# # Copyright (C) 2021 Vaticle # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0...
#!/usr/bin/env python # coding: utf-8 # # <a href="https://colab.research.google.com/github/aviadr1/learn-advanced-python/blob/master/content/14_pandas/edm_us_adult_census_income/questions.ipynb" target="_blank"> # <img src="https://colab.research.google.com/assets/colab-badge.svg" # title="Open this file in Go...
#!/usr/bin/env python """ _AcquireFiles_ MySQL implementation of Subscription.GetCompletedFiles """ __all__ = [] from WMCore.WMBS.MySQL.Subscriptions.GetAvailableFiles import GetAvailableFiles class GetCompletedFiles(GetAvailableFiles): sql = """SELECT wmsfc.fileid, wl.site_name FROM wmbs_sub_files_complete wm...
# Generated by Django 4.0.2 on 2022-03-01 16:57 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('Library', '0002_book_image'), ] operations = [ migrations.AlterField( model_name='book', name='Image', f...
#!/usr/bin/python3 import copy import itertools as it import os import unittest import unittest.mock as mock import plato_pylib.plato.parse_tbint_files as parseTbint import plato_pylib.plato.private.tbint_test_data as tData import plato_fit_integrals.core.coeffs_to_tables as tCode class TestIntegralHolder(unittest....
from unittest import TestCase, mock from flask import url_for from app import app class RootTests(TestCase): def setUp(self): self.app = app self.app.testing = True self.app_context = self.app.test_request_context() self.app_context.push() self.client = self.app.test_client...
from django.apps import AppConfig class DadfesConfig(AppConfig): name = "dadfes"
########################################################## ### PYGAME – Graph ### ### 1st Project for Data Structure at NYU Shanghai ### ########################################################## __author__ = "Jack B. Du (Jiadong Du)" __copyright__ = "Copyright 2014, the DS 1st P...
# -*- coding: utf-8 -*- """ DB操作层 只涉及DB操作,最好不涉及业务 """ from typing import List from app.exceptions import AuthenticationFailed, ObjNotFound from app.utils import sha256 from users.models import User, UserPermissionRelation, Permission, Role, UserRoleRelation, RoleMenuRelation, Menu, \ Platform def authenticate(p...
# -*- coding: utf-8 -*- """ MIT License Copyright (c) 2020 D. Craig Brinck, SE; tamalone1 """ import unittest # Run the tests in this module # Use warnings flag to suppress the PendingDeprecationWarning # from numpy.matrix # unittest.main(warnings='ignore') test_suite = unittest.TestLoader().discover("Testing", pat...
import logging import unittest from morm.q import Q LOGGER_NAME = 'morm-test-q-' log = logging.getLogger(LOGGER_NAME) class TestMethods(unittest.TestCase): def test_Q(self): self.assertEqual(Q('string'), '"string"') if __name__ == "__main__": unittest.main(verbosity=2)
""" Copyright (c) 2016 Jet Propulsion Laboratory, California Institute of Technology. All rights reserved """ import json from webservice.NexusHandler import NexusHandler, nexus_handler, AVAILABLE_HANDLERS from webservice.webmodel import NexusResults @nexus_handler class HeartbeatHandlerImpl(NexusHandler): name...
""" 263. Ugly Number Easy An ugly number is a positive integer whose prime factors are limited to 2, 3, and 5. Given an integer n, return true if n is an ugly number. Example 1: Input: n = 6 Output: true Explanation: 6 = 2 × 3 Example 2: Input: n = 1 Output: true Explanation: 1 has no prime factors, therefore ...
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'EMG3.ui' # # Created by: PyQt5 UI code generator 5.15.4 # # WARNING: Any manual changes made to this file will be lost when pyuic5 is # run again. Do not edit this file unless you know what you are doing. from PyQt5 import QtCore, QtGui, ...
iterable = [1, 2, 3, 4] for item in iterable: print(item) print('-') i = 0 while i<len(iterable): print(iterable[i]) i += 1 # tuple unpacking print('-') tupleList = [('a', 1), ('b', 2), ('c', 3)] for letter, number in tupleList: print("letter is ", letter) # need terminating condition and updation in wh...
# A List it's a collection of grouping of items item1 = 'bananas' item2 = 'lego set' # we can do it shorter -->> tasks = ['Install Python', 'Learn Python', 'Take a break'] length = len(tasks) # Shows the length of the List print(length) # Accessing specific element from List wi the square brackets and position numbe...
import torch from datasets import CubDataset from models import FineGrainedModel, ResNet18 from torchvision import transforms from torch.utils.data import DataLoader train_transforms = transforms.Compose( [ transforms.Resize((128, 128)), transforms.ToTensor(), transforms.Normalize((0.4819...
from gurobipy import * from prediction.predictor import predict_scores from utils.progress import inhour import time import numpy as np def sample_users(num_users, num_users_sampled): return np.random.choice(num_users, num_users_sampled, replace=False) def sample_items(candidate_items, num_items_sampled): r...
import json from rest_framework.fields import MISSING_ERROR_MESSAGE from rest_framework.relations import * from django.utils.translation import ugettext_lazy as _ from rest_framework_json_api.exceptions import Conflict from rest_framework_json_api.utils import Hyperlink, \ get_resource_type_from_queryset, get_res...
import kube_vars as globalvars import kube_factory as factory import kube_secret import kube_servicecheck import kube_pvc if __name__=="__main__": # This is the unified interface to accept parameters # Python model argparse be used to parse the input parameter # Subparser has been defined in git_handler.py...
import sys from PIL import Image, ImageDraw WRITABLES = [(0, 0, 7, 7), (24, 0, 39, 7), (56, 0, 63, 7)] imagePath = "schoolgirlsweater_tanukirotate.png" img = Image.open(imagePath) draw = ImageDraw.Draw(img) lengthPass = False length = 0 while not lengthPass: msg = input("Enter the messaage to encode ...
import os, sys sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))) import time import unittest import common.mqtt_connection as mqtt_connection import common.mqtt_messages as mqtt_messages import server.MQTT_callbacks as MQTT_callbacks import server.storage as server_storage ...
import os,copy import pandas as pd from collections import OrderedDict from pypospack.pyposmat.data import PyposmatDataAnalyzer from pypospack.pyposmat.data import PyposmatDataFile from pypospack.pyposmat.data import PyposmatConfigurationFile _fn_config = os.path.join("resources","pyposmat.config.in") _fn_results_in =...
def slugify(text): """ Removes all char from string that can cause problems whe used as a file name. :param text: text to be modified. :return: modified text """ return "".join(x for x in text if x.isalnum())
# Generated by Django 3.2.4 on 2021-06-21 18:04 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('pvs_suban', '0009_auto_20210621_1753'), ] operations = [ migrations.AddField( model_name='addre...
from PyQt5.QtWidgets import QBoxLayout from PyQt5.QtWidgets import QDialog from PyQt5.QtWidgets import QDialogButtonBox from PyQt5.QtWidgets import QLabel from PyQt5.QtWidgets import QLineEdit from PyQt5.QtWidgets import QMenu from PyQt5.QtWidgets import QPushButton from PyQt5.Qt import pyqtSignal from PyQt5.Qt import ...
"""Merge constrained primitives as property constraints.""" import collections from typing import Tuple, Optional, List, Mapping, MutableMapping, Sequence from icontract import ensure from aas_core_codegen import intermediate from aas_core_codegen.common import Error from aas_core_codegen.infer_for_schema import ( ...
from core.models import UrineDrugScreen from rest_framework import serializers class UrineDrugScreenSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = UrineDrugScreen fields = ('id', 'participant_id', 'date_of_test', 'uds_temp', 'pregnancy_test', 'opiates', 'fentanyl', 'bup', '...
from typing import Optional, List from pydantic import BaseModel from feeder.api.models import BasePaginatedList class GenericResponse(BaseModel): success: str = "ok" class FrontButton(BaseModel): enable: bool = True class UTCOffset(BaseModel): utc_offset: int = -7 class TriggerFeeding(BaseModel): ...
from al_utils.vaal_util import train_vae, train_vae_disc from al_utils import vae_sampling as vs import sys import pickle import torch import numpy as np import os from copy import deepcopy from pycls.core.config import custom_dump_cfg import pycls.datasets.loader as imagenet_loader def save_numpy_arrays(arrays, nam...
import sys import os import datetime import psycopg2 import pandas from subprocess import call, Popen print "dropping temporary members from database..." conn_string = "dbname='hamlethurricane' user=postgres port='5432' host='127.0.0.1' password='password'" try: conn = psycopg2.connect(conn_string) exc...
###################################################################### ###################################################################### # Copyright Tsung-Hsien Wen, Cambridge Dialogue Systems Group, 2016 # ###################################################################### ####################################...
# -*- coding: utf-8 -*- # Generated by Django 1.10.1 on 2018-07-30 19:16 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('data', '0053_merge_20180615_1859'), ] operations = [ migrations.AddField( ...
"""Allow _view property in graph file schema Revision ID: 8f6d4eef042d Revises: a2316139e9a3 Create Date: 2021-10-20 10:04:21.668552 """ import hashlib import json from os import path import fastjsonschema import sqlalchemy as sa from alembic import context from alembic import op from sqlalchemy import table, column...
# -*- coding: utf-8 -*- from abc import ABC, abstractmethod from fuocore.models import ( SongModel, ArtistModel, AlbumModel, PlaylistModel, LyricModel, UserModel, ) class AbstractProvider(ABC): """abstract music resource provider """ # A well behaved provider should implement it...
import warnings from mmdet.models.builder import (BACKBONES, DETECTORS, HEADS, LOSSES, NECKS, ROI_EXTRACTORS, SHARED_HEADS, build) from .registry import FUSION_LAYERS, MIDDLE_ENCODERS, VOXEL_ENCODERS from mmdet3d.datasets.pipelines import Compose def build_backbone(cfg): """Buil...
from flask import Flask from . import api_credentials_provider def create_app(test_config=None) -> Flask: """Main entry point of the service. The application factory is responsible for creating and confguring the flask app. It also defines a http ping endpoint and registers blueprints. Returns: F...
# encapsulation def outer(num1): print("outer") def inner_increment(num1): print("inner") return num1 + 1 num2 = inner_increment(num1) print(num1, num2) outer(10)
''' Extract special sequences from fasta file. You can specify which sequences get extracted by using the a separator. Usage: python extract <fasta_file> <output_file> <separator> Author: Nicolas Schmelling ''' from Bio import SeqIO import sys def extract(fasta_file, output_file, separator): with o...
"""Utilities for interacting with ProxyStore""" import proxystore as ps from typing import Any, Optional, Union from colmena.models import SerializationMethod class ColmenaSerializationFactory(ps.store.redis.RedisFactory): """Custom Factory for using Colmena serialization utilities""" def __init__(self, ...
from ... import error from ..entity import Entity from ..component import Component __all__ = ["Parent"] class Parent(Component): def __init__(self, parent: Entity): self._parent = parent def parent(self, err=True) -> Entity: if self._parent is None and err: raise error.ecs.Paren...
from microbit import * import utime class Rangefinder: def __init__(self, pin): '''Setup a rangefinder on the specified pin''' self.pin = pin def distance_cm(self): '''Returns the distance from a rangefinder in cm''' self.pin.write_digital(0) utime.sleep_us(200) ...