content
stringlengths
5
1.05M
from .reconstruction_GA import * from .reconstruction_single import * from .reconstruction_multi import * from .phasing import *
#!/usr/bin/env python3 import scrape_common as sc import re print('BE') d = sc.download('https://www.besondere-lage.sites.be.ch/besondere-lage_sites/de/index/corona/index.html') sc.timestamp() # 2020-03-30 """ <table cellspacing="0" summary="Laufend aktualisierte Zahlen zu den Corona-Erkrankungen im Kanton Bern"...
""" The app does not use the script while it is running. It was used for extracting russian comics data from xkcd_ru_tg_channel.html (get by "fully scrolled" https://t.me/s/xkcdru). (The images urls are relevant only for a day!) Saved for history. """ import re import json import aiofiles import aiofiles.os import aio...
import numpy from LU_Decomposition import backward_substitution, forward_substitution t = linspace(0,1,50) n = 12 m = 50 A = [] for i in range(m): z = [] for j in range(n): z.append(t[i]**j) A.append(z) A = array(A) b = array([cos(4*t)]).T # LU decomposition print("Chlolesky") M = A.T@A L = chol...
from src.services.crawler import Crawler from fastapi import APIRouter, Query router = APIRouter() @router.get("/") async def get_marketplace_data( item = Query(None), interval = Query(None) ): fields = { 'item': item, 'interval': interval } try: result = await Crawler.ge...
from lafontaine.helpers.feature_types import FeatureType from lafontaine.feature_director.feature_result.base_feature_result import BaseFeatureResult class SingleFrameFeatureResult(BaseFeatureResult): def __init__(self, result: bool, frames: int, feature: str): super().__init__(result, frames, feature, Fe...
#!/usr/bin/env python import argparse import glob import os import shutil from ard_gsm.mol import MolGraph, SanitizationError from ard_gsm.qchem import QChem, QChemError def main(): args = parse_args() os.makedirs(args.out_dir, exist_ok=True) for logfile in glob.iglob(os.path.join(args.qlog_dir, '*.log...
import proxybase import xmlrpclib import mimetypes import os import data ################################################################################ """ getInst returns an instance of a wpproxy object """ def getInst(url, user, password): wp = WordpressProxy(url, user, password) return wp ##########...
# Copyright (C) 2011 Sven Petai <hadara@bsd.ee> # Use of this source code is governed by the MIT license found in the LICENSE file. import sys import serial DEBUG_PROTOCOL = False def _string_convert_py3(s): if type(s) == type(b''): return s return bytes(s, 'latin-1') def _string_convert_py2(s): ...
#!/usr/bin/env python3 import os, os.path, sys from glob import glob import lxml.etree import re from builder_common import * def get_classes_conditional(doxy_xml_files, cond): """Get classes and members from a list of Doxygen XML files that meet the given condition.""" found = {} for xmlfile in d...
import tensorflow as tf import tensorflow as tf import numpy as np from tensorflow import keras from tensorflow.contrib import lite model=keras.Sequential([keras.layers.Dense(units=1,input_shape=[1])]) model.compile(optimizer='sgd',loss='mean_squared_error') xs=np.array([-1.0,0.0,1.0,2.0,3.0,4.0]) ys=np.array...
#!/usr/bin/env python from __future__ import print_function import boto3 import json import logging import os import requests import time import zlib from base64 import b64decode logger = logging.getLogger() logger.setLevel(logging.INFO) def lambda_handler(event, context): sqs = boto3.resource('sqs') c7n ...
from dataclasses import dataclass, field from enum import Enum from typing import Optional __NAMESPACE__ = "NISTSchema-SV-IV-list-NCName-enumeration-2-NS" class NistschemaSvIvListNcnameEnumeration2Type(Enum): EI_BENEFIT_W_TTHE_ARE_IS_CHAIRING_OF_TRANS_GSTAKEHOLDERS_ASKED_TO_BANDWIDTH_SENSE_INDUSTRY_OBJE_PROJECT_...
from bs4 import BeautifulSoup import urllib from urllib.request import urlopen import pymysql import pymysql.cursors #This function is for correcting the fetched texts. def strip_func(list): list = [s.strip('\r\n ') for s in list] list = [w.replace('\r', ' ') for w in list] list = [w.replace('\n', '...
# coding=utf-8 # Copyright 2020 The Tensor2Tensor Authors. # # 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...
from absl import flags import carla import erdos import sys import pylot.flags import pylot.operator_creator import pylot.perception.messages from pylot.perception.camera_frame import CameraFrame from pylot.perception.point_cloud import PointCloud from pylot.simulation.sensor_setup import RGBCameraSetup import pylot.u...
from ray import tune def get_config(): return { # === Environment === "env": "HalfCheetahBulletEnv-v0", "env_config": {"max_episode_steps": 1000, "time_aware": False}, # === Replay Buffer === "buffer_size": int(2e5), # === Optimization === # Name of Pytorch ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals __version__ = '0.0.1' import frappe @frappe.whitelist() def get_items(jf): s=[] t=[] t_qty = 0 t_amount = 0 doc = frappe.get_doc("Job Form",jf) for i in doc.get("job_item"): t_qty += i.qty t.append({"item_code":i.production_item,"item_name":i.i...
import discord from discord_slash import cog_ext, SlashContext from discord.ext import commands import json class Slash(commands.Cog): def __init__(self,client): self.client = client @commands.command(brief="work in progress") async def wip(self,ctx): await ctx.send("Slash commands are in work in progre...
from django.db import models from django.utils.text import slugify from django.urls import reverse from scieio.manufacturers.models import Manufacturer from scieio.categories.models import Category class Seller(models.Model): service_line = models.ForeignKey( Category, on_delete=models.CASCADE, ...
import numpy as np from os import sys, path import urllib2 import json import sys if __name__ == '__main__': gene_info_file = sys.argv[1] output_file = sys.argv[2] start = int(sys.argv[3]) geneLen = int(sys.argv[4]) res = np.loadtxt("jk.csv", dtype=int) outputStrings = [] for i in range(sta...
#!/usr/bin/env python3 """ Polar axes using azimuth and radius instead of *x* and *y*. """ import matplotlib.projections as mproj import matplotlib.ticker as mticker import numpy as np from .. import constructor from .. import ticker as pticker from ..config import rc from ..internals import ic # noqa: F401 from ..in...
from flask import jsonify from flask_restplus import Resource, Namespace, fields from flask_app.models.user import User from flask_jwt_extended import (JWTManager,create_access_token, create_refresh_token, get_jwt_identity, set_access_cookies, set_refresh_cookies, unset_jwt_cookies, jwt_...
from logging import basicConfig, getLogger, INFO from connect_to_ledger import create_qldb_driver from amazon.ion.simpleion import dumps, loads logger = getLogger(__name__) basicConfig(level=INFO) import datetime from constants import Constants from create_purchase_order_to_manufacturer import get_orderer_id from regi...
import traceback import functools import pdb import sys import torch import nestedtensor import unittest from utils import TestCase import random import utils ntnt = nestedtensor.nested_tensor # Given arguments to a constructor iterator over results for # as_nested_tensor and nested_tensor constructors. def _iter...
__version__ = '1.3.0' __author__ = 'Aashutosh Rathi <aashutoshrathi@gmail.com>' __all__ = []
#!/usr/bin/env python3 from db.conn import * # Open a cursor to perform database operations cur = conn.cursor() # Collecting column names columns = [] # Execute query cur.execute("select column_name from information_schema.columns where table_schema = 'public' and table_name = 'employee';") results = cur.fetchall()...
import unittest import stactools.package class TestModule(unittest.TestCase): def test_version(self): self.assertIsNotNone(stactools.package.__version__)
from __future__ import annotations import json import logging import os import sys from collections import defaultdict from typing import ( TYPE_CHECKING, Any, ContextManager, Dict, Optional, Sequence, Tuple, Type, TypeVar, cast, ) import boto3 from grapl_analyzerlib.grapl_clie...
from django.db import models from mptt.models import MPTTModel, TreeForeignKey from django.utils.translation import ugettext as _ class Channel(models.Model): name = models.CharField( max_length= 100, verbose_name=_("channel name"), ) primary_topic_tree = models.ForeignKey( 'TopicT...
from typing import Dict from objects.base import BaseModel class RegexDeleter(BaseModel): name: str regex: str chat_id: int for_all: bool def save(self) -> Dict[str, int]: return { 'name': self.name, 'regex': self.regex, 'chat_id': self....
# ----------------------------------------------------------------------------- # Copyright 2018 by I3py Authors, see AUTHORS for more details. # # Distributed under the terms of the BSD license. # # The full license is in the file LICENCE, distributed with this software. # ---------------------------------------------...
# -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making BK-BASE 蓝鲸基础平台 available. Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved. BK-BASE 蓝鲸基础平台 is licensed under the MIT License. License for BK-BASE 蓝鲸基础平台: ---------------------------------------------...
# Copyright 2021 Universidade da Coruña # # 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 ...
__author__ = 'Alex Gusev <alex@flancer64.com>' import json import logging import random from prxgt.config import Config from prxgt.domain.attribute import Attribute from prxgt.domain.instance import Instance, ATTR_ID_NAME from prxgt.domain.meta.attribute import Attribute as MetaAttribute from prxgt.repo.generator impo...
# Copyright 2015 IBM Corp. # # 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, so...
from io import BytesIO from django.http import HttpResponse from django.template.loader import get_template from .persian import PersianCalendar # from xhtml2pdf import pisa import qrcode import qrcode.image.svg from datetime import datetime from datetime import timedelta from openpyxl import Workbook from django.htt...
from sympy import invert, root, gcd from Crypto.Util.number import * n = 0x3ff77ad8783e006b6a2c9857f2f13a9d896297558e7c986c491e30c1a920512a0bad9f07c5569cf998fc35a3071de9d8b0f5ada4f8767b828e35044abce5dcf88f80d1c0a0b682605cce776a184e1bcb8118790fff92dc519d24f998a9c04faf43c434bef6c0fa39a3db7452dc07ccfced9271799f37d91d56b5...
# --------------------------------------------------------------------- # IGetFDPNeighbors # --------------------------------------------------------------------- # Copyright (C) 2007-2011 The NOC Project # See LICENSE for details # --------------------------------------------------------------------- # NOC Modules fr...
from django.conf.urls import patterns, url, include from api import UserResource user_resource = UserResource() urlpatterns = patterns('', url(r'^auth/', include(user_resource.urls)), (r'^users/edit/change-user-role-service/?$', 'api.views.change_user_role_service'), (r'^networks/edit/change-network-mem...
# -*- coding: utf-8 -*- from datetime import datetime from typing import Any, Optional, List from re import sub as re_sub from recc.chrono.datetime import today from recc.variables.database import ( TABLE_USER, TABLE_PROJECT, TABLE_PERMISSION, TABLE_GROUP_MEMBER, TABLE_PROJECT_MEMBER, DEFAULT_P...
# Train DCGAN model on CIFAR-10 data or other specified data # Originally written by Kingsley Kuan import tensorflow as tf import logging import importlib from data import utilities logger = logging.getLogger("gan.train") # Create CIFAR-10 input BATCH_SIZE = 32 def train(dataset, except_class_to_ignore, stop=300000)...
from __future__ import absolute_import # coding=utf-8 from flask_security import login_required from flask_login import current_user from flask_restful import Resource from firefly.models.user import User from .consts import OK, NOTFOUND, EXISTING from .utils import generate_status_fields class FollowUserApi(Resourc...
# Generated by Django 3.2.8 on 2021-11-05 21:22 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('django_airavata_auth', '0008_auto_20210422_1838'), ] operations = [ migrations.AlterField( model_name='emailverification', ...
import codecs import json import tldextract DATA_FILE = "/home/rkapoor/Documents/ISI/data/DIG-Nov-Eval/gt-v02-all.jl" DOMAIN_OF_INTEREST = 'backpage.com' def safe_copy(json_from, json_to, field): if field in json_from and json_from[field] is not None: json_to[field] = json_from[field] def get_domain(jso...
from django.conf.urls import patterns, url from . import views urlpatterns = patterns('', url(r'(?P<year>\d{4})-(?P<month>0[1-9]|1[0-2])-(?P<day>0[1-9]|[1-2][0-9]|3[0-1])/$', views.DayLogViewer.as_view(), name="log_day"), url(r'(?P<year>\d{4})-(?P<month>0[1-9]|1[0-2])-(?P<day>0[1-9]|[1-2][0-9]|3[0-1])...
from abc import ABCMeta, abstractmethod class UnionFind(object): __metaclass__ = ABCMeta @abstractmethod def union(self, v, w): pass @abstractmethod def connected(self, v, w): pass @staticmethod def create(size): return QuickUnion(size) class QuickFind(UnionFin...
from enum import Enum class ControlAction(Enum): RECONNECT = 'reconnect' START = 'start' STOP = 'stop'
import shutil import os import json import time import subprocess from pathlib import Path # variable GitPath = "" # Will return mod directory name def ExportMod(): directory = "build/libs" print("Directory : " + directory) files = os.listdir(directory) for f in files: print(" -- " + str(f)) shutil....
from django.contrib.auth.decorators import login_required from django.http import HttpResponse from django.shortcuts import render, redirect from ..forms import TarefaForm from ..entidades.tarefa import Tarefa from ..services import tarefa_service # Create your views here. @login_required() def listar_tarefas(request...
import boto3 import wget import json import numpy as np import sys import time start = time.time() endpoint_name = sys.argv[1] configuration_file = sys.argv[2] with open(configuration_file) as f: data = json.load(f) commit_id = data["Parameters"]["CommitID"] timestamp = data["Parameters"]["Timestamp"] endpoin...
# coding: utf-8 from fablib import python class Ceres(): def __init__(self): return def setup(self): python.setup() python.install_from_git('ceres', 'https://github.com/graphite-project/ceres.git')
import re from typing import List, Optional from pydantic import UUID4 from fief.db.workspace import get_workspace_session from fief.managers import ( ClientManager, TenantManager, WorkspaceManager, WorkspaceUserManager, ) from fief.models import Client, Tenant, Workspace, WorkspaceUser from fief.sche...
__author__ = 'frankegoesdown' from sqlalchemy import * from time import gmtime, strftime db = create_engine('sqlite:///base.sqlite') connection = db.connect() class SqlCommands: def add_user(self, login, password): sql = "INSERT INTO users (login, password) VALUES ('{0}', '{1}');".format(login,password) ...
from core.libs.bottle import SimpleTemplate, cached_property from functools import partial def tpl_include(tpl): return '<!--#include virtual="{}" -->'.format( tpl) class MetalTemplate(SimpleTemplate): class TemplateError(Exception): pass @cached_property def co(self): return ...
import asyncio import swiftsocket client = swiftsocket.SimpleClient(host='127.0.0.1', port=8001) client.register_request("helloworld") client.register_response("helloworld", data_definition={"text": str}) client.build_requests() async def main(): response = await client.requests.helloworld() print(response...
# !/usr/bin/python # -*- coding: UTF-8 -*- class Generator: """ 生成各种格式的小说 """ def __init__(self, converter): self.__converter = converter def make(self, book_info): self.__converter.make(book_info['title'], book_info['author'], book_info['intro'], bo...
# Copyright (c) Facebook, Inc. and its affiliates. # # 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 ...
import requests from .errors import ShareplumRequestError def get(session, url, **kwargs): try: response = session.get(url, **kwargs) response.raise_for_status() return response except requests.exceptions.RequestException as err: raise ShareplumRequestError("Shareplum HTTP Get ...
# -*- coding: utf-8 -*- # Copyright (c) 2014, Vispy Development Team. All Rights Reserved. # Distributed under the (new) BSD License. See LICENSE.txt for more info. """ Utilities for Vispy. A collection of modules that are used in one or more Vispy sub-packages. """ from ._logging import logger, set_log_level, use_lo...
import os from .....base import MetaWorkflow, load_config, register_workflow from traits.api import HasTraits, Directory, Bool, Button import traits.api as traits from ...scripts.QA_utils import cluster_image from .....flexible_datagrabber import Data, DataBase """ MetaWorkflow """ desc = """ Group Analysis: One Sampl...
class Passaro: def __init__(self, nome): self.nome = nome class Jogador: def __init__(self, camisa): self.camisa = camisa class CanarinhoPistola(Passaro, Jogador): def __init__(self, nome, camisa): #super().__init__(nome) Passaro.__init__(self, nome) Jogador.__init_...
import logging import os from rltrader import settings, data_manager from rltrader.policy_learner import PolicyLearner if __name__ == '__main__': stock_code = '005930' # 삼성전자 model_ver = '20190501172518' # 로그 기록 log_dir = os.path.join(settings.BASE_DIR, 'logs/%s' % stock_code) timestr = settings...
from math import hypot co= float(input("Qual o comprimento do cateto oposto: ")) ca= float(input("Qual o comprimento do cateto adjacente: ")) hi = hypot(co,ca) print("A hipotenusa vai medir {:.2f}".format(hi)) # co= float(input("Qual o comprimento do cateto oposto: ")) # ca= float(input("Qual o comprimento do cateto ...
from django.shortcuts import render from django.http import HttpResponse # home page def home(request): return render(request, 'homepage/homepage.html', {'insert_me': 'Hello this is a test'}) # return HttpResponse('<em>Home Page</em>') def help_page(request): return render(request, 'homepage/help.html',...
import os import unittest import argparse import tempfile from jflib import config_reader from jflib.config_reader import \ ArgparseReader, \ ConfigReader, \ ConfigValueError, \ DictionaryReader, \ EnvironReader, \ IniReader, \ load_readers_by_keyword, \ ReaderSelector, \ ReaderBase...
from requests import Session, exceptions from urllib.parse import urljoin session = Session() session.headers.update({'accept': 'application/json'}) # important should not contain a trailing slash BASE_URL = '' def get(name): res = session.get(urljoin(BASE_URL, f'/_api/boards/{name}')) return res.json() ...
import numpy as np def _batch_thm_scores(predictor, goal_embeddings, thm_embeddings, tactic_id=None): if tactic_id is not None: c = 3.0 * float(tactic_id) else: c = 2.0 return np.array([ np.sum(e1) + c * np.sum(e2) for (e1, e2) in zip(goal_embeddings, thm_embeddings) ])
from .libcommons import libcommons from .data_manager import data_manager import traceback, json class request_info: def Create_Request_Info(self, requestId, url, method, requestHeaders, requestBody, authType, requestDataType, responseDataType, expectedStatusCode, expectedResponseBody, username, password, files, ...
class TeaRequest: _PROPERTY_DEFAULT_MAP = { 'query': {}, 'protocol': 'http', 'port': 80, 'method': 'GET', 'headers': {}, 'pathname': "", 'body': None, } def __init__(self): self.query = {} self.protocol = "http" self.port = 80 ...
from math import * import matplotlib.pyplot as plt from src.plot import * import sympy as sp from matplotlib.pyplot import * from mpl_toolkits.mplot3d import Axes3D '''This script calculates the position Jacobian for general open chains using the symbolic package 'sympy' ''' def plot(q__, ax): # Plot world fra...
import os import glob import shutil # from scipy.ndimage import binary_fill_holes import itertools import numpy as np import dippykit as dip import matplotlib.pyplot as plt from tqdm import tqdm import cv2 from cv2 import INTER_AREA from skimage import filters from scipy.spatial import ConvexHull from scipy.ndimage.m...
import shutil from django.core.files.storage import default_storage from rest_framework import status from rest_framework.views import APIView from rest_framework.response import Response from ..models import * from ..serializers import * from ..permissions import * class BoardView(APIView, Helpers, BoardHelpers):...
# -*- coding: utf-8 -*- class Solution: def maxProduct(self, nums): best_max, current_max, current_min = float('-inf'), 1, 1 for num in nums: current_max, current_min = max(current_min * num, num, current_max * num),\ min(current_min * num, num, current_max * num) ...
"""Sub-package containing the matrix class and related functions.""" from defmatrix import * __all__ = defmatrix.__all__ from numpy.testing import Tester test = Tester(__file__).test bench = Tester(__file__).bench
from typing import Optional from pydantic import BaseModel class RequestCreateSwitch(BaseModel): status: bool machine_id: int controlledBy: str name: str
import tensorflow as tf import numpy as np from tensorflow.keras import backend as K from tensorflow.keras.layers import Layer import tensorflow.keras.layers as KL import numpy as np from tensorflow.keras.regularizers import l2 class Non_local_nn(tf.keras.layers.Layer): def __init__(self, filters, pool=False, re...
import cv2 import numpy as np import utils from CannyEdgeDetection import CannyEdgeDetection import matplotlib.pyplot as plt def main(path): ''' Main function :param path: image path :return: None ''' HW3 = CannyEdgeDetection() image = utils.load_image(path)[:, :, 0] # 2.a fim = HW3...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # @Time : 2019/7/18 5:55 PM # @Author : noduez # @File : urls.py # @Software: PyCharm from django.conf.urls import * from blog import views urlpatterns = [ # 主页 url(r'^$', views.archive, name='archive'), url(r'^create/', views.create_blogpost, name='...
'''Refaça o Ex51, lendo o primeiro termo e a razão de uma P.A mostrando os 10 primeiros termos da programação usando a estrutura while.''' ''' resolução do EX51 utilizando FOR print('TERMOS DE P.A') primeiro = int(input('1° Termo: ')) razão = int(input('Razão: ')) décimo = primeiro + (10 - 1) * razão for c in range(pr...
#===----------------------------------------------------------------------===// # # Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. # See https://llvm.org/LICENSE.txt for license information. # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception # #===----------------------------...
from typing import Optional, Union import arrow import discord from dateutil import parser from discord.ext import commands from bot.bot import Bot from bot.exts.core.extensions import invoke_help_command # https://discord.com/developers/docs/reference#message-formatting-timestamp-styles STYLES = {"Epoch": ("",), ...
# Copyright 2016 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 ag...
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors and The HugginFace Inc. team. # # 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/LICENS...
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import random import hashlib import json from collections import OrderedDict from . import config from .utils import convert_code, is_py2 __author__ = 'YangYang' __author_email__ = 'zhang-yangyang@foxmail.com' __version__ = '0.1' __license__ = 'MIT' try: fro...
from django.contrib import admin from django.forms import ModelForm from .models import Institution, Person, Reunion from suit.widgets import SuitDateWidget, SuitTimeWidget from suit_ckeditor.widgets import CKEditorWidget # Register your models here. from . import views from django.conf.urls import url class PersonAdm...
"""Ecuaciones termodinamicas ideales para el calculo de propiedades termodinamicas del Manual del ingeniero quimico Perry""" from math import sinh, cosh from scipy import integrate import numpy as np def antoine(T, C1, C2, C3, C4, C5): """Ecuación para calculo de presión de vapor (Pa)""" return np.exp(C1 + ...
""" Clipy YouTube video downloader disk storage DEBUG:asyncio:<_SelectorSocketTransport fd=9 read=polling write=<idle, bufsize=0>>: Fatal read error on socket transport Traceback (most recent call last): File "/usr/lib/python3.6/asyncio/selector_events.py", line 724, in _read_ready data = self._sock.recv(self.ma...
import logging import copy as cp from collections import deque import numpy as np from sklearn.cluster import KMeans from river.base import Classifier from river.utils import dict2numpy from . import libNearestNeighbor class SAMKNNClassifier(Classifier): """Self Adjusting Memory coupled with the kNN classifier...
from typing import Dict, List, Optional, Union from great_expectations.core.batch import Batch, BatchRequest, RuntimeBatchRequest from great_expectations.execution_engine.execution_engine import MetricDomainTypes from great_expectations.rule_based_profiler.domain_builder import DomainBuilder from great_expectations.ru...
from vic import lib as vic_lib def test_hitinhib(): temps = [-10, 0., 10., 20., 30., 55.] for t in temps: assert vic_lib.hiTinhib(t) >= 0.5 def test_darkinhib(): irrs = [-10, 0., 10., 20., 30., 55.] for i in irrs: if i < 0.: assert vic_lib.darkinhib(i) == 0. else:...
import firebase_admin from firebase_admin import credentials, firestore import google.cloud import xlrd cred = credentials.Certificate('./firebasekey.json') app = firebase_admin.initialize_app(cred) store = firestore.client() def get_documents(collection_name, state = None): doc_ref = store.collection(collection_...
import graphene import posts.schema #class Query(posts.schema.Query, graphene.ObjectType): # pass class Mutation(posts.schema.Mutation, graphene.ObjectType): pass schema = graphene.Schema( #query=Query, mutation=Mutation )
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import cv2 import numpy as np from matplotlib import pyplot as plt def show_image(image): plt.imshow(image) plt.show() img_rgb = cv2.imread('fuf.png') img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY) template = cv2.imread('out.png', 0) height, width = templa...
import random suits = 'CDHS' cards = 'A23456789TJQK' deck = [ j + i for i in suits for j in cards ] + [ 'FJ', 'SJ' ] r = random.Random() r.seed(230987459872341398732) shuffled = ''.join(r.sample(deck, len(deck))) if __name__ == '__main__': nperrow = 12 for i in xrange(0, len(shuffled), nperrow): print shuffled[i...
"""Activate coverage at python startup if appropriate. The python site initialisation will ensure that anything we import will be removed and not visible at the end of python startup. However we minimise all work by putting these init actions in this separate module and only importing what is needed when needed. For...
import datetime import json import logging from time import sleep # import grequests # import requests import pause from twython import Twython from twython.exceptions import TwythonError from twython.exceptions import TwythonRateLimitError from twython.exceptions import TwythonAuthError from utility.print_utility imp...
import asyncio import aiomas import logging import sqlalchemy from common import utils from common.config import config __all__ = ["CardViewer"] REPEAT_TIMER = 120 ANNOUNCE_DELAY = 5 log = logging.getLogger('cardviewer') class CardViewer: router = aiomas.rpc.Service() def __init__(self, lrrbot, loop): self.lr...
from django import forms from .models import BaseProduct, Product, Service, Tag from liberaction.users.models import User class BaseProductForm(forms.ModelForm): images = forms.FileField( widget=forms.ClearableFileInput(attrs={'multiple': True}), required=False) owner = forms.ModelChoiceField( ...
import csv import os def remove_if_exist(path): if os.path.exists(path): os.remove(path) def load_metadata(path): res = {} headers = None with open(path, newline='') as csvfile: reader = csv.reader(csvfile, delimiter=',', quotechar='"') for row in reader: if head...