content
stringlengths
5
1.05M
import datetime player_position = { '1B': ['el primera base', 'el inicialista'], '2B': ['el segunda base', 'el camarero'], 'SS': ['el campo corto'], '3B': ['el tercera base', 'el antesalista'], 'C' : ['el receptor', 'el catcher'], 'LF': ['el jardinero izquierdo', 'el left fielder'], 'CF': [...
# Script to train a gperc model on time series data from NSE Stock dataset for TATAMOTORS # Dataset preparation from https://github.com/ElisonSherton/TimeSeriesForecastingNN/blob/main/curateData.py from nsepy import get_history from datetime import datetime from sklearn.preprocessing import MinMaxScaler import numpy a...
from PIL import Image, ImageDraw, ImageFont, ImageFilter import random # 随机大写字母 def upperChar(): # chr() 方法返回数字对应的英文字母 return chr(random.randint(65, 90)) # 随机颜色 def randomColor(): return (random.randint(50,255), random.randint(50,255), random.randint(50,255)) width = 200 height = 50 fontSize = 45 image...
# -*- coding: utf-8 -*- # file: train_atepc.py # time: 2021/5/21 0021 # author: yangheng <[email protected]> # github: https://github.com/yangheng95 # Copyright (C) 2021. All Rights Reserved. ######################################################################################################################## ...
from scipy.special import softmax import numpy as np """ RNN and LSTM https://colab.research.google.com/github/mrm8488/shared_colab_notebooks/blob/master/basic_self_attention_.ipynb Attentions https://www.youtube.com/watch?v=S27pHKBEp30 Position Embeddings https://www.youtube.com/watch?v=dichIcUZfOw @ symbol https:...
#!/usr/bin/env python3 import argparse, importlib, inputs from datetime import datetime def import_solver(day, part): try: return importlib.import_module(f'solvers.advent_{day.zfill(2)}_{part}') except ImportError as e: raise Exception(f'Cannot find solver for day {day} part {part}. Reason: {str(e)}') de...
# -*- encoding: utf-8 -*- import random # V tej datoteki so definicije razredov Snake in Field ter nekaj pomožnih konstant in # funkcij. # Igralno polje sestoji iz mreze kvadratkov (blokov) WIDTH = 50 # sirina polja (stevilo blokov) HEIGHT = 30 # visina polja BLOCK = 20 # velikost enega bloka v tockah na zaslonu ...
from django.urls import path from users.views import profile app_name = "users" urlpatterns = [ # pyre-ignore[16]: This is fixed by https://github.com/facebook/pyre-check/pull/256. path("profile", profile, name="profile"), ]
from __future__ import division from __future__ import print_function import pickle import random import logging import torch import torch.nn as nn import torch.optim as optim torch.backends.cudnn.enabled = False import torch.utils.data as data from Models.Encoder import Encoder from Models.EncoderTxtCtx import Encode...
# Copyright 2016 Canonical Ltd # # 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, s...
import os import shutil import xml.etree.ElementTree as ET def copy_sources_from_proj(root_path, csproj_name): csproj_path = os.path.join(root_path, csproj_name) tree = ET.parse(csproj_path) for e in tree.getroot().iter("{http://schemas.microsoft.com/developer/msbuild/2003}Compile"): if 'Include' i...
""" KNN Prediction View""" __docformat__ = "numpy" import logging from typing import Union, Optional, List import pandas as pd from matplotlib import pyplot as plt from gamestonk_terminal.common.prediction_techniques import knn_model from gamestonk_terminal.common.prediction_techniques.pred_helper import ( plot_...
import numpy as np import pickle from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score from mvn.utils.op import translate_quaternion_to_euler angle_names = [ 'knee_angle_r', 'hip_flexion_r', 'hip_adduction_r', 'hip_rotation_r', 'hip_flexion_l', 'hip_adduction_l', 'hip...
from pydantic import BaseModel class UserIp(BaseModel): address: str
from app.common import settings class FlaskConfiguration: ENV = settings.app_env DEBUG = ENV == "development" API_TITLE = settings.app_name API_VERSION = settings.app_version MONGODB_SETTINGS = { "host": settings.mongodb_uri, } OPENAPI_VERSION = settings.openapi_version OPENA...
""" * Create a program to convert a variable of one type to another. * Create a variable named x and assign a string value '5' to it. * Create another variable y and assign '10' to it. * Convert the value stored in x and y to integers and multiply them. * Print the result. """ x = '5' y = '10' x = int(x) y = i...
""" smorest_sfs.modules.email_templates.schemas ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 电子邮件模板模块的Schemas """ from marshmallow import Schema, fields from smorest_sfs.extensions.marshal import SQLAlchemyAutoSchema from smorest_sfs.extensions.marshal.bases import BaseMsgSchema, BasePageSchema from . impo...
import os import getpass import socket import subprocess from urllib.parse import urlunparse, urlparse from tornado import web, gen, httpclient, process, ioloop from notebook.utils import url_path_join as ujoin from notebook.base.handlers import IPythonHandler from nbserverproxy.handlers import LocalProxyHandler d...
from pathlib import Path from demisto_sdk.commands.common.handlers import YAML_Handler from TestSuite.integration import Integration from TestSuite.test_tools import suite_join_path yaml = YAML_Handler() class Script(Integration): # Im here just to have one!!! def __init__(self, tmpdir: Path, name, repo, cr...
#coding=utf-8 """ Code based on Wang GUOJUN. Licensed under MIT License [see LICENSE]. """ import sys sys.path.append("..") import os import time import numpy as np import torch import rospy from ros_numpy import point_cloud2 from sensor_msgs.msg import PointCloud2, PointField from numpy.lib.recfunctions import stru...
import os, sys current_dir = os.path.dirname(os.path.realpath(__file__)) parent_dir = os.path.dirname(current_dir) sys.path.append(parent_dir) import simpy from collections import deque from msg import Msg, InfoType from priority_dict import * from debug_utils import * class RRQueue(): # Round Robin def __init__(se...
import requests import io import base64 """ Copyright 2017 Deepgram 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...
# =============== DEFINE BLUEPRINTS ============== import logging from functools import wraps import sys # =============== DEFINE LOGSTREAM ============== class LogStream(): def __init__(self, MAX_RECORDS ): self.logs = [] self.max_records = MAX_RECORDS self.lines = 0 def write(self,...
import os import time import numpy as np import torch from utils import prep_batch, epoch_time def train_step( model, source, src_len, targets, task, criterion, optimizer, clip, teacher_forcing=None, ): # source = [src_len, bsz] # targets = [trg_len, bsz] # src_len = [b...
use_on_heroku = True use_mockDB = True base_url = '' if use_on_heroku: base_url = 'https://bring-my-food.herokuapp.com/' else: base_url = 'http://127.0.0.1:5000/'
import time import datetime import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt from matplotlib.dates import DateFormatter, date2num import numpy as np import subprocess as sp import time import sys import os # Takes south_local_signal.txt and south_global_signal.txt # and adds microseconds, UTC ti...
import unittest from dicom_factory.factory import DicomFactory class TestFactory(unittest.TestCase): def test_create_factory_with_custom_data_size_works_properly(self): data_size = (100, 100) factory_args = {'Rows': data_size[0], 'Columns': data_size[1]} dicom = DicomFactory.build(facto...
import requests from bs4 import BeautifulSoup import smtplib import json import re from tld import get_tld ############################################## class scrapit(): def __init__(self, query, price ,email, soup): self.query = query self.price = price self.email = email self.so...
# -*- coding: utf-8 -*- #! \file ./tests/test_support/test_cmd/test_runtime.py #! \author Jiří Kučera, <[email protected]> #! \stamp 2016-04-07 18:58:51 (UTC+01:00, DST+01:00) #! \project DoIt!: Tools and Libraries for Building DSLs #! \license MIT #! \versi...
from django.contrib import admin from posts.models import Auther , Content class ContentInline(admin.TabularInline): model = Content extra = 1 class AutherAdmin(admin.ModelAdmin): list_display = ['name','topic','pub_date'] list_filter = ['pub_date'] search_fields = ['topic'] inlines = [Content...
# Chap06/stack_classification_ui.py import sys import json import pickle from argparse import ArgumentParser def get_parser(): parser = ArgumentParser() parser.add_argument('--model') return parser def exit(): print("Goodbye.") sys.exit() if __name__ == '__main__': parser = get_parser() ...
from hypothesis import given import hypothesis.strategies as st from hypothesis import given from volga.fields import Int, Bool, Float, Null, Str from volga.json import deserialize from volga.exceptions import ParsingError import json import pytest # type: ignore @given(st.integers()) def test_deserialize_int(x: ...
from google.protobuf.descriptor import FieldDescriptor from protobuf_serialization.constants import VALUE_TYPES from protobuf_serialization.deserialization.utils import proto_timestamp_to_datetime def protobuf_to_dict(proto, dict_cls=dict, omit_keys_if_null=False, fields=None): if fields: fields = set(fi...
import os import sys import glob import argparse import threading import six.moves.queue as Queue # pylint: disable=import-error import traceback import numpy as np import tensorflow as tf tf.compat.v1.disable_v2_behavior() import dnnlib.tflib as tflib import h5py #----------------------------------------------------...
import os import glob import json default_N_assign_more_sounds = 10 PATH_TO_FSL10K = "/static/FSL10K" PATH_TO_AC_ANALYSIS = os.path.join(PATH_TO_FSL10K, 'ac_analysis/') PATH_TO_METADATA = os.path.join(PATH_TO_FSL10K, 'fs_analysis/') def compile_annotated_sounds(annotations_path): annotated_sounds = {} a...
import tensorflow as tf import horovod.keras as hvd import model import keras def run(): # Horovod: initialize Horovod. hvd.init() # Horovod: pin GPU to be used to process local rank (one GPU per process) gpus = tf.config.experimental.list_physical_devices('GPU') for gpu in gpus: tf.conf...
# Copyright (c) 2019 Martin Olejar # # SPDX-License-Identifier: BSD-3-Clause # The BSD-3-Clause license for this file can be found in the LICENSE file included with this distribution # or at https://spdx.org/licenses/BSD-3-Clause.html#licenseText import pytest from mboot.properties import Version, BoolValue, ...
current_n = '1113222113' for n in xrange(40): current_count = 0 next_n = '' prev_d = current_n[0] for i,d in enumerate(current_n): if d == prev_d: current_count += 1 if i == len(current_n)-1: next_n += str(current_count) + prev_d else: next_n += str(current_count) + prev_d current_count = 1 ...
class NotepadqqMessageError(RuntimeError): """An error from Notepadqq""" class ErrorCode: NONE = 0 INVALID_REQUEST = 1 INVALID_ARGUMENT_NUMBER = 2 INVALID_ARGUMENT_TYPE = 3 OBJECT_DEALLOCATED = 4 OBJECT_NOT_FOUND = 5 METHOD_NOT_FOUND = 6 def __init__...
""" This file defines Petra expressions. """ import re from abc import ABC, abstractmethod from llvmlite import ir from typing import Optional from .codegen import CodegenContext from .validate import ValidateError from .symbol import Symbol from .type import Type from .typecheck import TypeContext, TypeCheckError ...
"""Test for single coil files from fastmri.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow_datasets import testing from tensorflow_datasets.image import fastmri class FastMRITest(testing.DatasetBuilderTestCase): DATASET_CLASS = fast...
from os import getenv from kombu import Queue, Exchange REDIS_HOST = getenv('REDIS_HOST') REDIS_PORT = getenv('REDIS_PORT') """ ========= Notes: ========= CPU Bound task celery -A <task> worker -l info -n <name of task> -c 4 -Ofair -Q <queue name> — without-gossip — without-mingle — without-heartbeat I/O task celery...
#!/usr/bin/env python import sys import simplejson as json import eiii_crawler_server as c import psycopg2 import psycopg2.extras psycopg2.extras.register_uuid() import uuid """ Use this script to reconstruct the crawler_result from the file dumped by the crawler. Supply the file with the crawler stats as well as the...
import cv2 import numpy as np img = cv2.imread('./images/blue_carpet.png') img_gaussian = cv2.GaussianBlur(img, (13,13), 0) img_bilateral = cv2.bilateralFilter(img, 13, 70, 50) cv2.imshow('Input', img) cv2.imshow('Gaussian filter', img_gaussian) cv2.imshow('Bilateral filter', img_bilateral) cv2.waitKey()
# -*- coding: utf-8 -*- import argparse import os import sys import transaction from gearbox.command import Command from paste.deploy import loadapp from webtest import TestApp from tracim.lib.exception import CommandAbortedError class BaseCommand(Command): """ Setup ap at take_action call """ auto_setup_ap...
from .course import course_service from .section import section_service
def i_love_python(): """ He charmed me^ now in any language can not write :) """ return "I love Python!" def test_function(): assert i_love_python() == "I love Python!"
from fastapi import FastAPI,Depends,status,Response,HTTPException from . import schemas,models from .database import engine,SessionLocal from sqlalchemy.orm import Session from typing import List app = FastAPI() models.Base.metadata.create_all(bind=engine) def get_db(): db = SessionLocal() try: ...
# Generated by Django 3.0.7 on 2020-08-22 19:35 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('staff', '0008_auto_20200822_2133'), ] operations = [ migrations.AlterField( model_name='staff', name='mname', ...
from rest_framework import serializers from .models import Articles, Rating, Likes, Comments, Favorites from django.db.models import Avg from authors.apps.authentication.serializers import UserSerializer from authors.apps.profiles.serializers import ProfileSerializer import readtime from drf_yasg.utils import swagger_s...
# coding: utf-8 __version__ = '0.0.1' default_app_config = 'myarticles.apps.AppConfig'
import pytest from web3.utils.abi import ( merge_args_and_kwargs, ) FUNCTION_ABI = { "constant": False ,"inputs": [ {"name":"a", "type":"int256"}, {"name":"b", "type":"int256"}, {"name":"c", "type":"int256"}, {"name":"d", "type":"int256"}, ], "name": "testFn", ...
""" Терминал """ import src.terminal.utils as terminal_utils __MESSAGE_ESCAPE = 'До встречи!' __MESSAGE_PRESS_ANY_KEY = 'Нажмите клавишу ВВОД, чтобы продолжить...' __MENU_POINT_EXIT = 'Выход' def __stop(terminal): terminal.to_terminal() terminal.to_terminal(__MESSAGE_ESCAPE) def run(actions=None, utils=Non...
from django.contrib import admin from .models import Category class CategoryAdmin(admin.ModelAdmin): pass admin.site.register(Category, CategoryAdmin)
""" Author Joshua I. Meza Magaña Date 16/08/2021 Version 1.0.0 A bot which helps with team organization. """ import discord from discord.ext import commands from dotenv import load_dotenv import os from Controller.keepAlive import * from Model.model import * from Controller.Commands.commandHelp import * from Controller...
from rllab.sampler.utils import rollout from rllab.sampler.stateful_pool import singleton_pool from rllab.misc import ext from rllab.misc import logger from rllab.misc import tensor_utils import numpy as np def _worker_init(G, id): import os os.environ['THEANO_FLAGS'] = 'device=cpu' G.worker_id = id def...
from django.urls import path from . import views urlpatterns = [ path('', views.home, name='Home'), path('merchants/', views.vendors_list, name='Vendors'), path('merchants/<int:pk>/<str:pk_test>/', views.vendors_view, name='VendorsView'), path('about/', views.about_us, name='AboutUs'), path('contact/', vi...
import sys sys.path.insert(1, "../../") import h2o, tests def pyunit_model_params(): pros = h2o.import_file(tests.locate("smalldata/prostate/prostate.csv")) m = h2o.kmeans(pros,k=4) print m.params print m.full_parameters if __name__ == "__main__": tests.run_test(sys.argv, pyunit_model_params)
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright (c) 2011 OpenStack, LLC. # 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...
# -*- coding: utf-8 -*- """Backend room logic.""" from time import sleep from random import random from sqlalchemy import or_, and_, func, text, select, update from ..database.table import Room, get_engine, get_session def update_period(): """Heart beat period""" return 3 def take_room(session, worker_i...
"""(c) All rights reserved. ECOLE POLYTECHNIQUE FEDERALE DE LAUSANNE, Switzerland, VPSI, 2017""" from django.test import TestCase from api.apikey import APIKey from api.redis import save_key, exists, get_apikeys, flush_all from config.settings.base import get_config from api.apikeyhandler import ApiKeyHandler class...
class Class: def __init__(self, name): self.name = name self.fields = [] def __str__(self): lines = ['class %s:' % self.name] if not self.fields: lines.append(' pass') else: lines.append(' def __init__(self):') for f in self.fields: ...
from Cimpl import * file = choose_file() original_image = load_image(file) def grayscale(image: Image) -> Image: """Return a grayscale copy of image. >>> image = load_image(choose_file()) >>> gray_image = grayscale(image) >>> show(gray_image) """ new_image = copy(image) for x, y, (r, g, ...
import unittest from numpy.testing import assert_array_almost_equal import torch import numpy as np from siren.siren import Sine, SIREN class SineTestCase(unittest.TestCase): """Class to test the Sine activation function""" def test_sine(self): dummy = torch.FloatTensor([np.pi, np.pi / 2]) sin...
from __future__ import print_function import sys import copy import random import numpy as np from collections import defaultdict import os def data_partition(fname, FLAGS): print("inside utility function") usernum = 1 itemnum = 1 User = defaultdict(list) user_train = {} user_valid = {} us...
import requests import re class Content(): def __init__(self, Requests, log): self.Requests = Requests self.log = log self.gameContent = {} def get_content(self): content = self.Requests.fetch("custom", f"https://shared.{self.Requests.region}.a.pvp.net/content-service/v3/conten...
# Shiny dataset but enable import os import glob import numpy as np import torch from PIL import Image from .shiny import ShinyDataset, center_poses, normalize, get_spiral, average_poses from .ray_utils import get_ray_directions_blender, get_rays, ndc_rays_blender class ShinyFewDataset(ShinyDataset): def __in...
from allauth.account.models import EmailAddress from allauth.socialaccount.adapter import DefaultSocialAccountAdapter # # class MySocialAccountAdapter(DefaultSocialAccountAdapter): # def authentication_error(self, request, provider_id, error, exception, extra_context): # print(provider_id) # print(...
from slacker.utility import parse_line from prompt_toolkit.completion import WordCompleter class Completer(WordCompleter): def __init__(self, words, meta_dict, registrar): self.__registrar = registrar self.__completers = {} super(Completer, self).__init__(words, meta_dict=meta_dict, ignore_case=True) ...
# movie/forms.py # Django modules from django.forms import ModelForm, Textarea # Locals from movie.models import Review # Form: ReviewForm # We need to inherit from ModelForm. class ReviewForm(ModelForm): ''' Similar as what we did with the UserCreationForm, we set some Bootstrap classes for our form fields. '...
import setuptools with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name='django-translate-po-files', version='0.0.7', scripts=['django-translate-po'], author="Bart Machielsen", author_email="[email protected]", description="Automatically translate al...
# # Copyright 2020 British Broadcasting 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...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Aug 9 23:43:32 2018 @author : gaurav gahukar : caffeine110 AIM : (p) TO Impliment UDACITY MiniProject ( Naive Bayes ) : (s) Email Classification to predict Author of the Email : --- Inspired by the story of J K Roling ---...
# 使用 __miss__ 构造一个默认值处理字典不存在 key 的异常情况
from flowws import try_to_import AutoencoderVisualizer = try_to_import( '.AutoencoderVisualizer', 'AutoencoderVisualizer', __name__ ) BondDenoisingVisualizer = try_to_import( '.BondDenoisingVisualizer', 'BondDenoisingVisualizer', __name__ ) ClassifierPlotter = try_to_import('.ClassifierPlotter', 'ClassifierPlo...
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import json import hashlib import requests import time import sys reload(sys) sys.setdefaultencoding('utf8') # debug key and secret key SECRET_KEY = 'ij1a4iltc4p2ml29swvkgjoanxyron5m' APP_KEY = '575e809b67e58eb219000d78' if os.path.exists(os.path.join(os.path.di...
from config_parser import parseConfig from db_lib import getColNames, getBrokerIp, isUp import json import logging import os from mqtt_socket import MqttSocket import paho.mqtt.publish as publish def printLogFolder(): log_folder = parseConfig()['log_folder'] print(os.path.expanduser(log_folder)) def initLogge...
class FormElementLacksAction(RuntimeError): """ The form element lacks an "action" attribute """ class FormElementLacksMethod(RuntimeError): """ The form element lacks a "method" attribute """ class FormNotFound(RuntimeError): """ The specified HTML form was not found on the page ...
""" This package is designed to wrap data for the data profiler. """
# Herança e Metodos Privados class ContaBancaria(object): def __init__(self, *args, **kwargs): self.saldo = 0 def depositar(self, valor): self.saldo += valor self.consultar_saldo() def sacar(self, valor): self.saldo -= valor self.consultar_saldo() def consult...
# coding=utf-8 import json from datetime import datetime from api.snippets import dthandler, delete_item_in_list, lookahead from common.settings import MONGO_LIMIT_REPORT def pretty_data(cursor_db, data_set_name, total, per_page, page_n, response_format='json', keys=None, search_data=None): retur...
from sqlalchemy import create_engine, MetaData from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker from scraper.settings import SQLALCHEMY_DATABASE_URL engine = create_engine( SQLALCHEMY_DATABASE_URL, pool_pre_ping=True ) SessionLocal = sessionmaker(autocommit=False...
''' Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight). Note: Note that in some languages, such as Java, there is no unsigned integer type. In this case, the input will be given as a signed integer type. It should not affect your implementation...
#%% # -*- coding: utf-8 -*- """ El DBSCAN solito sin nada más... °-° """ import LibraryTT.txt2array as conversion import numpy as np from numpy import sqrt import pandas as pd import matplotlib.pyplot as plt import random import math from mpl_toolkits.mplot3d import Axes3D #import open3d as o3d #%% conversion.bytxt...
# You are given an array of non-negative integers that represents a # two-dimensional elevation map where each element is unit-width wall and the # integer is the height. Suppose it will rain and all spots between two walls # get filled up. def contain_water(height): max_left, max_right = 0, 0 left, ...
def main(request, response): if "full" in request.GET: return request.url else: return request.request_path
# -*- coding: utf-8 -*- from django.contrib.syndication.views import Feed from django.shortcuts import reverse from django.utils.feedgenerator import Atom1Feed, Rss201rev2Feed from .models import Article class DBlogRssFeed(Feed): """ rss 订阅 , 仅显示文章摘要""" feed_type = Rss201rev2Feed title = 'xiaowu‘s django_blog' ...
import random class Player: """ Plays in games for their team Has skill/overall Has a salary """ def __init__(self, name, skill, salary): self.name = name self.salary = salary # skill/overall # generates the given overall of the player ...
from PyQt5.QtWidgets import QApplication import sys from ui import Login #self.close() def main(): app = QApplication(sys.argv) #ex = AppWindow() ex = Login() ex.show() sys.exit(app.exec_()) if __name__ == '__main__': main()
import unittest from papertrack.core import Configuration, Field class TestConfiguration(unittest.TestCase): def test__empty_configuration_created(self): config = Configuration() self.assertIsInstance(config, Configuration) def test_given_empty_configuration_returns_default_state_list(s...
#!/usr/bin/env python import os import sys from glob import glob input = sys.argv[1] os.chdir(input) print 'Please wait - gathering filelist...' tiffs = glob('*.tiff') counter = 0 filename = tiffs[0] # create new variable which trims the first 18 characters. head_good_filename = filename[:-11] print 'Current filen...
""" Test file for Hello World Module""" import pytest from src.hello_world import main_method def test_main_method(capfd): """Test to validate that the main method is called.""" main_method() out, err = capfd.readouterr() assert out == "Hello World!\n"
#! python3 from pytube import YouTube print("Please, paste the video's URL (web's address):") try: # Get the video url ytVideoUrl = YouTube(input()) print(ytVideoUrl.title) # Check if the video is the right one print('\nIs this the video you want to download? \nYes or No?') answ...
# -*- coding: utf-8 -*- from django.conf import settings from django.contrib.contenttypes.fields import GenericRelation from django.db import models from django.db.models import Count from django.urls import reverse from autoimagefield.fields import AutoImageField from common_utils.models import TimestampModelMixin fr...
import sys from PIL import Image # Paths of raw vs scatter composite = '/Users/kolbt/Desktop/ALL_FIGURES/supplemental_info/all_phase_planes/SI_plane_figure.png' rawPth = '/Users/kolbt/Desktop/ALL_FIGURES/supplemental_info/all_phase_planes/sim_overlay/' sctPth = '/Users/kolbt/Desktop/ALL_FIGURES/supplemental_info/all_p...
import unittest from io import StringIO from logging import StreamHandler, getLogger from pyskeleton.logging import configure_logger, DEBUG_LVL, WARNING_LVL from tests.utils import ( LoggingTester, DEBUG_MSG, INFO_MSG, WARNING_MSG, ERROR_MSG, CRITICAL_MSG, ) class LoggingTest(LoggingTester): ...
# # Strelka - Small Variant Caller # Copyright (c) 2009-2018 Illumina, Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # at your option) any later vers...
#!/usr/bin/env python from django.conf import settings from django.utils.translation import ugettext_lazy as _ def project_config(context) -> dict: # noqa pylint: disable=unused-argument return { 'DEBUG': settings.DEBUG, 'ENVIRONMENT_NAME': _(settings.ENVIRONMENT_NAME), 'ENVIRONMENT_COLOR...
__author__ = ["Francisco Clavero"] __email__ = ["[email protected]"] __status__ = "Prototype" """ Trainer class decorators with the implementation of common features, such as common optimizers. """ from typing import Callable from adabound import AdaBound from torch.nn import Module from torch.optim import SG...
M = int(input()) for i in range(2, int(M ** 0.5) + 1): if M % i == 0: print(i, M // i) break else: print(1, M)