content
stringlengths
5
1.05M
money = int(input()) money = 1000 - money fh = money // 500 money = money - fh * 500 oh = money // 100 money = money - oh * 100 fy = money // 50 money = money - fy * 50 ten = money // 10 money = money - ten * 10 five = money // 5 money = money - five * 5 one = money money = money - one print(fh + oh + fy + ten ...
import torch from PIL import Image from torchvision import transforms as T import cv2 from torchvision.models.detection import * from loguru import logger import numpy as np import pickle COCO_INSTANCE_CATEGORY_NAMES = [ '__background__', 'person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', '...
# -*- coding: utf-8 -*- import torch as th import torch.nn as nn from leibniz.nn.layer.hyperbolic import BasicBlock, Bottleneck class HyperBasic(nn.Module): extension = 1 least_required_dim = 1 def __init__(self, dim, step, ix, tx, relu, conv, reduction=16): super(HyperBasic, self).__init__() ...
"""The proxy component."""
""" # lint-amnesty, pylint: disable=django-not-configured Mobile API """
import turtle filename = "decoded_wavepattern.txt" #filename = "all about you cutted - decoded.txt" drawStamps = True drawRightLine = False def min(a, b): if (a < b): return a return b def drawgrid(): for i in range(int(len_vert / step_mark * 2)): a.forward(step_mark) ...
import os import numpy as np from PIL import Image import torch from torch import nn from torch.nn.modules.conv import _ConvNd from torch.nn.modules.batchnorm import _BatchNorm import torch.nn.init as initer def knn(x, k=20): inner = -2*torch.matmul(x.transpose(2, 1), x) xx = torch.sum(x**2, dim=1, keepdim=T...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- NAME_LIST = [ 'Dian', 'Nese', 'Falledrick', 'Mae', 'Valhein', 'Dol', 'Earl', 'Cedria', 'Azulei', 'Yun', 'Cybel', 'Ina', 'Foolly', 'Skili', 'Juddol', 'Janver', 'Viska', 'Hirschendy', 'Silka', 'Hellsturn', 'Essa', 'Mykonos', 'Fenton', 'Tyrena', 'Inqoul', 'Mankov...
# -*- coding: utf-8 -*- # Generated by Django 1.10.3 on 2017-02-06 22:53 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('docker_registry', '0001_initial'), ] operations = [ migrations.AlterField( ...
""" Module for processing Rss. Note: The main purpose of this module is to provide support for the RssSpider, its API is subject to change without notice. """ import lxml.etree from six.moves.urllib.parse import urljoin class Rss(object): """Class to parse Rss (type=urlset) and Rss Index (type=rssindex) fil...
from datetime import datetime from enum import Enum from typing import Iterable, Optional from httpnet._core import Element, Service class SpamFilter(Element): banned_files_checks: Optional[bool] delete_spam: Optional[bool] header_checks: Optional[bool] malware_checks: Optional[bool] modify_subjec...
class Solution(object): def detectCycle(self, head): """ :type head: ListNode :rtype: ListNode """ slow = fast = head while fast and fast.next: slow = slow.next fast = fast.next.next if slow == fast: break el...
# BSD 3-Clause License; see https://github.com/scikit-hep/uproot4/blob/main/LICENSE """ This module defines a versionless model for ``TList``. """ from __future__ import absolute_import import struct try: from collections.abc import Sequence except ImportError: from collections import Sequence import uproo...
from django.shortcuts import render, HttpResponseRedirect, HttpResponse from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView from django.db.models.deletion import ProtectedError from guifw.models.host import Host, FormHost # Create your views here. def multipleDelete(request): ...
from dataclasses import dataclass from .node_worker_target_type import NodeWorkerTargetType @dataclass class NodeWorkerTarget: targetCount: float targetType: NodeWorkerTargetType # KEEP @staticmethod def per_node(target_count: int) -> 'NodeWorkerTarget': return NodeWorkerTarget(target_co...
import os import sys import unittest from pyshex import ShExEvaluator from CFGraph import CFGraph class ShexEvalTestCase(unittest.TestCase): def test_biolink_shexeval(self) -> None: base_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'data')) g = CFGraph() g.load(os....
import matplotlib.pyplot as plt import numpy as np from optmize import * fig, axes = plt.subplots(nrows=1,ncols=2, figsize=(12,5)) all_data = loadCsv('./test.20.log') all_data = [np.random.normal(0, std, 100) for std in range(6, 10)] #fig = plt.figure(figsize=(8,6)) axes[0].violinplot(all_data, sh...
import os import re import numpy as np import pandas as pd def make_features(data,data_size,max_chars_per_sentence,max_length_vocab): char_level_features = np.zeros((data_size,max_chars_per_sentence,max_length_vocab)) for i in range(data_size): count = 0 sent_features = np.zeros((max_chars...
""" Generic recording functionality """ from copy import deepcopy from operator import attrgetter from collections import defaultdict from typing import Optional, Type from .system import SystemInterface class Recorder: """Generic recorder functor. Can be used as an `observer` in conjunction with a `Simula...
from io import StringIO from pathlib import Path import pytest from .._yaml_api import yaml_dumps, yaml_loads, read_yaml, write_yaml from .._yaml_api import is_yaml_serializable from ..ruamel_yaml.comments import CommentedMap from .util import make_tempdir def test_yaml_dumps(): data = {"a": [1, "hello"], "b": {...
from __future__ import annotations import io import struct import zipfile from dataclasses import dataclass from typing import Optional @dataclass() class SimpleLauncher: launcher: Optional[bytes] shebang: Optional[bytes] data: bytes # Note: zip def parse_simple_launcher(all_data: bytes, verbose: bool=...
def let_to_num (input): result=0 if input=='a': result=1 elif input=='b': result=2 elif input=='c': result=3 elif input=='d': result=4 return result while True: rotors=['b','c','d','e'] i...
# Convert "arbitrary" image files to rgb files (SGI's image format). # Input may be compressed. # The uncompressed file type may be PBM, PGM, PPM, GIF, TIFF, or Sun raster. # An exception is raised if the file is not of a recognized type. # Returned filename is either the input filename or a temporary filename; # in th...
# -*- coding: utf-8 -*- from .FileserveCom import FileserveCom class FilejungleCom(FileserveCom): __name__ = "FilejungleCom" __type__ = "downloader" __version__ = "0.57" __status__ = "testing" __pyload_version__ = "0.5" __pattern__ = r"http://(?:www\.)?filejungle\.com/f/(?P<ID>[^/]+)" _...
import pytest from gaphor import UML from gaphor.diagram.copypaste import copy, paste_link from gaphor.diagram.group import group from gaphor.diagram.tests.fixtures import copy_clear_and_paste_link from gaphor.UML.deployments import ArtifactItem, NodeItem @pytest.fixture def node_with_artifact(diagram, element_facto...
# Copyright 2015 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. from buildbot.status import builder as build_results from buildbot.status.base import StatusReceiverMultiService from twisted.internet.defer import inlineCal...
# -*- coding: utf-8 -*- import os import json import csv import argparse import pandas as pd import numpy as np from math import ceil from tqdm import tqdm import pickle import shutil import torch import torch.nn as nn from torch.autograd import Variable from torch.nn import CrossEntropyLoss from torchvision import d...
import tqdm import time import os.path as p from itertools import chain import torch import numpy as np import torch.nn.functional as F from datasets import load_from_disk, load_dataset from transformers import TrainingArguments from transformers import AdamW, get_linear_schedule_with_warmup from torch.utils.data impo...
import discord from discord.ext import commands import random class administracion(commands.Cog): def __init__(self, bot): self.bot = bot @commands.command(name='info', alises=['info'], brief="[informacion del servidor]") async def info(self, ctx): embed = discord.Embed(title=f"{ctx.guild....
print('2020-04-09') class Person: name = '34' __age = 0 def __init__(self, name): self.name = name @staticmethod def getname(): print(Person.name) def setAge(self, age): self.__age = age Person.getname() zhang = Person('张三') print(zhang.name) Person.getname() # p ...
from . import util def get_numbers(lines): return [int(line) for line in lines] def find_invalid(numbers, plen): window = set(numbers[:plen]) for idx, target in enumerate(numbers[plen:]): if not any(target - n != n and target - n in window for n in window): return target wind...
from datetime import datetime class Utc_Clock(): def __init__(self): pass def get_time(self): now = datetime.now() return now.second + 60* now.minute + 3600 * now.hour utc_clock = Utc_Clock() print("Current cclk: %d " %(utc_clock.get_time()))
from typing import TYPE_CHECKING, Any, Optional, Type, Union, cast from pypika import Case, Table, functions from pypika.functions import DistinctOptionFunction from pypika.terms import ArithmeticExpression from pypika.terms import Function as BaseFunction from tortoise.exceptions import ConfigurationError from torto...
import unittest,os from deterministic_encryption_utils.encryption.Encryption import Encryption, EncryptionException import tempfile import shutil from deterministic_encryption_utils.encryption.VirtualFile import VirtualFile class TestEncryption(unittest.TestCase): class _SaltProviderMock(object): def getS...
#!/usr/bin/env python # # Copyright 2011 Rodrigo Ancavil del Pino # # 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 click import os from tabulate import tabulate import myhacks as myh @click.command() @click.argument("rootdir", required=False) @click.option("--all/--changes", default=False) @click.option("--fetch/--no-fetch", default=False) @click.option("--outputformat", type=click.Choice(myh.OUTPUTS), default="simple") d...
""" This is stochastic_gradient_descent algorithm """ import numpy as np import matplotlib.pyplot as plt """ Creating the data for model and adding Gaussian Noise """ plt.style.use(['ggplot']) X = 2 * np.random.rand(100,1) y = 4 +3 * X+np.random.randn(100,1) plt.plot(X,y,'b.') plt.xlabel("$x$", fontsize=18) plt.yl...
# MINLP written by GAMS Convert at 04/21/18 13:51:24 # # Equation counts # Total E G L N X C B # 33 1 0 32 0 0 0 0 # # Variable counts # x b i s1s s2s sc ...
from rlgym.utils.state_setters import StateSetter from rlgym.utils.state_setters import StateWrapper import random import numpy as np class DefaultState(StateSetter): SPAWN_BLUE_POS = [[-2048, -2560, 17], [2048, -2560, 17], [-256, -3840, 17], [256, -3840, 17], [0, -4608, 17]] SPAWN_BLUE...
def init_app(app): Api(app)
# # adventure module # # vim: et sw=2 ts=2 sts=2 # for Python3, use: # import urllib.request as urllib2 import urllib2 import random import string import textwrap import time # "directions" are all the ways you can describe going some way; # they are code-visible names for directions for adventure authors directio...
from typing import Iterable def gen_content_block(s: str) -> str: return f"""<div>{s}</div>""" def report(content: Iterable[str]) -> str: result = f""" <!DOCTYPE html> <html> <body> { "".join(gen_content_block(s) for s in content) } </body> </html> """ return result
""" Module containing route for zookeeper journal """ import http.client import json import logging from flask import request, current_app, make_response from journal.main import MAIN # W0611: Unused import # This module import is needed for journal_obj.write from journal import mjournal # pylint: disable=W0611 from...
import random import numpy as np import torch import torch.distributed as dist from torch.utils.data.sampler import Sampler class SubsetSampler(Sampler): """Samples elements sequentially or randomly from a given list of indices, without replacement. Args: indices (list): a list of indices """ ...
"""Test functions for i_square.py. """ from datetime import datetime import os import pytest from squaredown.i_square import SquareInterface @pytest.fixture(name='square_if') def fixture_square_iface(): """Pytest fixture to initialize and return the SquareInterface object. """ # logger.debug(f'using fix...
# -*- coding: utf-8 -*- """ Astro functions ( """ import os import astropy.io.fits as fits import operator from scipy import (special, log10, array, sqrt, sin, exp, log, average, arange, meshgrid, std) from numpy.random import random_sample import numpy as np def CC(z...
import os import cv2 import numpy as np import time from tools.mytracking_sort import MyTrackingSort if __name__ == '__main__': ## ----------------------------------------- ## Init ## ----------------------------------------- # a. Model mt = MyTrackingSort(lenRecord=30, distance_th=0.005, time_th...
import unittest from ansiblelint import RulesCollection, Runner from ansiblelints.rules.HardCodePassword import HardCodePassword class TestHardCodePassword(unittest.TestCase): collection = RulesCollection() def setUp(self): self.collection.register(HardCodePassword()) def test_file(self): ...
import csv import datetime class Backtest(object): def __init__(self, data, brain): self.d = data self.b = brain self.backtest_data = [] self.backtest_data_file = self.d.datadir + '\\' + self.d.tradingpair + str(self.d.timeframe) + '_BACKTEST.csv' self.trade_data = [] ...
from setuptools import setup setup( name="document", version="0.1", packages=["document"], )
''' Roll and dice game ''' import tkinter as tk import random as rd def main(): ''' Main game loop ''' def rolling_dice(): roll.configure(text=rd.choice(dice)) roll.pack() window = tk.Tk() edge = int(window.winfo_screenheight()/2) window.geometry(str(edg...
import datetime import json import socket import redis as redis from channels.generic.websocket import AsyncJsonWebsocketConsumer from djim.models import UserSession, channel, UserList from djim.serializers import usersession_json, user_list_json from utils import const, ipHelper class ChatConsumer(AsyncJsonWebsock...
import uuid from itertools import product from functools import partial import numpy as np import zarr from numcodecs import Blosc from skimage import feature, filters import multiprocessing from scipy.optimize import minimize, basinhopping, differential_evolution from scipy.ndimage import map_coordinates from scipy im...
from django.conf.urls import patterns, url urlpatterns = patterns( 'api.views', url(r'^get_All_SugRec/$', 'get_All_SugRec', name='get_All_SugRec'), )
import sys check_type = int(sys.argv[1]) input_file = sys.argv[2] output_file = sys.argv[3] if check_type == 0: integer_file = sys.argv[4] # Check insertion code input_arr = [] integers = [] with open(input_file) as f: content = f.readlines() content = [x.strip() for x in content]...
from gpiozero import Servo from time import sleep servo = Servo(11) while True: servo.mid() sleep(0.5) servo.min() sleep(0.5) servo.max() sleep(0.5)
import pytest from wowDB import WowDB from wowapi.exceptions import * from dbConnect import config from PIL import Image, ImageChops import io locale = 'en_US' region = 'us' realm = 'Arathor' bnetcred = config('settings.ini', 'bnetcred') client_id = bnetcred['client_id'] client_secret = bnetcred['client_secret'] clas...
# Made by Mr. Have fun! Version 0.2 import sys from com.l2jserver import Config from com.l2jserver.gameserver.model.quest import State from com.l2jserver.gameserver.model.quest import QuestState from com.l2jserver.gameserver.model.quest.jython import QuestJython as JQuest qn = "292_CrushBrigands" GOBLIN_NECKLACE = 14...
import logic.game as game import os import asyncio async def main(print_foo=print, input_foo=input): print_foo('Welcome to Macau Game!') how_many_players = int(input_foo('How many players will play?: ')) if how_many_players < 2: raise Exception('Wrong number of players entered!') how_many_card...
import torch import torch.nn as nn from . import common from .ResNet import ResNet def build_model(args): return MSResNet(args) class conv_end(nn.Module): def __init__(self, in_channels=3, out_channels=3, kernel_size=5, ratio=2): super(conv_end, self).__init__() modules = [ comm...
#!/usr/bin/env python import random import dijkstra import goal import math as np import pygame class PRMGenerator: """ Class used to hold methods and variables that are important for the global path planning problem. This class generates the roadmap and finds the shortest path to the the goals by ...
import argparse def get_args(): parser = argparse.ArgumentParser() parser.add_argument('--key', required=True, help='Slack webhook key') parser.add_argument('--cpu', required=True, type=float, help='Limitation for cpu use percentage') parser.add_argumen...
# I took this very simple app from the gunicorn website. # It's how they suggested getting startd def app(environ, start_response): data = b"Hello, World!\n" start_response("200 OK", [("Content-Type", "text/plain"), ("Content-Length", str(len(data)))]) return iter([data])
# -------------------------------------------------------- # Domain adpatation training # Copyright (c) 2019 valeo.ai # # Written by Tuan-Hung Vu # -------------------------------------------------------- import os import sys from pathlib import Path import os.path as osp import numpy as np import torch i...
#!/usr/bin/env python """ Functions and objects to deal with meteoroids orbits """ __author__ = "Hadrien A.R. Devillepoix, Trent Jansen-Sturgeon " __copyright__ = "Copyright 2016-2017, Desert Fireball Network" __license__ = "MIT" __version__ = "1.0" import numpy as np from numpy.linalg import norm import matplotlib.p...
user = { 'basket': [1, 2, 3], 'greet': 'hello', 'age': 20 } user2 = { 'basket': [10, 20, 30], 'greet': 'hello', 'age': 30 } print(user['basket']) print(user2['basket']) print(user.get('name')) # None print(user.get('name', 'Elena')) # default = 'Elena'; print: Elena checker = 'basket' in use...
import requests def get_quotes(): url ='http://quotes.stormconsultancy.co.uk/random.json' response = requests.get(url) quote =response.json() return quote
# -*- coding: utf-8 -*- """create cities table Revision ID: 333c6c0afa8f Revises: 3741581c7fc4 Create Date: 2017-10-08 15:29:44.416140 """ # revision identifiers, used by Alembic. revision = '333c6c0afa8f' down_revision = '3741581c7fc4' branch_labels = None depends_on = None from alembic import op import sqlalchem...
# test_bsddb3_database.py # Copyright 2019 Roger Marsh # Licence: See LICENCE (BSD licence) """bsddb3_database tests""" import unittest import os try: from .. import bsddb3_database except ImportError: # Not ModuleNotFoundError for Pythons earlier than 3.6 bsddb3_database = None class Bsddb3Database(unitt...
""" utils.py ======== Utility functions Created by Maxim Ziatdinov (email: maxim.ziatdinov@ai4microscopy.com) """ from typing import Union, Dict import jax import jax.numpy as jnp import numpy as onp def enable_x64(): """Use double (x64) precision for jax arrays""" jax.config.update("jax_enable_x64", True)...
#!/usr/bin/env python3 import serial import sys import os import subprocess import hashlib import datetime import time import numpy as np dev = serial.Serial("/dev/ttyUSB0", 115200,timeout=10) def benchmarkBinary(binary): print("Flashing {}..".format(binary)) subprocess.run(["st-flash", "write", b...
import pathlib import os import sys import shutil import json from subprocess import check_output, run, CalledProcessError import time from tempfile import TemporaryDirectory os.chdir('..') repo_dir = pathlib.Path('.') root_files = list(repo_dir.glob('root/**/*.json')) translation_files = set(repo_dir.glob('transl...
# -*- encoding: UTF-8 -*- # Standard imports from os import path, makedirs, remove from dataclasses import dataclass # Third party imports import json from github import Github, AuthenticatedUser from github.GithubException import BadCredentialsException, GithubException from rich.prompt ...
# PyAlgoTrade # # Copyright 2011-2014 Gabriel Martin Becedillas Ruiz # # 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 a...
""" Pay to delegated puzzle or hidden puzzle In this puzzle program, the solution must choose either a hidden puzzle or a delegated puzzle on a given public key. The given public key is morphed by adding an offset from the hash of the hidden puzzle and itself, giving a new so-called "synthetic" public key which has t...
import os import shutil from .helpers import build_in_container def deploy_layer(runtime, env): print('Beginning deployment...') os.chdir('.layer') print('Building layer...') error = build_in_container(runtime) if error: os.chdir('..') shutil.rmtree('.layer') exit() ...
# AUTOGENERATED BY NBDEV! DO NOT EDIT! __all__ = ["index", "modules", "custom_doc_links", "git_url"] index = {"sparsify": "neighbors.ipynb", "hstack": "neighbors.ipynb", "vstack": "neighbors.ipynb", "stack": "neighbors.ipynb", "NMSLibSklearnWrapper": "neighbors.ipynb", "Fa...
"""empty message Revision ID: 623662ea0e7e Revises: d1edb3cadec8 Create Date: 2020-11-24 16:34:02.327556 """ import sqlalchemy_utils from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '623662ea0e7e' down_revision = 'd1edb3cadec8' branch_labels = None depends_on = None...
'''Backup a cluster''' from logging import getLogger import click from hazelsync.cli import with_cluster log = getLogger('hazelsync') @click.command() @click.argument('name') def stream(name): '''Pull some data to ease the backup speed''' with with_cluster(name) as cluster: log.info("Running hazel ...
from __future__ import annotations from typing import TYPE_CHECKING, List, Optional from PyQt5 import QtCore, QtGui, QtWidgets from electroncash import address from electroncash.address import Address, AddressError from electroncash.avalanche.delegation import ( Delegation, DelegationBuilder, WrongDelega...
# coding: UTF-8 """ Simple load balancing with pypar (based on demo3.py from pypar demo package) Felix Richter <felix.richter2@uni-rostock.de> """ import sys import time import numpy import pypar PYPAR_WORKTAG = 1 PYPAR_DIETAG = 2 def mprint(txt): """ Print message txt with indentation following the node...
import os, os.path import errno import json def mkdir_p(path): try: os.makedirs(path) except OSError as e: if e.errno == errno.EEXIST and os.path.isdir(path): pass else: raise def load_json(path): data = {} try: with open(path) as f: ...
import numpy as np import numba as nb import linoplib def jacobi(A, v0, f, nu_1=1): """If for some reason you want to use the original Jacobi solver (not the weighted version), it's implemented here. As I understand it, there's no reason you'd want this for solving Av=f. """ return weighted_jacobi(A,...
# Copyright 2018-present Kensho Technologies, LLC. import codecs import datetime from os import path import random import re import sys from .animals import get_animal_generation_commands from .events import get_event_generation_commands from .species import get_species_generation_commands # https://packaging.pytho...
from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals from __future__ import print_function import os from torch.utils.data import Dataset import numpy as np import json from dataloaders.rawvideo_util import RawVideoExtractor class DiDeMo_DataLoader(Dataset): ...
'''Faça um programa para imprimir: 1 1 2 1 2 3 ..... 1 2 3 ... n para um n informado pelo usuário. Use uma função que receba um valor n inteiro imprima até a n-ésima linha.''' print('-----DESAFIO 100-----') def imprimir(valor): if isinstance(valor, int): x = 1 while ...
# Generated by Django 3.0.5 on 2020-06-14 16:22 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('submission', '0045_auto_20200607_1710'), ] operations = [ migrations.AlterField( model_name='submission', name='stat...
def bubble(lst,size,a=0,b=0): if a == size: return lst else: if b == size: return bubble(lst,size,a+1,a+1) if lst[a]>lst[b]: lst[a],lst[b] = lst[b],lst[a] return bubble(lst,size,a,b+1) def findmed(lst): tmp = lst.copy() tmp = bubble(tmp,len(tmp)) ...
file = open("input", "r") good_passwords = 0 for line in file.readlines(): counts, char, word = line.strip().split() count_low, count_high = counts.split("-") char = char[0] num = word.count(char) if num>=int(count_low) and num <=int(count_high): good_passwords+=1 print(good_passwords)...
import os from typing import ( Any, Sequence, List ) def ensure_list(value: Any) -> List: # if isinstance(value, Sequence) and not isinstance(value, str): if hasattr(value, '__iter__') and not isinstance(value, str): return list(value) else: return [value] def files_exist(files: ...
from typing import Tuple import math import torch import torchaudio from torch import Tensor __all__ = [ 'get_mel_banks', 'inverse_mel_scale', 'inverse_mel_scale_scalar', 'mel_scale', 'mel_scale_scalar', 'spectrogram', 'fbank', 'mfcc', 'vtln_warp_freq', 'vtln_warp_mel_freq', ...
"""Define weapons and their stats""" class Weapon: def __init__(self): self.name = 'Undefined Weapon' self.description = 'Undefined' self.damage = 0 self.value = 0 raise NotImplementedError("Not a real Weapon!") def __str__(self): return self.name class Rock(W...
from .client import ( AnsaClient, get_grpc_connection_options ) from .AnsaGRPC_pb2_grpc import ( LassoAnsaDriverServicer, LassoAnsaDriverStub ) __all__ = [ 'AnsaClient', 'get_grpc_connection_options', "LassoAnsaDriverStub", "LassoAnsaDriverServicer"]
import os from matplotlib import pyplot as plt import numpy as np from mpl_toolkits.mplot3d import Axes3D fig = plt.figure() ax = fig.add_subplot(111, projection='3d') filename = 'part3.npy' x=np.linspace(-1.2,0.6,50) y=np.linspace(-0.07,0.07,50) X,Y = np.meshgrid(x,y) if os.path.exists(filename): data = np.loa...
from pydataset import data import time import sys sys.path.insert(1, '../') import fastg3.ncrisp as g3ncrisp df = data("diamonds") xparams = { 'carat':{ 'type': 'numerical', 'predicate': 'absolute_distance', 'params': [0.05] }, 'x':{ 'type': 'numerical', 'predicate...
import sklearn from sklearn import datasets from sklearn import svm from sklearn import metrics from sklearn.neighbors import KNeighborsClassifier cancer=datasets.load_breast_cancer() # Features print(cancer.feature_names) # Labels print(cancer.target_names) # Splitting Data x = cancer.data # All of the features y =...
from django.core.exceptions import ObjectDoesNotExist from django.db import models from django.utils.translation import gettext_lazy as _ from .location import Location class LocationTracker(models.Model): class Status(models.TextChoices): ACTIVE = "AC", _("Active") INACTIVE = "IN", _("Inactive")...
import pathlib import matplotlib.pyplot as plt import networkx as nx import numpy as np import pandas as pd from fa2 import ForceAtlas2 from matplotlib.collections import LineCollection from ccgowl.data.make_synthetic_data import standardize from ccgowl.evaluation.cluster_metrics import spectral_clustering from ccgow...
# -*- coding: utf-8 -*- from pyramid.exceptions import ConfigurationError from oereb_client import __version__ class Index(object): def __init__(self, request): """Entry point for index rendering. Args: request (pyramid.request.Request): The request instance. """ self...
import re import settings def main(): try: from github import Github from github.GithubException import BadCredentialsException except ImportError: print('No github module found, try running pip install pygithub') return g = Github(settings.ACCESS_TOKEN) try: ...