content
stringlengths
5
1.05M
from dimagi.ext import jsonobject from dimagi.utils.logging import notify_exception from soil.progress import STATES, get_task_status from soil.util import get_task class TaskStatus(jsonobject.StrictJsonObject): # takes on values of soil.progress.STATES state = jsonobject.IntegerProperty() progress = json...
from typing import Callable, Dict import json from decimal import Decimal from collections import namedtuple import urllib.request import urllib.parse import asyncio import websockets # Define urls needed for order book streams URL_ORDER_BOOK = "https://api.binance.com/api/v1/depth" URL_ORDER_BOOK_PERP = "https://dap...
import json import os import random import time import requests from bs4 import BeautifulSoup from firebase import init_firebase, updateData base_url = 'https://movie.naver.com/movie/point/af/list.nhn?&page={}' init_firebase() def main(): while True: for idx in range(1, 1001): print(f'Page ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from PythonMiddleware.graphene import Graphene from PythonMiddleware.instance import set_shared_graphene_instance from pprint import pprint import time #nodeAddress = "wss://api.cocosbcx.net" nodeAddress = "ws://test.cocosbcx.net" #nodeAddress = "ws://127.0.0.1:8049" ...
from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse, JsonResponse, HttpResponseRedirect from django.urls import reverse from django.contrib.auth.decorators import login_required from rest_framework.parsers import JSONParser from rest_framework.decorators import api_view from .m...
''' Что покажет приведенный ниже фрагмент кода? ''' counter = 0 for i in range(99, 102): temp = i while temp > 0: counter += 1 temp //= 10 print(counter)
"""ordia.query. Usage: ordia.query iso639-to-q <iso639> ordia.query get-wikidata-language-codes [options] ordia.query form-to-iso639 <form> Options: --min-count=<min-count> Minimum count [default: 0] Description: Functions in this module query the Wikidata Query Service and thus requires Internet acces...
# app/elephant_queries.py import os from dotenv import load_dotenv import psycopg2 load_dotenv() #> loads contents of the .env file into the script's environment DB_NAME = os.getenv("DB_NAME") DB_USER = os.getenv("DB_USER") DB_PASSWORD = os.getenv("DB_PASSWORD") DB_HOST = os.getenv("DB_HOST") connection = psycopg2....
__version__ = "4.0.1" # __version__ has to be define in the first line """ pysal.lib: Python Spatial Analysis Library (core) ================================================ Documentation ------------- PySAL documentation is available in two forms: python docstrings and an html \ webpage at http://pysal.org...
from rest_framework import permissions from rest_framework.viewsets import ReadOnlyModelViewSet from ggongsul.agreement.models import Agreement from ggongsul.agreement.serializers import ( AgreementFullSerializer, AgreementShortSerializer, ) class AgreementViewSet(ReadOnlyModelViewSet): queryset = Agreem...
""" recursive parse """ from typing import List, Any, Union, Tuple def parse(filename: str) -> List[Any]: with open(filename, "r") as file: lines = [line.rstrip() for line in file.readlines()] # remove newline character lines = [line for line in lines if len(line) > 0] # remove empty lines return parse_line...
import numpy as np import torch import os from common import tensor from pde2d_base import RegularPDE from spinn2d import Plotter2D, App2D, SPINN2D from mayavi import mlab class SquareSlit(RegularPDE): def __init__(self, n_nodes, ns, nb=None, nbs=None, sample_frac=1.0): self.sample_frac = sample_frac ...
# Copyright (C) 2020 TU Dresden # Licensed under the ISC license (see LICENSE.txt) # # Authors: Robert Khasanov import copy from mocasin.representations import SimpleVectorRepresentation from mocasin.tetris.schedule import ( Schedule, MultiJobSegmentMapping, SingleJobSegmentMapping, ) class BaseVariantS...
from setuptools import setup, Extension import numpy import os from setuptools import Extension, setup ### --- # peakfinder8 Cython installation adapted from OnDA: https://github.com/ondateam/onda DIFFRACTEM_USE_CYTHON = os.getenv("DIFFRACTEM_USE_CYTHON") ext = ".pyx" if DIFFRACTEM_USE_CYTHON else ".c" # pylint: d...
# Using py.test framework from service import Intro, MNIST def test_example_message(client): """Example message should be returned""" client.app.add_route('/mnist', Intro()) result = client.simulate_get('/mnist') assert result.json == { 'message': 'This service verifies a model using the MNIS...
from __future__ import print_function import cv2 as cv import numpy as np import argparse source_window = 'Source image' corners_window = 'Corners detected' max_thresh = 255 def cornerHarris_demo(val): thresh = val # Detector parameters blockSize = 2 apertureSize = 3 k = 0.04 # Detecting corn...
# incomplete_iteration.py # # LICENSE # # The MIT License # # Copyright (c) 2020 TileDB, Inc. # # 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 limitati...
# -*- coding: utf-8 -*- import itertools from metrika.contender import Contender from metrika.variable import * __author__ = 'Javier Pimás' class Suite: def __init__(self, name=""): self.name = name self.variables = [] def add_variable_from_dict(self, name, values): values = [NamedV...
import gtk class DragTarget(object): """ A DragTarget supports a certain mime type and has methods to figure out if a drag is possible as well as to retrieve the actual text-data representation for the drag """ app = 0 widget = 0 actions = gtk.gdk.ACTION_COPY | gtk.gdk.ACTION_MOVE | gtk...
import unittest from .. import util class TestUtil(unittest.TestCase): def test_state_dict_names(self): state_dict = { 'conv1.weight': 0, 'conv1.bias': 0, 'fc1.weight': 0, 'fc2.weight': 0, 'fc2.bias': 0 } layer_names = util.stat...
""" Name: thomas.py Goal: Numerical resolution of linear equations with the method of Thomas Author: HOUNSI madouvi antoine-sebastien Date: 08/03/2022 """ from os.path import join, dirname import sys import numpy as np from linearEq.utils.gaussForVal import gauss class Thomas: def __init__(self, ...
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
# Copyright (c) 2017 Intel Corporation. All rights reserved. # Use of this source code is governed by a MIT-style # license that can be found in the LICENSE file. from tests.integration.utils.test_blockdevices.test_blockdevice import TestBlockDevice class TestBlockDeviceLinux(TestBlockDevice): _supported_device...
import unittest import requests from unittest import mock from dataverk.connectors import NaisS3Connector from tests.dataverk.connectors.storage.test_resources.mock_nais_s3_api import mock_requests_put, mock_requests_get from tests.dataverk.connectors.storage.test_resources.nais_s3_storage_common import NAIS_S3_ENDPOI...
''' Core algorithm. Key algorithm parameters: - ga_priority (p) = probability that the next task issued is a GA evaluation - population (n) - workers (w) = number of parallel workers - task_limit (l) = number of function evaluations to carry out Describing the algorithm as (p, n, w, l): - (0, 1, 1...
import torch import torch.nn as nn import torch.nn.functional as F import torch.autograd as autograd from torch.autograd import Variable from utils import * from config import parameters START_TAG = '<START>' STOP_TAG = '<STOP>' def to_scalar(var): return var.view(-1).data.tolist()[0] def argmax(vec): _, id...
import os, sys, inspect cmd_subfolder = os.path.realpath(os.path.abspath(os.path.join(os.path.split(inspect.getfile( inspect.currentframe() ))[0],".."))) if cmd_subfolder not in sys.path: sys.path.insert(0, cmd_subfolder)
#coding: UTF-8 '''Message is the carrier of a simple Pub/Sub system on top of ccnet''' import datetime import re import uuid import time MESSAGE_PATTERN = re.compile(r'(?P<flags>[\d]+) (?P<from>[^ ]+) (?P<to>[^ ]+) (?P<id>[^ ]+) (?P<ctime>[^ ]+) (?P<rtime>[^ ]+) (?P<app>[^ ]+) (?P<body>.*)') class Message(object): ...
#!/usr/bin/env python # coding: utf-8 # # Generate Long Audio Sample from trained model # ## Boilerplate # In[1]: import os, sys root_dir, _ = os.path.split(os.getcwd()) script_dir = os.path.join(root_dir, 'scripts') sys.path.append(script_dir) os.environ['CUDA_VISIBLE_DEVICES'] = '0' # In[2]: import tensorfl...
import random import torch import torch.nn as nn import torch.nn.functional as F from torchvision.models import resnet50, resnet18 class ReorderResNet(nn.Module): def __init__(self, resnet_type='resnet50', pretrained=True): super(ReorderResNet, self).__init__() self.resnet_type = resnet_type ...
# -*- coding: utf-8 -*- """Shared test cases.""" import os from dfvfs.file_io import tsk_file_io from dfvfs.file_io import tsk_partition_file_io from dfvfs.lib import definitions from dfvfs.lib import errors from dfvfs.path import factory as path_spec_factory from dfvfs.path import tsk_path_spec from dfvfs.path impor...
from flask import Flask, jsonify, request, Response from functools import wraps from werkzeug.routing import Rule from optparse import OptionParser from pprint import pprint import time VERBOSE = 'verbose' BASIC_AUTH = 'basic_auth' AUTH_USERNAME = 'auth_username' AUTH_PASSWORD = 'auth_password' config = { BASIC_A...
''' *************************************************************************** * (c) Andrew Robinson (andrew.robinson@latrobe.edu.au) 2013 * * La Trobe University & * * Life Sciences Computation Centre (LSCC, part of VLSCI) * * ...
from django.contrib import admin from .models import ExampleSlackModel class ExampleSlackAdmin(admin.ModelAdmin): """Simple admin view for looking over data""" admin.site.register(ExampleSlackModel, ExampleSlackAdmin)
# -*- coding: utf-8 -*- from guillotina import configure from guillotina.behaviors.instance import AnnotationBehavior from guillotina.behaviors.properties import FunctionProperty from guillotina.interfaces import IResource from guillotina.utils import get_authenticated_user_id from guillotina_cms.interfaces import IFol...
from collections import namedtuple from functools import partial from typing import Any, Dict, Union from quilldelta import utils as _ __all__ = ['Insert', 'Retain', 'Delete', 'OperationType', 'is_retain', 'is_insert', 'is_delete', 'it_insert_text', 'load_operation'] def _sum_operation(instanc...
import binascii import uuid from base64 import b64decode from datetime import datetime, timedelta from urllib.parse import parse_qs, parse_qsl, urlencode, urlparse, urlunparse from django.core.exceptions import ImproperlyConfigured from django.db.models import F, Func, TextField from rest_framework.pagination import B...
import gc import torch import numpy as np import random from transformers import AutoTokenizer, AutoModelForSequenceClassification def cleanup(): gc.collect() torch.cuda.empty_cache() def turn_off_grad(model): for param in model.parameters(): param.requires_grad = False def turn_on_grad(model)...
# twitter/views_admin.py # Brought to you by We Vote. Be good. # -*- coding: UTF-8 -*- from .controllers import delete_possible_twitter_handles, retrieve_possible_twitter_handles from .models import TwitterLinkPossibility from admin_tools.views import redirect_to_sign_in_page from candidate.models import CandidateCamp...
import logging from asreview.ascii import welcome_message from asreview.config import DEFAULT_MODEL, DEFAULT_FEATURE_EXTRACTION from asreview.config import DEFAULT_QUERY_STRATEGY from asreview.config import DEFAULT_BALANCE_STRATEGY from asreview.config import DEFAULT_N_INSTANCES from asreview.config import DEFAULT_N_...
# -*- coding: utf-8 -*- # @Time : 2021/2/22 18:54 # @Author : duyu # @Email : abelazady@foxmail.com # @File : my_hook.py # @Software: PyCharm import torch from mmcv.runner import HOOKS, Hook from mmcv.runner.hooks.optimizer import OptimizerHook @HOOKS.register_module() class MyOptimizerHook(Optimiz...
n=int(input('tabuada de qual numero vc quer?')) for c in range(0,11): print(n,'*' , c,'=' ,n* c)
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # 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...
# Packages up pygw so it's pip-installable from setuptools import setup, find_packages with open('README.md', 'r') as fh: long_description = fh.read() def get_version(): try: from maven_version import get_maven_version version = get_maven_version() except ModuleNotFoundError: # If ...
import pytest from mars_profiling.profile_report import ProfileReport def test_phases_empty(): profile = ProfileReport(None) with pytest.raises(ValueError) as e: profile.to_html() assert ( e.value.args[0] == "Can not describe a `lazy` ProfileReport without a DataFrame...
import random from datetime import date, datetime, timedelta, timezone from typing import List, Optional from fastapi.exceptions import HTTPException from starlette import status from app.models.phq import AvgAndEstimatedPhqScore, Phq, SingleQuestionAvgScore from app.models.user import User from app.schema.phq import...
import StringIO import json import logging import random import urllib import urllib2 import requests # for sending images from PIL import Image import multipart # standard app engine imports from google.appengine.api import urlfetch from google.appengine.ext import ndb import webapp2 TOKEN = '356407842:AAFndoaIMeEf...
import os #Predicates = {} class dataset: current_path = os.path.dirname(os.path.realpath(__file__)) os.chdir(current_path) def get_resource(self): # current_path= os.path.dirname(os.path.realpath(__file__)) # os.chdir(current_path) Rfile = open(".\\Resources.txt", 'r') R...
""" Policy Network for training imitation learning model. For discrete case, we use classifier. For continuous case, we use regressor. """ import numpy as np import torch import torch.nn as nn from torchlib.common import move_tensor_to_gpu, convert_numpy_to_tensor, enable_cuda from torchlib.deep_rl import BaseAgent fr...
from marshmallow_jsonapi import Schema, fields from marshmallow import validate from flask.ext.sqlalchemy import SQLAlchemy from sqlalchemy.exc import SQLAlchemyError db = SQLAlchemy(session_options={"autoflush": True}) class CRUD(): def add(self, resource): db.session.add(resource) return db....
__author__ = 'filipkulig' import time from board import Board from draw import Draw class Engine(): draw = None board = None def __init__(self): self.draw = Draw() self.board = Board() self.draw.set_board(self.board) def run(self): info = self.draw.get_board_info(...
#!/usr/bin/env python # Copyright 2020 Stanford University, Los Alamos National Laboratory # # 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 ...
# # This file is part of Bakefile (http://bakefile.org) # # Copyright (C) 2009-2013 Vaclav Slavik # # 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...
# %% ####################################### def split_string(string: str, size: int): """Splits a string into smaller strings of the desired size value. Examples: >>> string = 'hey hey hiya'\n >>> split_string(string, 4)\n ['hey ', 'hey ', 'hiya'] References: https://youtu.be/pG3L2Ojh...
import torch import torch.nn as nn import torchvision.models as models import torch.nn.functional as F from scipy.optimize import linear_sum_assignment class DetrLoss(nn.Module): def __init__(self, matcher, num_classes, eos_coef, losses): super().__init__() self.num_classes = num_classes ...
# -*- coding: utf-8 -*- # __author__ = "wynterwang" # __date__ = "2020/9/24" from __future__ import absolute_import __all__ = ["ResourceIsolation", "ResourceIsolationByUser"] class ResourceIsolation: def isolation_filters(self, request): """ :param request: request object :type request: ...
''' This script is used to rerun previously run scenarios during the fuzzing process ''' import sys import os sys.path.append('pymoo') carla_root = '../carla_0994_no_rss' sys.path.append(carla_root+'/PythonAPI/carla/dist/carla-0.9.9-py3.7-linux-x86_64.egg') sys.path.append(carla_root+'/PythonAPI/carla') sys.path.appen...
import unittest from pathlib import Path import json import pandas as pd from filmweb_integrator.fwimdbmerge.filmweb import Filmweb from pandas.io.json import json_normalize DATA_STATIC = str(Path(__file__).parent.parent.parent.parent.absolute()) + '/data_static' FILMWEB_EXAMPLE_JSON = DATA_STATIC + '/example_test_01...
# V0 # V1 # http://bookshadow.com/weblog/2018/06/17/leetcode-exam-room/ # https://blog.csdn.net/fuxuemingzhu/article/details/83141523 # IDEA : bisect.insort : https://www.cnblogs.com/skydesign/archive/2011/09/02/2163592.html class ExamRoom(object): def __init__(self, N): """ :type N: int ...
# Copyright 2021 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import contextlib import difflib import filecmp import os import shutil import tempfile import unittest from json5_generator import Json5File, Writer @con...
from Classes.EdgeData import EdgeData class Edges(object): """Class to store and process edge data. Attributes ---------- rec_edge_method: str Method used to determine coef for rec. edge 'Fixed', 'Variable'. vel_method: str Method used to compute the velocity used 'MeasMag', 'Vect...
# Created On: 2011-11-27 # Copyright 2013 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "BSD" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.hardcoded.net/licenses/bsd_license from qtlib.c...
import requests import json RIDEEM_HOST = 'https://rideem.io' def API(key = None, host = RIDEEM_HOST): return Rideem(key, host) class Rideem(object): def __init__(self, key = None, host = RIDEEM_HOST): self._key = key # app private key self._host = host def create_app(self, name, email =...
#!/usr/bin/python3 """ Given a non-negative integer, you could swap two digits at most once to get the maximum valued number. Return the maximum valued number you could get. Example 1: Input: 2736 Output: 7236 Explanation: Swap the number 2 and the number 7. Example 2: Input: 9973 Output: 9973 Explanation: No swap. No...
# coding: utf-8 from django.conf import settings from django.conf.urls import include, patterns, url from django.contrib.auth.views import logout from django.contrib import admin from django.views.generic.base import TemplateView urlpatterns = patterns( '', url(r'^', include('mapa_cidadao.core.urls')), ur...
import io import platform import os import sys import setuptools try: from numpy import get_include except ImportError: import subprocess errno = subprocess.call([sys.executable, '-m', 'pip', 'install', 'numpy']) if errno: print('Please install numpy') raise SystemExit(errno) else:...
#!/usr/bin/python # Copyright (c) 2017 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module:...
import pytest from libqtile.widget import BatteryIcon from libqtile import images import cairocffi from .conftest import TEST_DIR def test_images_fail(): """Test BatteryIcon() with a bad theme_path This theme path doesn't contain all of the required images. """ battery = BatteryIcon(theme_path=TEST_D...
# views_counter plugin server # Developed by Raven, 2021.12.28 # Copyright (c) RavenKiller # This source code is licensed under the MIT License found in the # LICENSE file in the root directory of this source tree. import tornado.ioloop import tornado.web import hashlib import sqlite3 from datetime import datetime as...
import sys def triple_trouble(one, two, three): s = '' for i in range(len(one)): s += one[i] s += two[i] s += three[i] return s if __name__ == "__main__": if len(sys.argv) == 4: print(triple_trouble(one=sys.argv[1], two=sys.argv[2], three=sys.argv[3])) else: ...
#!/usr/bin/python3 """ Creating table investment """ import models from datetime import datetime import sqlalchemy from sqlalchemy import Column, String, ForeignKey from sqlalchemy import Integer, DateTime, Float from models import investor from models.base_model import BaseModel, Base class Investment(BaseModel, Bas...
import os import torch from torch import autograd from ..infer.line_of_best_fit import line_of_best_fit # A system for autonomous steering using an LSTM network to generate a steering angle based on the slope and intercept # of the line of best fit calculated for the center line of the road # Created by brendon-ai,...
########################################################################## # # Copyright (c) 2019, Cinesite VFX Ltd. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions ...
import torch import torch.nn as nn from model import common import math def make_model(opt): return LAUNet(opt) class Evaluator(nn.Module): def __init__(self, n_feats): super(Evaluator, self).__init__() self.conv1 = nn.Sequential(nn.Conv2d(3, n_feats, kernel_size=3, stride=2)) self.c...
import unittest import src.Models.AircraftDynamics as ad import numpy as np class AircraftDynamicsTest(unittest.TestCase): def test_stright_line(self): dynamics = ad.AircraftDynamics(step_time=0.001, cruise_speed=20.0) start_state = np.array([10, 10, np.pi/4.0]) end_state = dynamics.update(...
from django.http import JsonResponse from django.utils.deprecation import MiddlewareMixin class FirstMiddleware(MiddlewareMixin): def process_request(self, request): print('FirstMiddleware: process_request') # return JsonResponse({'Hello': 'Django BBS'}) def process_view(self, request, vi...
import yt import os as os from glob import glob import pandas as pd from tqdm import tqdm import pyrats sims=[] init=1 for s in sims: cx=[]; cy=[]; cz=[]; t=[]; x=[]; y=[]; z=[] os.chdir('/home/pfister/scratch/'+s) files=glob('output_*') #for i in tqdm(range(3)): for i in tqdm(range(len(files)-in...
from typing import cast import gym from gym.spaces import Discrete def get_action_size_from_env(env: gym.Env) -> int: if isinstance(env.action_space, Discrete): return cast(int, env.action_space.n) return cast(int, env.action_space.shape[0])
#!/usr/bin/env python import os import subprocess import os.path as p import sys DIR_OF_THIS_SCRIPT = p.dirname( p.abspath( __file__ ) ) DIR_OF_THIRD_PARTY = p.join( DIR_OF_THIS_SCRIPT, 'third_party' ) DIR_OF_YCMD_THIRD_PARTY = p.join( DIR_OF_THIRD_PARTY, 'ycmd', 'third_party' ) python_path = [] for folder in os.lis...
import dataiku INPUT_DATASET = "mydataset" COLUMN_TO_PARTITION_BY = "mypartitioningcolumn" dataset = dataiku.Dataset(INPUT_DATASET) df = dataset.get_dataframe(columns = [COLUMN_TO_PARTITION_BY]) combinations = df[COLUMN_TO_PARTITION_BY].unique() combinations_str = "/".join(combinations) client = dataiku.api_client(...
#! /home/alessap/miniconda3/bin/python import subprocess print("Setting pointers properties") # xinput_output = str(subprocess.check_output(["xinput"])).split("\n").split("\n") # print([line for line in xinput_output if "Master" in line]) ps = subprocess.Popen(("xinput"), stdout=subprocess.PIPE) output = str(sub...
""" PEP8+ code style for better code ============================================================================= PEP8 is the defacto standard for coding style for Python. Code conforming to that is fairly readable, but some cases could be better. From experience, I have learned additional guidelines to improve code ...
"""Imports Tapis CLI settings to a Jinja environment Prefixes TAPIS_PY and TAPIS_CLI are stripped and key names are lowercased. """ import re from tapis_cli import settings BLACKLIST = ['TAPIS_CLI_ALLOW_EMPTY_VARS'] __all__ = ['key_values'] def key_values(): key_vals = dict() cli_settings = settings.all_se...
from django.apps import AppConfig from django.db.models.signals import pre_save class NodeConfig(AppConfig): name = 'node' def ready(self): from node.models import IncomingNode from node.signals.node.pre_save import node_pre_save pre_save.connect(node_pre_save, sender=IncomingNode)
import numpy as np import csv import time np.random.seed(1234) # seed 고정 def randomize(): np.random.seed(time.time()) # 현재시각을 seed로 RND_MEAN = 0 RND_STD = 0.0030 LEARNING_RATE = 0.001 def abalone_exec(epoch_count=10, mb_size=10, report=1): load_abalone_dataset() init_model() train_and_test(epoch_c...
import numpy as np import pytest import unittest from mvc.models.metrics.base_metric import BaseMetric class BaseMetricTest(unittest.TestCase): def setUp(self): self.metric = BaseMetric() def test_add(self): with pytest.raises(NotImplementedError): self.metric.add(np.random.rando...
# coding: utf-8 import lxml.html from .abstract import get_strategy class TestTags: def test_adding_tags_for_page(self): # Given strategy = get_strategy({ 'start_urls': [{ 'url': 'http://foo.bar/api', 'tags': ["test"] }] }) s...
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. import os import argparse from azureml.core import Datastore import aml_utils def main(datastore, data_path): # Get snapshot of your data and save it in datastore os.makedirs(data_path, exist_ok=True) with o...
"""The package with different tools serving as helpers in other modules.""" from .xmath import Xmath as xmath __all__ = ["xmath", ]
import pickle from conftest import Benchmark, random_rat from donuts import RationalFunction def test_rat_to_string(benchmark: Benchmark) -> None: r = random_rat(nterms=1000) result = benchmark(str, r) assert result def test_rat_from_string(benchmark: Benchmark) -> None: r = random_rat(nterms=1000...
from datetime import datetime, timedelta from random import randint from zeeguu_core_test.rules.article_rule import ArticleRule from zeeguu_core_test.rules.base_rule import BaseRule from zeeguu_core_test.rules.language_rule import LanguageRule from zeeguu_core_test.rules.rss_feed_rule import RSSFeedRule from zeeguu_co...
from Blueprint3DJSBPY.bp3dpy.model.half_edge import HalfEdge; from mathutils import Vector; class Room(): def __init__(self, name, floorplan, corners): self.__name = name; self.__floorplan = floorplan; self.__corners = corners; self.__walls = []; self.__interiorCorners = [];...
# -*- coding: utf-8 -*- # Generated by Django 1.10.2 on 2016-11-26 10:54 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('premises', '0001_initial'), ] operations = [ ...
# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"). You # may not use this file except in compliance with the License. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file accompa...
#!/usr/bin/env python import copy from importlib import import_module import logging import numpy as np from openquake.hazardlib.gsim.base import GMPE from openquake.hazardlib.gsim.boore_2014 import BooreEtAl2014 from openquake.hazardlib.gsim.campbell_bozorgnia_2014 import CampbellBozorgnia2014 from openquake.hazard...
# Author: Mathieu Blondel, 2019 # License: BSD import numpy as np from scipy.optimize import fmin_l_bfgs_b from sklearn.base import BaseEstimator from sklearn.preprocessing import LabelBinarizer from sklearn.preprocessing import LabelEncoder from sklearn.utils.extmath import safe_sparse_dot from sklearn.preprocessin...
################################################################################ # (c) 2006, The Honeynet Project # Author: Jed Haile jed.haile@thelogangroup.biz # # 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...
from setuptools import setup, find_packages setup(name='busypenguin', version='0.0.0', description='Publish slack notifications for tasks using context managers', url='https://github.com/kyrias/busypenguin', author='Johannes Löthberg', author_email='johannes@kyriasis.com', licens...
import argparse import logging import os import sys from src.utils import construct_new_filename logging.basicConfig( format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO, ) def main(): a_p = argparse.ArgumentParser( "Rename all 'MacOS screenshot files' like %Y-%m-%...