content
stringlengths
0
1.05M
origin
stringclasses
2 values
type
stringclasses
2 values
import sys from tkinter import * from slideShow import SlideShow if len(sys.argv) == 2: picdir = sys.argv[1] else: picdir = '../gifs' root = Tk() Label(root, text="Two embedded slide shows: each side uses after() loop").pack() SlideShow(msecs=200, parent=root, picdir=picdir, bd=3, relief=SUNKEN).pa...
nilq/baby-python
python
class Transform(object): """Transform coordinate systems: scale / translate""" def __init__(self, scale, translate): """Set up the parameters for the transform""" self.scale = scale self.translate = translate def forward(self, pt): """From the original box to (-1,-1),(1,1) ...
nilq/baby-python
python
from facenet_pytorch import InceptionResnetV1 class SiameseNet(nn.Module): def __init__(self): super().__init__() self.encoder = InceptionResnetV1(pretrained='vggface2') emb_len = 512 self.last = nn.Sequential( nn.Linear(4*emb_len, 200, bias=False), ...
nilq/baby-python
python
Import("env") from SCons.Script import COMMAND_LINE_TARGETS def buildWeb(source, target, env): env.Execute("cd web; pnpm build") print("Successfully built webui") def convertImages(source, target, env): env.Execute("cd converter; go run .") print("Successfully converted images") env.AddPreAction("bui...
nilq/baby-python
python
from . import tables from . unquote import unquote as _unquote __all__ = 'Quote', 'unquote' SHORT_ASCII = '\\u{0:04x}' LONG_ASCII = '\\u{0:04x}\\u{1:04x}' def Quote(b): return _QUOTES[bool(b)] def unquote(s, strict=True): return _QUOTES[s[0] == tables.SINGLE].remove(s, strict) class _Quote: def __in...
nilq/baby-python
python
""" predict.py Predict flower name from an image with predict.py along with the probability of that name. That is, you'll pass in a single image /path/to/image and return the flower name and class probability. Basic usage: python predict.py /path/to/image checkpoint Args: --img --checkpoint --top_k ...
nilq/baby-python
python
import accounting.config import pytransact.testsupport def pytest_configure(config): global unconfigure unconfigure = pytransact.testsupport.use_unique_database() accounting.config.config.set('accounting', 'mongodb_dbname', pytransact.testsupport.dbname) def pytest_unconf...
nilq/baby-python
python
#!/usr/bin/python3 import math #Generate the ovsf tree def ovsfGenerator(numberOfMobile): #calculate the depth of the OVSF code tree numberOfColumn = math.ceil(math.log(numberOfMobile,2)) column = [1] #Generation of the list of codes for i in range (0,numberOfColumn): newColumn=[] xornu...
nilq/baby-python
python
from pprint import pprint as pp from funcs import * import time import random import ConfigParser config= ConfigParser.ConfigParser() config.read('config.cfg') PERIOD = int(config.get('Run','period')) ## currently set to make it so we don't hit window ## rate limits on friendship/show ## should be able to increase t...
nilq/baby-python
python
#!/usr/bin/env python3.6 # # uloop_check.py # # Gianna Paulin <pauling@iis.ee.ethz.ch> # Francesco Conti <f.conti@unibo.it> # # Copyright (C) 2019-2021 ETH Zurich, University of Bologna # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. #...
nilq/baby-python
python
"""Cron job code.""" from google.appengine.ext import ndb import cloudstorage import datetime import logging from api import PermissionDenied from model import (Email, ErrorChecker, Indexer, User) import config import util class Cron: """A collection of functions and a permission scheme for running cron jobs. ...
nilq/baby-python
python
###################################################################################################################### # Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # ...
nilq/baby-python
python
""" Operators with arity 2. Take 2 colors and mix them in some way. Owns two 0/1 arity operators, which calculate the initial colors. Adds a shift by colors, that is, for two colors [rgb] + [RGB] can mix as ([rR gG bB], [rG gB bR], [rB gR bG]). """ from abc import ABC, abstractmethod from .base import Operator, ope...
nilq/baby-python
python
from urllib.parse import urlparse def parse_link(link): href = link.attrs.get("href") return href and urlparse(href)
nilq/baby-python
python
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: percent # format_version: '1.3' # jupytext_version: 1.13.7 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # %% [markdown] slideshow={"slide_type": "slide"} # ...
nilq/baby-python
python
import matplotlib.pyplot as plt import matplotlib.animation as animation def ani_easy(tas, cmap='BrBG'): # Get a handle on the figure and the axes fig, ax = plt.subplots(figsize=(12,6)) # Plot the initial frame. cax = tas[0,:,:].plot( add_colorbar=True, cmap=cmap, #cmap='BrBG', #cmap='m...
nilq/baby-python
python
from collections import ChainMap, defaultdict from itertools import chain import pathlib import re from cldfbench import Dataset as BaseDataset, CLDFSpec from pybtex.database import parse_string from pydictionaria.sfm_lib import Database as SFM from pydictionaria.preprocess_lib import marker_fallback_sense, merge_mar...
nilq/baby-python
python
import requests from django.conf import settings DEBUG = getattr(settings, 'DEBUG') class AppleService(object): def __init__(self, base_url): self.base_url = base_url def notify_all(self, resources, message): for resource in resources: data = '{"resource": "' + resource +...
nilq/baby-python
python
from keepkeylib.client import proto, BaseClient, ProtocolMixin from ..trezor.clientbase import TrezorClientBase class KeepKeyClient(TrezorClientBase, ProtocolMixin, BaseClient): def __init__(self, transport, handler, plugin): BaseClient.__init__(self, transport) ProtocolMixin.__init__(self, transpo...
nilq/baby-python
python
userInput = ('12') userInput = int(userInput) print(userInput)
nilq/baby-python
python
import json import os from typing import Any, Dict, List, Union here = os.path.abspath(os.path.dirname(__file__)) def _load_list(paths: List[str]) -> dict: content: Dict[str, Any] = {} for p in paths: with open(p) as h: t = json.load(h) content.update(t) return content d...
nilq/baby-python
python
''' Copyright (c) 2018 Modul 9/HiFiBerry 2020 Christoffer Sawicki Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use,...
nilq/baby-python
python
# Module fwpd_histogram import ctypes as ct import time from modules.example_helpers import * def enable_characterization(ADQAPI, adq_cu, adq_num, channel, enable, only_metadata): # Enable logic and release reset assert (channel < 5 and channel > 0), "Channel must be between 1-4." # Lookup base ...
nilq/baby-python
python
# # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # import pytest import mlos.global_values from mlos.OptimizerEvaluationTools.ObjectiveFunctionFactory import ObjectiveFunctionFactory, objective_function_config_store from mlos.Optimizers.RegressionModels.GoodnessOfFitMetrics import Dat...
nilq/baby-python
python
from allauth.account import signals from allauth.account.views import SignupView from allauth.account.utils import send_email_confirmation from allauth.exceptions import ImmediateHttpResponse from django.contrib.auth import get_user_model from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin fr...
nilq/baby-python
python
# encoding: utf-8 import sys from PyQt5 import QtQuick from PyQt5.QtCore import QObject, pyqtSlot, QTimer from PyQt5.QtGui import QIcon from PyQt5.QtQml import QQmlApplicationEngine from PyQt5.QtWidgets import QWidget, QApplication, QLabel from resources import resources print(QtQuick) print(resources) class MyApp...
nilq/baby-python
python
import logging import os import posixpath from dvc.config import Config from dvc.config import ConfigError from dvc.utils import relpath from dvc.utils.compat import urlparse logger = logging.getLogger(__name__) class RemoteConfig(object): def __init__(self, config): self.config = config def get_s...
nilq/baby-python
python
# DAACS ~= NASA Earthdata data centers DAACS = [ { "short-name": "NSIDC", "name": "National Snow and Ice Data Center", "homepage": "https://nsidc.org", "cloud-providers": ["NSIDC_CPRD"], "on-prem-providers": ["NSIDC_ECS"], "s3-credentials": "https://data.nsidc.earthda...
nilq/baby-python
python
from tkinter import * from SMExp import* from DMExp import* import pygame import time import random class SMPage(Frame): MUTE = False INFO = False DIM = 0 def __init__(self, parent, controller): Frame.__init__(self, parent) pygame.mixer.init() SGMWall = PhotoImage(fi...
nilq/baby-python
python
#!/usr/bin/env python3 # # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import functools import multiprocessing import sys import unittest from io import StringIO import click import tempf...
nilq/baby-python
python
import random import json import requests from flask import Flask, request, render_template from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) @app.route('/', methods=['GET', 'POST']) def home(): rcomb = request.args.get('rcomb','http://appcombiner:5003/rcomb') return render_template('index.html',...
nilq/baby-python
python
from django.urls import reverse from django.views import generic from . import forms class KindeditorFormView(generic.FormView): form_class = forms.KindeditorForm template_name = "form.html" def get_success_url(self): return reverse("kindeditor-form") kindeditor_form_view = KindeditorFormView....
nilq/baby-python
python
#!/usr/bin/env python # # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # # Michael A.G. Aivazis # California Institute of Technology # (C) 1998-2003 All Rights Reserved # # <LicenseText> # # ~~~~~~~~~~~~~~~~~~~~~~~~...
nilq/baby-python
python
from pathlib import Path from typing import List def get_asset(name: str) -> Path: try: path = next(Path(__file__).parent.rglob(name)) except StopIteration: raise FileNotFoundError(name) return path def find_asset(name: str) -> List[Path]: paths = list(Path(__file__).parent.rglob(nam...
nilq/baby-python
python
import pandas as pd import numpy as np from scipy.stats import multivariate_normal from sklearn.metrics import accuracy_score def bayesiano(classes,x_train,y_train,x_test,y_test): #### Realiza a classificacao #### # Matriz que armazena as probabilidades para cada classe P = pd.DataFram...
nilq/baby-python
python
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! import grpc from google.ads.google_ads.v3.proto.resources import bidding_strategy_pb2 as google_dot_ads_dot_googleads__v3_dot_proto_dot_resources_dot_bidding__strategy__pb2 from google.ads.google_ads.v3.proto.services import bidding_strategy_service...
nilq/baby-python
python
# coding: utf-8 # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "...
nilq/baby-python
python
import re, sys, glob from os.path import join from tabulate import tabulate indir = sys.argv[1] outfile = join(indir, "xfold_eval.txt") name2fold = {} for fold in range(5): if fold not in name2fold: name2fold[fold] = {} file = join(indir, f"fold{fold}/eval.txt") with open(file, 'r') as f: tuple_performance,...
nilq/baby-python
python
# coding: utf-8 __doc__ = """包含一些继承自默认Qt控件的自定义行为控件。""" import os from PyQt5.QtCore import Qt from PyQt5.QtWidgets import QLineEdit, QTextEdit class QLineEditMod(QLineEdit): def __init__(self, accept="dir", file_filter=set()): super().__init__() self.setContextMenuPolicy(Qt.NoContextMenu) ...
nilq/baby-python
python
""" A collection of constants including error message """ ERROR_CLONE_TIMEOUT_EXPIRED = 'Timeout expired error' ERROR_CLONE_FAILED = 'Cloning failed error'
nilq/baby-python
python
########################################################################## # # Copyright (c) 2013, Image Engine Design Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistrib...
nilq/baby-python
python
from fastapi import Request from geobook.db.backends.mongodb import exceptions from starlette.responses import JSONResponse async def validation_exception_handler( request: Request, exc: exceptions.ValidationError, ) -> JSONResponse: headers = getattr(exc, 'headers', None) if headers: return J...
nilq/baby-python
python
# Generated by Django 2.0.5 on 2018-06-12 17:31 import django.contrib.postgres.fields.jsonb from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('webarchives', '0004_auto_20180609_1839'), ] operations = [ migrations.AlterField( model_name...
nilq/baby-python
python
from collections import deque import numpy as np from gym import spaces from gym.envs.atari.atari_env import AtariEnv from . import utils class MultiFrameAtariEnv(AtariEnv): metadata = {'render.modes': ['human', 'rgb_array']} no_op_steps = 30 def __init__(self, game='pong', obs_type='image', buf_size=4, gr...
nilq/baby-python
python
from random import randint from time import sleep computador = randint(0, 5) print('-=' * 20) print('Vou pensar em um número entre 0 e 5.Tente adivinhar...') print('-=' * 20) jogador = int(input('Em que número eu pensei? ')) print('Processando...') sleep(3) if jogador == computador: print('Parabéns! Você acertou!')...
nilq/baby-python
python
try: from pycaret.internal.pycaret_experiment import TimeSeriesExperiment using_pycaret=True except ImportError: using_pycaret=False
nilq/baby-python
python
#! /usr/bin/env python import json import argparse from dashboard.common import elastic_access from dashboard.common import logger_utils from dashboard.conf import config from dashboard.conf import testcases from dashboard_assembler import DashboardAssembler from visualization_assembler import VisualizationAssembler ...
nilq/baby-python
python
#!/home/ubuntu/DEF/PG/project/venv3/bin/python3 from django.core import management if __name__ == "__main__": management.execute_from_command_line()
nilq/baby-python
python
from .layers import *
nilq/baby-python
python
import os import json class Config: def __init__(self, configpath): self._data = self._get_config_data(configpath) self.client_id = self._data['client_id'] self.username = self._data['username'] self.account_id = self._data['account_id'] self.redirect = self._data['redirect...
nilq/baby-python
python
class OpenL3Error(Exception): """The root OpenL3 exception class""" pass
nilq/baby-python
python
from aiogram.dispatcher.filters.state import State, StatesGroup class AddStoreForm(StatesGroup): city_id = State() store_id = State() class SearchSku(StatesGroup): select_sku = State()
nilq/baby-python
python
import os import json from flask import request, abort, jsonify, make_response, Response from jsonschema import validate, ErrorTree, Draft4Validator as Validator from app.properties import properties_bp from .models import Property from .repositories import PropertyRepository as Repository from .utils import load @pr...
nilq/baby-python
python
from .annotation_decorator import annotate from .annotation_decorator import annotate_class from .annotation_decorator import annotate_method from .application import WinterApplication from .component import Component from .component import component from .component import is_component from .component_method import Com...
nilq/baby-python
python
import sys printf = lambda fmt,*args: sys.stdout.write(fmt%args) printf ("This is a %s of %is of possibilities of %s","test",1000,printf)
nilq/baby-python
python
#!/usr/bin/python import pickle import pandas as pd import numpy as np def convert_and_clean_data(data_dict, fill_na = 1.e-5): ''' Takes a dataset as a dictionary, then converts it into a Pandas DataFrame for convenience. Replaces all NA values by the value specified in 'fill_na' (or None). Cleans up...
nilq/baby-python
python
SIZE = (640,480) TITLE = "Pipboy" TEXT_COLOUR = (0,255,0) TEXT_SIZE = 12 TEXT_FONT = '../resources/monofonto.ttf' BOARDER_SPACE = 10 TOP_BOARDER = 6 BOX_SPACE = 20
nilq/baby-python
python
import os import sys import copy import argparse from avalon import io from avalon.tools import publish import pyblish.api import pyblish.util from pype.api import Logger import pype import pype.hosts.celaction from pype.hosts.celaction import api as celaction log = Logger().get_logger("Celaction_cli_publisher") p...
nilq/baby-python
python
# Copyright 2018 Canonical Ltd. # # 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 writin...
nilq/baby-python
python
import numpy as np; import numpy.matlib as npm; import DataHelper; # consume class is 0, 1, ..., discrete feature values is 0, 1, 2, ... class NaiveBayes: def __init__(self, smoothingFactor): self.__smoothingFactor = smoothingFactor; self.__discreteFeatureIndices = None; self.__discreteFe...
nilq/baby-python
python
# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html # For details: https://github.com/PyCQA/astroid/blob/main/LICENSE # Copyright (c) https://github.com/PyCQA/astroid/blob/main/CONTRIBUTORS.txt """This module contains mixin classes for scoped nodes.""" from typing import TYPE_CHECKIN...
nilq/baby-python
python
# -*- coding: utf-8 -*- # Generated by Django 1.10.2 on 2017-07-14 12:19 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration): initial = True depe...
nilq/baby-python
python
>>> 3 3 >>> _*_, _**0.5 (9, 1.7320508075688772) >>>
nilq/baby-python
python
import bson import os, base64, zlib, random from bson import BSONCoding, import_class class Member(BSONCoding): def __init__(self, username = "", code = "00", password = ""): self.username = username self.code = code self.password = password def __str__(self): di...
nilq/baby-python
python
# library/package semantic version __api_version__ = '1.4' __generation__ = 1
nilq/baby-python
python
from math import ( sin, cos, tan, acos, radians, degrees, ) from datetime import ( timedelta, ) def earth_declination(n): return 23.45 * sin(radians(360/365 * (284+n))) def td(lat): dec = earth_declination(119) #TODO Change this literal cofactor = -(tan(radians(lat)) * tan(rad...
nilq/baby-python
python
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2015-2018 CERN. # # Invenio is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """Test app.""" from __future__ import absolute_import import pytest from flask imp...
nilq/baby-python
python
''' Tests for the lookup module. ''' import sys import unittest from io import StringIO from unittest.mock import patch from modules import rec_lookup sys.path.insert(0, "0_1_0/") class TestLookup(unittest.TestCase): '''Lokup Tests''' def setUp(self): self.nodes_json = StringIO( ...
nilq/baby-python
python
# author: Artan Zandian # date: 2022-02-18 import tensorflow as tf from tensorflow.keras.layers import ( Input, Conv2D, MaxPooling2D, Dropout, Conv2DTranspose, concatenate, ) def encoder_block(inputs=None, n_filters=32, dropout=0, max_pooling=True): """ Convolutional e...
nilq/baby-python
python
##parameters=add='', edit='', preview='' ## from Products.PythonScripts.standard import structured_text from Products.CMFCore.utils import getUtilityByInterfaceName from Products.CMFDefault.utils import decode from Products.CMFDefault.utils import html_marshal from Products.CMFDefault.utils import Message as _ atool =...
nilq/baby-python
python
import pytest from django.urls import reverse from google.auth.exceptions import GoogleAuthError from crm.factories import UserSocialAuthFactory, ProjectMessageFactory from crm.models import ProjectMessage @pytest.mark.django_db def test_project_message_index(admin_app, project_message...
nilq/baby-python
python
""" Copyright 2015 INTEL RESEARCH AND INNOVATION IRELAND LIMITED 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...
nilq/baby-python
python
from django.contrib.auth import authenticate from django.test import TestCase from django.urls import resolve from .models import User from .views import index_view, dashboard_view from django.contrib.auth.views import LoginView, LogoutView from django.contrib.auth.decorators import login_required class UserLoggedInT...
nilq/baby-python
python
""" Example Vis Receive workflow """ # pylint: disable=C0103 import logging import ska_sdp_config import os # Initialise logging and configuration logging.basicConfig() log = logging.getLogger('main') log.setLevel(logging.INFO) config = ska_sdp_config.Config() # Find processing block configuration from the configur...
nilq/baby-python
python
# coding:utf-8 from django.contrib.auth import authenticate,login,logout from django.shortcuts import render_to_response from django.contrib.auth.decorators import login_required, permission_required,user_passes_test from django.views.decorators.csrf import csrf_exempt from django.shortcuts import get_object_or_404 fro...
nilq/baby-python
python
import random import numpy as np a = [5, -1, 0, -1, 2] b=-9 if sum(a) > 3 and b < -1: print(True)
nilq/baby-python
python
from keras.callbacks import TensorBoard import tensorflow as tf from keras.callbacks import EarlyStopping, ModelCheckpoint from exercise_performance_scorer.data_creator import ExercisePerformanceDataCreator from exercise_performance_scorer.model import ExercisePerformanceModel class ExercisePerformanceTrainer: de...
nilq/baby-python
python
from urllib.parse import urlparse from app import logger import requests class ControllerService: def init_app(self, app): return def send_command(self, gate, command='open', conditional=False): try: if gate.type == 'gatekeeper': if command == 'open' and not conditional: requests....
nilq/baby-python
python
from quart import Blueprint home = Blueprint("home", __name__) @home.route("/") def index(): """Home view. This view will return an empty JSON mapping. """ return {}
nilq/baby-python
python
from django.contrib import admin from froide.helper.admin_utils import ForeignKeyFilter class FollowerAdmin(admin.ModelAdmin): raw_id_fields = ( "user", "content_object", ) date_hierarchy = "timestamp" list_display = ("user", "email", "content_object", "timestamp", "confirmed") li...
nilq/baby-python
python
""" @author: Viet Nguyen <nhviet1009@gmail.com> """ import cv2 import numpy as np from collections import OrderedDict # https://github.com/tensorflow/datasets/blob/master/tensorflow_datasets/image_classification/quickdraw_labels.txt # Rule: key of category = index -1, with index from the link above CLASS_IDS = Ordere...
nilq/baby-python
python
import json import os TEST_FILE_BASE_PATH = 'tests' def __test_pages(app): testapp = app.test_client() pages = ('/') for page in pages: resp = testapp.get(page) assert resp.status_code == 200 def test_nearest_stations_mapper(): from transporter.utils import NearestStationsMapper ...
nilq/baby-python
python
import unittest from pyalink.alink import * import numpy as np import pandas as pd class TestPrintStreamOp(unittest.TestCase): def test_printstreamop(self): df = pd.DataFrame([ [0, "abcde", "aabce"], [1, "aacedw", "aabbed"], [2, "cdefa", "bbcefa"], [3, "bdefh...
nilq/baby-python
python
from sqlalchemy import * from sqlalchemy.orm import relationship, validates from db import db class ConfigTemplate(db.Model): __tablename__ = "config_template" id = Column(String, primary_key=True) doc = Column(Text, nullable=False) language_id = Column(String, ForeignKey('language.id')) ser...
nilq/baby-python
python
import random import logging from . import scheme __all__ = ('MTProtoSessionData',) log = logging.getLogger(__package__) class MTProtoSessionData: def __init__(self, id): if id is None: id = random.SystemRandom().getrandbits(64) log.debug('no session_id provided,...
nilq/baby-python
python
import argparse import torch import os from tqdm import tqdm from datetime import datetime import torch.nn as nn import torch.utils.data as data from torch.utils.tensorboard import SummaryWriter import deepab from deepab.models.PairedSeqLSTM import PairedSeqLSTM from deepab.util.util import RawTextArgumentDefaultsHelp...
nilq/baby-python
python
from flask_wtf import FlaskForm as Form from wtforms import StringField from wtforms.validators import DataRequired class LoginForm(Form): username = StringField('username', validators=[DataRequired()]) password = StringField('password', validators=[DataRequired()])
nilq/baby-python
python
import os import json import numpy as np import matplotlib.pyplot as plt def compute_iou(box_1, box_2): ''' This function takes a pair of bounding boxes and returns intersection-over- union (IoU) of two bounding boxes. ''' iou = np.random.random() width = min(box_1[2], box_2[2]) - max(box_1[0],...
nilq/baby-python
python
# # Project: # glideinWMS # # File Version: # # Description: # This module implements functions and classes # to handle forking of processes # and the collection of results # # Author: # Burt Holzman and Igor Sfiligoi # import cPickle import os import time import select from pidSupport import register_sighan...
nilq/baby-python
python
from click import Option from preacher.app.cli.executor import PROCESS_POOL_FACTORY, THREAD_POOL_FACTORY from preacher.app.cli.option import LevelType, ExecutorFactoryType from preacher.core.status import Status def test_level_type(): tp = LevelType() param = Option(["--level"]) assert tp.get_metavar(pa...
nilq/baby-python
python
# Represents smallest unit of a list with value, reference to succeding Node and referenece previous Node class Node(object): def __init__(self, value, succeeding=None, previous=None): pass class LinkedList(object): def __init__(self): pass
nilq/baby-python
python
## @package csnListener # Definition of observer pattern related classes. class Event: """ Generic event class. """ def __init__(self, code, source): self.__code = code self.__source = source def GetCode(self): return self.__code def GetSource(self): return self._...
nilq/baby-python
python
#code for feature1
nilq/baby-python
python
import unittest import pytest from botocore.exceptions import ClientError from localstack import config from localstack.utils.aws import aws_stack from localstack.utils.common import short_uid from .lambdas import lambda_integration from .test_integration import PARTITION_KEY, TEST_TABLE_NAME TEST_STREAM_NAME = lam...
nilq/baby-python
python
import json import os import tkinter as tk def cancelclick(): exit(0) class GUI: def okclick(self): data = {"url": self.urlentry.get(), "telegramAPIKEY": self.apikeyentry.get(), "telegramCHATID": self.chatidentry.get(), "databaseFile": self.databaseent...
nilq/baby-python
python
import io from collections import deque from concurrent.futures import ThreadPoolExecutor import numba from bampy.mt import CACHE_JIT, THREAD_NAME, DEFAULT_THREADS from . import zlib from ...bgzf import Block from ...bgzf.reader import BufferReader, EmptyBlock, StreamReader, _Reader as __Reader @numba.jit(nopython=...
nilq/baby-python
python
"""test format Revision ID: b45b1bf02a80 Revises: a980b74a499f Create Date: 2022-05-11 22:31:19.613893 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = 'b45b1bf02a80' down_revision = 'a980b74a499f' branch_labels = None depends_on = None def upgrade(): # ##...
nilq/baby-python
python
from myhdl import * import random from random import randrange from .alu import def_alu from .ctrl import def_ctrl random.seed(4) def test_ctrl(): """Test bench for the ALU control. """ clk = Signal(bool(0)) reset = ResetSignal(0, active=1, async=True) alu_op = Signal(intbv(0)[2:]) func...
nilq/baby-python
python
import asyncio import logging from datetime import datetime, timedelta from .login import BiliUser from .api import WebApi, medals, get_info, WebApiRequestError logging.basicConfig( level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s" ) logger = logging.getLogger("dailyclockin") cla...
nilq/baby-python
python
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2016-2017 China Telecommunication Co., Ltd. # # 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/lice...
nilq/baby-python
python