content
stringlengths
5
1.05M
from __future__ import absolute_import, unicode_literals from django.db.models.signals import post_delete from wagtail.wagtaildocs.models import Document # Receive the post_delete signal and delete the file associated with the model instance. def post_delete_document_file_cleanup(sender, instance, **kwargs): # ...
from HSTB.kluster.gui.backends._qt import QtGui, QtCore, QtWidgets, Signal from dask.distributed import get_client from HSTB.kluster.dask_helpers import dask_find_or_start_client from HSTB.kluster import kluster_variables class DaskClientStart(QtWidgets.QDialog): """ Widget that allows you to manually start ...
import discord import discord from discord.ext import commands import json from utils.checks import plugin_enabled import numexpr as ne import numpy async def get_counting_channel(guild): with open("./database/db.json") as f: data = json.load(f) for i in data: if i["guild_id"] == guild.id: ...
"""Utils for crawler google scholar """ import pandas as pd import glob def enable_debug_mode(debug_bool): if debug_bool == True: web_site = "http://127.0.0.1:5000" base_url = "http://127.0.0.1:5000/" else: web_site = "https://scholar.google.com" base_url = "https://scholar.goog...
#!/usr/bin/env python import storm_analysis def _test_frc(): mlist_name = storm_analysis.getData("test/data/test_drift_mlist.bin") results_name = storm_analysis.getPathOutputTest("test_drift_frc.txt") from storm_analysis.frc.frc_calc2d import frcCalc2d frcCalc2d(mlist_name, results_name, False) ...
# coding: utf-8 import os import time from pathlib import Path import numpy as np import pandas as pd import pmutt.constants from SALib.analyze import sobol from SALib.sample import saltelli from pmutt import pmutt_list_to_dict from pmutt.empirical.nasa import Nasa from pmutt.empirical.references import Reference, Ref...
from typing import List import minecraft_launcher_lib import requests import pytest import shutil import os def check_argument(command: List[str], argument: str, value: str) -> bool: # Checks if a argument has the given value try: index = command.index(argument) except: return False tr...
import pytest import numpy as np import pandas as pd from samplics.categorical.comparison import Ttest auto = pd.read_csv("./tests/categorical/auto2.csv") y = auto["mpg"] make = auto["make"] foreign = auto["foreign"] y1 = auto["y1"] y2 = auto["y2"] one_sample_known_mean = Ttest(samp_type="one-sample") @pytest....
"""Create table with the number of genes per chromosome for different gene subsets. rows: major chromosomes cols: gene sets (FlyBase r6.26, Expressed, Widely Expressed, Tau, TSPS) values: number of genes """ # %% import pandas as pd import joblib from larval_gonad.config import read_config # %% # File Names annot = ...
"""Creates the X""" def up(conn, cursor): cursor.execute( ''' ALTER TABLE endpoints DROP CONSTRAINT endpoints_path_key ''' ) print(cursor.query.decode('utf-8')) cursor.execute( ''' ALTER TABLE endpoints ADD COLUMN verb TEX...
# SPDX-FileCopyrightText: 2020 Robert Cohn # # SPDX-License-Identifier: MIT from os.path import join import pandas as pd import pytest @pytest.fixture def signal_events_df(data_dir): return pd.read_csv(join(data_dir, 'signal-events.csv'))
# Generated by Django 2.2.2 on 2019-06-08 02:34 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('zoo_checks', '0009_auto_20190607_1744_squashed_0011_auto_20190607_1849'), ] operations = [ migrations.RenameField( model_name='g...
# coding: utf-8 """ App Center Client Microsoft Visual Studio App Center API # noqa: E501 OpenAPI spec version: preview Contact: benedetto.abbenanti@gmail.com Project Repository: https://github.com/b3nab/appcenter-sdks """ import pprint import re # noqa: F401 import six class AppUserPermiss...
"""This script generates all the wordclouds involving keyword plus for IAB 2021 report""" # importing all necessary modules from wordcloud import WordCloud, STOPWORDS import matplotlib.pyplot as plt import pandas as pd from PIL import Image import numpy as np import os from WOS_key_data_prep import ( year1, yea...
from argparse import ArgumentParser import os import random import numpy as np import torch import logging import time import dill import neptune import hyperdash import shutil, json import dill import pickle from sklearn.metrics import precision_recall_curve import matplotlib.pyplot as plt with open("/root/keys.json...
import random from datetime import datetime from urlparse import urlparse from django.http import HttpResponse,HttpResponseBadRequest,HttpResponseForbidden,HttpResponseGone from django.shortcuts import get_object_or_404 from django.views.decorators.http import require_GET,require_POST,require_http_methods from django....
import os, re, string, subprocess #------------------------------------------------------------------------------ def stntuple_codegen_script(source, target, env, for_signature): # print "\n>>> mod_codegen called: pwd = "+os.environ['PWD']; # print ">>> source = ",len(source),str(source[0]) # print ">>> target...
import requests import sys import yaml class Notify: @classmethod def send(self, message, path): with open(path) as file: yml = yaml.load(file, Loader=yaml.SafeLoader) url = "https://notify-api.line.me/api/notify" token = yml["token"] headers = {"Authorization" : "...
from CMS.enums import enums class Job: def __init__(self, job_data, display_language): self.display_language = display_language if job_data: self.job = job_data.get('job', '') self.percentage = job_data.get('percentage_of_students', 0) if self.display_language...
import os import shutil import unittest from datetime import datetime, date from moca.helpers import get_cpu_count from moca.pipeline import Pipeline from moca.bedoperations import fimo_to_sites from moca.helpers import read_memefile import zipfile import psycopg2 import yagmail import json import utils import sys def...
""" Code adapted from: https://github.com/mseitzer/pytorch-fid/blob/master/fid_score.py Licensed under the Apache License, Version 2.0: https://github.com/mseitzer/pytorch-fid/blob/master/LICENSE; Copyright https://github.com/mseitzer to use tensors instead of file paths Calculates the Frechet Inception Distan...
#!/usr/bin/env python # -*- coding: UTF-8 -*- # ============================================================================= # REUSE LOCAL BEHAVE, if available # ============================================================================= import os.path import sys # -------------------------------------------------...
# -*- coding: utf-8 -*- """ Created on Thu May 27 20:20:47 2021 @author: Raktim """ #Data Load for Segmentation #PATH should contain TWO folder #ONE is IMAGE folder and another one MASK folder #This same structure has to be for both train and test image #train_path ########### Image ########### Mask #...
__author__ = 'mdavid' from BaseResolver import BaseResolver from addressimo.data import IdObject from addressimo.util import LogUtil from uuid import uuid4 log = LogUtil.setup_logging() class LocalResolver(BaseResolver): obj_config = { '1234567890abcdef': { 'wallet_address': '1CpLXM15vjULK3...
"""Implementation of cell API.""" from .. import admin from .. import authz from .. import context from .. import schema class API(object): """Treadmill Cell REST api.""" def __init__(self): def _admin_cell(): """Lazily return admin object.""" return admin.Cell(context.GLOB...
import datetime import data_algebra from data_algebra.data_ops import * import data_algebra.test_util import data_algebra.BigQuery def test_bigquery_user_fns_integrated(): pd = data_algebra.default_data_model.pd datetime_format = "%Y-%m-%d %H:%M:%S" date_format = "%Y-%m-%d" d = pd.DataFrame( ...
# Code for anonymizing utorid data # Libraries import click import logging from pathlib import Path from dotenv import find_dotenv, load_dotenv import os import pandas as pd import hashlib @click.command() @click.argument('in_filepath', type=click.Path(exists=True)) @click.argument('out_filepath', type=click.Path(), ...
import time import logging from authlib.common.urls import urlparse from authlib.consts import default_user_agent from authlib.common.security import generate_token from .errors import ( MismatchingStateError, MissingRequestTokenError, MissingTokenError, ) log = logging.getLogger(__name__) class BaseApp(...
#!/usr/bin/python3 # -*- coding: utf-8 -*- import os import sys BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # 基地址是本项目根目录 sys.path.append(BASE_DIR) import datetime from yxf_yixue.wannianli import WannianliApi from yxf_yixue.wannianli._realsolar import RealSolar from yxf_yixue.wannianli._calen...
EXT_STANDARD = 1 INT_STANDARD = 2 EXT_HQ = 3 INT_HQ = 4 EXT_HOUSE = 5 INT_HOUSE = 6
from django.core.management.base import BaseCommand, CommandError from optparse import make_option from django.conf import settings from bfrs.utils import update_users import os import sys import logging logger = logging.getLogger(__name__) class Command(BaseCommand): help = 'Updates the Django DB wi...
#!/usr/bin/env python # coding=utf-8 import web import lib.user as user from lib.response import json as json from model import userModel, recordModel import config """记录查看管理页""" def getUserId(): u = user.getUser() if not u: raise web.seeother("/") else: return u['id'] def parseWay(way): ...
#!/usr/bin/env python # # Copyright (c) 2019 Opticks Team. All Rights Reserved. # # This file is part of Opticks # (see https://bitbucket.org/simoncblyth/opticks). # # 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...
from flask import url_for from pycroft.model._all import PropertyGroup from tests import FrontendWithAdminTestBase class PropertiesFrontendTestCase(FrontendWithAdminTestBase): def test_property_gets_added(self): url = url_for('properties.property_group_create') group_name = "This is my first prop...
#A demo program to demonstrate the negative indexing of the String IBM Digital Nation Courses string = "Alphabet" last_char = string[-1] last_char= last_char.capitalize() print(last_char) #end of the program
# -*- coding: utf-8 -*- ''' The module is used for upload pdf file! ''' import logging import json import datetime import azure.functions as func from ..share_code import fileSystem def main(req: func.HttpRequest) -> str: ''' Upload a pdf file! ''' #json str need to be upload! if r...
from rdkit import RDConfig import unittest from rdkit import Chem from rdkit.Chem import Draw, AllChem from rdkit.Chem.Draw import rdMolDraw2D class TestCase(unittest.TestCase): def setUp(self): pass def test1(self): m = Chem.MolFromSmiles('c1ccc(C)c(C)c1C') AllChem.Compute2DCoords(m) d = Draw.M...
def get_target_journals(): """Find the ISSN of the Journals that appear at Journal Citation Reports (JCR) 2014 under both categories: Engineering Biomedical and radiology""" # Import url request try: # Try importing for Python 3 # pylint: disable-msg=F0401 # pylint: disable-msg=E...
import re import sys sys.path.append("../../../..") from text import * from audioExtractor import * import importlib import os import pdb #---------------------------------------------------------------------------------------------------- pd.set_option('display.width', 1000) #------------------------------------------...
import magma as m # Loads LB = m.BitPattern("b?????????????????000?????0000011") LH = m.BitPattern("b?????????????????001?????0000011") LW = m.BitPattern("b?????????????????010?????0000011") LBU = m.BitPattern("b?????????????????100?????0000011") LHU = m.BitPattern("b?????????????????101?????0000011") # Stores SB = ...
from mongoengine import * from mongoengine import signals from models.user import User from controllers.main import MainController def animals(): return ('pig', 'cow', 'sheep') def init_db(): connect('_test_sj_farm') print("init db complate") def main(): init_db() MainController() if __name__ ==...
import logging from pprint import pformat # noqa from authlib.jose import JsonWebToken, JsonWebKey from authlib.integrations.flask_client import OAuth from authlib.jose.errors import DecodeError from aleph import settings oauth = OAuth() log = logging.getLogger(__name__) def configure_oauth(app, cache): if set...
import sys import socket import requests import json import hashlib import os
import tensorflow as tf from libs.models.yolos import yolo_v3, yolo_v3_tiny from configs import cfg __all__ = ['get_yolo'] def get_yolo(ckpt_path=None, training=False, cfg=cfg): if cfg.model_name == 'yolo_v3': model = yolo_v3 elif cfg.model_name == 'yolo_v3_tiny': model = yolo_v3_tiny el...
#!/usr/bin/env python # Copyright 2019 Tetrate # # 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 agr...
"""The module for the Nampi data entry form parser. Classes: Nampi_data_entry_form """ import logging from typing import List, Optional import pandas from pandas import Series from rdflib.term import URIRef from modules.appellation import Appellation, Appellation_type from modules.appellation_assignment import A...
## example Flow code ## this will only work off the deploy-2.0 branch of Prefect import prefect from prefect import task, Flow @task(name="Welcome", slug="welcome-task") def welcome_logger(): logger = prefect.context["logger"] with open("/ascii-welcome.txt", "r") as f: lines = "\n\n" + "".join(f.rea...
import tempfile import typing from dataclasses import dataclass from typing import Type import dolt_integrations.core as dolt_int import doltcli as dolt import pandas from dataclasses_json import dataclass_json from google.protobuf.json_format import MessageToDict from google.protobuf.struct_pb2 import Struct from fl...
#! /usr/bin/env python from .. import SimulatorRuntime def test_simulator_runtime_none_persistent(): from tolteca.simu import example_configs as cfgs cfg = cfgs['toltec_point_source'] rc = SimulatorRuntime(config=cfg) assert rc.config['simu']['jobkey'] == cfg['simu']['jobkey'] # check update ...
# HARDWARE PROCESS
# diagnostics.py # # Anders Poirel # # 05-19-2019 import matplotlib.pyplot as plt def plot_loss(history): plt.plot(history.history['loss']) plt.plot(history.history['val_loss']) plt.title('Model loss') plt.ylabel('Loss') plt.xlabel('Epoch') plt.legend(['Train', 'Test'], loc='upper right') ...
from abc import ABC, abstractmethod, ABCMeta from domain.models.container_settings import ContainerSettings from domain.models.container_info import ContainerInfo class AbstractJobManagementService(ABC): __metaclass__ = ABCMeta @abstractmethod def start_container(self, container_settings: ContainerSetting...
from flaskrestgen.generator import RESTApi
import unittest from unittest.mock import patch from znail.ui import app class TestHealthCheck(unittest.TestCase): def setUp(self): perform_health_check_patcher = patch("znail.ui.api.healthcheck.perform_health_checks") self.perform_health_check = perform_health_check_patcher.start() self....
#!/usr/bin/env python3 # an indicator so to know that the following messages may be related to # git-notif. from sys import stderr print("[ + ] Git-Notif", file = stderr) import atexit import git import json import os from http import HTTPStatus from http.client import HTTPSConnection, HTTPS_PORT from sys import ex...
#-*- coding: utf-8 -*- """OAuth 2.0 Django Models""" import time from hashlib import sha512 from uuid import uuid4 from django.db import models from django.conf import settings from .consts import CLIENT_MODEL from .consts import CLIENT_KEY_LENGTH, CLIENT_SECRET_LENGTH from .consts import ACCESS_TOKEN_LENGTH, REFRE...
import json import os from azure.media.videoanalyzeredge import * from azure.iot.hub import IoTHubRegistryManager #run pip install azure-iot-hub to get this package from azure.iot.hub.models import CloudToDeviceMethod, CloudToDeviceMethodResult from datetime import time device_id = os.getenv("iothub_deviceid"); modu...
# coding=utf-8 """Contact creation, failure cases.""" from functools import partial from pytest_bdd import ( given, scenario, then, when, ) from pbraiders.contact import ContactFakerFactory # pylint: disable=import-error from pbraiders.pages.contacts.actions import ContactCreateAction # pylint: disab...
# -*- coding: utf-8 -*- import argparse import logging import os from pymlsql.aliyun.dev.instance_context import ECSInstanceContext logging.basicConfig(level=logging.INFO) logger = logging.getLogger("build_mysql_server") parser = argparse.ArgumentParser(description='run shell in new ECS instance.') parser.add_argume...
import re import sys # h - headers of displaying column h = ['id', 'name', 'type', 'location', 'address', 'status', 'food', 'zip'] # p - position of columns that we are interested p = [0, 1, 2, 4, 5, 10, 11, 28] # w - width of displaying of the columns w = [8, 32 , 10, 48, 16, 10, 48, 5 ] # in memory db dataRecord...
from pyemitter import Emitter from threading import Thread import logging log = logging.getLogger(__name__) class Source(Emitter): name = None def __init__(self): self.thread = Thread(target=self._run_wrapper) def start(self): self.thread.start() def run(self): pass de...
import sys phonetic_features = ['sound_type', 'manner', 'place', 'voice', 'secondary', 'length', 'vertical', 'horizontal', 'rounding', 'nasalization'] def list2dict(feat_list): """ Transforms a list into a dictionary that maps the list elements to their indices w...
""" http://pythontutor.ru/lessons/lists/problems/swap_neighbours/ Переставьте соседние элементы списка (A[0] c A[1], A[2] c A[3] и т. д.). Если элементов нечетное число, то последний элемент остается на своем месте. """ lst = input().split() for i in range(0, len(lst) - 1, 2): lst[i], lst[i + 1] = lst[i + 1], lst...
# -*- encoding: utf-8 -*- """ Copyright (c) 2019 - present AppSeed.us """ from django.contrib import admin from django.urls import path, include # add this from django.conf import settings from django.conf.urls.static import static from django.contrib.auth import views as auth_views from django.conf.urls import url, ...
# Copyright 2016 - Nokia # # 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, sof...
import pytest from MAQTextSDK.BatchSetup import BatchSetup def test_unit_init(): with pytest.raises(TypeError): inputTransform = BatchSetup('test string') inputTransform.makeBody() def test_unit_makeBody(input_text): inputTransform = BatchSetup(input_text) actual = inputTransform.makeBody...
# %% Imports import pandas as pd import re def flatten_columns(df): df.columns = ["_".join(df) for df in df.columns.ravel()] df.columns = [re.sub(r"_$", "", col) for col in df.columns] return df def rename_cols_3m(df): df.columns = [f"{col}_3m" if col not in INDEX else col for col in df.columns] ...
import argparse import numpy as np import tensorflow as tf import socket import importlib import os import sys from tqdm import tqdm from timeit import default_timer as timer import utils.tfrecord_utils as tfrecord_utils from tensorflow.python.client import timeline def log_string(out_str): #LOG_FOUT.write(out_st...
class Locations: def __init__(self, connection): self.connection = connection def create(self): # Types self.connection.execute_query(create_city_location) # Cities self.connection.execute_query(create_anchorhead) # Types create_city_location = """ INSERT ...
import copy import sys, time, argparse, os, subprocess, shutil import math, numbers, random, bisect from random import Random from skimage import io, transform from os import listdir from os.path import join from glob import glob import numpy as np import torch import torch.utils.data as data class imageDataset()...
# Generated by Django 3.1.1 on 2020-09-26 23:45 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('character', '0004_auto_20200926_1843'), ] operations = [ migrations.RenameField( model_name='character', old_name='item', ...
from types import MethodType from typing import ( Any, Callable, Iterable, Mapping, Optional, Text, Type, TypeVar, Union, ) from wired import ServiceContainer, ServiceRegistry from zope.interface import Interface __version__ = "0.1.dev0" T = TypeVar("T") class AutowireError(Exce...
""" This script is just a proof of concept for payload generation, supplementing ZAP's native generation mechanism(s). It generates payload1 for field1 and calculates the payload (payload2 = sha1(base64(payload1))) for field2, something like Battering Ram without the hassle of generating the payload2 wordlist first "...
# Generated by Django 3.2.8 on 2021-11-25 21:28 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('empresas', '0001_initial'), ] operations = [ migrations.CreateModel( name='...
""" File: analyze_flake8.py Date: 4.14.2020 Author: Kyle Lanier Purpose: This file is an abstraction from the .github workflows cicd.yml and its purpose is to analyze flake8 linting errors locally in the repository. The cicd.yml is used in the github docker runtime and cannot be executed locally, hence this p...
import requests def get_weather(city: str, api_key: str) -> dict[str, str] | None: try: r = requests.get( f"https://api.openweathermap.org/data/2.5/weather?q={city}&units=metric&appid={api_key}", headers={"User-agent": "Mozilla/5.0"}, ) data = r.json() temp =...
#! /usr/bin/env python # Copyright (c) 2015-2020 Avere Systems, Inc. All Rights Reserved. # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See LICENSE in the project root for license information. from future.moves.urllib import parse as urlparse from future.utils import vie...
# -*- coding: utf-8 -*- # # Copyright (c) 2019, Martin Chatterjee. All rights reserved. # ----------------------------------------------------------------------------- import unittest import os import vfxtest # ----------------------------------------------------------------------------- class TestCaseTestCase(unitt...
# All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in...
import pandas as pd import argparse import json import math import os import random import re import sys import urllib3 from datetime import datetime, timedelta from typing import Union from urllib3.exceptions import ReadTimeoutError from models.Trading import TechnicalAnalysis from models.exchange.binance import AuthA...
# Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. """ Constants """ COOKIECUTTER_URL = "https://github.com/goanpeca/jupyterlab-language-pack-cookiecutter" EXTENSIONS_FOLDER = "extensions" JUPYTERLAB = "jupyterlab" LANG_PACKS_FOLDER = "language-packs" LC_MESSAGES = "LC...
# Cooccurrence matrix construction tools # for fitting the GloVe model. import numpy as np try: # Python 2 compat import cPickle as pickle except ImportError: import pickle from .corpus_cython import construct_cooccurrence_matrix class Corpus(object): """ Class for constructing a cooccurrence mat...
# Generated by Django 2.1.1 on 2018-10-27 18:27 import django.core.validators from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Book', ...
from tests.mock import Mock from hellbox import Hellbox, Chute from hellbox.task import Task USAGE = """\ │ » build │ Does the building ╽ ┣━ Bar(level=2, grade=3) ┃ ┗━ Foo ┗━ Foo ┗━ Bar(level=2) │ » package │ Does the packaging │ Zips and tars ╽ ┗━ Foo """ Noop = Chute.create(lambda x: x) class Foo(Ch...
# Copyright 2016 A Family For Every Child # # 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 agr...
import os import pytest import ray import yaml import time from pytest_mock import MockerFixture from malib.agent.agent_interface import AgentFeedback from malib.utils import logger from malib.utils.typing import SimulationDescription, TaskRequest, TaskType from malib.backend.coordinator.task import CoordinatorServer...
# -*- coding: utf-8 -*- from __future__ import (absolute_import, print_function, unicode_literals) from external.six import iteritems from colorclass import (Color, Windows) from acli.output import (output_ascii_table, ou...
# Copyright 2016 The Fuchsia Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import os.path import platform FUCHSIA_DIR = os.environ["FUCHSIA_DIR"] ZIRCON_ROOT = os.path.join(FUCHSIA_DIR, "zircon") FUCHSIA_BUILD_DIR = os.environ["FUC...
from django.contrib.auth import get_user_model from django.test import TestCase from django.urls import reverse from rest_framework import status from rest_framework.test import APIClient CREATE_USER_URL = reverse('user:create') CREATE_API_TOKEN = reverse('user:token') MANAGE_USER_URL = reverse('user:manage') VALID...
# -*- coding: utf-8 -*- # Copyright (c) 2017-18 Richard Hull and contributors # See LICENSE.rst for details. """ Encapsulates sending commands and data over a serial interface, whether that is I²C, SPI or bit-banging GPIO. """ import errno import time import luma.core.error from luma.core import lib __all__ = ["i2c...
#installing tensorflow 2.3.1 !pip install tensorflow==2.3.1 import tensorflow as tf print(tf.__version__) # installing tensorflow and torchaudio import tensorflow as tf !pip install soundfile #to save wav files !pip install --no-deps torchaudio==0.5 !pip install git+https://githu...
from django.test import TestCase from lithium.forum.models import Forum, Thread, Post class ForumTest(TestCase): fixtures = ['forum.json'] def testDelete(self): forum = Forum.objects.get(pk=3) forum.delete() self.failUnlessEqual(Forum.objects.all().__str__(), '[<Forum: 1>, <Forum: ...
import sys def eprint(*args, **kwargs): """Print to stderr.""" print(*args, file=sys.stderr, **kwargs) def bail(error: str): """Print message to stderr and exit with an error code.""" eprint(error) sys.exit(1)
import json orm = wiz.model("dizest/orm").use() config = wiz.model("dizest/config") def update(wiz): dbupdate = wiz.request.query("db", False) data = wiz.request.query("data", True) data = json.loads(data) if dbupdate == 'false': prev = config.load() data['db'] = prev.db config.upd...
import click import numpy as np from tqdm import tqdm from shutil import copyfile from pathlib import Path from collections import Counter from sklearn.utils import check_random_state def random_oversampling(src_dir, n_folds=5, random_state=42): """ Perform's random oversampling ...
# -*- coding: utf-8 -*- """ Tests for :func:`safe.util.expand_path`. :author: Joe Joyce <joe@decafjoe.com> :copyright: Copyright (c) Joe Joyce and contributors, 2016-2019. :license: BSD """ import os import pwd from safe.util import expand_path HOME = pwd.getpwuid(os.getuid()).pw_dir def test_absolute(): """C...
""" pxutil ~~~~~ Peter Jiping Xie's personal utils. :copyright: © 2019 by Peter Jiping Xie. :license: MIT. """ # Control the version directly in setup.py # __version__ = '0.0.1' # import func/classes from .pxutil here so users can them directly, i.e. pxutil.bash() instead of pxutl.pxutil.bash(). from .pxutil import...
from src.dataset.distillation_dataset import DistillationDataset from src.dataset.entailment_dataset import EntailmentDataset from src.utils.metrics import EmbeddingSimilarityMeter from src.dataset.sts_dataset import StsDataset from src.modules.pooling import SentenceEncodingCombineStrategy from src.models.losses impor...
import os,sys import numpy as np import random import re import time import _pickle as pickle import csv import cv2 import torch random.seed(0) from torchvision.transforms import functional as F from torchvision.ops import roi_align, nms from scipy.optimize import linear_sum_assignment # add relevant packages and di...
## import skeleton process from PhysicsTools.PatAlgos.patTemplate_cfg import * # verbose flags for the PF2PAT modules #process.Tracer = cms.Service("Tracer") runOnMC = True if runOnMC: from PhysicsTools.PatAlgos.patInputFiles_cff import filesRelValProdTTbarAODSIM process.source.fileNames = filesRelValProdTTb...