content
stringlengths
5
1.05M
#!/usr/bin/python # # Copyright 2002-2021 Barcelona Supercomputing Center (www.bsc.es) # # 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 ...
import nox_poetry @nox_poetry.session(python=["3.7", "3.8", "3.9", "3.10"]) def test(session: nox_poetry.Session): session.install(".") session.install("pytest", "pytest-cov", "pytest-timeout") session.env["COVERAGE_FILE"] = f".coverage.{session.python}" session.run("python", "-m", "pytest", "--cov", ...
# Generated by Django 2.0 on 2018-01-06 12:21 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('blog', '0004_auto_20180106_1620'), ] operations = [ migrations.RenameField( model_name='post', old_name='Aauthor', ...
#!/usr/bin/env python """ uncertainty_sampler.py """ import sys import h5py from datetime import datetime import numpy as np from libact.base.dataset import Dataset from libact.models import LinearSVC from libact.query_strategies import UncertaintySampling class UncertaintySampler(object): def __init__...
#!/usr/bin/python import sys from urlparse import urlparse for line in sys.stdin: data = line.strip().split(" ") if len(data) == 10: ip, hp1, hp2, date, gmt, req, path, req_type, status, val = data relative_path = urlparse(path).path print "{0}".format(relative_path)
from django.test import SimpleTestCase from matrixstore.build.dates import generate_dates class TestDates(SimpleTestCase): def test_generate_dates(self): results = generate_dates("2019-02", 15) expected = [ "2017-12-01", "2018-01-01", "2018-02-01", ...
import os import sys import pickle import matplotlib.pyplot as plt import numpy as np def create_hist(y_pred_fn, y_test_fn, title, subplot, add_axes, alpha): """ y_pred_fn: pickle filename y_test_fn: pickle filename num_bins: int """ # load numpy arrays from pickled files y_pred = None ...
""" [2015-06-17] Challenge #219 [Hard] The Cave of Prosperity https://www.reddit.com/r/dailyprogrammer/comments/3aewlg/20150617_challenge_219_hard_the_cave_of_prosperity/ #Description Mandy is out in the woods one day hiking with her backpack Steven (yes, she named her backpack Steven) when she suddently sees a cave ...
import enum from typing import Any from typing import Dict from kubernetes.client import V1Pod from typing_extensions import TypedDict class DockerVolume(TypedDict): host_path: str container_path: str mode: str # XXX: Literal["RO", "RW"] once we drop older Python support class SecretEnvSource(TypedDic...
#!usr/bin/python """ summ of 10 nums if any num is summ of not much then 10 any others print 'YES' """ __author__ = "JayIvhen" from collections import deque nums = list(input('Enter numbers string: ')) N = input('Enter Number : ') summ = 0 i = 0 flag = False iteration_n = 0 def rec_fun(summ, nums, i): global fl...
# *-* coding: utf-8 *-* """ Created on: 5-Jul-2018 @author: Ai """ import scrapy from googletrans import Translator class AmazonReviewsSpider(scrapy.Spider): name = 'amazon-reviews-spider' def __init__(self, store=None, product_id=None, *args, **kwargs): super(AmazonReviewsSpider, self).__init__(*ar...
pass pass pass pass pass a = None b = 1 c = None d = 1 e = 1 f = 1 aa = None aaa = None A = 1 B = 1 C = 1 """asd""" class C: pass pass pass def foo(): pass def bar(): pass
from .test_config_attribute_api import * from .test_config_attributes import *
#!/usr/bin/env python # Copyright (c) 2007-2018 Carnegie Mellon University. All Rights Reserved. # See COPYRIGHT file for details. import unittest import StringIO import feature_extraction as fe from feature_extraction.tests.coverity_input import CoverityJsonV2, CoverityJsonV2Event, CoverityJsonV2Issue from feature_e...
import threading, time, datetime import OmniDB_app.include.Spartacus as Spartacus import OmniDB_app.include.Spartacus.Database as Database import OmniDB_app.include.Spartacus.Utils as Utils import OmniDB_app.include.OmniDatabase as OmniDatabase from OmniDB import settings database = OmniDatabase.Generic.InstantiateD...
import numpy as np import json import os.path from shutil import copyfile import tensorflow as tf import extract_training_data as extractor import training_routines import training_data_provider if __name__ == "__main__": tf.logging.set_verbosity(tf.logging.INFO) model_load_checkpoint = None #training_routines._get_...
class Member(object): """ Base class to manage members as extracted from the MassHealth excel workbook. Each member will have one or more Affiliate objects to represent that data. This is used to condense the multiple duplicated rows for a given member and put the data that differs as new Affiliate ob...
"""Provides the wrapper for Comsol model objects.""" __license__ = 'MIT' ######################################## # Dependencies # ######################################## import numpy # fast numerics from numpy import array # numerical array ...
""" support classes for DBAdapter/pyodbc tests """ from __future__ import absolute_import, print_function, division from unittest import TestCase import os import dbadapter.pyodbc as pyodbc from contextlib import contextmanager import functools _conn_string_key = 'IOPRO_PYODBC_TEST_CONNSTR' _conn_string = os.enviro...
""" Found usages are returned from all core search functions as async generators which the methods in this module can consume and loop through to output in different formats. """ import json from aiostream import stream separators_with_no_spaces_to_match_jq_compact_format = (",", ":") def as_json_line(usage): ...
""" Script that computes correlations of KINASE tasks. """ from __future__ import print_function from __future__ import division from __future__ import unicode_literals import os import numpy as np import tempfile import shutil import deepchem as dc import pandas as pd import matplotlib # Force matplotlib to not use ...
from flask import Flask, render_template, request, session from flask_socketio import SocketIO, emit import logging from services.AutoScaleService import AutoScaleService from view.QueryView import QueryView as dv from view.AutoScaleView import AutoScaleView from view.AuthenticationView import AuthenticationView as au...
from django.apps import AppConfig class SvtransformConfig(AppConfig): name = 'svtransform'
from funcionsimport import preguntar_operacio_usuari from file2 import operacionvalores from file3 import valors from Output2 import guardar_resultat def calcular_operacio() : operacio_matematica = preguntar_operacio_usuari() valor1, valor2 = valors() resultat_operacio = operacionvalores(valor1,valor2, o...
from setuptools import setup, find_packages setup( name = 'spamm', version = '0.0.1', description = 'AGN spectral Bayesian decomposition', keywords = ['astronomy'], classifiers = ['Programming Language :: Python', 'Programming Language :: Python :: 3', 'Develop...
# run this using py.test from top-level directory # ref: https://pytest.org/latest/getting-started.html from __future__ import print_function, division from theoretical_model import test_detector_model import fast_detector import numpy as np REL_TOLERENCE = 1e-4 def test_c_vs_python_implementation(): df = test_de...
""" Given two non-negative integers low and high. Return the count of odd numbers between low and high (inclusive). Example: Input: low = 3, high = 7 Output: 3 Explanation: The odd numbers between 3 and 7 are [3,5,7]. Constraints: - 0 <= low <= high <= 10^9 """ #Difficulty: Easy #...
from diagrams import Diagram from diagrams.aws.compute import EC2 from diagrams.aws.database import RDS from diagrams.aws.network import ELB with Diagram("Hello World", show=False): ELB("Load Balancer") >> EC2("Message Server") >> RDS("Message Store")
from pathlib import Path import yaml from kass_nn.level_2.eif_module import eif from kass_nn.level_2.danger_labeling.dangerousness import get_dangerousness_int from kass_nn.util.parse_logs import LogParser from kass_nn.util import kass_plotter as plt from kass_nn.util import load_parsed_logs as lp class IPMinURL: ...
import iso8601 import pytz def dateTimeConverter(dateStr): _date_obj=iso8601.parse_date(dateStr) _date_utc=_date_obj.astimezone(pytz.utc) _date_utc_zformat=_date_utc.strftime('%Y-%m-%dT%H:%M:%S+08:00') return _date_utc_zformat
import angr class sleep(angr.SimProcedure): #pylint:disable=arguments-differ,unused-argument def run(self, seconds): return 0
from fr import frobject c = frobject() status = c.frfunction(c.encoding) print(status)
from __future__ import unicode_literals from django.core.urlresolvers import reverse from django.db import models from django.conf import settings from django.db.models.signals import pre_save, post_save from datetime import datetime from django.utils.text import slugify from category.models import Category class Pos...
from __future__ import print_function, division, absolute_import from functools import partial import sys from time import sleep import unittest from tornado.ioloop import IOLoop from tornado import gen import pytest from distributed import Client, Worker, Nanny from distributed.deploy.local import LocalCluster from...
from tkinter import * raiz=Tk() raiz.title("Ventana de Prueba") raiz.resizable(0,0) #ancho y alto raiz.iconbitmap("Iconos\system.ico") raiz.geometry("750x550")#Tamaño de la venta raiz.config(bg="white") raiz.mainloop() #Bucle Infinito
from flask import Flask, Response from kafka import KafkaConsumer consumer = KafkaConsumer('my-topic', bootstrap_servers='localhost:9092') app = Flask(__name__) def kafkastream(): for message in consumer: yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + message.value + b'\r\n\r...
import numpy as np import torch class L2Metric: def __init__(self): self.name = f"L2" self.feature_extractor = Flatter() self.metric = lambda x,y: np.mean((x-y)**2, axis=-1) class Flatter(torch.nn.Module): def __init__(self): super(Flatter, self).__init__() def get_fv(se...
import numpy as np import taichi as ti import taichi_glsl as ts from .geometry import * from .shading import * from .transform import * from .common import * import math @ti.data_oriented class ModelBase(AutoInit): pass class Model(ModelBase): def __init__(self, pos_n, tex_n, nrm_n, faces_n): self.L...
from .SoftTriple import SoftTriple
# Problem: https://www.hackerrank.com/challenges/equal/problem # Score: 30
import unittest from .. import TEST_DTYPES import torch from pytorch_metric_learning.reducers import DoNothingReducer class TestDoNothingReducer(unittest.TestCase): @classmethod def setUpClass(self): self.device = torch.device('cuda') def test_do_nothing_reducer(self): reducer = DoNothing...
import os import requests, json import pytest import pdb import app def test_mol_api(): host = "http://apitest.MoveOnLibra.com" url = "/v1/libra/about" params = {} headers = app.gen_api_header(False, "explorer.moveonlibra.com") assert len(headers.items()) == 1 response = request...
import pandas as pd base = pd.read_csv('./datasets/census.csv') forecasts = base.iloc[:,0:14].values classes = base.iloc[:,14].values #Encode string labels in num values from sklearn.preprocessing import LabelEncoder, OneHotEncoder label_encoder_forecasts = LabelEncoder() forecasts[:,1] = label_encoder_forecasts.fi...
#!/usr/bin/env python3 def steps(points): # print(points) for step in points: yield(step) def test_steps(): listofsteps = [100e3, 300e3, 1e6] # print(listofsteps) stepper = steps(listofsteps) assert next(stepper) == 100e3 assert next(stepper) == 300e3 assert next(stepper) == ...
from .common import wait_for_template_to_be_created, \ wait_for_template_to_be_deleted, random_str import time def test_catalog(admin_mc): client = admin_mc.client name1 = random_str() name2 = random_str() url = "https://github.com/StrongMonkey/charts-1.git" catalog1 = client.create_catalog(na...
from django.shortcuts import render, get_object_or_404 from sdu_beta_career.resumes.models import Resume def resume_detail(request, pk): resume_details = get_object_or_404(Resume, pk=pk) return render(request, 'resume.html', {'resume': resume_details})
# 복소수(complex) # 실수와 허수로 구성된 숫자 타입입니다. # `real + imag * 1j` 값을 가진 복소수를 돌려주거나 문자열 또는 숫자를 복소수로 변환합니다. # 리터럴 선언 방식 c = 3j # <class 'complex'> print(type(c)) # 3j print(c) # 생성자 선언 방식 # 첫 번째 인자는 실수 `real`, 두 번째 인자는 허수 `imag` 입니다. c = complex(0, 3) # 3j print(c) # real # 복소수의 실수 부분을 반환합니다. real = c.real # 0...
# ---------------------------------------------------------------------------- # ppytty # ---------------------------------------------------------------------------- # Copyright (c) Tiago Montes. # See LICENSE for details. # ---------------------------------------------------------------------------- import logging ...
from django.contrib.auth.models import User from django.db import models import uuid # Create your models here. from django.db.models import CASCADE from django.urls import reverse class Design(models.Model): name = models.CharField(max_length=128) content_image = models.FileField(upload_to="content", blank=...
from pathlib import Path import numpy as np import pandas as pd import matplotlib.pyplot as plt from ibllib.atlas import AllenAtlas from ibllib.atlas.flatmaps import plot_swanson, annotate_swanson import matplotlib.pyplot as plt cmap = 'Blues' ba = AllenAtlas() STAGING_PATH = Path('/datadisk/FlatIron/tables/bwm_sav...
import struct import os import pygame import time import numpy as np import coordcalc pygame.init() screen = pygame.display.set_mode((800, 800)) def readFloat(filepointer): rawbytes = filepointer.read(4) [f] = struct.unpack('f', rawbytes) return f def writeFloat(filepointer, value): ...
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'assets/ui/MainWindow.ui' # # Created: Wed Aug 16 03:25:30 2017 # by: pyside-uic 0.2.15 running on PySide 1.2.4 # # WARNING! All changes made in this file will be lost! from PySide import QtCore, QtGui class Ui_MainWindow(object): ...
# code up a Graph class implementing with an adjacency list class Graph: """ Represent a Graph as dictionary of vertices map the labels to edges.""" # constructor def __init__(self): # empty dictionary for verts self.vertices = {} # add vertex def add_vertex(self, vertex_id): ...
from typing import Union import beet import onyx.storage from onyx.class_types import Buildable, Vector2, Vector3 from onyx.commands import Commands from onyx.dev_util import translate from onyx.pack_manager import Function from onyx.registries import anchor, axis, dimension from onyx.scoreboard import Expression, Pl...
from django.contrib import admin from .models import Booking # Register your models here. admin.site.register(Booking)
# Created by MechAviv # ID :: [865000000] # Commerci Republic : San Commerci sm.createQuestWithQRValue(17929, "1") sm.warp(865020000, 2)
""" --- Day 8: Handheld Halting --- https://adventofcode.com/2020/day/8 """ import re import aocd pattern = re.compile(r"(acc|jmp|nop) ([+-]?\d+)$") program = [] for line in aocd.data.splitlines(): m = re.match(pattern, line) if not m: raise ValueError("invalid entry '%s'" % line.strip()) program...
"""Utility classes.""" import ROOT as R import numpy as np class Color(int): """Create a new R.TColor object with an associated index. https://root-forum.cern.ch/t/how-to-form-a-color-t-from-a-tcolor/25013/2. """ def __new__(cls, r, g, b, name=""): self = int.__new__(cls, R.TColor.GetFreeCol...
from .global_options import * class CreateExtractsParser: """ Parser for createextracts command """ @staticmethod def create_extracts_parser(manager, command): """Method to parse create extracts arguments passed by the user""" create_extract_parser = manager.include(command) ...
from http import HttpResponse, Http400, Http403, Http404, Http405, HttpConflict, Http411, Http500, JSONResponse from requestmanager import RequestManager from decorators import JSONContent, requireContentLength
import sys from gssl.datasets import load_dataset from gssl.inductive.datasets import load_ppi from gssl.utils import seed def main(): seed() # Read dataset name dataset_name = sys.argv[1] # Load dataset if dataset_name == "PPI": load_ppi() else: load_dataset(name=dataset_na...
import enum __all__ = ['reCAPTCHAType'] class reCAPTCHAType(enum.IntEnum): ### # Determine the reCAPTCHA type automatically # # NOTE: this is a guess as to what 0 means. it is the default in the # official client, but values of 0 are not mentioned in the API docs. # AUTO = 0 ...
try: from collections import OrderedDict except ImportError: from .OrderedDictFallback import OrderedDictFallback as OrderedDict
# ************************ General Information ************************ ''' VERSION: ------- Version (by release date): 2019-11-08 DEVELOPER INFORMATION: --------------------- Name: Omid Mirzaei Laboratory: Computer Security Lab (COSEC) University: Universidad Carlos III de Madrid Website: https://cosec.inf.uc3m.es/...
#!/usr/bin/env python ## # This software was developed and / or modified by Raytheon Company, # pursuant to Contract DG133W-05-CQ-1067 with the US Government. # # U.S. EXPORT CONTROLLED TECHNICAL DATA # This software product contains export-restricted data whose # export/transfer/disclosure is restricted by U.S. law....
# -*- coding: utf-8 -*- """ Created on Fri Jun 12 17:52:32 2020 @author: Danish """ import tensorflow as tf import numpy as np class BatchGenerator: def __init__(self, X, batch_size): self.X = X self.batch_size = batch_size self.counter = 0 def get_nextBatch(self, batch_shap...
# coding=utf-8 from __future__ import absolute_import, division, print_function, \ unicode_literals from iota import Address, Iota, ProposedTransaction, Tag, TryteString from iota.adapter.sandbox import SandboxAdapter # Create the API client. api = Iota( # To use sandbox mode, inject a ``SandboxAdapter``. ...
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys, os import logging import boto3 import argparse from merritt_atom import MerrittAtom import requests import json REGISTRY_BASE = 'https://registry.cdlib.org/' numeric_level = getattr(logging, 'INFO', None) logging.basicConfig( level=numeric_level, form...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations def add_honeypot(apps, schema_editor): Destination = apps.get_model("notify", "Destination") try: obj = Destination.objects.get(name="honeypot") except Destination.DoesNotExist: obj = Destinat...
from selenium import webdriver from selenium.webdriver.support.ui import Select from selenium.webdriver.chrome.options import Options from webdriver_manager.chrome import ChromeDriverManager import os import time import pandas as pd import pickle def main(): urls = [("https://ultrasignup.com/results_event.aspx?did...
import smtplib import ssl from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart import re import pandas as pd import message_templates as templates import yaml import logging # noinspection PyArgumentList logging.basicConfig(handlers=[logging.FileHandler("../log.log"), logging.StreamHandl...
# coding=utf-8 # Filename: db.py # pylint: disable=locally-disabled """ Database utilities. """ from __future__ import division, absolute_import, print_function from datetime import datetime import ssl import sys import json import re import pytz try: import pandas as pd except ImportError: print("The databa...
""" # ***************************************************************** # (C) Copyright IBM Corp. 2021. 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...
""" The LLVM Compiler Infrastructure This file is distributed under the University of Illinois Open Source License. See LICENSE.TXT for details. Helper functions for working with sockets. """ # Python modules: import io import socket # LLDB modules import use_lldb_suite def recvall(sock, size...
# Copyright 2015 Google Inc. 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 ...
import asyncio from pathlib import Path # import aiohttp import pytest from pfm_util.async_lib.http_queue import ( # save_processed_response,; save_response,; save_response_to_csv,; save_response_to_json,; StorePageTextOnParentAction,; StorePageJsonOnParentAction, CheckForPages, ExampleAction, ExampleHan...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import sys def get_route(): """ Запросить данные о маршруте """ start = input("Название начального пункта маршрута? ") finish = input("Название конечного пункта маршрута? ") number = int(input("Номер маршрута? ")) return { 'start': ...
# $ pytest -sv # $ pytest -sv -m "not debug" # $ pytest -sv -m "not debug" --pdb import random import pytest from typing import Tuple, List from .main import * class TestExpressionTree(object): def test(self): n1 = ExpressionTreeNode() n1.set_value('+') n1.left = ExpressionTreeNode() ...
# -*- coding: utf-8 -*- """ :mod:`marker` module : Module to manage markers :author: `Dpt Informatique - FST - Univ. Lille <http://portail.fil.univ-lille1.fr>` :date: 2018, january A marker is a represented as a String. """ import random import copy class Marker: def __init__ (self,number): """ ...
# Copyright 2017 Intel Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# -*- coding: utf-8 -*- """ This module """ import attr import typing from ..core.model import ( Property, Resource, Tag, GetAtt, TypeHint, TypeCheck, ) from ..core.constant import AttrMeta #--- Property declaration --- @attr.s class PropResponsePlanSsmParameter(Property): """ AWS Object Type = "AWS::S...
from utaka.src.exceptions.UtakaException import UtakaException class PreconditionFailException(UtakaException): def __init__(self, args): UtakaException.__init__(self, args, 412)
import os class Config: # Either set environment variables, or change this. SECRET_KEY = os.environ.get('SECRET_KEY') or 'The most super secret ever, but not really'
import glob import os import pathlib import plistlib import sqlite3 import json from packaging import version import scripts.artifacts.artGlobals from scripts.artifact_report import ArtifactHtmlReport from scripts.ilapfuncs import logfunc, tsv, timeline, is_platform_windows def get_knowCinferredmotion(files_found, ...
from random import randint class Engine: def __init__(self, world_width=10, world_height=10): ''' Initialise the snake engine where all game operations will take place. :param world_width: Width of the game world the snake should roam :param world_height: Height of the game world ...
from collections import defaultdict, namedtuple import os.path import time from sims4.callback_utils import CallableList from sims4.common import is_available_pack from sims4.service_manager import Service from sims4.tuning.merged_tuning_manager import get_manager import paths import sims4.core_services import sims4.lo...
from lms.lmsweb.tools.validators import EmailNotExists from flask_babel import gettext as _ # type: ignore from flask_wtf import FlaskForm from wtforms import StringField from wtforms.fields.simple import PasswordField from wtforms.validators import Email, EqualTo, InputRequired, Length class ResetPassForm(FlaskForm...
import random class Combat: dodgeLimit = 6 attackLimit = 6 #randomly check if the entity can dodge/attack def dodge(self): roll = random.randint(1, self.dodgeLimit) return roll > 4 def attack(self): roll = random.randint(1, self.attackLimit) return roll > 4
from django.apps import AppConfig class DataVisConfig(AppConfig): name = 'data_vis'
NO_ERROR = 0 MISTAKE = 1 FIXED_MISTAKE = 2 CHEAT = 3 ACROSS = 0 DOWN = 1 def make_hash(data): try: from hashlib import md5 m = md5() except: import md5 m = md5.new() m.update(data) return m.hexdigest() class BinaryFile: def __init__(self, filename=None): if...
import os import pickle import traceback import warnings import torch from libyana.modelutils import modelio from meshreg.models.meshregnet import MeshRegNet def load_opts(resume_checkpoint): # Identify if folder or checkpoint is provided if resume_checkpoint.endswith(".pth"): resume_checkpoint = o...
#%% ''' <reference> re-implementation code of https://github.com/zhixuhao/unet - only binary classification ''' #%% # import tensorflow as tf # tf.keras.preprocessing.image.ImageDataGenerator import tensorflow.keras as keras from keras.preprocessing.image import ImageDataGenerator from keras.models import * from keras...
class Solution(object): def kidsWithCandies(self, candies, extraCandies): """ :type candies: List[int] :type extraCandies: int :rtype: List[bool] """ greatest = max(candies) output = [] for i in candies: output.append(extraCandies + i >= gr...
"""A helper script to generate the News gallery""" import os def format_icon(title, description, link, image): under = "+" * len(title) body = f""" --- :img-top: _static/news/{image} {description} .. link-button:: {link} :type: url :text: {title} :classes: btn-outlin...
# Implementation of walk-forward validation for XGBoost model development # # Makridakis (1998) shampoo sales data set, walk-forward validation from pandas import to_datetime from pandas import read_csv # Load data DIR = './' FILE = 'household_power_consumption.csv' filename = DIR + FILE # Below if swapping to file f...
""" Library Features: Name: lib_wrf_generic Author(s): Fabio Delogu (fabio.delogu@cimafoundation.org) Date: '20200310' Version: '1.0.1' """ ################################################################################# # Library import logging from copy import deepcopy from datetime imp...
import argparse import numpy as np from keras.models import load_model import matplotlib.pyplot as plt import matplotlib.patches as mpatches import matplotlib.lines as mlines import json from sklearn.metrics import roc_curve, auc, f1_score, accuracy_score, recall_score, precision_score import csv from random import ran...
from __future__ import division import warnings import math import numpy __docformat__="restructuredtext en" def identity_matrix(): return numpy.identity(4,dtype=numpy.float64) def translation_matrix(direction): M=numpy.identity(4) M[:3,3]=direction[:3] return M def translation_from_matrix(matrix): return nump...
import unittest from maze import room class TestRoom(unittest.TestCase): def setUp(self): self.r10 = room.Room(1, 0) self.r01 = room.Room(0, 1) self.r00 = room.Room(0, 0) self.r00.passages['N'] = self.r01 self.r00.passages['E'] = self.r10 self.r10.passages['W'] = ...
from typing import List numbers_list: List[int] = [ int(x) for x in input() ] print(f'Odd sum = {sum(filter(lambda n: (n % 2) != 0, numbers_list))}, Even sum = {sum(filter(lambda n: (n % 2) == 0, numbers_list))}')