content
stringlengths
5
1.05M
""" unit test module for testing ridge regression use synthetic data to test """ import unittest from sklearn.datasets import make_classification import biome class Test_ridge(unittest.TestCase): """ unit test for knn_regression module, this class is inhered child class of unittest. unittest.TestCase i...
class Letter(str): """Letter primitive, used to represent drive letters.""" def __new__(cls, s='A'): return str.__new__(cls, s) class String(str): """Strings, used to represent filenames and file contents.""" pass def serialize(typ, val): """Serialization function.""" # Serializati...
# Copyright Amazon Web Services and its Affiliates. 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...
from __future__ import division import os,time,cv2 import tensorflow as tf import tensorflow.contrib.slim as slim import numpy as np def lrelu(x): return tf.maximum(x*0.2,x) def identity_initializer(): def _initializer(shape, dtype=tf.float32, partition_info=None): array = np.zeros(shape, dtype=float)...
# Copyright (c) 2020-2021, NVIDIA CORPORATION. # # 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 agre...
""" Exception Payloads -> Exceptions can carry payload data. -> Most exceptions accept a single string in their constructor call. -> The most common exception you'll likely raise is ValueError. -> Most exception payloads are strings containing a helpful message. """
from flask import Flask #API Keys are taken from OS environment! app = Flask(__name__) import dont_binge.views
import json import os import random from langcodes import Language from .has_logger import HasLogger from .nlu_data_entry import NLUDataEntry # Other imports only for the type hints from typing import Optional, List from .types import DataSetTitle class NLUDataSet(HasLogger): def __init__( self, ...
# !/usr/bin/env python3 # pylint: skip-file """ Execute unit tests for the Question object. Making sure that it parses correctly """ from quizmake import parser CREATION_CASES = "tests/test_data/questions/unit_test_questions" VALID_QUESTIONS = "tests/test_data/questions/valid_questions" cases = [ # fmt: off ...
# Crie um pequeno sistema modularizado que permite cadastrar pessoas pelo # seu nome e idade em um arquivo de texto simples. O sistema só vai ter 2 # opções: cadastrar uma nova pessoa e listar todas as pessoas cadastradas. from Exercicios.Exercicio116.lib.Interface import * from Exercicios.Exercicio116.lib.Arquivo impo...
# Generated by Django 2.2.9 on 2020-02-06 12:53 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('references', '0038_delete_location'), ] operations = [ migrations.CreateModel( name='CityCountyStateCode', fields=[ ...
from gensim import models import numpy as np class EmbeddingFeaturizer(object): def __init__(self, glove=False, w2v=False, emoji=False): if glove: self.glove_model = self.load_glove_embeddings() if w2v: self.w2v_model = self.load_w2v_embeddings() if emoji: ...
# coding:utf-8 from flask_sqlalchemy import SQLAlchemy, Model class UnlockedReadAlchemy(SQLAlchemy): def apply_driver_hacks(self, app, info, options): if "isolation_level" not in options: options["isolation_level"] = "READ UNCOMMITTED" return super(UnlockedReadAlchemy, self).apply_driv...
import cv2 img = '~.png' src = cv2.imread(img, cv2.IMREAD_COLOR) dst = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY) cv2.imwrite('gray_'+img, dst)
from __future__ import absolute_import, unicode_literals, division __all__ = ('DEFAULT_DELETE_TIMEOUT_SECONDS', 'DEFAULT_EXPIRATION_SECONDS', 'DEFAULT_PING_SECONDS', 'DEFAULT_SHARE_ADMIN_JQUERY') DEFAULT_DELETE_TIMEOUT_SECONDS = 0 DEFAULT_EXPIRATION_SECONDS = 180 DEFAULT_PING_SECONDS = 15 DEFAULT_SHARE_ADM...
import cv2 #cap = cv2.VideoCapture('build/Debug/tmp1.bmp') frame = cv2.imread('build/Debug/tmp1.bmp') roi = cv2.selectROI("Frame", frame, fromCenter=False, showCrosshair=True) print(roi) print('done')
from hyquest.verifiers.common import getTaskResultSet, getUserAction from hyquest.constants import TASK_TIMEMAP # This handles matching up TimeMap state to associated TimeMap Tasks def matchingTimeMapTasks(user, timeMapState): tasks = getTaskResultSet(user).filter(type=TASK_TIMEMAP) activeTasks = [] other...
#!/usr/bin/env python3 # ---------------------------------------------------------------------------- # Copyright 2019 Drunella # # 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:/...
import unittest import torch import numpy as np from nose.plugins.attrib import attr from embryovision.tvmaskrcnn.objectsegmentation import ObjectSegmentationModel @attr('slow') class TestOutputObjectSegmentation(unittest.TestCase): @classmethod def setUpClass(cls): # Create model cls.base_m...
#! /usr/bin/env python # Author: David Goodger # Contact: goodger@users.sourceforge.net # Revision: $Revision: 4213 $ # Date: $Date: 2005-12-14 15:51:59 +0100 (Wed, 14 Dec 2005) $ # Copyright: This module has been placed in the public domain. """ Tests for misc.py "raw" directive. """ import os.path import sys from ...
import urlparse from base import BaseHandler from logic import url_factory import tornado.web class WebfingerHandler(BaseHandler): def get(self): acct = self.get_argument("q").split('acct:') # remove acct: if it's there if len(acct) > 1: acct[0] = acct[1] if acct[0].find('@') != -1: a...
#!/usr/bin/env python3 # coding=utf-8 """A utility to get the next available combination number. The output of the utility is the next combination number, i.e. '2'. To use this utility you will need to ensure that your AWS credentials are available via expected environment variables. Please refer to the AWS boto3 doc...
# -*- coding: utf-8 -*- from django.conf.urls import url, include from . import views from django.views.generic import TemplateView, ListView, View class IndexView(TemplateView): template_name = 'blog/base.html' urlpatterns = [ url(r'^home/$', IndexView.as_view(template_name='blog/base.html'), name="home"), ...
# -*- coding: utf-8 -*- from __future__ import print_function import operator def regex_or(*items): return '(?:' + '|'.join(items) + ')' # This file contains mapping functions # this function takes as arguemnt a token and # and determines whather the argument is # and sad or happhy emoticons by analyzing the # ...
#!/usr/bin/env python import os import shutil from utilities.file_and_folder_operations import subfiles def rearrange_dir(root_dir): image_dir = os.path.join(root_dir, 'images') label_dir = os.path.join(root_dir, 'labels') if not os.path.exists(image_dir): os.makedirs(image_dir) print(...
"""This module has utility functions for parsing text from HTML. It helps extract the title, description (e.g., what shows up on Google), paragraphs, and images. A URL and the HTML of its associated webpage can be collected using expand_with_content(). """ __all__ = [ "search_webpage_title", "search_webpage_des...
# Copyright (C) 2020 Arm Limited or its affiliates. All rights reserved. # # SPDX-License-Identifier: Apache-2.0 # # 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 # # www.apache.org/licenses/LICE...
#!/usr/bin/env python3 """An example that prints all Crownstone IDs seen on the mesh.""" import time, json from crownstone_uart import CrownstoneUart, UartEventBus, UartTopics uart = CrownstoneUart() # Start up the USB bridge. uart.initialize_usb_sync() def showNewData(data): print("New data received!") print(d...
# + import torch from torch.nn import Module from torch.distributions import MultivariateNormal, LowRankMultivariateNormal from theforce.regression.kernel import White from theforce.regression.algebra import jitcholesky, projected_process_auxiliary_matrices_D from theforce.regression.scores import coeff_of_determinatio...
import os import datetime as dt from collections import defaultdict import numpy as np import pandas as pd import praw from psaw import PushshiftAPI class RedditCBBScrape: def __init__(self, client_id, client_secret, user_agent): self.reddit = praw.Reddit(client_id=client_id, client_secret=client_secr...
import mysql.connector from os import getenv as env import urllib.parse as urlparse import logging from utils import setup_logging logger = logging.getLogger() OPENCAST_DB_URL = env("OPENCAST_DB_URL") OPENCAST_RUNNING_JOB_STATUS = 2 def parse_db_url(): db_url = urlparse.urlparse(OPENCAST_DB_URL) return { ...
import twitterscraper.entrypoint twitterscraper.entrypoint.main()
# -*- coding:utf-8 -*- # 图像旋转处理 import cv2 as cv import numpy as np img = cv.imread('F:/OpenCV/python/CoreOperations/demo2.jpg', 0) rows, cols = img.shape pts1 = np.float32([[50,50], [200, 50], [50, 200]]) pts2 = np.float32([[10,100], [200, 50], [100, 250]]) M = np.float32([[1, 0, 100], [0, 1, 50]]) M2 =cv.getRotati...
""" Composition is an object oriented design concept that models a has a relationship. In composition, a class known as composite contains an object of another class known to as component. In other words, a composite class has a component of another class. """
from flask import Blueprint from naijasaver.blueprints.user.models import User user = Blueprint('user', __name__) @user.route('/') def home(): return {"message" : 'Naijasaver saves you cash'} @user.route('/login') def login(): return {"message" : 'login details'}
import sys sys.path.append('../') import copy import numpy as np import pandas as pd from datetime import timedelta, date import fit_and_predict import warnings import load_data warnings.filterwarnings("ignore") from models import exponential_modeling from pmdl_weight import pmdl_weight from tqdm import tqdm very...
import os import requests import time import base64 from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import serialization, hashes from cryptography.hazmat.primitives.asymmetric import padding, rsa class AuthenticatedClient: def __init__(self, token): self.co...
def remedy_scale_ambari_bootstrap(vdf_url=None): script="sed -i 's/hostname=localhost/hostname=master1.packone/g' /etc/ambari-agent/conf/ambari-agent.ini\n\n" \ "ambari-agent start 2>&1\n\n" \ 'if [ `hostname` == "master1.packone" ]; then\n' \ 'yum -q -y install epel-release 2>&1\n' \ ...
from hashlib import sha1 def hash_password(password: str) -> str: """ Retorna o hash da senha em sha1, em formato hexadecimal. """ return sha1(password.encode("UTF-8")).hexdigest()
DATE_FORMAT = 'MMM D, YYYY' TIME_FORMAT = 'h:mm a' REMINDER_SUCCESS = """🤖 Sure {remind_first_name}, I will be messaging you on *{when}* ({when_humanized}) to remind you. _Do NOT delete the original message._ """ REMINDER_NO_FUTURE_DATE = '❌ You must specify a date in the future.' REMINDER_INVALID_DATE = '❌ You mu...
# -*- coding: utf-8 -*- ''' #------------------------------------------------------------------------------- # NATIONAL UNIVERSITY OF SINGAPORE - NUS # SINGAPORE INSTITUTE FOR NEUROTECHNOLOGY - SINAPSE # Singapore # URL: http://www.sinapseinstitute.org #------------------------------------------------------------------...
#----------------------------------------------------------------------------- # Copyright (c) 2012 - 2017, Anaconda, Inc. All rights reserved. # # Powered by the Bokeh Development Team. # # The full license is in the file LICENSE.txt, distributed with this software. #---------------------------------------------------...
import logging import sdk_cmd LOG = logging.getLogger(__name__) def add_acls(user: str, task: str, topic: str, zookeeper_endpoint: str, env_str=None): """ Add Porducer and Consumer ACLs for the specifed user and topic """ _add_role_acls("producer", user, task, topic, zookeeper_endpoint, env_str) ...
import pygame, os import engine, scene, soundmanager, level, universal from config import * pygame.init() os.environ['SDL_VIDEO_WINDOW_POS'] = f"{0},{0}" display = pygame.display.set_mode((SCREEN_W, SCREEN_H)) universal.sound_manager = soundmanager.SoundManager() universal.level_manager = level.PermLevel() universal...
/home/runner/.cache/pip/pool/ab/75/d9/5b603d464cb50615106cd1c5eb584cd445d0e7b740ef0c4f9e548ec77b
import logging import time from contextlib import contextmanager @contextmanager def timer_decorator(prefix=''): start = time.time() try: yield '' except Exception as e: logging.warn( "NOT swallowing exception: %s", str(e) ) raise finally: delta = time.time() - start ...
import serial """ sample uart communication """ # Serial takes two parameters: serial device and baudrate ser = serial.Serial('/dev/ttyACM0', 9600) counter = 0 # data = ser.read(ser.inWaiting()) data_ = "f" licz = False while (1): data = ser.read(1) # data = ser.read(ser.inWaiting()) # print(data.encode('he...
from typing import Optional, List import offchain import pytest from flask import Response from offchain import Status, AddressObject from wallet.services.offchain import p2p_payment as pc_service from werkzeug.test import Client CURRENCY = "XUS" ADDRESS = "tdm1pzmhcxpnyns7m035ctdqmexxad8ptgazxhllvyscesqdgp" ADDRESS_...
# one tight loop and multiple schedulers import threading import time class Timer(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.fineInterval = 0.0001 self.courseInterval = 0.001 self.timers = [] def register(self,ref,ms): self.timers.append([ref,ms,time.time()]) ...
# -*- coding: utf-8 -*- import torch from ..aggregators_base import AggregatorBase from ...registry import AGGREGATORS from typing import Dict @AGGREGATORS.register class Crow(AggregatorBase): """ Cross-dimensional Weighting for Aggregated Deep Convolutional Features. c.f. https://arxiv.org/pdf/1512.040...
def get_first_value(number_list): return number_list[0] get_first_value([1, 2, 3]) #1 get_first_value([80, 5, 100]) #80 get_first_value([-500, 0, 50]) #-500
from .exceptions import * import random # Complete with your own, just for fun :) LIST_OF_WORDS = ["rmotr","python","code"] def _get_random_word(list_of_words): if list_of_words: return random.choice(list_of_words) raise InvalidListOfWordsException () def _mask_word(word): if word: ...
name, age = "Shelby De Oliveira", 29 username = "shelb-doc" print ('Hello!') print("Name: {}\nAge: {}\nUsername: {}".format(name, age, username))
from .cli import cli from .serial_entry import serial_pipeline from .serial_entry_onpolicy import serial_pipeline_onpolicy from .serial_entry_offline import serial_pipeline_offline from .serial_entry_il import serial_pipeline_il from .serial_entry_reward_model_ngu import serial_pipeline_reward_model_ngu from .serial_en...
import mock import pytest from api.base.settings.defaults import API_BASE from api_tests.requests.mixins import NodeRequestTestMixin @pytest.mark.django_db class TestNodeRequestListCreate(NodeRequestTestMixin): @pytest.fixture() def url(self, project): return '/{}nodes/{}/requests/'.format(API_BASE, p...
x1 = int(input()) y1 = int(input()) x2 = int(input()) y2 = int(input()) if y2 - y1 == 1: if x2 - x1 == 1: print('YES') elif x2 - x1 == -1: print('YES') else: print('NO') else: print('NO')
import time import os import subprocess import csv import uuid from collections import OrderedDict from Bio import SeqIO from Bio.Seq import Seq from Bio.SeqRecord import SeqRecord from string import Template from pyparsing import Literal, SkipTo import pandas as pd from KBaseReport.KBaseReportClient import KBaseRepor...
'''This module provides the object representation of a CurrencyCloud Payment''' from currencycloud.resources.resource import Resource from currencycloud.resources.actions import DeleteMixin, UpdateMixin class Payment(DeleteMixin, UpdateMixin, Resource): '''This class represents a CurrencyCloud Payment''' pas...
import argparse import os import pdb import numpy as np import subprocess import ffmpeg import time def main(video_dir): print('MAIN') t1 = time.time() videos = os.listdir(video_dir) videos = [v for v in videos if v.endswith('.mp4')] for videoname in videos: video_file = os.path.join(video...
"""Test methods in `qibo/core/hamiltonians.py`.""" import pytest import numpy as np from qibo import hamiltonians, K from qibo.tests.utils import random_complex def test_hamiltonian_init(): with pytest.raises(TypeError): H = hamiltonians.Hamiltonian(2, "test") H1 = hamiltonians.Hamiltonian(2, np.eye(4...
nome = str(input('qual o seu nome completo? ')).strip() x = nome.upper() print(f'seu nome tem silva? {"SILVA" in x}')
# !/usr/bin/env python # -------------------------------------------------------------- # File: tracer.py # Project: PyEvoAlg # Created: Sunday, 8th December 2019 12:25:31 pm # @Author: Molin Liu, MSc in Data Science # Contact: molin@live.cn # Last Modified: Sunday, 8th December 2019 12...
"""Leetcode 269. Alien Dictionary (Premium) Hard URL: https://leetcode.com/problems/alien-dictionary There is a new alien language which uses the latin alphabet. However, the order among letters are unknown to you. You receive a list of non-empty words from the dictionary, where words are sorted lexicographically by ...
import logging from azure.mgmt.web.models import (Site, SiteConfig, NameValuePair) from c7n_azure.session import Session from c7n_azure.constants import CONST_DOCKER_VERSION, CONST_FUNCTIONS_EXT_VERSION from c7n.utils import local_session class FunctionAppUtilities(object): def __init__(self): self.loca...
#!/usr/bin/env python3 # (C) Copyright 2020 ECMWF. # # This software is licensed under the terms of the Apache Licence Version 2.0 # which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. # In applying this licence, ECMWF does not waive the privileges and immunities # granted to it by virtue of its statu...
from psycopg2 import connect import subprocess from dotenv import load_dotenv import boto3 import json from utils.query import s3, con, cursor, pd_query from config.config import S3_BUCKET, S3_WEIGHTS_FOLDER, WEIGHTS_PATH,\ AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, S3_STDOUT_FOLDER from train_command import setup_p...
# -*- coding: utf-8 -*- from __future__ import unicode_literals, absolute_import import json as _json from . import fernet_encode, fernet_decode, force_text MIMETYPE = 'application/x-fernet-json' register_args = ( fernet_encode(_json.dumps), fernet_decode(force_text(_json.loads)), MIMETYPE, 'utf-8',...
# (OOP approach w/ inheritance) import pandas class CustomFrame(pandas.DataFrame): """ Param: my_df (pandas.DataFrame) containing a column called "abbrev" """ def add_state_names(self): """ Adds corresponding state names to a dataframe. """ # type(new_df["abbrev"...
#!/usr/bin/env python3 import re import requests import selenium from devtools.proxy import CHROME_WRAPPER_PATH from selenium.webdriver.common.by import By from selenium.webdriver.common.desired_capabilities import DesiredCapabilities from selenium.webdriver.support import expected_conditions from selenium.webdriver....
import unittest, tempfile from doorman.doorman import DoormanConfig, DoormanException """ Test the parseYAML function in the Doorman class """ class DoormanConfigTest(unittest.TestCase): """ Setup the temporary files """ def setUp(self): self.yml = tempfile.NamedTemporaryFile() self.tx...
# !/usr/local/python/bin/python # -*- coding: utf-8 -*- # (C) Wu Dong, 2020 # All rights reserved # @Author: 'Wu Dong <wudong@eastwu.cn>' # @Time: '2020-05-12 10:03' from flask import Flask from pre_request import pre, Rule app = Flask(__name__) app.config["TESTING"] = True client = app.test_client() multi_params =...
import os from transform import app if __name__ == '__main__': port = int(os.getenv("PORT")) app.run(debug=True, host='0.0.0.0', port=port)
# A colormap can be a list of dicts # or a matplotlib colormap. Either case # the returned object will be a list of dicts. def rgba2hex(rgba): """Convert rgba values to hex.""" # Slice the tuple so that # we don't get alpha and # convert values to 8 bit ints rgb = tuple([min(max(int(255 * i), 0), ...
"""module with git command implementations of the basic interfaces :note: we could add all implementations of the basic interfaces, its more efficient though to obtain them from the pure implementation""" from git.exc import ( GitCommandError, BadObject ) from git.base import ( OInfo, ...
from rest_framework import serializers from teleband.submissions.models import Grade, Submission, SubmissionAttachment from teleband.assignments.api.serializers import AssignmentSerializer class SubmissionSerializer(serializers.ModelSerializer): class Meta: model = Submission fields = ["id", "sub...
import hashlib from redis import Redis from redisgraph import Node as RedisNode, Edge as RedisEdge from tqdm import tqdm from .graph import Graph as RedisGraph from .triplet_loader import load_rdf_graph BLOCK_SIZE = 100 def make_node(value: str, alias=None): return RedisNode( label='Node', alias=alias, ...
# Standard imports import sys # Third party imports import nose # Local imports from mendeley import client_library ''' Things to test: - Starting up (which I guess includes syncing?) - Checking for documents - Adding to library - Updating a file from a local copy - Syncing after m...
#!/usr/bin/env python # encoding: utf-8 # Copyright (c) 2012-2016 Seafile Ltd. import hashlib import random import sys import time # Use the system PRNG if possible try: random = random.SystemRandom() using_sysrandom = True except NotImplementedError: import warnings warnings.warn('A secure pseudo-ran...
from sympy import * import numpy as np import cmath import math import matplotlib.pyplot as plt import matplotlib.axes as ax from mpl_toolkits.mplot3d import Axes3D from scipy.integrate import ode global dx global tau tau = 1 dx = 0.01 num = int(2 / dx) + 1 def MMPDE(u, x): num = int(u.shape[0]) A = np.zeros(...
# -*- coding: utf-8 -*- # Generated by Django 1.10.2 on 2016-10-23 12:46 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('products', '0001_initial'), ] ...
# strawpoll module by CantSayIHave # Created 2018/01/26 # # Create polls because why do more work when the bot can import json import aiohttp class StrawPoll: api_endpoint = 'https://www.strawpoll.me/api/v2/polls' dupcheck_options = ['normal', 'permissive', 'disabled'] create_options = ['title', 'optio...
from decimal import Decimal from typing import List import graphene from django.db import IntegrityError, transaction from tabletop.models import DurationType, Entity, Game, GameEntity, GameRating from tabletop.schema import DecimalField, EntityTypeEnum, GameNode class EntityInput(graphene.InputObjectType): nam...
import os import struct import numpy as np import pandas as pd from abc import ABC, abstractmethod class Dataset(ABC): """ Abstract data interface class. """ @abstractmethod def __init__(self): """ Must define: self.X -- numpy array of data samples; sel...
# Created by MechAviv # Quest ID :: 1401 # Warriors of Perion sm.setSpeakerID(1022000) sm.sendNext("So, you are the person Mai recommended. You seek to become a Warrior, am I right? I am Dances with Balrog, the Warrior Job Instructor. I instruct newcomers in the ways of battle.") sm.setSpeakerID(1022000) sm.sendSay(...
# coding: utf-8 # In[ ]: from collections import Counter from math import log, exp import re import os import sys import numpy as np import pandas as pd from bs4 import BeautifulSoup as bs # TODO: In your final submission, set `ALPHA` # to the value you think will be optimal for predicting on # unseen ...
from __future__ import annotations from dataclasses import dataclass from typing import Optional @dataclass class ValidatedAddress(): validated_street_number : str validated_street : str validated_city : str validated_zipcode : str # validated_province : Optional[Region] ...
import datetime import logging from dis_snek.client import Snake from dis_snek.models import Scale, Embed, InteractionContext, timestamp from dis_snek.models.application_commands import ( PermissionTypes, slash_command, slash_option, slash_permission, Permission, ContextMenu, cont...
# Custom exception classes """ Contains all the custom exceptions used in the simulation package """ class BatteryEmptyError(Exception): pass
################################## # #TODO test To do Viterbi decoding ################################# import numpy as np def decode(t_matrix, states, start, end, path_len): n = len(states) # keep the max probs probs_matrix = np.zeros((path_len, n)) # keep the last best state I was at prev = n...
from . import real from . import complex
import os import argparse import tqdm import cv2 import numpy as np DEBUG = False def show(img): cv2.imshow("image", img) cv2.waitKey(0) def strip_extension(s): return os.path.splitext(s)[0] def main(images_dir, masks_dir, output_dir, mask_weight=1): image_names = set(strip_extension(f) for f in...
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: MIT-0 import sys import subprocess # we need a special package for cleaning our data, lets pip install it first subprocess.check_call([sys.executable, "-m", "pip", "install", "pywavelets==1.1.1"]) import argparse import os ...
# @Time: 2022/4/14 17:41 # @Author: chang liu # @Email: chang_liu_tamu@gmail.com # @File:3.12.Converting_Days_to_seconds_and_other_basic_time_conversions.py from datetime import timedelta a = timedelta(days=2, hours=6) b = timedelta(hours=4.5) c = a + b print(c.days) print(c.seconds) print(c.total_seconds()) from ...
__version__ = "__version__ = '0.0.12'" from snakemake import shell def concat(file_list, output_file): shell("head -1 {file_list[0]} > {output_file}") for afile in file_list: shell("tail -n +2 {afile} >> {output_file}")
from __future__ import with_statement from django.shortcuts import render, redirect, get_object_or_404 from django.contrib.auth import logout from .models import Product, MyUser import random from tracker import forms from bs4 import BeautifulSoup import requests from django.template.loader import render_to_string fro...
import time import os from options.test_options import TestOptions from data.data_loader import CreateDataLoader from models.models import create_model from util.visualizer import Visualizer from pdb import set_trace as st # from util import html import numpy as np opt = TestOptions().parse() opt.nThreads = 1 # tes...
import pymysql from fixture.orm import ORM_fixture from model.configurations_group import Configurations_group db = ORM_fixture (host="127.0.0.1", name="addressbook", user="root", password="") try: l = db.get_users_not_in_group(Configurations_group(id="60")) for item in l: print(item) print(len(...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Utility functionality for pyflex. :copyright: Lion Krischer (krischer@geophysik.uni-muenchen.de), 2014 :license: GNU General Public License, Version 3 (http://www.gnu.org/copyleft/gpl.html) """ from __future__ import (absolute_import, division, print_functi...
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'DownloadWindow.ui' # # Created by: PyQt5 UI code generator 5.11.3 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_DownloadDialog(object): def setupUi(self, DownloadDialog): ...
from datetime import datetime from .database.models import TestDBO class Test: def __init__(self, identifier, level_id, algorithm, steps, run_date): self.identifier = identifier self.level_id = level_id self.algorithm = algorithm self.steps = steps self.run_date = run_dat...