content
stringlengths
5
1.05M
{% extends "_common/main.py" %} {% set typeStep = "Delete" %}
#! /usr/bin/python2 # # Copyright (c) 2017 Intel Corporation # # SPDX-License-Identifier: Apache-2.0 # # # Configuration file for ttbd (place in ~/.ttbd/) or run ttbd with # `--config-file PATH/TO/THISFILE` # import ttbl.tt_qemu def nw_default_targets_zephyr_add(letter, bsps = [ 'x86', 'arm', 'nios2', ...
from collections import Counter anzZweier, anzDreier = 0,0 with open('AdventOfCode_02_1_Input.txt') as f: for zeile in f: zweierGefunden, dreierGefunden = False, False counter = Counter(zeile) for key,value in counter.items(): if value == 3 and not dreierGefunden: anzDreier += 1 dr...
import pandas as pd import numpy as np from scipy.sparse import data from sklearn.experimental import enable_iterative_imputer from sklearn.impute import SimpleImputer from sklearn.impute import IterativeImputer from sklearn.impute import KNNImputer class BasicImputation(): """ This class supports basic imputati...
# 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under t...
# https://leetcode.com/problems/pascals-triangle/description/ class Solution(object): def generate(self, numRows): if numRows == 0: return [] elif numRows == 1: return [[1]] elif numRows == 2: return [[1], [1, 1]] res = [[1], [1, 1]] ...
from math import ceil def to_bytes(n): binary = '{:b}'.format(n) width = int(ceil(len(binary) / 8.0) * 8) padded = binary.zfill(width) return [padded[a:a + 8] for a in xrange(0, width, 8)]
#!python3 import numpy as np from magLabUtilities.datafileutilities.timeDomain import importFromXlsx from magLabUtilities.signalutilities.signals import SignalThread, Signal, SignalBundle from magLabUtilities.signalutilities.hysteresis import XExpQA, HysteresisSignalBundle from magLabUtilities.uiutilities.plotti...
#!/usr/bin/env python # # 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 ...
# place `import` statement at top of the program import string # don't modify this code or the variable may not be available input_string = input() # use capwords() here print(string.capwords(input_string))
#!/usr/bin/env python # Select sequences by give seqIDs import sys import os import myfunc usage=""" usage: selectfastaseq.py -f fastaseqfile [ ID [ID ... ] ] [-l FILE] [ [-mine FLOAT ] [-maxe FLOAT] ] Description: select fasta sequences by seqID from the giv...
# -*- coding: utf-8 -*- """ Created on Wed Nov 29 00:56:43 2017 @author: roshi """ import pandas as pd import matplotlib.pyplot as plt import dash import dash_core_components as dcc import dash_html_components as html import plotly.graph_objs as go from app import app data = pd.read_csv('./data/youth_to...
import numpy as np import matplotlib.pyplot as plt from infinity import inf from scipy.spatial import ConvexHull from scipy.spatial.distance import euclidean from shapely.geometry import LineString, Point from sklearn.model_selection import KFold from .metrics import MetaMetrics from . import util class Meta: d...
"""Parameter layer in TensorFlow.""" import tensorflow as tf from tensorflow.python.ops.gen_array_ops import broadcast_to def parameter(input_var, length, initializer=tf.zeros_initializer(), dtype=tf.float32, trainable=True, name='parameter'): ...
import gym import torch as th from stable_baselines3.common.torch_layers import BaseFeaturesExtractor from torch import nn class CNNFeatureExtractor(BaseFeaturesExtractor): def __init__(self, observation_space: gym.spaces.Box, features_dim: int = 128, **kwargs): super().__init__(observation_space, feature...
#!/usr/bin/env python # coding: utf-8 import numpy as np from wopsego import Optimization, ValidOptimumNotFoundError # Objective def G24(point): """ Function G24 1 global optimum y_opt = -5.5080 at x_opt =(2.3295, 3.1785) """ p = np.atleast_2d(point) return -p[:, 0] - p[:, 1] # Constraints <...
document = ["Whip-Off World Championships - Gallery","ROWDY DH COURSE PREVIEW! 2019 iXS European Downhill Cup #5, Spicak","IXS Launch the Trigger FF, The Lightest Full Face Out There.","Watch: Breck Epic Day 2","Cam Zink Slams Hard on a 110 Foot Backflip Attempt.","Pivot’s All-New Mach 4 SL","Meet The Riders And Their ...
"""Test the Aurora ABB PowerOne Solar PV sensors.""" from datetime import timedelta from unittest.mock import patch from aurorapy.client import AuroraError from homeassistant.components.aurora_abb_powerone.const import ( ATTR_DEVICE_NAME, ATTR_FIRMWARE, ATTR_MODEL, ATTR_SERIAL_NUMBER, DEFAULT_INTE...
from typing import Generic, List, Optional, TypeVar from py_moysklad.entities.context import Context from py_moysklad.entities.meta_entity import MetaEntity T = TypeVar("T", bound=MetaEntity) class ListEntity(MetaEntity, Generic[T]): context: Optional[Context] rows: Optional[List[T]]
from .script import test def main(): test()
def rosenbrock_list(**kwargs): num_fns = kwargs['functions'] # if num_fns > 1: # least_sq_flag = true # else: # least_sq_flag = false x = kwargs['cv'] ASV = kwargs['asv'] # get analysis components #an_comps = kwargs['analysis_components'] #print an_comps f0 = ...
from django.test import TestCase from ..factories import UrlFactory from ..helpers import BASE62IdConverter from ..models import Url class TestUrlManager(TestCase): def setUp(self): self.url_objs = [UrlFactory() for i in range(100)] def test_get_by_shortcut(self): received_url_obj = [ ...
from Pluto.Libraries.Libraries.GLM import *
""" BOVI(n)E getsecuritygroup endpoint """ import json import boto3 from botocore.exceptions import ClientError from lib import rolesession def get_instance_info(session, account, sg_id): """ Get EC2 instance info for a specific security group. :param session: AWS boto3 session :param account: AWS accou...
from typing import Dict def count_duplicates(sample_dict: Dict) -> int: """takes a single dictionary as an argument and returns the number of values that appear two or more times >>> sample_dict = {'red': 1, 'green': 1, 'blue': 2, 'purple': 2, 'black': 3, 'magenta': 4} >>> count_duplicates(sample_dict) ...
#!/usr/bin/env python # ---------------------------------------------------------------------------- # Copyright (c) 2013--, scikit-bio development team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed with this software. # ---------------------...
# This file is part of BenchExec, a framework for reliable benchmarking: # https://github.com/sosy-lab/benchexec # # SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org> # # SPDX-License-Identifier: Apache-2.0 """This module contains function declarations for several functions of libc (based on ctyp...
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: mars/serialize/protos/chunk.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import ...
def subset(arr, ind, sub, ans): if ind == len(arr): return ans for i in range(ind, len(arr)): temp = sub.copy() temp.append(arr[i]) ans.append(temp) subset(arr, i + 1, temp, ans) return ans arr = [1, 2, 3] ans = [] ans = subset(arr, 0, [], ans) for i in range(len(ans)): print(ans[i])
import numpy as np import os from scipy.io import loadmat from sklearn.datasets import load_svmlight_file def gisette2npz(): data_path = "./dataset/GISETTE" train_data = np.loadtxt(os.path.join(data_path, "GISETTE/gisette_train.data")) train_labels = np.loadtxt(os.path.join(data_path, "GISETTE/gisette_tr...
""" Web application main script. """ import os from typing import Any, Dict, List import cfbd import streamlit as st import college_football_rankings as cfr import ui import ui.rankings import ui.schedule from college_football_rankings import iterative FIRST_YEAR: int = 1869 LAST_YEAR: int = 2020 RANKINGS_LEN = 25 ...
import app.api.point import app.api.track import app.api.tracker import app.api.user
from functools import wraps from flask import session, flash, redirect, url_for from app.log import get_logger logger = get_logger(__name__) # Login required decorator def login_required(f): @wraps(f) def wrap(*args, **kwargs): if "logged_in" in session: return f(*args, **kwargs) ...
#!/usr/bin/env python """ Functions for building tutorial docs from Libre Office .fodt files using PanDoc Required formats are: html pdf (eBook) pdf will need to be generated by Sphinx via LaTeX intermediate """
num1 = int(input('Primeiro valor: ')) num2 = int(input('Segundo valor: ')) num3 = int(input('Treceiro valor: ')) # verificando qual é o menor menor = num1 if num2 < num1 and num2 < num3: menor = num2 if num3 < num1 and num3 < num2: menor = num3 # verificando qual é o maior maior = num1 if num2 > num1 and num2 >...
from collections import defaultdict from dataclasses import dataclass from typing import List import torch import torch.nn as nn from luafun.model.actor_critic import ActorCritic class TrainEngine: def __init__(self, train, model, args): self.engine = LocalTrainEngine(*args) @property def weigh...
# -*- coding: utf-8 -*- # Generated by Django 1.11.15 on 2019-01-09 09:04 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('submission', '0008_submission_sender'), ] operations = [ migrations.AlterF...
from .core import Event, EventType class JoyAxisMotion(Event): __slots__ = ('axis', 'value', ) type = EventType.JOY_AXIS_MOTION def __init__(self, source, axis, value): super().__init__(source) self.axis = axis self.value = value def __repr__(self): return f'<{self._...
import numpy as np import pytest from psydac.core.bsplines import make_knots from psydac.fem.basic import FemField from psydac.fem.splines import SplineSpace from psydac.fem.tensor import TensorFemSpace from psydac.fem.vector import ProductFemSpace from psydac.f...
from pyrules.dictobj import DictObject class RuleContext(DictObject): """ Rule context to store values and attributes (or any object) The rule context is used to pass in attribute values that for the rules to consider. A rule does not have access to any other data except provided in this rule...
from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals import numpy as np import tensorflow as tf from ladder_network import tensor_utils from ladder_network.wrappers import Registry initializers = Registry('Initialization') @initializers.register('glorot_un...
import netns import pdb fin = open("host.config", "r") _ = fin.readline() host_mnet_pid = int(fin.readline().split()[0]) with netns.NetNS(nspid=host_mnet_pid): from scapy.all import * class sync_header(Packet): name = "sync_header" fields_desc = [\ BitField("msg_type", 0, 8),\ ...
import unittest from cellular_automata_population_python import Model class TestModel(unittest.TestCase): def setUp(self): """Set up a model""" self.model = Model.Model() self.model.run() def test_model(self): """Test that the model is not null""" self.assertIsNotNone...
from functools import cached_property from typing import Tuple from prompt_toolkit.completion import Completer from .argument_base import ArgumentBase from ..errors import FrozenAccessError from ..utils import abbreviated class FrozenArgument(ArgumentBase): """An encapsulation of an argument which can no longer...
################################################################################## # # By Cascade Tuholske on 2019.12.31 # Updated 2020.02.23 # # Modified from 7_make_pdays.py now in oldcode dir # # NOTE: Fully rewriten on 2021.02.01 see 'oldcode' for prior version / CPT # # These are the functions needed ...
#!/usr/bin/env python3 import os, logging from argparse import ArgumentParser from mg996r import MG996R start_degree = 360 state_file = '.servo-state' if __name__ == '__main__': # set logging level logging.basicConfig(level=logging.DEBUG) # parse arguments parser = ArgumentParser() parser.add_arg...
import threading import random from time import sleep from math import sqrt,cos,sin,pi from functools import partial from Tkinter import * import tkMessageBox as messagebox from ttk import * import tkFont from PIL import Image, ImageTk import numpy as np import networkx as nx from event import myEvent from Object im...
# -*- coding: utf-8 -*- """ @author:XuMing(xuming624@qq.com) @description: evaluate with mscc data set The function create_mscc_dataset is Copyright 2016 Oren Melamud Modifications copyright (C) 2018 Tatsuya Aoki This code is based on https://github.com/orenmel/context2vec/blob/master/context2vec/eval/mscc_text_token...
# Source # ====== # https://www.hackerrank.com/contests/projecteuler/challenges/euler011 # # Problem # ======= # In the 20x20 grid (see Source for grid), four numbers along a diagonal # line have been marked in bold. # # The product of these numbers is 26 x 63 x 78 x 14 = 1788696. # # What is the greatest product of f...
from SpellCorrect import input_processing from Organize_Names import Corpus_Combo, Combined_words,Word_Classfication,import_file,Remov_Num,Remove_nan,Remove_strNum,Clean_Word,Valuable_word from Import_corpus import input_file from Get_Synonyms import Get_SynonymFromlst from Standard_corpus import standarlized_outpu...
#! /usr/bin/env python3 # -*- coding: utf-8 -*- # File : environ.py # Author : Jiayuan Mao # Email : maojiayuan@gmail.com # Date : 01/19/2018 # # This file is part of Jacinle. # Distributed under terms of the MIT license. import contextlib from copy import deepcopy from jacinle.utils.meta import dict_deep_keys,...
import uuid import json from django.core.cache import cache from django.core.mail import send_mail from django.shortcuts import reverse from django.conf import settings def validate_email(user, email): title = '验证你的电子邮箱 | conus 通知推送' token = uuid.uuid4().hex body = ( '请打开下方连接以验证你的电子邮箱:\n' ...
import unittest from braintreehttp.testutils import TestHarness from braintreehttp.serializers import FormPart class FormPartTest(unittest.TestCase): def test_init_lowercase_headers(self): form_part = FormPart({ "key": "value" }, { "content-type": "application/json" }) self.assertTrue("Content-T...
#!/usr/bin/python from pathlib import Path import os import shutil from readConfig import ReadConfig from datetime import datetime class Utils: """ 工具类 """ @staticmethod def save_file(file_name, row_list, mode): """ 将 row_list 中的股票数据保存到 file_name 路径文件中 :param file_name: 路径文...
""" Switch based on e.g. a MCP23017 IC, connected to a Raspberry Pi board. It is expected that a server part is running, through a Redis in-memory database. Commands are sent to the Redis database, and responses captured. The server would then process the actions in background. Author: find me on codeproject.com --> Ju...
import logging import os from rich import print from typing import Dict from sfaira.commands.utils import get_ds from sfaira.consts.utils import clean_doi from sfaira.data import DatasetBase log = logging.getLogger(__name__) class H5adExport: datasets: Dict[str, DatasetBase] doi: str doi_sfaira_repr: ...
from typing import Optional, Sequence from kubragen import KubraGen from kubragen.builder import Builder from kubragen.consts import PROVIDER_K3D, PROVIDER_K3S from kubragen.data import ValueData from kubragen.exception import InvalidParamError, InvalidNameError from kubragen.helper import QuotedStr from kubragen.kdat...
from pathlib import Path import pandas as pd from modules.settings.settings import SettingsManager class PseudoIDManager: """ Class for setting, getting pseudo_id filepaths and getting pseudo_id value """ def __init__(self, l2c: dict, settm: SettingsManager): self._settm = settm self._l2c = ...
# 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 # distribu...
# -*- coding: utf-8 -*- """ Helpers for our web and worker (scraper) instances """ from werkzeug.contrib.atom import AtomFeed from flask import make_response import json from bson import json_util import datetime import pymongo from conn import db def _get_plans(count=1000, query={}): return list(db.plans.find...
from django.urls import include, path from rest_framework.routers import DefaultRouter from .views import CreatePollViewSet, GetResultViewSet, PollViewSet v1_router = DefaultRouter() v1_router.register('createPoll', CreatePollViewSet, basename='create_poll') v1_router.register('poll', PollViewSet, basename='vote_poll...
# Gumby theft detection program # Created Feb 8, 2018 # Copyright (c) Sambhav Saggi 2018 # All rights reserved # Created for Gregory Calvetti # Output may be wrong #Set some constants DENSITY_THRESH=0.7 #Get ready to compare numbers def takeClosest(list, derp): meme = [] for i in list: meme.append(abs...
from . import command from opensfm.actions import match_features class Command(command.CommandBase): name = 'match_features' help = 'Match features between image pairs' def run_impl(self, dataset, args): match_features.run_dataset(dataset) def add_arguments_impl(self, parser): pass
# -*- coding: utf-8 -*- """ Jakob Seidl, Nanoelectronics Group UNSW Sydney """ import pyvisa as visa import pyneMeas.Instruments.Instrument as Instrument import time import math import numpy as np @Instrument.enableOptions class SRS830(Instrument.Instrument): """ SRS830 Lock-In Amplifier ...
# Copyright (C) 2020-Present the hyssop authors and contributors. # # This module is part of hyssop and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php ''' File created: November 21st 2020 Modified By: hsky77 Last Updated: March 27th 2021 19:31:11 pm ''' from .server import Ai...
# -*- coding: utf-8 -*- """ lantz.drivers.newport ~~~~~~~~~~~~~~~~~~~~~ :company: Newport. :description: Test and Measurement Equipment. :website: http://www.newport.com/ --- :copyright: 2015, see AUTHORS for more details. :license: GPLv3, """ from .motionesp301 import ESP301, ESP30...
import typing import os import aiohttp from urllib.parse import quote from deta.utils import _get_project_key_id from deta.base import FetchResponse, Util def AsyncBase(name: str): project_key, project_id = _get_project_key_id() return _AsyncBase(name, project_key, project_id) class _AsyncBase: def __...
#!/usr/bin/env python3 # Software License Agreement (BSD License) # # Copyright (c) 2018, UFACTORY, Inc. # All rights reserved. # # Author: Vinman <vinman.wen@ufactory.cc> <vinman.cub@gmail.com> from ..core.config.x_config import XCONF class APIState(object): NOT_CONNECTED = -1 # 已断开或未连接 NOT_READY = -2 # ...
from pykgr.package import Package from pykgr.shell import Shell from pykgr.configuration import conf as config from pykgr.environment import Environment from pykgr.builder import Builder from pykgr.package import Package
#!/usr/bin/env python # encoding: utf-8 from unittest import TestCase from ycyc.libs.statelib.state import ( FreeState, SequenceState, QSequenceState, StateNotAllowError, EndOfSequenceStateError, SequenceStateFinishedError, ) class TestFreeState(TestCase): def test_usage(self): stat...
import streamlit as st # https://github.com/streamlit/release-demos/blob/master/0.65/demos/query_params.py query_params = st.experimental_get_query_params() default = query_params["text"][0] if "text" in query_params else "" x = st.text_area('Enter Text', value=default) st.write('The text in uppercase is ', x.upper(...
from parser import EPL import glob import os import numpy as np import matplotlib.pyplot as plt import matplotlib from matplotlib.lines import Line2D import copy class Experiment: def __init__(self, suppath, file_regex='*-analyzed.txt', parser=EPL): self.suppath = suppath self.parser = parser ...
import time import picamerax frames = 60 with picamerax.PiCamera() as camera: camera.resolution = (1024, 768) camera.framerate = 30 camera.start_preview() # Give the camera some warm-up time time.sleep(2) start = time.time() camera.capture_sequence([ 'image%02d.jpg' % i for...
#----------------------------------------------------------------------------- # Copyright (c) 2013-2019, PyInstaller Development Team. # # Distributed under the terms of the GNU General Public License with exception # for distributing bootloader. # # The full license is in the file COPYING.txt, distributed with this s...
#!/usr/bin/env python from flask_babel import _ import os basedir = os.path.abspath(os.path.dirname(__file__)) POSTGRES = { 'user': 'catalog', 'pw': 'catalog', 'db': 'catalog', 'host': 'localhost', 'port': '5432', } class Config(object): """ App configuration """ CLIENT_SECRET_JSON = os....
#!/usr/bin/env python3 """ Simulate 3D aggregate mixing Generate simulated aggregates that can be analyzed by `analyze_3d_aggregate_mixing.py` .. code-block:: bash $ ./simulate_3d_aggregate_mixing.py \\ --num-red 400 \\ --num-green 127 \\ --aggregate-radius 75.3 \\ --neighbor-rad...
from statuscheck.services.bases._statuspageio import BaseStatusPageAPI class ServiceAPI(BaseStatusPageAPI): name = "Epic Games" domain_id = "ft308v428dv3" status_url = "https://status.epicgames.com/" service_url = "http://epicgames.com/"
# -*- coding: utf-8 -*- from __future__ import print_function from __future__ import unicode_literals from __future__ import division import unittest from tr55.water_quality import get_volume_of_runoff, get_pollutant_load from tr55.tables import POLLUTION_LOADS class TestWaterQuality(unittest.TestCase): def tes...
import pytorch_lightning as pl class TeacherForcingAnnealCallback(pl.Callback): def __init__(self, start, end, epochs): assert start >= end self.start = start self.end = end self.epochs = epochs self.slope = float((start - end)) / epochs def on_validation_ep...
import datetime import pandas as pd import io import os import boto3 from io import BytesIO from io import StringIO from airflow import DAG from airflow.providers.amazon.aws.operators.redshift_sql import RedshiftSQLOperator from airflow.operators.dummy import DummyOperator from airflow.operators.redshift_to_s3_operat...
import databases import sqlalchemy import logging import os import json from fastapi import FastAPI from sqlalchemy import text logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(__name__) db_string = "postgresql://{0}:{1}@{2}/{3}".format(os.getenv("POSTGRES_USER"), ...
#!/usr/bin/env python import socket import warnings import pytest from flask import _request_ctx_stack from ._internal import _determine_scope from ._internal import _make_accept_header from ._internal import _rewrite_server_name from .live_server import LiveServer @pytest.fixture def client(app): """A Flask te...
from Jumpscale import j def main(self): """ to run: kosmos 'j.clients.zdb._tests_run(name="admin")' """ c = j.servers.zdb.test_instance.client_admin_get() c.reset() c.namespaces_list() assert c.namespaces_list() == ["default"] c.namespace_new("test_namespace") assert c.nam...
class IdentityHashingService: def hash(self, value): return value
class Solution: """ @param s: a string @param words: a list of words @return: all starting indices of substring(s) """ def findSubstring(self, s, words): # write your code here m = len(s) target = len(words) result = [] if m == 0 or target == 0: ...
import requests import json import logging logging.basicConfig() logging.getLogger().setLevel(logging.DEBUG) requests_log = logging.getLogger("requests.packages.urllib3") requests_log.setLevel(logging.DEBUG) requests_log.propagate = True auth_server = 'https://api.amazon.com/auth/register' alexa_user_name = 'username...
#!/usr/bin/env python a = [66.25, 333, 333, 1, 1234.5] print("\na=", a) print("\na.count(333) = %d, a.count(66.25) = %d, a.count('x') = %d" % (a.count(333), a.count(66.25), a.count('x')) ) print("\na.insert(2, -1) = ", a.insert(2, -1)) print("a = ", a) print("\na.append(333) = ", a.append(333)) print("a = ", a) pr...
'''The doc module provides decorator functions that will modify a functions __apidoc__ object. For example, when using `method('GET')` it will set the value of the functions method as 'get' on its __apidoc__''' from http import HTTPStatus from oapispec.core.utils import merge, not_none def doc(**kwargs): '''A d...
import itertools import json from collections import defaultdict from django.core.serializers.json import DjangoJSONEncoder from .orm_lookups import get_django_filter from .query import BoundQuery from .types import ASC, DSC def _filter(qs, path_str, filter_): negation = False lookup = filter_.lookup i...
""" Unit tests for \ landlab.components.vegetation_dynamics.vegetation_dynamics """ from nose.tools import assert_equal, assert_true, assert_raises, with_setup from numpy.testing import assert_array_almost_equal try: from nose.tools import assert_is_instance except ImportError: from landlab.testing.tools im...
import os #We don't want to show the pygmy version and welcome message. Snif os.environ['PYGAME_HIDE_SUPPORT_PROMPT'] = "hide" from random import uniform,randint import tqdm """ We import pygame in order to create a patch for the long calculations If the QLearning calculation time or the creation of the path is t...
# -*- coding: utf-8 -*- import time # from datetime import datetime, timedelta from flask import Blueprint, request, Response, abort from sqlalchemy import func, and_, or_ import os import math import ujson import logging from datetime import datetime from models import FDMEvent, FDMEventType, FDMEventGroup, DataQarSe...
from typing import Tuple import requests from bs4 import BeautifulSoup from hospital_types import ( ScrapedData, AppointmentAvailability, HospitalAvailabilitySchema, ) import aiohttp, asyncio URL: str = "http://netreg.afph.tsgh.ndmctsgh.edu.tw/webreg/calendar_type/5xn1z9fPG5H4JDJEV98dHQ%3D%3D" async def...
from django.contrib.auth import get_user_model from django.test import TestCase UserModel = get_user_model() class UserModelTest(TestCase): def setUp(self) -> None: self.user = UserModel.objects.create_user( email='test@abv.bg', ) self.user.set_password = '1234567890Mazen' ...
#!/usr/bin/env python ################################################## # Gnuradio Python Flow Graph # Title: FCCH Bursts Detector # Author: Piotr Krysik # # Description: Detects positions of FCCH bursts. At the end of each # detected FCCH burst adds to the stream a tag with key "fcch" and value # which is a frequen...
import logging def get_logger(LEVEL='info', log_file = None,name=None): head = '[%(asctime)-15s] [%(levelname)s] %(message)s' if LEVEL == 'info': logging.basicConfig(level=logging.INFO, format=head) elif LEVEL == 'debug': logging.basicConfig(level=logging.DEBUG, format=head) logger = lo...
from sklearn.neighbors import KNeighborsClassifier from sklearn import datasets from sklearn.metrics import accuracy_score iris = datasets.load_iris() X, y = iris.data, iris.target knn = KNeighborsClassifier() knn.fit(X, y) accuracy_score(y, knn.predict(X))
import random import discord from discord.ext import commands from .inputs import cl, cf, chill, cfe, ur from .utils import COLOR class Coffee(commands.Cog): def __init__(self, client): self.client = client @commands.command(aliases=['ask_out']) async def wannagrabacoffee(self, ctx, *, member: d...
# Copyright (c) Facebook, Inc. and its affiliates. import unittest import torch from mmf.common.sample import Sample from mmf.models.transformers.heads.itm import ITM from mmf.models.transformers.heads.mlm import MLM from mmf.models.transformers.heads.mlp import MLP from omegaconf import OmegaConf from tests.test_uti...
import pandas as pd from sklearn.model_selection import train_test_split class DataLoader: def __init__(self): self.dataset = None self.sensor = None self.target = None def load(self,file,isTest=False): if not isTest: print("loading") self.dataset = pd.r...