content
stringlengths
5
1.05M
import random messages = ['It is certain', 'It is decidedly so', 'Yes definitely', 'Reply hazy try again', 'Ask again later', 'Concentrate and ask again', 'My reply is no', 'Outlook not so good', 'Very doubtful'] print(mes...
import os import re import subprocess import xml.etree.ElementTree as ET from toolsws.utils import wait_for from toolsws.wstypes import GenericWebService from toolsws.wstypes import JSWebService from toolsws.wstypes import LighttpdPlainWebService from toolsws.wstypes import LighttpdWebService from toolsws.wstypes impo...
""" Test the Input block. """ # pylint: disable=missing-docstring, no-self-use, protected-access # pylint: disable=invalid-name, redefined-outer-name, unused-argument, unused-variable # pylint: disable=wildcard-import, unused-wildcard-import import pytest import edzed from .utils import * def test_noinit(circuit)...
# -*- coding: utf-8 -*- import json import os from datetime import timedelta from openprocurement.api.models import get_now import openprocurement.relocation.api.tests.base as base_test from copy import deepcopy from openprocurement.api.tests.base import ( PrefixedRequestClass, test_tender_data, test_organization ...
from django.shortcuts import render from django.http import HttpResponseRedirect from core.models import Post from django.contrib.admin.models import LogEntry def theory_page(request): """ Theory page with blog items :param request: request :return: JSON with objects """ try: query = P...
import json import pickle import time from queue import Queue, Empty from threading import Thread, Event import numpy as np import os import sys import cv2 # Multithreded script to run the evaluation for the Orig2D ablation experiment. Online version displays the result. # Offline version first saves all detections a...
#!/usr/bin/env python """ CloudGenix Python SDK - POST **Author:** CloudGenix **Copyright:** (c) 2017-2021 CloudGenix, Inc **License:** MIT """ import logging __author__ = "CloudGenix Developer Support <developers@cloudgenix.com>" __email__ = "developers@cloudgenix.com" __copyright__ = "Copyright (c) 2017-2021 Clou...
# coding: utf-8 ''' ----------------------------------------------------------------------------- Copyright 2016 Esri 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...
cars = 100 space_in_a_car = 4.0 drivers = 30 passengers = 90 cars_not_driver = cars - drivers cars_driven = drivers carpool_capacity = cars_driven * space_in_a_car averger_passergers_per_car = passengers / cars_driven print('There are', cars, 'cars avaliable.')
from utils import load_data, data_to_series_features, get_data_loader, is_minimum, make_cuda from algorithm import (initialize_weights, individual_to_key, pop_to_weights, select, reconstruct_population) from train import train, evaluate from model import weightedLSTM import argparse import numpy ...
from descent.case import CaseUnapply1 class Tree: def copy(self): return self class Empty(Tree): pass class Ignore(Tree): def consume(self, val): return self class Rule: def __init__(self, name): self.name = name self.body = None def define(self, body): ...
# Solve the Assignment problem using the Hungarian method. # input A - square cost matrix # return - the optimal assignment import numpy as np from scipy.optimize import linear_sum_assignment def Hungarian(A): _, col_ind = linear_sum_assignment(A) # Cost can be found as A[row_ind, col_ind].sum() return c...
# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- import sy...
import locale import curses print(curses.baudrate()) print(curses.beep()) print(curses.can_change_color()) print(curses.cbreak()) color_number = 1000 print(curses.color_content(color_number)) print(curses.color_pair(color_number)) print(curses.curs_set(visibility)) print(curses.def_prog_mode()) print(curses.def_shell_m...
from structure import * allpassed = True for sg in range(1, 231): print("Calculating spacegroup " + str(sg)) wyckoffs = get_wyckoffs(sg) for index, wp in enumerate(wyckoffs): v = np.random.random(3) for i in range(3): if np.random.random() < 0.5: v[i] *= -1 ...
_global_para = { "category": { "red": 0, "blue": 1 }, "DEBUG_SETTING": { True: True, False: False } } _global_dict = {} def set_value(name, key, value): _global_dict[name] = _global_para[key][value] def get_value(name, defValue=None): try: return _glo...
def normalize_cf(cf_json): if isinstance(cf_json, dict): ref = cf_json.get('Ref') if ref is not None: return ref normalized = {} for key, value in cf_json.items(): normalized[key] = normalize_cf(value) return normalized if isinstance(cf_json, list)...
# _*_ coding:gbk _*_ ''' Author: Ruan Yang Email: ruanyang_njut@163.com Reference: https://keras-cn.readthedocs.io/en/latest/getting_started/sequential_model/ ''' import keras from keras.models import Sequential from keras.layers import Dense,Dropout,Activation from keras.optimizers import SGD # Gener...
import time from multiprocessing import Process import sys from p001 import P001 from p002 import P002 from p003 import P003 from p004 import P004 from p005 import P005 from p006 import P006 from p007 import P007 from p008 import P008 from p009 import P009 from p010 import P010 from p011 import P011 from p012 import ...
from nltk.tokenize import word_tokenize, sent_tokenize print(word_tokenize("This is the queen's castle. Yay!")) # ['This', 'is', 'the', 'queen', "'s", 'castle', '.', 'Yay', '!'] print(sent_tokenize(got)[1:3]) # ['"The wildlings are \ndead."', '"Do the dead frighten you?"']
import FWCore.ParameterSet.Config as cms source = cms.Source("EmptySource") from GeneratorInterface.Hydjet2Interface.hydjet2DefaultParameters_cff import * generator = cms.EDFilter("Hydjet2GeneratorFilter", collisionParameters5020GeV, qgpParameters, hydjet2Parameters, fNhsel = cms.int32(2), # Flag to include je...
""" This file is part of the TheLMA (THe Laboratory Management Application) project. See LICENSE.txt for licensing, CONTRIBUTORS.txt for contributor information. Worklist series experiment design rack table. """ from sqlalchemy import Column from sqlalchemy import ForeignKey from sqlalchemy import Integer from sqlalch...
r""" Vector Space Morphisms (aka Linear Transformations) AUTHOR: - Rob Beezer: (2011-06-29) A vector space morphism is a homomorphism between vector spaces, better known as a linear transformation. These are a specialization of Sage's free module homomorphisms. (A free module is like a vector space, but with s...
# Generated by Django 3.2.5 on 2021-07-26 20:43 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('clinic_app', '0002_patient'), ] operations = [ migrations.CreateModel( name='Visit', ...
''' Python module for Mopidy Pummeluff volume tag. ''' __all__ = ( 'Volume', 'VolumeUp', 'VolumeDown', ) from logging import getLogger from .base import Action LOGGER = getLogger(__name__) class Volume(Action): ''' Sets the volume to the percentage value retreived from the tag's parameter. ...
from .target_marker import TargetMarker
import numpy as np import torch from torch import nn import copy from collections import defaultdict from absl import logging from musco.pytorch.compressor.decompositions.tucker2 import Tucker2DecomposedLayer from musco.pytorch.compressor.decompositions.cp3 import CP3DecomposedLayer from musco.pytorch.compressor.deco...
import glob import os import numpy as np import scipy.io.wavfile as wavfile import librosa import argparse from scipy.io.wavfile import write def parse_args(): parser = argparse.ArgumentParser() parser.add_argument("--data_path", default='../datasets/vcc2018', type=str) args = parser.parse_args() return...
print('1533776805')
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: ondewo/nlu/session.proto from google.protobuf.internal import enum_type_wrapper from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _r...
from picamera.array import PiRGBArray from picamera import PiCamera from time import sleep import cv2 as cv import time camera = PiCamera() rawCapture = PiRGBArray(camera) #cap = camera.start_preview() sleep(0.1) camera.capture(rawCapture, format="bgr") image = rawCapture.array cv2.imshow("image", image) cv2.waitk...
# coding=utf-8 import os __all__ = ['is_running_under_teamcity'] teamcity_presence_env_var = "TEAMCITY_VERSION" def is_running_under_teamcity(): return os.getenv(teamcity_presence_env_var) is not None
import unittest import json import sys sys.path.insert(0, '../') import app.MessageParser class UnitTests(unittest.TestCase): def test_HighestProbabilityTagMeetingThreshold(self): MessageParser = app.MessageParser.MessageParser() message1=json.loads("[{\"Tag\": \"banana\",\"Probability\": 0.4}, {\"...
class WrapperRobertaTokenizer(): def __init__(self, tokeniser): self.tokeniser = tokeniser def convertTokenToIds(self, token): return self.tokeniser(token)['input_ids'][1:-1] def convertSentToIds(self, sent): return [1] + [item for sublist in sent.split() for item in self.convertTo...
""" Font Style Contains the style attributes of font. """ from dataclasses import dataclass from .slant import FontSlant from .weight import FontWeight __all__ = [ "FontStyle", ] @dataclass class FontStyle: slant: FontSlant weight: FontWeight
import re from setuptools import setup import subprocess import sys try: result = subprocess.run( [sys.executable, "-m", "pip", "show", "pkg_utils"], check=True, capture_output=True) match = re.search(r'\nVersion: (.*?)\n', result.stdout.decode(), re.DOTALL) assert match and tuple(match.grou...
import unittest import rpy3.robjects as robjects rinterface = robjects.rinterface import array class REnvironmentTestCase(unittest.TestCase): def testNew(self): env = robjects.REnvironment() self.assertEquals(rinterface.ENVSXP, env.typeof) def testNewValueError(self): self.assertRaises...
from __future__ import absolute_import, division, print_function __metaclass__ = type import logging import qb.logging # Find a Display if possible try: from __main__ import display except ImportError: try: from ansible.utils.display import Display except ImportError: display = None el...
"""Intialize Database file.""" import os import random import sys import transaction from pyramid.paster import ( get_appsettings, setup_logging, ) from pyramid.scripts.common import parse_vars from ..models.meta import Base from ..models import ( get_engine, get_session_factory, get_tm_session,...
import json import os import torch from nltk import sent_tokenize, word_tokenize import copy import Constants from Dict import Dict import string total_data = 0 def tokenize(st, sentence_split=None, option=False): #TODO: The tokenizer's performance is suboptimal if option and (st[-1] in string.punctuation or...
import torch import distdl.nn.padnd as padnd from distdl.utilities.misc import DummyContext t = torch.ones(3, 4) print(f't =\n{t}') ctx = DummyContext() pad_width = [(1, 2), (3, 4)] t_padded = padnd.PadNdFunction.forward(ctx, t, pad_width, value=0) print(f't_padded =\n{t_padded}') t_unpadded = padnd.PadNdFunction....
import argparse from processing.hdf5creator import create_hdf_database, set_createdb_parser from processing.core import set_geometry_parser, process, set_charges_parser, set_rism_parser functions = {"createdb":create_hdf_database,"geometry":process,"charges":process,"rism":process} parser = argparse.ArgumentParser(de...
#!/usr/bin/env python3 import apx import sys, os if __name__ == "__main__": with open(sys.argv[1]) as fp: node = apx.Parser().load(fp) inDataSize = sum([port.dsg.packLen() for port in node.requirePorts]) outDataSize = sum([port.dsg.packLen() for port in node.providePorts]) ...
"""Different models to describe the vertical relative humidity distribution.""" import abc import numpy as np from scipy.interpolate import interp1d from konrad.component import Component from konrad.physics import vmr2relative_humidity from konrad.utils import gaussian class RelativeHumidityModel(Component, metacl...
# # This file is part of Python Client Library for STAC. # Copyright (C) 2019 INPE. # # Python Client Library for STAC is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. # """STAC Item module.""" import json import shutil import requests...
#!/usr/bin/env python # -*-mode: python -*- -*- coding: utf-8 -*- """ Implements the (W3C WG Note) RIF-in-RDF mapping. By Sandro Hawke, 16 June 2010. Revised 3 October 2010 to match current version of RIF_in_RDF. Revised 12 May 2011 to fix a few bugs. Copyright © 2010,2011 World Wide Web Consortium, (Massachusetts ...
#!/usr/bin/env python # ---------------------------------------------------------------------- # Copyright (c) 2011-2016 Raytheon BBN Technologies # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and/or hardware specification (the "Work") to # deal in the Work without ...
# coding=utf-8 import sys,os import sqlite3 import errno import json import sys reload(sys) sys.setdefaultencoding('utf8') import re import csv import xlrd import xlwt import codecs def open_excel(file= 'file.xls'): try: data = xlrd.open_workbook(file) return data except Exception,e: p...
# Copyright (c) OpenMMLab. All rights reserved. import os.path as osp from .base_generation_dataset import BaseGenerationDataset from .registry import DATASETS @DATASETS.register_module() class GenerationPairedDataset(BaseGenerationDataset): """General paired image folder dataset for image generation. It as...
from django.contrib import admin from .models import Description, Category admin.site.register(Description) admin.site.register(Category)
#!/usr/bin/python # coding: UTF-8 # Winstar WEG010032ALPP5N00000 Graphic OLED and WS0010 OLED driver code for # Raspberry Pi GPIO library. Some code originally found at # http://forums.adafruit.com/viewtopic.php?f=8&t=29207&start=15#p163445 # Based on http://www.rpiblog.com/2012/11/interfacing-16x2-lcd-with-raspberry-...
# Copyright 2017 The Bazel Authors. 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 la...
# GUI to visualize how a galaxy spectrum evolves over time ''' ''' import fsps import os import sys import time import pandas as pd import numpy as np import matplotlib.pyplot as plt from matplotlib.widgets import Slider, Button, SpanSelector from generate_ssp import get_filename, ages_allowed os.environ["SPS_HOM...
# # Corda Certificate Generator # requires Java Keytool to be installed # see also requirements.txt for Python dependencies # import sys import re import argparse import os import subprocess from ruamel.yaml import YAML yaml = YAML() from munch import Munch from colorama import Fore, Back, Style CERT_ROLES = { "...
import yaml class Parser: def __init__(self,config): self.config_file=config def get_tests(self): with open(self.config_file,'r') as file: data=file.read() data=yaml.load(data) for test in data['tests']: yield test
"""Results using grey-matter maps.""" import numpy as np import pandas as pd from sklearn.svm import SVR from sklearn.model_selection import KFold from utils import plot_results, GridSearchCVRBFKernel # Load the data df = pd.read_csv('gm/Kernels/euclidean_norm.csv', index_col=0) X = df.values y = pd.read_csv('gm/T...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019/1/8 00:02 # @Author : Yuecheng Jing # @Site : www.nanosparrow.com # @File : PathSum # @Software: PyCharm # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.righ...
# Chapter 2 concepts x = 2 y = 4 z = x * y print(f"{x} * {y} = {z}") print("Hello Python world!") name = "Marcel" last_name = "Houary" full_name = name + " " + last_name print(f"First name: {name}, Last name: {last_name}, Full name: {full_name}") n = "Marcel" ln = "Houary" fn = n + " " + ln print(f"First name: ...
# When the MVP is deployed using Kubernetes ingress controller implemented by Traefik, # TLS certificates are not served correctly. This results in https and secure # websockets not being enabled. This test case is to verify this bug. # To test using local ip address, assign local ip to env variable 'IP_FOR_INGRESS_TES...
import streamlit as st from streamlit.logger import get_logger from duplicazer.core import remove_duplicate, find_duplicate from duplicazer.constant import APP_PARAMS st_logger = get_logger(__name__) st.set_page_config( layout=APP_PARAMS["layout"], page_title=APP_PARAMS["title"], page_icon=APP_PARAMS["ic...
# MODULES from . import schemas from . import __demo__ from . import blueprints from . import sanic # STRUCTURE __plugins__ = { "schemas" : schemas.__dir__(), "__demo__" : __demo__.__dir__(), "blueprints" : blueprints.__dir__(), "sanic" : sanic.__dir__(), }
# TODO Throw this away and use https://github.com/googledatalab/pydatalab instead # - Supports full API, e.g. use_cached_results, max_billing_tier # - See examples: https://github.com/googledatalab/notebooks # - But verify it works with arrays and structs... from collections import OrderedDict import pandas as p...
from distutils.core import setup setup(name='m', version='0.1.0', packages=['m', 'm.security', 'm.extensions', 'm.extensions.sqlalchemy'], install_requires=[ 'WebOb>=1.6.1', 'sqlalchemy>=1.0.0', 'pyhocon>=0.3.0', ], author="comyn", author_email="me@xuem...
'''A Python module for reading and writing C3D files.''' from __future__ import unicode_literals import array import io import numpy as np import struct import warnings import codecs PROCESSOR_INTEL = 84 PROCESSOR_DEC = 85 PROCESSOR_MIPS = 86 class DataTypes(object): ''' Container defining different data types...
import argparse import sys from .drawing import Drawing from .runner import makeDrawbotNamespace, runScriptSource def main(args=None): if args is None: args = sys.argv[1:] parser = argparse.ArgumentParser( prog="drawbot", description="Command line DrawBot tool.", ) parser.add_...
# -*- coding: utf-8 -*- """ Solution to Project Euler problem 120 Author: Jaime Liew https://github.com/jaimeliew1/Project_Euler_Solutions """ def run(): S = 0 for a in range(3, 1001): r_max = 0 for n in range(1, a*2+2): r = ((a-1)**n + (a+1)**n)%a**2 if n == 1: ...
# !/usr/bin/env python # -*- coding:utf-8 -*- ############################################################## # Lempel-Ziv-Stac decompression # BitReader and RingList classes # # Copyright (C) 2011 Filippo Valsorda - FiloSottile # filosottile.wiki gmail.com - www.pytux.it # # This program is free software: you can red...
#!/usr/bin/env python3 """ Build model """ import tensorflow.keras as Keras def build_model(nx, layers, activations, lambtha, keep_prob): """ Build model """ model = Keras.Sequential() l2 = Keras.regularizers.l2(lambtha) model.add(Keras.layers.Dense( layers[0], activation=act...
import requests import logging import json import boto3 from botocore.exceptions import ClientError from urllib2 import build_opener, HTTPHandler, Request logger = logging.getLogger() logger.setLevel(logging.INFO) def get_secret(secret_name, ssm_endpoint_url, region_name): session = boto3.session.Session() c...
import logging import random import os import datetime import json import pytz import sentry_sdk from dff import dialogflow_extension import common.dialogflow_framework.utils.state as state_utils import common.dialogflow_framework.utils.condition as condition_utils from common.constants import CAN_CONTINUE_PROMPT, MUS...
#! /usr/bin/env python3 """dosomethingwith.py input: a file with file or directory names initially written to programmatically change directory names from a list produced using Double Commander copy, rename and adapt the below function(s) to suit your needs """ import sys import pathlib def reorder_names(temp_file)...
import logging import re import subprocess from anime_downloader.extractors.base_extractor import BaseExtractor from anime_downloader.sites import helpers from anime_downloader.util import eval_in_node logger = logging.getLogger(__name__) class Streamango(BaseExtractor): def _get_data(self): url = self...
# coding=utf-8 import pytest from mockito import verifyStubbedInvocationsAreUsed, when from epab.utils import _next_version, get_next_version CALVER = '2018.1.2' @pytest.fixture(autouse=True) def _mock_calver(): when(_next_version)._get_calver().thenReturn(CALVER) yield verifyStubbedInvocationsAreUsed()...
# -*- coding: utf-8 -*- model = { u'en ': 0, u'er ': 1, u' de': 2, u'der': 3, u'ie ': 4, u' di': 5, u'die': 6, u'sch': 7, u'ein': 8, u'che': 9, u'ich': 10, u'den': 11, u'in ': 12, u'te ': 13, u'ch ': 14, u' ei': 15, u'ung': 16, u'n d': 17, u'nd ': 18, u' be': 19, u'ver': 20, u'es ': 21, u' zu': 2...
# Exercise 01.3 # Author: Leonardo Ferreira Santos def quadratic(a, b, c): delta = (b ** 2 - 4 * a * c) x1 = (-b + delta ** (1 / 2)) / (2 * a) x2 = (-b - delta ** (1 / 2)) / (2 * a) solution = 0 if type(x1) != complex: solution = solution + 1 if type(x2) != complex: solution ...
from assets.models import * from assets.utils import * from assets.datasets import * from atkEnv.keys import * # secret keys stored here, ignored in git commits, *change this to .env file secret keys from sys import platform import time, base64 def detect( cfg, data_cfg, weights, imag...
"""Photo module.""" from __future__ import annotations import saas.storage.datadir as DataDirectory import saas.storage.refresh as refresh from saas.web.url import Url from abc import ABCMeta from typing import Type import uuid import os class Photo(metaclass=ABCMeta): """Base Photo class.""" def __init__( ...
from __future__ import annotations from abc import ABC, abstractmethod from logger.logger import Logger from config.config import Config from pathlib import Path from tensorflow import keras as K class BaseModel(ABC): def __init__(self): Logger.log(f"Initializing {self.__class__.__name__}...") sel...
#------------------------------------------------------------------------------- # Name: Go board recognition project # Purpose: Deep-learning network testing module # # Author: kol # # Created: 19.07.2019 # Copyright: (c) kol 2019 # License: MIT #----------------------------------------------...
import math from time import sleep print('='*30) print(' ') ang = int(input('Digite o valor do ângulo em graus: ')) angr = math.radians(ang) print('Calculando...') sleep(0.5) print(f'O seno de {ang}º é igual a: {math.sin(angr):.2f}\nO cosseno é igual a: {math.cos(angr):.2f}\nA tangente é igual a: {math.tan(angr):.2...
#!/usr/bin/python3 """ testbed for temperature, humidity, pressure and gas sensors """ # MIT License # # Copyright (c) 2019 Dave Wilson # # 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 with...
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from ... import _utilities fro...
from django.contrib.auth.mixins import LoginRequiredMixin from django.db.models import Q from django.shortcuts import render from django.urls import reverse_lazy from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView, RedirectView from .models import Post, Category from .forms impor...
# -*- coding: utf-8 -*- # Copyright (c) 2020 Niklas Rosenstein # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to # deal in the Software without restriction, including without limitation the # rights to use, copy, m...
"""Customizing a legend box""" from vedo import * s = Sphere() c = Cube().x(2) e = Ellipsoid().x(4) h = Hyperboloid().x(6).legend('The description for\nthis one is quite long') lb = LegendBox([s,c,e,h], width=0.3, height=0.4).font(5) show(s, c, e, h, lb, __doc__, axes=1, bg='ly', bg2='w', size=(1400,800), viewu...
# Author: Nam Nguyen Hoai # coding: utf-8 from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker import config import models _SESSION_FACTORY = None _ENGINE_FACTORY = None def setup_database_engine(): global _SESSION_FACTORY, _ENGINE_FACTORY engine = create_engine(config.DATABASE_URI, ...
"""Add administrator level to admin Revision ID: 26745016c3ce Revises: 3a731ce5846e Create Date: 2014-04-15 17:55:26.716534 """ # revision identifiers, used by Alembic. revision = '26745016c3ce' down_revision = '3a731ce5846e' from alembic import op import sqlalchemy as sa def upgrade(): op.execute("UPDATE Use...
__author__ = 'mpetyx' from django.conf.urls import patterns, include, url from django.contrib import admin from django.views.generic.base import TemplateView from tastypie.api import Api from .Resources import PhotoResource api = Api(api_name='media') api.register(PhotoResource()) urlpatterns = api.urls
with open("../in/input15.txt", "r") as file: data = [int(y) for y in [x.strip() for x in file.read().splitlines()][0].split(',')] occurences = {data[i-1]:[i] for i in range(1, len(data)+1)} current = data[-1] for i in range(len(data)+1,30000001): if len(occurences[current]) == 1: ...
# -*- coding: utf-8 -*- """ Fixtures for all abagen tests """ import os import pytest from abagen.datasets import (fetch_desikan_killiany, fetch_microarray, fetch_raw_mri, fetch_rnaseq) @pytest.fixture(scope='session') def datadi...
#!/usr/bin/env python #pythonlib import os import sys import re #appion from appionlib import appionLoop2 from appionlib import apFindEM from appionlib import apImage from appionlib import apDisplay from appionlib import apDatabase from appionlib import apPeaks from appionlib import apParticle from appionlib import ap...
from pymesh.TestCase import TestCase import pymesh import numpy as np class CurvatureTest(TestCase): def test_balls(self): ball_r1 = pymesh.generate_icosphere(1.0, [0.0, 0.0, 0.0], 4) ball_r2 = pymesh.generate_icosphere(2.0, [1.0, 0.0, 0.0], 4) ball_r3 = pymesh.generate_icosphere(3....
import pygame from game_objects.player import Player from utils import settings class HeadsUpDisplay: """User Interface Heads up Display Draws the Stats and Weapon/Magic to the game screen """ def __init__(self) -> None: # General Info: self.display_surface = pygame.display.get_s...
from Validation import * from enum import Enum class Type(Enum): econom = 1 standart = 2 comfort = 3 minibus = 4 class Taxi: @staticmethod def atributes(): return ["DriverName", "Type", "StartTime", "EndTime", "StartPlace", "EndPlace"] def __init__(self, *item): for i in ra...
import glob import os import scipy.io as sio from torch.utils.data import Dataset # Dataset class from PyTorch from PIL import Image, ImageChops # PIL is a nice Python Image Library that we can use to handle images import torchvision.transforms as transforms # torch transform used for computer vision applications impor...
# -*- coding: utf-8 -*- import requests from alf.tokens import Token, TokenError, TokenStorage from alf.adapters import mount_retry_adapter class TokenManager(object): def __init__(self, token_endpoint, client_id, client_secret, token_storage=None, token_retries=None): self._token_endp...
from keras import activations, layers from keras.utils.generic_utils import register_keras_serializable from keras.utils.tf_utils import shape_type_conversion @register_keras_serializable(package='TFSwin') class MLP(layers.Layer): def __init__(self, ratio, dropout, **kwargs): super().__init__(**kwargs) ...
from django.db import models # Create your models here. class MeditationSession(models.Model): date = models.DateField() time = models.TimeField() duration = models.IntegerField() def __str__(self): return "session " + str(self.id) + " @ " + str(self.time) + str(self.date) class Song(models.Model): session =...
# Copyright (c) Microsoft. All rights reserved. '''Some helper functions for PyTorch, including: - get_mean_and_std: calculate the mean and std value of dataset. - msr_init: net parameter initialization. - progress_bar: progress bar mimic xlua.progress. ''' import os import errno import logging import shuti...
from reputation.models import Withdrawal from user.tests.helpers import create_random_default_user ADDRESS_1 = '0x0000000000000000000000000000000000000000' ADDRESS_2 = '0x1123581321345589144233377610987159725844' def create_withdrawals(count): for x in range(count): user = create_random_default_user(f'w...