content
stringlengths
5
1.05M
import sys import json import logging import blosc import boto3 import hashlib import numpy as np from PIL import Image from spdb.c_lib.ndtype import CUBOIDSIZE from spdb.c_lib import ndlib from bossutils.multidimensional import XYZ, Buffer from bossutils.multidimensional import range as xyz_range handler = logging.S...
# -*- coding: utf-8 -*- from __future__ import absolute_import, print_function, unicode_literals import time from ava.util.clock import Clock import pytest @pytest.fixture def clock(): return Clock() class TestClock(object): def test_milliseconds_round_up(self): t = time.time() pt = round(...
"""Simple audio examples""" from taped import LiveWf from know.util import pairwise, source_slices from functools import partial mk_audio_stream = partial( LiveWf, input_device_index=None, # if None, will try to guess the device index sr=44100, sample_width=2, chk_size=4096, stream_buffer_si...
from django import template from django.contrib.sites.models import Site from django.conf import settings from dinette.models import Ftopics, SiteConfig, NavLink register = template.Library() class BaseDinetteNode(template.Node): @classmethod def handle_token(cls, parser, token): tokens = token.cont...
import sys import os from scipy import stats import tenseal as ts import numpy as np from scipy.stats import chi2 sys.path.append(os.path.abspath('../../tensealstat')) from tensealstat.tools_context import ToolsContext as tc from tensealstat.algebra.algebra_numpy import AlgebraNumpy from tensealstat.algebra.algebra_...
""" Classes to define hierarchical configuration options which support inheriting from other options, default values, overriding options, etc. """ from abc import ABC, abstractmethod from copy import deepcopy from dataclasses import dataclass import os from pathlib import Path from typing import Any, Dict, Iterable, I...
class ZaloAppInfo: def __init__(self, app_id, secret_key): self.app_id = app_id self.secret_key = secret_key self.callback_url = None
#!/usr/bin/env python2 from __future__ import print_function from codecs import open from setuptools import setup setup(name="scrapy-moviesinconcert", author="Wieland Hoffmann", author_email="themineo@gmail.com", packages=["scrapy_moviesinconcert"], package_dir={"scrapy_moviesinconcert": "scra...
n = int(input()) a = input().split() t = [int(m) for m in a] m = int(input()) #行列 c = [] for i in range(m):#h:高さ c.append([int(m) for m in input().split()]) k = sum(t) for i in range(m): print(k - t[c[i][0] - 1] + c[i][1])
#! /usr/bin/env python # # Copyright (C) 2013 Olivier Grisel <olivier.grisel@ensta.org> description = """Cloud compute cluster configuration tool""" import sys import os import shutil from distutils.command.clean import clean as Clean DISTNAME = 'cardice' DESCRIPTION = 'Cloud compute cluster configuration tool' #LO...
from src.Transition import Transition from src.Graph import Graph def acceptation(graph, words): """Fonction de vérification d'acceptation de mots par un automate Algorithme prenant un automate déterministe et un mot, et décidant si le mot est accepté par l'automate. Args: graph (Graph): Un ...
import logging from discord.ext.commands import Bot, Cog, Context, command, BucketType from discord.ext import commands import asyncio from butt_library import valid_user_or_bot, vacuum_enabled_in_guild, can_speak_in_channel import mojang log = logging.getLogger('bot.' + __name__) class MojangCog(Cog): def __in...
# # lmbspecialops - a collection of tensorflow ops # Copyright (C) 2017 Albert Ludwigs University of Freiburg, Pattern Recognition and Image Processing, Computer Vision Group # Author(s): Lukas Voegtle <voegtlel@tf.uni-freiburg.de> # # This program is free software: you can redistribute it and/or modify # it unde...
#!/usr/bin/python3 from docopt import docopt import importlib import os import sys import lib.init as init from lib.services import color, git __version__ = "0.9.4" # did you change this in docs/conf.py as well? if git.get_branch() != "master": __version__+= "-"+git.get_branch()+"-"+git.get_commit() __doc__ ...
"""Convert segmentation from RGB encoding to 32 bit TIFF""" import click import numpy as np from dtoolbioimage.segment import Segmentation3D def convert_segmentation(input_fpath, output_fpath, output_encoding): segmentation = Segmentation3D.from_file(input_fpath) segmentation.save(output_fpath, encoding=...
import numpy as np import datetime import torch from dateutil import tz import logging import os import random from nltk.tokenize import WhitespaceTokenizer from allennlp.modules.elmo import batch_to_ids from transformers import BertTokenizer import json from pathlib import Path from collections import Orde...
from rest_framework.response import Response from rest_framework.views import APIView from rest_framework.generics import get_object_or_404 from .models import Article, Author from .serializers import ArticleSerializer, AuthorSerializer class ArticleView(APIView): def get(self, request): articles = Articl...
#: W191 if False: print # indented with 1 tab #: #: W191 y = x == 2 \ or x == 3 #: E101 W191 W504 if ( x == ( 3 ) or y == 4): pass #: E101 W191 if x == 2 \ or y > 1 \ or x == 3: pass #: E101 W191 if x == 2 \ or y > 1 \ or x == 3: pass #: #: E101 W...
""" - Takes fixed points data from fixed point dictionary file - Computes matrix L and eigenvalues for the fixpoint, located, corresponding to a wave with wave numbers (k1,k2). - Creates a subfolder and save the result INPUT: - args: k1, k2, delta0, tol - fixpoint_dict.pkl -> dictionary of fixed points """ import sys ...
with open('../input.txt','rt') as f: lst = set(map(int,f.readlines())) for x in lst: if 2020-x in lst: print(x*(2020-x))
# Problem 2 # (10/10 points) # Assume s is a string of lower case characters. # Write a program that prints the number of times the string 'bob' occurs in s. # For example, if s = 'azcbobobegghakl', then your program should print: Number of times bob occurs is: 2 count = 0 for i in range(len(s)-2): if s[i:i+3] == ...
# -*- coding: utf-8 -*- # Generated by Django 1.11.6 on 2017-11-06 22:49 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('catalog', '0004_auto_20171106_1747'), ] operations = [ migrations.AddField(...
from IPython import embed from engine import * class CLI(): def __init__(self): self.query = "\nLast move: {}\nYour move: " def gen_move(self, engine, color): last = engine.last_move last = "" if not last else engine.string_from_move(last) while True: print(engine)...
""" Classes, that represents various value types that can appear in the configuration and problem definitionfiles. Each grammar type can both parse string containing a value of a given type, and to create the string containing a given value. """ import pyparsing as pp import io import inspect from pyparsing import W...
#!/usr/bin/env python3 import requests import sys from random_rekt import random_rekt import time from decouple import config from promote import promote from demote import demote from notes import notes, save, del_note, get from time_convert import time_convert from pin_message import pin_msg, unpin_msg from userManag...
from prkng.database import db class Analytics(object): @staticmethod def get_user_data(): today = db.engine.execute(""" SELECT count(id) FROM users WHERE (created AT TIME ZONE 'UTC') AT TIME ZONE 'US/Eastern' >= (NOW() AT TIME ZONE 'US/Eastern')::date ...
#Faça um programa que leia uma matriz 3x3 de inteiros #e retorne a linha de maior soma. #Imprima na tela a matriz, #a linha de maior soma #e a soma. from random import randint mat=[] for i in range(3): linha=[] for j in range(3): linha.append(randint(1,10)) mat.append(linha) for i in range(3): ...
#! /usr/bin/env python3 # -*- coding: utf-8 -*- """Support functions for connecting with libreoffice Calc.""" # standard imports import numpy as np from pathlib import Path import os import inspect import psutil import signal import subprocess import time import warnings # import uno from unotools import Socket, conn...
# coding:utf-8 #import导包部分 import requests import base64 import re import rsa import urllib import json import binascii import time ''' #INFO信息说明 1, 在提交POST请求之前, 需要GET 获取两个参数。 地址是:http://login.sina.com.cn/sso/login.php?client=ssologin.js(v1.3.18) 得到的数据中有 "servertime" 和 "nonce" 的值, 是随机的,其他值貌似没什么用。 2, 通过ht...
from os import getenv import logging from flask import Flask, request from glados import ( Glados, GladosBot, GladosRequest, RouteType, SlackVerification, GladosRouteNotFoundError, read_config, ) from test_plugin.test_plugin import TestPlugin from example import FLASK_HOST, FLASK_PORT impo...
# Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 # Licensed under the Apache License, Version 2.0 https://aws.amazon.com/apache-2-0/ import boto3 import sys import time import os import json try: agent_config_file = os.environ['AGENT_CONFIG_FILE'] ex...
import time class Timer: def __init__(self): self._start = None self.duration = [] def __enter__(self): self._start = time.time() return self def __exit__(self, *args, **kwargs): self.duration.append(time.time() - self._start)
from typing import Any class Pagination: def __init__(self, items: list[Any], page: int, per_page: int, total: int): self.items = items self.page = page self.per_page = per_page self.total = total def __repr__(self) -> str: return f'<Pagination {self.page}:{self.per_pa...
import re import os def Test(fPath): # fPath = r'C:\Users\jackw\Documents\弹幕姬\Plugins\DanmuLog\Data-10313214-20220116.txt' fp = open(fPath,'r',encoding='utf-8') lines = fp.readlines() lastLine = lines[-1] print(lastLine) test= lastLine pattern = r'Uname":"([\w\u4E00-\u9FA5\-_]{4,16}[^"])", ...
from rest_framework.response import Response def success(self, message, data, total): return { success: True, self.__message: message, self.__data: data, self.__total: total } def not_found(self, message, data): return { success: False, self.__message: mes...
import pytest import torch from easydict import EasyDict from ding.policy.r2d3 import R2D3Policy from ding.utils.data import offline_data_save_type from tensorboardX import SummaryWriter from ding.model.wrapper.model_wrappers import ArgmaxSampleWrapper, HiddenStateWrapper, EpsGreedySampleWrapper import os from typing i...
import time import serial def getBeacons(ser: serial.Serial): beacons = [] ser.write(b'S') res = b'' while True: res += ser.read(ser.inWaiting()) time.sleep(0.01) if res.endswith(b'OK+DISCE\r\n'): break for line in res.split(b'\r\n'): ...
""" Testing Script testing from commandline: put: curl http://localhost:5000/CsvReader/path1 -d "csvFilePath=C:/Users/Nicho/Desktop/Projects/CsvPlotterAndGrapher/csvTest.csv" -X PUT get: curl http://localhost:5000/CsvReader/path1 """ from flask import Flask, request from requests import get,put def read_csv(...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- #.--. .-. ... .... -. - ... .-.-.- .. -. import click from flask.ext.script import Manager from shady import create_app, app manager = Manager(app) @manager.command def runserver(): "Runs the App" create_app() app.run(host = app.config['SERVE_HOST'], ...
from enum import Enum, Flag, IntEnum, IntFlag class MyEnum(Enum): a = "letter a" b = "letter b" class MyStrEnum(str, Enum): a = "letter a" b = "letter b" class MyIntEnum(IntEnum): a = 1 b = 2 class MyFlag(Flag): a = 1 b = 2 class MyIntFlag(IntFlag): a = 1 b = 2
import pickle from nose.tools import eq_ from .. import revision from ....datasources import revision_oriented from ....dependencies import solve h_headings_ds = revision.datasources.heading_titles_matching(r"h") h_headings = revision.heading_titles_matching(r"h") lvl_2_headings_ds = revision.datasources.headings_by...
import os def check_dir(): return os.getcwd()
import pytest from carsus.util.selected import element, element_range, \ selected_atoms, parse_selected_atoms, species_entry, \ parse_selected_species @pytest.mark.parametrize("test_input, exp_atomic_number",[ ("H", 1), ("Zn", 30), ("Uuo", 118), ("h", 1) ]) def test_element(test_input, exp_at...
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import pulumi import pulumi.runtime class Router(pulumi.CustomResource): """ Manages a V2 router resource within OpenStack. ...
# coding: utf-8 # /*########################################################################## # # Copyright (c) 2004-2016 European Synchrotron Radiation Facility # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to d...
# -*- coding: utf-8 -*- import pandas as pd import numpy as np import matplotlib.pyplot as plt import scipy.misc from scipy.ndimage import rotate from scipy.stats import bernoulli import cv2,os import scipy.misc import cv2 #PATH = './data_extra' PATH = './data/' data_csv = '/driving_log.csv' DRIVING_LOG_FILE = ''#'./d...
import os from yozuch.generators.template import TemplateEntry, TemplateGenerator class PageGenerator(TemplateGenerator): def __init__(self, url_template, name): super().__init__(url_template, name, None) def generate(self, context): for filename in context.site.get('pages', []): ...
# -*- coding: utf-8 -*- from setuptools import setup, find_packages with open('README.rst') as f: readme = f.read() with open('LICENSE') as f: license = f.read() setup( name='name_extractor', version='0.1.0', description='Statistical name extractor for HTML.', long_description=readme, author='João Mat...
import itertools import logging import re from logrec.dataprep.model.containers import ProcessableTokenContainer from logrec.dataprep.model.word import ParseableToken from logrec.dataprep.preprocessors import java from logrec.dataprep.model.chars import NewLine, MultilineCommentEnd, MultilineCommentStart, \ OneLi...
"""ResNeXt architecture. Based on: https://arxiv.org/abs/1611.05431 Original implementation: https://github.com/facebookresearch/ResNeXt This model is based on torchvision's ResNet model: https://github.com/pytorch/vision/blob/master/torchvision/models/resnet.py """ import torch.nn as nn import torch.ut...
import idc import idaapi # Vient d'un projet perso # Le code est potentiellement trouvable sur internet a mon nom. all_breakpoint = {} class BreakPoint(object): BP_TYPE = idc.BPT_DEFAULT BP_SIZE = 0 def __init__(self, addr, size=None): if size is None: size = self.BP_SIZE se...
import berserk class Bots(berserk.clients.Bots): def decline_challenge(self, challenge_id, reason="generic"): """Decline an incoming challenge. :param str challenge_id: ID of a challenge :param str reason: reason for declining :return: success :rtype: bool """ ...
from typing import Union from torch import Tensor from torch.nn import Module from torch.nn import functional as F class Interpolate(Module): def __init__( self, size: Union[int, tuple] = None, scale_factor: Union[float, tuple] = None, mode: str = "nearest", align_corners:...
import numpy as np from game_state_base import BaseGameState class AccumulateGameState(BaseGameState): environment_shape = [1] def _reset(self): self.state = 0 def _score(self): return self.state def _terminal(self): self.time_steps = 100 def _apply_action(self, action)...
import unittest from rcd_str import capitalize_word_sequences class TestCapita(unittest.TestCase): def test(self): self.assertEqual(capitalize_word_sequences('усть-каменогорск'), 'Усть-Каменогорск') self.assertEqual(capitalize_word_sequences('нижний тагил'), 'Нижний Тагил...
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under t...
import random as r s = ["a","e","i","o","u"] li = [] for i in range(r.randint(1,20)): temp = "" for j in range(r.randint(1,10)): temp += r.choice(s) li.append(temp) print(len(li)) for i in li: print(i) # print(30 | 28)
import du from du._test_utils import equal def test_memoize(): x = [0] @du.memoize def foo(): x[0] += 1 equal(x[0], 0) foo() equal(x[0], 1) foo() equal(x[0], 1) def test_attr_dict(): x = du.AttrDict(foo=3, bar=2) equal(x.foo, 3) x.bar = 4 equal(x.bar, 4)
import unittest import subprocess import requests import time import json from glockr.config import PORT from glockr.client import GClient BASE_URL = 'http://127.0.0.1:{}'.format(PORT) class TestClient(unittest.TestCase): _server_process = None @staticmethod def get_current_dict() -> dict: targ...
""" 迁移学习的网络结构 """ import os import torch import torch.nn as nn from torchvision import datasets, models, transforms import torch.nn.functional as F try: import softpool_cuda from SoftPool import soft_pool2d, SoftPool2d except ImportError: print('Please install SoftPool first: https://github.com/alexandros...
# Notes # This module not really designed for general purpose use. I wrote this as a study mechanism for # decomposition algorithms. The codes are not well tested and may be naive. # # lapack working notes at http://www.netlib.org/lapack/lawns/ import pyJvsip as pv def eye(t,n): """ Usage: I=eye(t,n) cre...
# -*- coding: utf-8 -*- import os import sys from PySide2.QtWidgets import QApplication from nodedge.logger import highLightLoggingSetup, setupLogging from nodedge.mdi_window import MdiWindow from nodedge.utils import dumpException sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "..")) # noqa: E402...
# Extract radar traffic count data from KITS database and publish # new records to City of Austin Open Data Portal. # Attributes: # socrata_resource (str): Description import hashlib import pdb import arrow import knackpy import _setpath from config.secrets import * import argutil import datautil import emailuti...
# coding: utf-8 from __future__ import unicode_literals from .common import InfoExtractor class MuseScoreIE(InfoExtractor): _VALID_URL = r'(?:https?://)(?:www\.)?musescore\.com/(?:user/\d+|[^/]+)(?:/scores)?/(?P<id>[^#&?]+)' _TESTS = [{ 'url': 'https://musescore.com/user/73797/scores/142975', ...
import random print('____________________________________') print('| |') print('| Bem vindo ao Jogo de Adivinhação |') print('|__________________________________|\n') numero_secreto = random.randrange(1,101) #gera numero entre 0.0 1.0 total_de_tentativas = 0 pontos = 1000 print('Esco...
from __future__ import print_function ''' Arabic Handwritten Digit Recognition Using DNN Akm Ashiquzzaman Fall 2016 13101002@uap-bd.edu zamanashiq3@gmail.com The Simple Convnet model classifing ''' #Numpy and Scipy Import import numpy as np np.random.seed(1337) ''' In 1000 epoch Test score: 0.196029246261 Test a...
# 「3Dビュー」エリア → 「メッシュエディット」モード → ツールシェルフ → 「シェイプキーツール」パネル import os, re, sys, bpy, time, bmesh, mathutils from . import common """ class VIEW3D_PT_tools_mesh_shapekey(bpy.types.Panel): bl_label = "シェイプキーツール" bl_idname = 'VIEW3D_PT_tools_mesh_shapekey' bl_region_type = 'TOOLS' bl_space_type = 'VIEW_3D' bl_category ...
import time import requests from importlib import reload from _config import * def get_safe(url, headers=None, cookies=None, error=0, rtype='text'): try: response = requests.get(url, headers=headers, cookies=cookies) except Exception as e: if error > 2: return '' print(str(...
import cv2 from matplotlib import pyplot as plt cv2.ocl.setUseOpenCL(False) img1 = cv2.imread('test.jpg',0) # training image blur1 = cv2.GaussianBlur(img1,(5,5),0) ret1,th1 = cv2.threshold(blur1,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU) img2 = cv2.imread('test.jpg',0) #query image blur2 = cv2.GaussianBlur(img...
from __future__ import print_function, division import argparse import sys import torch from torch.utils.data import DataLoader import torchvision import pandas as pd from utils import net_builder from ssl_dataset import SSL_Dataset, construct_transforms, get_transform from haparams import create_hparams def main(a...
from classifier import clf from flask import Flask, render_template, jsonify, request, json from hand_data import get_hand_position from lib import Leap import pickle import random import redis app = Flask(__name__) controller = Leap.Controller() controller.set_policy(Leap.Controller.POLICY_BACKGROUND_FRAMES) past_s...
import pytoml as toml import os def load_env(): """ load environment variables from the environment. If empty, use default values from config.toml.example. :return: config dictionary of dictionaries. """ with open('config.toml.example') as defaultconf: configdict = toml.load(defaultco...
import matplotlib.pyplot as plt def graph(l_Gs, l_Ds): fig = plt.figure(figsize=(10, 7)) loss = fig.add_subplot(1, 1, 1) loss.plot(range(len(l_Gs)), l_Gs, label='Generator Loss') loss.plot(range(len(l_Ds)), l_Ds, label='Discriminator Loss') loss.set_xlabel('epoch') loss.set_ylabel('loss') loss...
''' Question 10 Write a program that accepts a sequence of whitespace separated words as input and prints the words after removing all duplicate words and sorting them alphanumerically. Suppose the following input is supplied to the program: hello world and practice makes perfect and hello world again Then, the output ...
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by...
class Solution: def shortestCommonSupersequence(self, str1: str, str2: str) -> str:
import networkx as nx import numpy as np import scipy def is_symmetric(A, tol=1e-8): return scipy.sparse.linalg.norm(A - A.T, scipy.Inf) < tol def get_tsp_features(G): """ Generates a list of TSP based features for the given graph Args: G (object): networkx graph object Returns: ...
# terrascript/data/pagerduty.py import terrascript class pagerduty_escalation_policy(terrascript.Data): pass class pagerduty_schedule(terrascript.Data): pass class pagerduty_user(terrascript.Data): pass class pagerduty_team(terrascript.Data): pass class pagerduty_vendor(terrascript.Data): ...
from HDMR import RBF_HDMR from Objective_function import Func_3d from collections import OrderedDict import numpy as np from pyGPGO.GPGO import GPGO from pyGPGO.surrogates.GaussianProcess import GaussianProcess from pyGPGO.acquisition import Acquisition from pyGPGO.covfunc import matern52 import warnings f_objective =...
def linear_search(the_list, target): for x in range(len(the_list)): if the_list[x] == target: print("Found at index", x) return x print("Target is not in the list") return -1 my_list = [6 ,3, 4, 2, 5, 7] linear_search(my_list, 5) linear_search(my_list, 3) lin...
import numpy as np from tqdm import tqdm from mf.knnbased import MFKnn from mf.centbased import MFCent from mf.hyperplanebased import MFHyperPlaneErrors, MFHyperPlaneAcima class MetaFeatures(object): """ Implementation of """ def __init__(self, groups, k: int = -1): #cosknn, coscent, l2knn, l2cent, k_neig: i...
# Generated by Django 2.1.7 on 2020-02-19 12:15 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('roboPortal', '0003_auto_20200219_1730'), ] operations = [ migrations.AlterField( model_name='problem_statement', nam...
# Copyright The IETF Trust 2016, All Rights Reserved import six import debug # pyflakes:ignore from inspect import isclass from django.conf.urls import url as django_url from django.views.generic import View def url(regex, view, kwargs=None, name=None): if callable(view) and hasattr(vi...
from typing import Any import os.path import pandas as pd def read_num_profiles(filepath: str, column_length: int = 12) -> int: with open(filepath, "r") as f: first_part = f.readline()[:column_length] no_spaces = "".join(first_part.split(" ")) return int(no_spaces) def read_all_profi...
# Copyright 2014 Intel Corporation. # 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 requ...
import json import logging import platform from pathlib import Path import requests from rich import print log = logging.getLogger(__name__) if platform.system() == 'Windows': from .terminal_commands.windows import * elif platform.system() == 'Linux' or platform.system() == 'Darwin': from .terminal_commands....
import urllib2 import urllib import json import datetime import hashlib import base64 import binascii import hmac import os import time import webapp2 from webapp2_extras import auth from webapp2_extras import sessions from google.appengine.api import memcache from google.appengine.api import users from google.appeng...
"""Query interfaces and their information of a device.""" from typing import Dict, Callable, List, Any import pytest from nornir.core.filter import F from nornir.core.task import MultiResult, Result from nornir_napalm.plugins.tasks import napalm_get from nuts.context import NornirNutsContext from nuts.helpers.filters...
# !/usr/bin/python # -*- coding:utf-8 -*- import numpy as np import matplotlib.pyplot as plt import sklearn.datasets as ds import matplotlib.colors from sklearn.cluster import AffinityPropagation from sklearn.metrics import euclidean_distances if __name__ == "__main__": N = 400 centers = [[1, 2], [-1, -1], [1...
def test_import(): """Test the imports work""" import poker_ai from poker_ai import ai, poker from poker_ai.ai import runner from poker_ai.terminal import runner from poker_ai.games.short_deck import player, state from poker_ai.poker import actions, card, dealer, deck, engine, player fro...
from autoflow.workflow.components.data_process_base import AutoFlowDataProcessAlgorithm __all__ = ["RepeatedEditedNearestNeighbours"] class RepeatedEditedNearestNeighbours(AutoFlowDataProcessAlgorithm): class__ = "RepeatedEditedNearestNeighbours" module__ = "imblearn.under_sampling"
string = "hello world python" print(string.title())
from .register import RegisterSerializer from .login import LoginSerializer
''' This package is the base Python client for the Spreader distributed work system. The client should be fairly lightweight, to allow easy portability. Since all the work is done on the DB server, that should be fairly easy to accomplish. ''' NAME = 'pyspreader'
# -*- coding: utf-8 -*- from setuptools import setup setup( name='locust_exporter', version='1.1.0', description="Website load testing framework", long_description="""Locust is a python utility for doing easy, distributed load testing of a web site""", classifiers=[ "License :: OSI Approve...
import unittest, time, sys sys.path.extend(['.','..','py']) import h2o, h2o_cmd, h2o_hosts, h2o_glm, h2o_browse as h2b, h2o_import as h2i class Basic(unittest.TestCase): def tearDown(self): h2o.check_sandbox_for_errors() @classmethod def setUpClass(cls): localhost = h2o.decide_if_localhost...
# Copyright 2019 Allan Galarza # # 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 writi...
# -*- coding: utf-8 -*- """ 邮件提醒功能 """ import smtplib from email.mime.text import MIMEText from email.header import Header class EmailNotification(object): """邮件提醒类""" sender = 'hujb2015@163.com' password = 'IlovePython' smtpserver = 'smtp.163.com' enable = False @staticmethod def set...
# coding: utf-8 import re from collections import Counter LOGNAME = '../data/201603021414.log' MOVEREX = re.compile('/move/([rps]+)/([rps]+)', re.I) MOVES = "rps" DRAW = 0 HWIN = 1 CWIN = -1 # implementera i JS def switch_count(s, step=1): cnt = Counter() trucnt = Counter() prev = None i = 1.0 ...
import numpy as np import subprocess, os, shutil from astropy.io import fits, ascii as ap_ascii from astropy.table import Table def TelluricCorrectPrimary(path_list,probenum,molecfit_dir=''): hdulist = fits.open(path_list[1]) fibre = hdulist['FIBRES_IFU'] # Load in SS flux data ww = np.wher...