content
stringlengths
5
1.05M
import re import logging from typing import List, Dict from functools import lru_cache from datetime import datetime, timezone import pygsheets from sheet2linkml.model import ModelElement from sheet2linkml.source.gsheetmodel.mappings import Mappings from sheet2linkml.source.gsheetmodel.entity import Entity, EntityWo...
import matplotlib.pyplot as plt from matplotlib.patches import Circle, PathPatch from matplotlib.text import TextPath from matplotlib.transforms import Affine2D # This import registers the 3D projection, but is otherwise unused. from mpl_toolkits.mplot3d import Axes3D # noqa: F401 unused import import mpl_toolkits.mpl...
import pygame from pygame import sprite from settings import PROJECT_PATH, ENEMY_DEFAULT_SIZE, BRUTALISK_POINTS class Brutalisk(sprite.Sprite): def __init__(self, x_pos, y_pos): sprite.Sprite.__init__(self) self.image = pygame.transform.scale(pygame.image.load(PROJECT_PATH + ...
import utils.import_envs # noqa: F401 pylint: disable=unused-import from contrastive_highlights.Interfaces.frogger_interface import FroggerInterface from contrastive_highlights.Interfaces.gym_interface import GymInterface def get_agent(args): """Implement here for specific agent and environment loading scheme"...
import numpy import logging from blocks.bricks import Brick from blocks.select import Selector logger = logging.getLogger(__name__) def save_params(bricks, path): """Save bricks parameters. Saves parameters with their pathes into an .npz file. Parameters ---------- bricks : Brick or Selector ...
""" 56.19% """ # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def isSubtree(self, s, t): """ :type s: TreeNode :type t: TreeNode :rtype...
# 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, software # d...
from __future__ import division from typing import Optional, Union import numpy as np # type: ignore import cupy as cp # type: ignore from gepapy.operations import Operations class Single_Machine(Operations): """Single_Machine.""" def __init__( self, processing_time: Optional[Union[list, n...
import glypy from glypy.structure import constants, substituent, glycan from glypy.structure import link, named_structures, structure_composition from glypy.io import glycoct, linear_code from glypy.utils import StringIO, identity as ident_op, multimap, pickle, ET, enum structures = {} monosaccharides = glypy.monosac...
import setuptools setuptools.setup( name = "m-spacedog", packages = setuptools.find_packages(where = "python"), package_dir = { "" : "python" }, classifiers = ( "Programming Language :: Python ...
# Generic/Built-in import json import logging import os # Owned from cloudmesh.common.console import Console from cloudmesh.configuration.Config import Config from cloudmesh.storagelifecycle.StorageABC import StorageABC # Other import boto3 from botocore.exceptions import ClientError class Provider(StorageABC): ...
import requests import json import base64 import random from Sakurajima.models import ( Anime, RecommendationEntry, Relation, AniWatchEpisode, Episode, ChronicleEntry, UserAnimeListEntry, UserMedia, UserOverview, AniwatchStats, Notification, WatchListEntry, Media, ) f...
# # PySNMP MIB module CISCOSB-BRIDGE-SECURITY (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCOSB-BRIDGE-SECURITY # Produced by pysmi-0.3.4 at Wed May 1 12:21:55 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 ...
import json import logging from enum import Enum from http import HTTPStatus import pytz import requests from django.conf import settings from django.http import JsonResponse from django.utils import timezone from errors.views import ErrorCodes, getError from Users.utils import getUserByAccessToken # Get an instance ...
"""Read and process data for Instagram from Quintly.""" import datetime as dt import json from time import sleep from typing import Dict, Optional from django.db.utils import IntegrityError from django.db.models import Q, Sum from loguru import logger from sentry_sdk import capture_exception from ...models.insta imp...
sum_square = 0 sum = 0 for i in range(1,101): sum_square += i**2 sum +=i square_sum = sum**2 diff = square_sum - sum_square print(diff)
from error_matrix import ErrorMatrix from ensemble import Ensemble from model import Model import multiprocessing as mp import numpy as np import os class AutoLearner: def __init__(self, selected_algorithms='all', selected_hyperparameters='default', ensemble_size=3, ensemble_method='Logit', ...
from PIL import Image import glob, os, sys, face_recognition, itertools, subprocess, concurrent.futures, numpy, face_util global is_verbose global known_faces global known_encodings def print_help(): print(" ") print("Usage: ") print(" ") print("python3 sort.py [ -f faces-dir ] [ -t 0.5] [ -v ] [ -h ...
#!/usr/bin/env python # -*- coding: utf8 -*- import sys import tkinter import math scale = 4 robotSpeed = 6 robotSize = 22 * scale robotX = 600 robotY = 600 robotCatchZone = 30 robotForwarding = 4 ballSize = 7.4 * scale ballX = 600 ballY = 600 touchDistancingDeg = 1 #内側からの距離補正の次数.2以上だと加速度が滑らかに,1だと無駄な安定な点ができない touc...
from .node import Node class BreakNode(Node): """Key word BREAK""" __slots__ = () class ReturnNode(Node): """Key word RETURN""" __slots__ = ()
# from https://linked.data.gov.au/dataset/bdr/conservation-status-taxa-wa # in the sop_recipe_abis_model datagraphs CONSERVATION_STATUS_TAXA = [ "https://test-idafd.biodiversity.org.au/name/afd/70162908", "https://test-idafd.biodiversity.org.au/name/afd/70162916", "https://test-idafd.biodiversity.org.au/nam...
from collections import defaultdict import xmltodict begin_year = 2008 end_year = 2010 user_badges = defaultdict(set) with open('Badges.xml') as xml_file: for element in xml_file: if element.strip().startswith('<row'): row = xmltodict.parse(element)['row'] if begin_year <= int(ro...
import os import itertools import logging as L import numpy as np from perf_compare import execute L.basicConfig(format='%(levelname)s:%(message)s', level=L.DEBUG) class Autotune(): def __init__(self, template_list, key_values, cmd): """ template_list: ['GroupCOOSparseMatrix.h.t', 'cnnBench2.cu.t...
A= input('Digite a primeira nota:') B= input('Digite a segunda nota:') C= input('Digite a terceira nota:') D= input('Digite a quarta nota:') MA= (int(A)+int(B)+int(C)+int(D))/4 print ('A média aritmética é ',MA)
import time from CreeDictionary.utils.profiling import timed def test_timed_decorator(capsys): @timed(msg="{func_name} finished in {second:.1f} seconds") def quick_nap(): time.sleep(0.1) quick_nap() out, err = capsys.readouterr() assert "quick_nap finished in 0.1 seconds\n" == out
preço = float(input('Qual é o preço do produto RS')) desconto = preço - (preço * 5 / 100) print('O produto que custava {:.2f} na promoção com desconto de 5% vai custar {:.2f} RS'.format(preço, desconto, ))
# Executable to append voter-codes to voter records # Import external modules import argparse import random # Import app modules import security # Handle command-line arguments. parser = argparse.ArgumentParser() parser.add_argument( '--file', help='Path to file containing voter records as tab-separated-values', r...
from irods.session import iRODSSession import ssl import os class TuRODSSession(iRODSSession): def __init__(self, client_user=None): host = os.environ.get('IRODS_HOST', '') port = os.environ.get('IRODS_PORT', '') user = os.environ.get('IRODS_USER', '') ...
import numpy as np from nntoolbox.losses import PinballLoss import torch class TestPinball: def test_pinball(self): """ Adopt from https://www.tensorflow.org/addons/api_docs/python/tfa/losses/PinballLoss """ target = torch.from_numpy(np.array([0., 0., 1., 1.])) input = torc...
"""Tests for causal inference methods.""" import numpy as np import pytest import whynot as wn from whynot.algorithms import ols, propensity_score_matching, propensity_weighted_ols def generate_dataset(num_samples, num_features, true_ate=1.0, seed=1234): """Generate an observational dataset.""" np.random.see...
import pandas as pd import numpy as np from PIL import Image,ImageDraw,ImageFont from pandas.core.frame import DataFrame import requests import time from requests.api import options import streamlit as st from PIL import Image import requests from PIL import Image import requests import base64 data = pd.read_csv("da...
import smart_imports smart_imports.all() E = 0.001 class RaceInfo(typing.NamedTuple): race: rels.relations.Record percents: float optimal_percents: float persons_percents: float delta: float class Races(object): def __init__(self, races=None): if races is None: races...
# Copyright 2021, The TensorFlow Federated Authors. # # 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 o...
from gevent.hub import PYPY if PYPY: from gevent import corecffi as _core else: from gevent import corecext as _core for item in dir(_core): if item.startswith('__'): continue globals()[item] = getattr(_core, item) __all__ = _core.__all__
""" You are given a perfect binary tree where all leaves are on the same level, and every parent has two children. The binary tree has the following definition: struct Node { int val; Node *left; Node *right; Node *next; } Populate each next pointer to point to its next right node. If there is no next right nod...
""" .. automodule:: eumjeol_util 이 모듈은 Krcorpus에서 음절관련 기능을 담당하는 부분이다. 음절은 한국어에서 한글자를 의미하는 것으로 음절을 음소로 분해하거나 음소를 다시 음절을 합치는 등의 유틸리티 기능이 있다. """ import traceback #: 종성없음 JONGSUNG_TYPE_NONE = 1 #: 종성이 유음(ㄹ) JONGSUNG_TYPE_LIEUL = 2 #: 종성이 ㄹ을 제외한 받침 JONGSUNG_TYPE_COMMON = 3 _HANGUL_CODE_START = 44032 ...
#!/usr/bin/env python3 # coding=utf-8 """ debounced buttons for PyBadge HW: Adafruit PyBadge """ from adafruit_pybadger import pybadger from adafruit_debouncer import Debouncer ########################################## # main class class PyBadgeButtons(object): """PyBadgeButtons - debounced.""" def __in...
# install_certifi.py # # sample script to install or update a set of default Root Certificates # for the ssl module. Uses the certificates provided by the certifi package: # https://pypi.python.org/pypi/certifi import os import os.path import ssl import stat import subprocess import sys STAT_0o775 = (stat.S_IR...
from __future__ import print_function import time import argparse import grpc from jaeger_client import Config from grpc_opentracing import open_tracing_client_interceptor from grpc_opentracing.grpcext import intercept_channel import command_line_pb2 def run(): parser = argparse.ArgumentParser() parser.ad...
import os import sys from email.mime.text import MIMEText import smtplib import tempfile email_content = tempfile.NamedTemporaryFile(mode='w+t') smtp_server = "localhost" print >>email_content, "This is my content" print >>email_content, smtp_server print >>email_content, "Thank you for reading" email_content.seek(0...
#!/usr/bin/env python # -*- coding: utf-8 -*- import re import ast from os import path from setuptools import setup, find_packages here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'README.md'), 'rb') as readme_file: readme = readme_file.read().decode('utf-8') _version_re = re.compile(r'__v...
""" Administration for photos and galleries. """ from django.contrib import admin from django.db.models import Count from django.utils.translation import gettext_lazy as _ from .forms import PhotoForm from .models import Gallery, Photo class PhotoInline(admin.TabularInline): """ Administration for photos. ...
class Caesar: """ Summary: This is a class for text encryption using Caesar cipher algorithm. Attributes: crypto() """ def __init__(self, msg: str, key: int, mode: bool): """ The constructor for Caesar class. :param msg: The message to be encrypted. ...
from django.urls import path from onlineLibrary.books.views import home, add_book, book_details, edit_book, delete_book urlpatterns = [ path('', home, name='home'), path('add', add_book, name='add book'), path('details/<int:pk>', book_details, name='details'), path('edit/<int:pk>', edit_book, name='ed...
import cv2 # Lectura image = cv2.imread("../images/logo_platzi.png") # Escritura cv2.imwrite("logo_platzi2.png", image) # Visualización cv2.imshow("Logo de la razon de media vida nuestra", image) cv2.waitKey(0) cv2.destroyAllWindows()
import pandas as pd import numpy as np import sys,os import time import biosppy import pandas as pd import matplotlib.pyplot as plt import numpy as np import scipy from sliding.ecg_slider import ECGSlider from sliding.slider import Slider from statistic.wasserstein_distance import WassersteinDistance, WassersteinDista...
import numpy as np from typing import Tuple from .constants import ( DEFAULT_MAX_ITER, DEFAULT_CONC_PARAM, DEFAULT_SPLITSIZE, DEFAULT_SAMPLE_SIZE, DEFAULT_START_FRAME, ) class StateArrayParameters: """ Struct encapsulating settings for a complete state array analysis. init ---- ...
from django.shortcuts import render from django.http import HttpResponse # Create your views here. def forth_index(request): # 实例一,显示一个基本的字符串在网页上 # string = u'我交朋友不在乎你们有没有钱,反正都没我有钱,大家好,我是王思聪了解一下' # return render(request,'app_forth/forth_home.html',{'string':string}) # 实例二,讲解了基本的for 循环 和 List内容的显示 ...
def trailingZero(n): count = 0 i = 5 while (n/i >= 1): count += n/i i *= 5 return int(count) if __name__ == "__main__": print(trailingZero(12))
import socket import selectors selector = selectors.DefaultSelector() def server(): server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server_socket.bind(('localhost', 5000)) server_socket.listen() selector.regis...
# Copyright 2019 SUSE Linux GmbH # # 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 writ...
"""Implementation details to interact with the serialization means.""" import asyncio import datetime import json import math import dolon.db_conn as db_conn import dolon.exceptions as exceptions import dolon.impl.constants as constants # Aliases. DbConnection = db_conn.DbConnection _PREFETCH_SIZE = 100 async def ...
with open("day08.in") as f: INSTRUCTIONS = [line.strip() for line in f.readlines()] def execute(instrs): pc = 0 acc = 0 visited = set() while pc not in visited and pc < len(instrs): visited.add(pc) op, arg = instrs[pc].split() if op == "nop": pc += 1 e...
import os, sys, torch import os.path as osp import numpy as np import torchvision.datasets as dset import torchvision.transforms as transforms from copy import deepcopy from PIL import Image import random from config_utils import load_config import pdb import torch, copy, random import torch.utils.data as data Dataset...
# Generated by Django 3.1.7 on 2021-04-04 11:04 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('study', '0010_auto_20210404_1402'), ] operations = [ migrations.CreateModel( name='DerslerModel', fields=[ ...
# -*- coding: utf-8 -*- """The Symantec AV log file event formatter.""" from __future__ import unicode_literals from plaso.formatters import interface from plaso.formatters import manager from plaso.lib import errors class SymantecAVFormatter(interface.ConditionalEventFormatter): """Formatter for a Symantec AV lo...
import click from parsec.cli import pass_context, json_loads from parsec.decorators import custom_exception, dict_output, _arg_split @click.command('search_repositories') @click.argument("q", type=str) @click.option( "--page", help="page requested", default="1", show_default=True, type=int ) @clic...
# -*- coding:utf-8 -*- #!/usr/bin/env python import gevent from gevent import monkey monkey.patch_all(thread=False) from requests import get from filetype import guess from os import rename from os import makedirs from os.path import exists from json import loads from contextlib import closing from lxml import etree fr...
VENV_PREFIX = "pipenv run" _COMMON_TARGETS = ["pycon_archive_past_website", "tests"] COMMON_TARGETS_AS_STR = " ".join(_COMMON_TARGETS)
# post processing, add sequence and additional annoation info if available from six.moves.urllib.parse import urlencode from galaxy.datatypes.images import create_applet_tag_peek def exec_after_process(app, inp_data, out_data, param_dict, tool, stdout, stderr): primary_data = next(iter(out_data.values())) #...
import json from datetime import datetime from django.test import TestCase from django.utils import timezone from twitter_stream import settings from twitter_stream.models import Tweet class TweetCreateFromJsonTest(TestCase): def validate_json(self, tweet_json, correct_data): """ create_from_jso...
from sqlalchemy import (engine_from_config, MetaData, Table, Column, ForeignKey, PrimaryKeyConstraint, Index) from sqlalchemy.types import (SmallInteger, String, Integer, DateTime, Float, Enum, BINARY, Text, Date) from geoalchemy import (GeometryExtensionColumn, Point, GeometryDDL, MultiPolygon) engine = ...
import os import platform import re import subprocess import sys import sysconfig from distutils.version import LooseVersion from pathlib import Path from typing import List from setuptools import Extension class CMakeExtension(Extension): def __init__(self, name: str, sourcedir: str = "") -> None: super...
from student_code.simple_baseline_net import SimpleBaselineNet from student_code.experiment_runner_base import ExperimentRunnerBase from student_code.vqa_dataset import VqaDataset import torch from torchvision import transforms class SimpleBaselineExperimentRunner(ExperimentRunnerBase): """ Sets up the Simpl...
from .antispoof_processor import ProcessAntiSpoof
import pandas as pd import numpy as np from matplotlib import pyplot as plt from toolz import merge, curry from sklearn.preprocessing import LabelEncoder @curry def elast(data, y, t): return (np.sum((data[t] - data[t].mean())*(data[y] - data[y].mean())) / np.sum((data[t] - data[t].mean())**2)) ...
#!/usr/bin/env python """ This simple script scans website pai.pt for a particular category and prints the list of emails found. The emails found are printed one per line in the output (along with status messages) and also writen to a csv file called emails.csv with <email,category> structure It uses Bea...
# Generated by Django 3.1.5 on 2021-01-13 03:17 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('supermap', '0003_auto_20210112_1506'), ] operations = [ migrations.AddField( model_name='businesscircle', name='coun...
from . import AWSObject, AWSProperty from .validators import * from .constants import * # ------------------------------------------- class KinesisStream(AWSObject): """# AWS::Kinesis::Stream - CloudFormationResourceSpecification version: 1.4.0 { "Attributes": { "Arn": { "PrimitiveTy...
import pytest from meltano.core.m5o.m5o_file_parser import MeltanoAnalysisFileParser class TestMeltanoAnalysisFileParser: @pytest.fixture def subject(self, project): return MeltanoAnalysisFileParser(project) def test_parse(self, add_model, subject): topics = subject.parse_packages() ...
from flask import Flask from delivery.extensions import config def create_app(): """Create main factory""" app = Flask(__name__) config.init_app(app) return app
# This file is subject to the terms and conditions defined in # file 'LICENSE.md', which is part of this source code package. # Embedded-solutions 2017-2020, www.microdaq.org import microdaq # connect to MicroDAQ device mdaq = microdaq.Device("10.10.1.1") # read data from channels 1..4, input range from -10V to 10V,...
# -*- coding: utf-8 -*- """The module finding similarity ratio between two strings."""
import keras import numpy as np from keras import optimizers from keras.models import Sequential, load_model from keras.layers import Conv2D, Dense, Flatten, MaxPooling2D from keras.callbacks import LearningRateScheduler, TensorBoard, ModelCheckpoint from keras.preprocessing.image import ImageDataGenerator from keras.r...
#!/usr/bin/env python3 import rospy, tf, actionlib import actionlib_msgs.msg from rosplan_planning_system.ActionInterfacePy.RPActionInterface import RPActionInterface from std_srvs.srv import Empty from geometry_msgs.msg import PoseStamped from move_base_msgs.msg import MoveBaseAction, MoveBaseGoal from high_level_r...
import csv import glob import math import os import sys from random import random, seed import socket from timeit import default_timer as timer import time from statistics import mean from pathlib import Path import networkx as nx import numpy as np from scapy.layers.inet import IP, UDP from scapy.utils import PcapWrit...
def negate(x: float): return -x def add(x: float, y: float): return x + y def subtract(x: float, y: float): return x - y def multiply(x: float, y: float): return x * y def divide(x: float, y: float): return x / y
# 6-svep.py import time import board import neopixel pixel_pin = board.A0 # På vilken pinne sitter pixeln num_pixels = 1 # Hur många pixlar pixels = neopixel.NeoPixel(pixel_pin, num_pixels, brightness=0.3, auto_write=False) def lysa(color): pixels.fill(color) # Fyll pixeln med färg pixels.show() # Tänd pixel...
from Jumpscale import j from Jumpscale.core.InstallTools import Tools import os import sys Tools = j.core.tools MyEnv = j.core.myenv class SSHAgent(j.application.JSBaseClass): __jslocation__ = "j.clients.sshagent" def _init(self): if MyEnv.sshagent: self._default_key = None ...
import os import lmdb # install lmdb by "pip install lmdb" from PIL import Image def checkImageIsValid(file): valid = True try: Image.open(file).load() except OSError: valid = False return valid def writeCache(env, cache): with env.begin(write=True) as txn: for k, v in cac...
import sys sys.path.append('../../wrapper/') import cxxnet import numpy as np data = cxxnet.DataIter(""" iter = mnist path_img = "./data/train-images-idx3-ubyte.gz" path_label = "./data/train-labels-idx1-ubyte.gz" shuffle = 1 iter = end input_shape = 1,1,784 batch_size = 100 """) print 'init data iter' de...
#!/usr/bin/env python # -*- coding: utf-8 -*- """Setup package.""" from setuptools import setup, find_packages from setuptools.command.sdist import sdist from setuptools.command.build_py import build_py import sys import os import importlib.util class BuildPy(build_py): """Custom ``build_py`` command to always bu...
import os import pytest from endpoint import app HOT_DOG_URL='https://upload.wikimedia.org/wikipedia/commons/thumb/f/fb/Hotdog_-_Evan_Swigart.jpg/320px-Hotdog_-_Evan_Swigart.jpg' TACO_URL='https://upload.wikimedia.org/wikipedia/commons/thumb/7/73/001_Tacos_de_carnitas%2C_carne_asada_y_al_pastor.jpg/320px-001_Tacos_de...
import numpy as np from .core import Signal, signal @signal class Operation(Signal): left: Signal right: Signal class Plus(Operation): """Add a signal and a signal or value. >>> one = Value(1) >>> two = Value(2) >>> result = 3 + one + two + 3 >>> result.render_frame() >>> assert n...
import numpy as np import time import cv2 import copy import os import os.path as path import imageio from scipy.spatial.transform import Rotation as R import matplotlib.pyplot as plt import argparse from numpy.linalg import inv import torch from train_network import data_transform import train_network import tools d...
import json import logging import os import socketio from threading import Thread from flask import Flask from urllib.parse import parse_qs, urlparse from jose import jwt import jose.exceptions from models import Option from monitoring.constants import LOG_SOCKETIO from monitoring.database import Session session ...
""" During the 70s and 80s, some handheld calculators used a very different notation for arithmetic called Reverse Polish notation [http://en.wikipedia.org/wiki/Reverse_Polish_notation] (RPN). Instead of putting operators (+, *, -, etc.) between their operands (as in 3 + 4), they were placed behind them: to calculate 3...
# Licensed to Modin Development Team under one or more contributor license agreements. # See the NOTICE file distributed with this work for additional information regarding # copyright ownership. The Modin Development Team licenses this file to you under the # Apache License, Version 2.0 (the "License"); you may not u...
#!/usr/bin/env python import pygame, sys, os, time, random from pygame.locals import * # optional if not pygame.font: print 'Warning, no fonts' if not pygame.mixer: print 'Warning, no sound' pygame.init() def loadImage(filename): return pygame.image.load(os.path.join(filename)) paddle_surface = loadImage("paddl...
# General imports import argparse # Data imports from aides_dataset import AidesDataset # Models imports from bertopic import BERTopic # BERTopic for topic modeling from transformers import pipeline # We will load XNLI for zeroshot classification if __name__=="__main__": parser = argparse.Argu...
def isCaseInsensitivePalindrome(inputString): ''' Given a string, check if it can become a palindrome through a case change of some (possibly, none) letters. ''' lowerCase = inputString.lower() return lowerCase == lowerCase[::-1] print(isCaseInsensitivePalindrome("AaBaa")) print(isCaseInsensitiveP...
# -*- coding: utf-8 -*- """ DATS_6501: Capstone Spring 2020 """ import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import Toolbox as tls #Import data df2018 = tls.dataClean('psam_', 2018) df2018 = tls.additionalClean(df2018) X = df2018.iloc[:,:-1] catCols = X.columns[:10] numC...
def fib_num(n): f_1 = 0 f_2 = 1 f_3 = 1 even_fib = [] while f_3 <= n: if f_3 % 2 == 0: even_fib.append(f_3) f_1 = f_2 f_2 = f_3 f_3 = f_1 + f_2 print(even_fib) return sum(even_fib)
import sys input = sys.stdin.readline sys.setrecursionlimit(10 ** 7) x = int(input()) if x >= 0: print(x) else: print(0)
from collections import namedtuple import pandas as pd import numpy as np from etfl.io.json import load_json_model from etfl.optim.config import standard_solver_config, growth_uptake_config from etfl.optim.variables import GrowthActivation, BinaryActivator, \ mRNAVariable, EnzymeVaria...
# Copyright 2019 BDL Benchmarks 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 applica...
import torch import numpy as np from tqdm import tqdm from time import time import sys from os.path import join import lpips from Hessian.GAN_hessian_compute import hessian_compute from torchvision.transforms import ToPILImage from torchvision.utils import make_grid ImDist = lpips.LPIPS(net='squeeze').cuda() use_gpu = ...
"""Script to get the air quality based on the user's current location""" import sys import requests as req if __name__ == "__main__": if len(sys.argv) > 1: url = "https://api.waqi.info/feed/here/?token=" + sys.argv[1] response = req.get(url, verify=False) if response.json()['status'] == "...
import timeit HASHES = [ ("pyblake2", "blake2b"), ("pyblake2", "blake2s"), ("hashlib", "md5"), ("hashlib", "sha1"), ("hashlib", "sha256"), ("hashlib", "sha512"), ] SIZES = [64, 128, 1024, 2047, 2048, 1000000] SETUP_CODE = """ from {mod} import {fn} as hasher data = b'x'*{size} """ BENCH_...
import os import sys cmd = "/workspace/onnxruntime_training_bert {}".format(" ".join(sys.argv[1:])) print(cmd) os.system(cmd)