content
stringlengths
5
1.05M
from .utils import add_dok from typing import List, Optional, Dict, Tuple ItemState = int ItemID = str def count(evaluations: List[Tuple[List[ItemState], List[ItemID]]], direct_dok: Optional[Dict[Tuple[ItemID, ItemID], int]] = None, direct_detail: Optional[Dict[Tuple[ItemID, ItemID], int]] = None,...
import logging import os import random import threading import time # https://pypi.python.org/pypi/python-daemon/ from daemon import runner from queue import Queue BASE_DIR = os.path.dirname(os.path.abspath(__file__)) class ProducerThread(threading.Thread): def __init__(self, group=None, target=None, name=None...
# -*- coding: utf-8 -*- """Thils file set ups matplotlib plot functions for the whole package. Import all necessary Matplotlib modules and set default options To use this module, import * from it: Examples -------- >>> from crtomo.mpl_setup import * """ import sys already_loaded = 'matplotlib' in sys.modules #...
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.response.AlipayResponse import AlipayResponse class AnttechBlockchainFinancePfApplySendResponse(AlipayResponse): def __init__(self): super(AnttechBlockchainFinancePfApplySendResponse, self).__init__() self._financing_i...
#!/usr/bin/env python from __future__ import division import time, array import rospy import numpy as np from aclswarm_msgs.msg import Formation from snapstack_msgs.msg import QuadGoal from std_msgs.msg import UInt8MultiArray from geometry_msgs.msg import Point, PoseStamped, Vector3, Vector3Stamped from visualizatio...
from ikaTools.main import *
a=input('enter a paragraph').split(' ') b=input('find-') for i in range(len(a)): for j in range(len(b)): if(a[i]==b): print(a[i])
import unittest from datetime import datetime from unittest.mock import Mock, patch from uuid import uuid4 from registry.constants import OrganizationStatus, Role, OrganizationMemberStatus from registry.consumer.organization_event_consumer import OrganizationCreatedAndModifiedEventConsumer from registry.infrastructure...
""" Notes: This script generates data for the pictures in part 5.2.1 and 5.2.2. The authors mention, in 5.2.1, that all tokens come from 5000 sentences; however, the entire dataset includes 5.9M sentences and they do not mention how those 5000 sentences are selected. I will select the first 5000 sentences for now for ...
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! """Client and server classes corresponding to protobuf-defined services.""" import grpc from alphausblue.api import operation_pb2 as api_dot_operation__pb2 from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2 from alphausblue....
from .dbscan import ( dbscan_labels, get_largest_dbscan_clusters, segment_dbscan, ) from .segRedStick import ( get_red_mask, ) from .boundary import ( boundary_of_center_object, boundary_of_drivemap, boundary_of_lowest_points, ) __all__ = [ 'dbscan_labels', 'get_larges...
from app import app from datetime import * from app import db from flask import url_for from werkzeug.security import generate_password_hash, check_password_hash from flask_login import UserMixin from app import login from hashlib import md5 from flask_sqlalchemy import SQLAlchemy import sys class User(UserMixin, db....
# ========================= eCAL LICENSE ================================= # # Copyright (C) 2016 - 2019 Continental 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...
import rich def print_name(): print( """ ████████╗░██████╗░░█████╗░░█████╗░██╗░░░██╗███╗░░██╗████████╗███████╗██████╗░ ╚══██╔══╝██╔════╝░██╔══██╗██╔══██╗██║░░░██║████╗░██║╚══██╔══╝██╔════╝██╔══██╗ ░░░██║░░░██║░░██╗░██║░░╚═╝██║░░██║██║░░░██║██╔██╗██║░░░██║░░░█████╗░░██████╔╝ ░░░██║░░░██║░░╚██╗██║░░██╗██║░░...
from typing import Any, Callable, List, Type, Union, Optional from fastapi import APIRouter, Depends from pydantic import BaseModel from starlette import status from starlette.exceptions import HTTPException from starlette.requests import Request from .schema import BaseApiOut, ItemListSchema, CrudEnum, Paginator fro...
import requests import time from datetime import date, datetime from bs4 import BeautifulSoup from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By # Enforce incognito mode chro...
""" Module for parsing SPDI variant descriptions. """ import os from lark import Lark def _read_grammar_file(file_name): grammar_path = os.path.join(os.path.dirname(__file__), f"ebnf/{file_name}") with open(grammar_path) as grammar_file: return grammar_file.read() class SpdiParser: """ SPD...
from external import wxPyPlot import gen_utils from module_base import ModuleBase from module_mixins import IntrospectModuleMixin import module_utils try: import Numeric except: import numarray as Numeric import vtk import wx class histogram1D(IntrospectModuleMixin, ModuleBase): """Calculates and sh...
from setuptools import setup, find_packages from codecs import open from os import path from sauna import __version__ as version here = path.abspath(path.dirname(__file__)) # Get the long description from the README file with open(path.join(here, 'README.rst'), encoding='utf-8') as f: long_description = f.read()...
# Створити список з 12 елементів lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] # Добавити в середину списку новий елемент зі значенням 56 ( середина має обчислюватися автоматично ) l = len(lst) middle = l // 2 lst.insert(middle, 56) print(lst) # Обновити 2й елемент до 25 lst[2]= 25 print(lst) # Додати в кінець сп...
""" Write a Python program to find all the common characters in lexicographical order from two given lower case strings. If there are no common letters print "No common characters". """ from collections import Counter def common_chars(str1, str2): d1 = Counter(str1) d2 = Counter(str2) common_dict = d1 & d2 ...
#!/usr/bin/env python # -*- coding: utf-8 -*- import os demoDataYaml=""" linksDemoData: mySites: google: www: https://google.fr gitlab: www: gitlab.fr """ def getDemoData(): return demoDataYaml def register(config_dict,st_dict): st_dict["type"]="www" st_dict["content"]=config_d...
#!/usr/bin/env python3 # # Copyright (c) 2020 Miklos Vajna and contributors. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ The config module contains functionality related to configuration handling. It intentionally doesn't import any other 'own' modules, so ...
class Song(object): def __init__(self, path): self.path = path def seekAndPlay(self, seconds): raise NotImplementedError() def stop(self): raise NotImplementedError()
import argparse def str2bool(v): if isinstance(v, bool): return v # pylint: disable=no-else-return if v.lower() in ("yes", "true", "t", "y", "1"): return True elif v.lower() in ("no", "false", "f", "n", "0"): return False else: raise argparse.ArgumentTypeError("Bool...
from flask import Blueprint from flask_jwt_extended import verify_jwt_in_request from pluggy import HookimplMarker from .category import _register_routes as register_category_routes from .forum import _register_routes as register_forum_routes from .topic import _register_routes as register_topic_routes from .post impo...
#Nihar T. #Shimona P. #Pratibha A. import paramiko import threading import socket import logging import sys from datetime import date import os today = date.today() HOST_KEY = paramiko.RSAKey(filename='server.key') PORT = 2222 logfile = 'loggers/ssh_honeypot_{}.logging'.format(today.strftime('%m_%d_%Y')) logging.bas...
import pygame from states.basestate import BaseState class HighScoresState(BaseState): pass
'''ABSTRACT This program shows an example of using PyBenchFCN to do optimization. The sample code shows a differential evolution algorithm solving 10-D rastrigin function. With a numpy seed of 1001, the result should be the same as what is shown in the end of this file. For the further information, please visit https:/...
penta2 = lambda x: x * (3*x - 1) / 2 set_of_pentas = set(penta2(i) for i in range(1, 10001)) D = lambda j, k: int(abs(penta2(j) - penta2(k))) for a in range(1, 2500): for k in range(2, 2500): if a <= k: pa, pk = penta2(a), penta2(k) if abs((pa - pk)) in set_of_pentas and (pa + pk) i...
from utils.constants import * import torch.nn as nn import torchvision.models.vgg as vgg import torchvision def deeplabv3_segmentation(n_classes): model = torchvision.models.segmentation.deeplabv3_resnet101(pretrained=False, progress=True, num_classes=n_classes, aux_loss=None) model = model.to(DEVICE) re...
from unittest import TestCase import os from mock import patch from configuration_py.configuration_load import _generate_possible_paths_to_config class TestGeneratePossiblePathsToConfig(TestCase): @patch('configuration_py.configuration_load._generate_possible_config_file_names', return_value=['testconfig.yaml'...
""" MIT License Copyright (c) 2021 Emc235 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, modify, merge, publish, distri...
import re import math from os import system import sys import traceback def inlst(lst, value, key=lambda x:x): for i in range(len(lst)): each = lst[i] if key(each) == value: return i return -1 recipes = {} def main(): global recipes ...
from latex import build_pdf from latex.build import LatexMkBuilder # the example below should not compile on pdflatex, but on xelatex min_latex = r""" \documentclass[12pt]{article} \usepackage{fontspec} \setmainfont{Times New Roman} \title{Sample font document} \author{Hubert Farnsworth} \date{this month, 2014} ...
"""module for required modifier.""" from __future__ import annotations from typing import TYPE_CHECKING from ..fdef import Fdef from .modifier import Modifier from ..fdef import FStore from ..jconf import JConf from ..isjsonclass import isjsonobject if TYPE_CHECKING: from ..ctx import Ctx class RequiredModifier(M...
import os import pytest import numpy as np from PIL import Image from .. import PDFExtractorSegmenter expected_text = "A cat poem\nI love cats, I love every kind of cat,\nI just wanna hug all of them, but I can't," \ "\nI'm thinking about cats again\nI think about how cute they are\nAnd their whisker...
from collections import OrderedDict from decimal import Decimal from django.urls import reverse from silver.tests.api.specs.metered_feature import spec_metered_feature from silver.tests.api.utils.path import absolute_url def spec_plan(plan): return OrderedDict([ ("name", plan.name), ("url", abso...
#!/usr/bin/env python # -- coding: utf-8 -- __version__ = '1.0.8' from .tools import *
# Generated by Django 2.1.3 on 2018-11-05 15:49 from django.conf import settings from django.db import migrations, models import django.db.models.deletion import django_simple_coupons.helpers class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(sett...
# Copyright 2021 IBM All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed t...
''' Response objects are generated by a gateway after data is sent back from Veritrans about a request. Response formats can vary depending on the type of error encountered from Veritrans, so the only two parameters that are required for ALL responses are status_code, and status_message. The rest are all purely option...
from flask import Blueprint from flask_saml2.exceptions import CannotHandleAssertion from .views import ( AssertionConsumer, CannotHandleAssertionView, Login, LoginIdP, Logout, Metadata, SingleLogout) def create_blueprint(sp): idp_bp = Blueprint(sp.blueprint_name, 'flask_saml2.sp', template_folder='temp...
"""Provides an interface to send messages to the Message Queue.""" from __future__ import absolute_import, unicode_literals import datetime import sys from enum import Enum from django.conf import settings from django.utils import timezone import boto3 from data_refinery_common.enums import Downloaders, ProcessorP...
# solution1: performance is not very good # Array concatenation takes time. class Solution(object): def inorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ # Pattern: Stop when root is None if root == None: return [] ...
import os import sys from glob import glob from setuptools import Extension, find_packages, setup try: from tableauhyperapi.impl.util import find_hyper_api_dll except ImportError: # renamed in version 0.0.10309 from tableauhyperapi.impl.util import find_hyper_api_library as find_hyper_api_dll here = os.pat...
#!/usr/bin/env python # -*- mode: python; coding: utf-8 -*- ''' CLI tool to get basic info from ethereum via JSON-RPC ''' from ethtoollib.eth_rpc import * from ethtoollib.eth_util import * import argparse def main(): ''' Main function ''' parser = argparse.ArgumentParser(add_help=True) parser.add_argumen...
import typing from datetime import datetime from diem import txnmetadata from offchain import CommandRequestObject, GetPaymentInfo from offchain.types import ( GetInfoCommandResponse, InitChargePaymentResponse, PaymentInfoObject, ) from wallet import storage from wallet.services.offchain import utils from ...
from docx.shared import Pt from docx.enum.text import WD_ALIGN_PARAGRAPH from matplotlib import font_manager class FontFeature: @staticmethod def system_font(): raw_list = font_manager.findSystemFonts(fontpaths=None, fontext='ttf') font_list = [] for font in raw_list: cutof...
from typing import Iterable, List, Optional, TYPE_CHECKING import os import numpy as np from skimage.color import label2rgb from skimage.color.colorlabel import DEFAULT_COLORS import torch from catalyst import utils from catalyst.callbacks import ILoggerCallback from catalyst.contrib.tools.tensorboard import Summary...
#! /usr/bin/env python3 from subprocess import call call(['/usr/bin/python3 /home/pi/powerpi/reader/reader.py 2>/dev/null'], shell=True)
# set represent unique value myset = set(); print(myset) myset.add(1) myset.add(2) print(myset)
#! /usr/bin/env python3 # -*- coding: utf-8 -*- import enum import sys # pylint: disable=unused-import import urwid class MODIFIER_KEY(enum.Enum): """Represents modifier keys such as 'ctrl', 'shift' and so on. Not every combination of modifier and input is useful.""" NONE = "" SHIFT = "shi...
from __future__ import annotations import traceback import uuid from enum import Enum from typing import Union, NamedTuple, Callable, Awaitable, Optional, List, TypeVar, Dict, cast from async_generator import async_generator, yield_, asynccontextmanager from pydantic import BaseModel, Json from starlette.requests imp...
__version__ = '0.0.1' from .pdfcutter import PDFCutter # noqa
#!/usr/bin/env python """Tests for `generalrepytivity` package.""" import generalrepytivity as gr import sympy t, x, y, z = sympy.symbols('t x y z') e0, e1, e2, e3 = sympy.symbols('e_0 e_1 e_2 e_3') def test_return_value_tensor(): dict_of_values = { ((), (0,0)): -1, ((), (1,1)): 1, ((), ...
# -*- coding: utf-8 -*- # # Copyright 2015 Google 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.org/licenses/LICENSE-2.0 # # Unless requir...
import sys import unittest from contextlib import ContextDecorator import gcontext as g class TestCase(unittest.TestCase): def run(self, result): with g.add_context({'result': result}, {'testcase': self}): return super().run(result) class SubTest(unittest.TestCase): parent = g.Context...
#!/usr/bin/env python2 from __future__ import print_function import collections import curses import math import random from drawille import Canvas, line class Widget(object): def __init__(self, scr, enc="utf-8", name="Widget"): self.borders = { "tl": u"\u250C".encode(enc), "bl": u"\u2514".encode(enc), "t...
from __future__ import annotations import asyncio from collections import deque from typing import Any, Awaitable, Optional, Union import aiohttp from ..auth import Auth from ..store import DataStore, DataStoreManager from ..typedefs import Item from ..ws import ClientWebSocketResponse class BinanceDataStore(DataS...
import numpy as np from collections import Counter import collections import csv import re def check_odds(): expected_probability = (5/69) while 1 == 1: numbers_im_looking_for_input = "["+input("Please type in a comma separated list of the numbers you're looking for. Or, type 'quit' to quit. ")+"]" ...
# MenuTitle: Create a perpendicular guide from another guide. # -*- coding: utf-8 -*- from __future__ import division, print_function, unicode_literals from Foundation import NSPoint __doc__=""" Create a perpendicular guide from another guide. Select a guide and run it. """ font = Glyphs.font glyphs = font.glyphs ...
import datetime import json from random import randint from typing import Optional, List from types import CoroutineType from urllib.parse import urlencode from faker import Faker from sqlalchemy.engine import Connection from tracker.db.schema import ( UserRoleEnum, projects_table, roles_table, users_table ) fa...
from django import template from metashare.settings import MEDIA_URL from metashare.repository.model_utils import get_resource_license_types from replace import pretty_camel register = template.Library() @register.filter("licence_icon") def licence_icon(licence): if licence == "non-standard/Other_Licence/Terms": ...
from sklearn.base import BaseEstimator, TransformerMixin from sklearn.preprocessing import LabelEncoder, OneHotEncoder, OrdinalEncoder import numpy as np import pandas as pd from ml_tools.helpers import Logging class EncoderTransformer(BaseEstimator, TransformerMixin): def __init__(self, method: str = 'label', ...
import mysql.connector import dbconfig as cfg db = mysql.connector.connect( host=cfg.mysql['host'], user=cfg.mysql['user'], password=cfg.mysql['password'], ) cursor = db.cursor() sql="CREATE DATABASE datarepresentation" cursor.execute(sql)
import setuptools with open("README.md", "r") as fh: readme = fh.read() with open("CHANGES.md", "r") as fh: changes = fh.read().replace("# Changelog", "Changelog\n=========\n") long_description = "%s\n\n%s" % (readme, changes) with open("requirements-no-dev.txt", "r") as fh: requirements = [line.rstrip() ...
from hcrystalball.model_selection import ModelSelector from hcrystalball.utils import generate_multiple_tsdata from hcrystalball.wrappers import get_sklearn_wrapper from sklearn.linear_model import LinearRegression from hcrystalball.model_selection import load_model_selector import os import pytest def test_model_sel...
import random import pylab def flipPlot(minExp, maxExp): ratios = [] diffs = [] xAxis = [] for exp in range(minExp, maxExp + 1): xAxis.append(2**exp) for numFlips in xAxis: numHeads = 0 for n in range(numFlips): if random.random() < 0.5: ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Sep 13 13:34:04 2019 @author: ana """ import numpy as np import qiskit import json import time import zmq from numpy import linalg as LA from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit import BasicAer, execute from qis...
"""Console script for amazon_gift_reload.""" import argparse import sys import getpass from .amazon_gift_reload import AmazonGiftReloader def main(): """Console script for amazon_gift_reload.""" parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter ) parser....
# coding:utf-8 import requests from bs4 import BeautifulSoup import re # 検索したい文字列 product = input("検索したい商品名を入力してください:") # 何ページ分スクレイピングするか page_count = int(input("何ページ分実行しますか?(半角数):")) # 何件以上の入札分を出力するか bid_count = int(input("何件以上の入札分を出力しますか?(半角数):")) # 出力ファイル名 file = "sample.txt" page = 1 i = 0 while i < page_count:...
"""Unit testing of the Popular Books Recommender Methods""" import numpy as np from django.test import TestCase, tag from RecommenderModule.recommenders.resources.popular_books_recommender_methods import PopularBooksMethods from RecommenderModule.recommenders.resources.data_provider import DataProvider import math @t...
import os import tempfile from infra_buddy.aws import s3 as s3util from infra_buddy.aws.cloudformation import CloudFormationBuddy from infra_buddy.aws.s3 import S3Buddy from infra_buddy.deploy.deploy import Deploy from infra_buddy.utility import print_utility class S3Deploy(Deploy): def __init__(self, artifact_i...
from interactions.utils.loot_basic_op import BaseLootOperation from rewards.reward import Reward import sims4.log logger = sims4.log.Logger('RewardOperation', default_owner='rmccord') class RewardOperation(BaseLootOperation): FACTORY_TUNABLES = {'reward': Reward.TunableReference(description='\n The rewa...
""" The Nodes used in the DAG as nodes for the networkx.DiGraph """ import dataclasses from typing import List from mlinspect.inspections._inspection_input import OperatorContext @dataclasses.dataclass(frozen=True) class CodeReference: """ Identifies a function call in the user pipeline code """ line...
""" domonic.ext ==================================== This dir is for extending domonic to be useable with other python libs. """ # HELLO WORLDS - hello world code for other libs # "django" # "bottle" # "pyramid" # "werkzeug" # "tornado" # "aiohttp" # "fastapi" # "starlette" # "blacksheep" # "muffin" # "f...
_clang_tidy_repo_build_file_contents = """ alias( name = "clang-tidy", visibility = ["//visibility:public"], actual = "{clang_tidy_path}", ) """ def _clang_tidy_repo_impl(rctx): clang_tidy_path = rctx.which("clang-tidy") if clang_tidy_path == None: fail("Cannot find clang-tidy in PATH") ...
__version__ = '0.1.0' from .heap import MaxHeap, MinHeap from .trie import Trie from .stack import Stack from .queue import Queue from .linkedlist import SinglyLinkedList
""" Sphinx extension to add ReadTheDocs-style "Edit on GitHub" links to the sidebar. Loosely based on https://github.com/astropy/astropy/pull/347 Modified by NEM to get the feedback url. """ import os import warnings __licence__ = 'BSD (3 clause)' def get_github_url(app, view, path): return 'https://github.co...
import numpy as np class Layer(object): """ An "abstract" class that represents the layer in the network ... Attributes ---------- previous : Layer object previous layer in the network's queue of layers next : Layer object next layer in the queue of layers in the network ...
from sqlalchemy import Column, Integer, String from app.db.base_class import Base class Status(Base): __tablename__ = 'status' id = Column(Integer, primary_key=True, index=True, autoincrement=True) status = Column(String(100), unique=True, index=True)
from eflow._hidden.parent_objects import FileOutput from eflow._hidden.custom_exceptions import PipelineSegmentError, UnsatisfiedRequirments from eflow.utils.sys_utils import dict_to_json_file,json_file_to_dict,get_all_files_from_path, create_dir_structure from eflow.utils.string_utils import create_hex_decimal_string ...
# Generated by Django 3.0.6 on 2020-06-20 19:02 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('luchapp', '0003_product'), ] operations = [ migrations.AlterField( model_name='payment', name='day_paid', ...
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. from os.path import join import abc import time import os import numpy as np import tensorflow as tf from tensorflow import keras from reco_utils.recommender.deeprec.deeprec_utils import cal_metric __all__ = ["BaseModel"] ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # author:denghuabing@cecgw.cn # date:2017/11/16 # version:1.0 import smtplib import glob import re import os import sys from email.mime.multipart import MIMEMultipart from email.mime.base import MIMEBase from email import encoders from email.mime.image import MIMEImage d...
"""This module holds serializers and constants used across the Marsha project.""" import re from django.core.exceptions import ValidationError from rest_framework import serializers from ..defaults import ERROR, HARVESTED, PROCESSING, READY, STATE_CHOICES from ..models import TimedTextTrack from ..utils import time_...
#!/usr/bin/env python3 # McGraw hill express library ebook downloader. # Copyright (c) 2020 Anoop S. Licensed under the MIT license (see LICENSE.txt). import requests import argparse import subprocess import os import platform from sys import argv import re import tarfile # colors GREEN = '\033[32m' YELLOW = '\033[33m...
import os from acs.instance import Instance from read.algorithm import open_results dir = os.path.dirname(__file__) instance = Instance.load_from_file(os.path.join(dir,'instances','real', 'instance.txt')) concept_coverage = instance.concepts_materials.T objectives = instance.objectives _acs_results = open_results(...
from bitmovin_api_sdk.encoding.outputs.ftp.ftp_api import FtpApi from bitmovin_api_sdk.encoding.outputs.ftp.customdata.customdata_api import CustomdataApi from bitmovin_api_sdk.encoding.outputs.ftp.ftp_output_list_query_params import FtpOutputListQueryParams
from app.economics.fee_counter.normal_counter import NormalCounter def test_count_chargeLessThanMinFee_returnsMinFee(): fee_min = 5.0 fee_rate = 1.0 fee_added = 0.0 fee_max = 10.0 charge = 1.0 counter = NormalCounter(fee_min, fee_rate, fee_added, fee_max) fee = counter.count(charge) ...
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) # ---------------------------------------------------------------------------- # If you submit this package back to Spack ...
# Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ An example of an XML-RPC server in Twisted. Usage: $ python xmlrpc.py An example session (assuming the server is running): >>> import xmlrpclib >>> s = xmlrpclib.Server('http://localhost:7080/') >>> s.echo("lala") ['lala...
"""Partition Equal Subset Sum""" class Solution(object): def canPartition(self, nums): """ :type nums: List[int] :rtype: bool """ ## practice: if sum(nums)%2 != 0: return False target = sum(nums)/2 dp = [1]+[0]*target for num in nu...
# Copyright © 2019 Province of British Columbia # # Licensed under the Apache License, Version 2.0 (the 'License'); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agr...
import numpy as np from ...tests.instance import gaussian_group_instance from ..approx_reference_grouplasso import group_lasso, approximate_grid_inference def test_approx_pivot(n=500, p=200, signal_fac=0.1, sgroup=3, groups=np.ara...
import unittest import os import itertools import pandas as pd import numpy as np import TRANSPIRE.utils import TRANSPIRE.data THIS_DIR = os.path.dirname(os.path.abspath(__file__)) class TestUtils(unittest.TestCase): def setUp(self): self.data = TRANSPIRE.data.import_data.load_data(os.path.join(THIS_DI...
from CSDGAN.classes.image.ImageDataset import ImageFolderWithPaths, ImageFolder import utils.image_utils as iu import utils.utils as uu import CSDGAN.utils.constants as cs from torch.utils import data import torchvision from sklearn.model_selection import train_test_split import shutil import torchvision.transforms as...
import pandas as pd from transformers import AutoTokenizer, RobertaForMaskedLM, AutoConfig from transformers import Trainer, TrainingArguments from components.util import seed_everything from components.dataset import MLMDataset from components.optimizer import get_optimizer_robertaMLM, get_scheduler import torch impor...
import matplotlib.pyplot as plt import math xtab = [] ytab = [] for i in range(0, 628): # Calculate polar coordinates for provided equation phi = float(i) / 100.0 r = 4 * math.cos(2 * phi) # Convert to Cartesian and store in lists x = r * math.cos(phi) y = r * math.sin(phi) xtab.append(x)...