content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
import electrum
from aiohttp import web
from base import BaseDaemon
class BTCDaemon(BaseDaemon):
name = "BTC"
electrum = electrum
DEFAULT_PORT = 5000
daemon = BTCDaemon()
app = web.Application()
daemon.configure_app(app)
daemon.start(app)
| nilq/baby-python | python |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
def migrate_HeatSensor(apps, schema_editor):
HeatSensor = apps.get_model('heatcontrol', 'HeatSensor')
HeatControl = apps.get_model('heatcontrol', 'HeatControl')
HeatControlProfile = apps.get_model('hea... | nilq/baby-python | python |
from __future__ import print_function
from loguru import logger
import io3d
import io3d.datasets
import sed3
import numpy as np
import matplotlib.pyplot as plt
logger.enable("io3d")
logger.disable("io3d")
import matplotlib.pyplot as plt
from pathlib import Path
import bodynavigation
import exsu
import sys
import os
... | nilq/baby-python | python |
"""
-*- test-case-name: PyHouse.Modules.Computer.Mqtt.test.test_computer -*-
@name: PyHouse/src/Modules/Computer/Mqtt/mqtt_client.py
@author: D. Brian Kimmel
@contact: D.BrianKimmel@gmail.com
@copyright: (c) 2015-2016 by D. Brian Kimmel
@license: MIT License
@note: Created on Jun 5, 2015
@Sum... | nilq/baby-python | python |
import torch.nn as nn
from ..builder import VQA_MODELS, build_backbone, build_encoder, build_head
@VQA_MODELS.register_module()
class VISDIALPRINCIPLES(nn.Module):
def __init__(self, vocabulary_len, word_embedding_size, encoder, backbone, head):
super().__init__()
self.embedding_model = nn.Embe... | nilq/baby-python | python |
import numpy as np
from mchap import mset
from mchap.assemble import inheritence
def test_gamete_probabilities__hom():
genotypes = np.array([[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]], np.int8)
probabilities = np.array([1])
gametes_expect = np.array([[[0, 0, 0], [0, 0, 0]]], np.int8)
probs_expec... | nilq/baby-python | python |
# Copyright 2019 New Relic, Inc.
#
# 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... | nilq/baby-python | python |
import altair as alt
from data import get_nullity_matrix_data
def nullity_matrix_chart(
data, keep_original_col_order=True, show_tooltip=False, threshold=0.5, h=400
):
nm_data, n_rows = get_nullity_matrix_data(data)
text_font_size = 10
base = alt.Chart(nm_data, height=h)
chart = base.mark_rect(... | nilq/baby-python | python |
#!encoding=utf-8
from textblob import TextBlob
import os, sys, re
def textblob_process(line):
blob = TextBlob(line)
return blob.tags
def process_tag_result(tag_res):
nps = []
i = 0
while i < len(tag_res):
while i < len(tag_res) and not tag_res[i][1].startswith('NN'):
i += 1... | nilq/baby-python | python |
from ..crypto import Nonce
from . import constants
from io import BytesIO
from datetime import datetime
import binascii
import struct
import base58
import json
FIELDS = {
'i64le': [8, '<q'],
'i64be': [8, '>q'],
'u64le': [8, '<Q'],
'u64be': [8, '>Q'],
'i32le': [4, '<i'],
'i32be': [4, '>i'],
'u32le': [4, '<I'],
... | nilq/baby-python | python |
#----------
#author:someone120
#----------
import pypinyin as py
import lxml
import sqlite3 as sql
from urllib import request as url
#导包结束
def run():
print(get(1).decode('gbk'))
def get(num):
"""
num为页码
"""
header={
'User-Agent':'Mozilla/5.0 (Linux; Android 8.1.0; Redmi 5 Build/OPM1.171019.... | nilq/baby-python | python |
# pylint: disable=not-callable
# pylint: disable=no-member
import torch
import torch.nn as nn
from torch.nn import functional as F
class RecurrentDynamics(nn.Module):
def __init__(
self,
hidden_size,
state_size,
action_size,
node_size,
embedding_size,
act_f... | nilq/baby-python | python |
import vcr
import zlib
import json
import six.moves.http_client as httplib
from assertions import assert_is_json
def _headers_are_case_insensitive(host, port):
conn = httplib.HTTPConnection(host, port)
conn.request("GET", "/cookies/set?k1=v1")
r1 = conn.getresponse()
cookie_data1 = r1.getheader("set-... | nilq/baby-python | python |
# uncompyle6 version 3.2.4
# Python bytecode 2.7 (62211)
# Decompiled from: Python 2.7.15 (v2.7.15:ca079a3ea3, Apr 30 2018, 16:30:26) [MSC v.1500 64 bit (AMD64)]
# Embedded file name: lib.coginvasion.toon.NameTag
from panda3d.core import TextNode
from direct.fsm import ClassicFSM, State
from lib.coginvasion.globals imp... | nilq/baby-python | python |
# Copyright 2016-2021 IBM Corp. 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... | nilq/baby-python | python |
# ---------------------------------------------------------------------
# Project "Track 3D-Objects Over Time"
# Copyright (C) 2020, Dr. Antje Muntzinger / Dr. Andreas Haja.
#
# Purpose of this file : Parameter file for tracking
#
# You should have received a copy of the Udacity license together with this program.
#
# ... | nilq/baby-python | python |
#-*- encoding=utf-8 -*-
#a example to demo multi threading python app for mq handling
#ganben
import Queue
import threading
import time
import paho.mqtt.client as mqtt
queueLock = threading.Lock()
posiQueue = Queue.Queue(100)
callQueue = Queue.Queue(100)
threads = []
threadID = 1
def on_connect(client, userdata, rc)... | nilq/baby-python | python |
from flask_plugin import Plugin
from flask import redirect, url_for, abort
plugin = Plugin()
@plugin.route('/say/<string:name>', methods=['GET'])
def say(name: str):
return 'Hello ' + name
@plugin.route('/admin', methods=['GET'])
def hello2admin():
return redirect(url_for('.say', name='Doge'))
@plugin.r... | nilq/baby-python | python |
import os
from chr.core import chr_compile_module
chr_compile_module(os.path.dirname(__file__), verbose=False, overwrite=True)
| nilq/baby-python | python |
from django.test import TestCase
# Create your tests here.
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
class MultiSelectFunctionalTests(TestCase):
base_url = 'http://localhost:8000/tests'
fixtures=['publications']
def setUp(self):
self.driver = webdriver.Firefox... | nilq/baby-python | python |
import tkinter as tkinter
from tkinter import filedialog as FileDialog
from Properties import Properties
class Main():
def __init__(self):
self.Window = tkinter.Tk()
self.Properties = Properties()
self.setTitle('Bloc Note')
self.setSize(self.Properties.x, self.Properties.y)
self.Frame = tkinter.Frame(self.W... | nilq/baby-python | python |
import unittest
from unittest.mock import MagicMock
import builtins
class micropython:
def const(self, number):
return number
class TestCase(unittest.TestCase):
orig_import = __import__
module_mock = MagicMock()
@classmethod
def import_mock(cls, name, *args):
if name == "uasyncio":
return cls... | nilq/baby-python | python |
# http://github.com/timestocome
# adapted from http://natureofcode.com/book/chapter-9-the-evolution-of-code/
# 3 letter match ~ 20 generations
# 4 letters ~ 120 generations
import string as st
import re
import numpy as np
import copy
bots = []
new_bots = []
scores = []
n_letters = 4
n_bots = 100
target =... | nilq/baby-python | python |
#encoding:utf-8
subreddit = 'CryptoMoonShots'
t_channel = '@r_CryptoMoonShot'
def send_post(submission, r2t):
return r2t.send_simple(submission)
| nilq/baby-python | python |
from seagulls.engine import ActiveSceneClient
class FakeGameScene:
pass
class TestActiveSceneClient:
def test_apply(self) -> None:
fake_scene = FakeGameScene()
def callback(scene: FakeGameScene) -> None:
assert scene == fake_scene
client = ActiveSceneClient(fake_scene) ... | nilq/baby-python | python |
import asyncio
import logging
from struct import Struct
from time import time
logger = logging.getLogger(__name__)
class CyKitClient:
def __init__(self, reader, writer, channels=14, sample_rate=128):
self.sample_rate = sample_rate
self._reader, self._writer = reader, writer
self._struct ... | nilq/baby-python | python |
__author__ = "Anand Krishnan Prakash"
__email__ = "akprakash@lbl.gov"
import pymortar
import datetime
import pandas as pd
import argparse
def get_error_message(x, resample_minutes=60):
dt_format = "%Y-%m-%d %H:%M:%S"
st = x.name
st_str = st.strftime(dt_format)
et_str = (st+datetime.timedelta(minutes=... | nilq/baby-python | python |
# Данные для входа
LOGIN = "логин"
PASSWORD = "пароль"
# Некоторые параметры API
MAX_COUNT = 100 # Максимальное кол-во записей, которое можно получить по *.wall.get, деленное на 25.
LIMIT = 500
AGE1 = 14
AGE2 = 20
AGE3 = 35
AGE4 = 50
"""
LIMIT - Максимальное кол-во записей, скачиваемое со страницы по *wall.get (в... | nilq/baby-python | python |
"""
Sponge Knowledge Base
Provide action arguments - element value set
"""
class FruitsElementValueSetAction(Action):
def onConfigure(self):
self.withLabel("Fruits action with argument element value set")
self.withArg(ListType("fruits", StringType()).withLabel("Fruits").withUnique().withProv... | nilq/baby-python | python |
# dna.py - DNA class and related functions
# RMM, 11 Aug 2018
#
# This file contains the implementation of DNA in the txtlsim toolbox.
# This includes objects that represent the individual elements of a
# DNA assembly as well as the functions required to create the models
# associated with gene expression.
#
# Copyrigh... | nilq/baby-python | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from services import svcProject
from utils.exceptionHandle import DefaultError
def list_project():
"""
GET /api/projects
:return:
"""
try:
return {
'title': 'Succeed to List Project',
'detail': svcProject.list_project(... | nilq/baby-python | python |
import pytz
from cogs.Permissions import dm_commands, moderator_perms
from GompeiFunctions import load_json, save_json
from dateutil.parser import parse
from discord.ext import commands
from datetime import datetime
from config import Config
import asyncio
import discord
import os
class Voting(commands.Cog):
""... | nilq/baby-python | python |
from typing import List, Type
import warnings
import numpy as np
import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
from astropy import wcs
from astropy.coordinates import SkyCoord
from astropy.io import fits
from astropy.modeling import models
from astropy.utils.exceptions import AstropyWarning
fr... | nilq/baby-python | python |
import socket, time
from kubism.util.dkr import PyApp_Image
import docker
import kubism.util.dkr as dkr
SERVER = '172.24.12.161'
CLIENT = '172.24.12.160'
echo_port = 8080
# Echo Test
# Create Echo Server
print('Building and pushing images...')
echo_srv = PyApp_Image('./examples/py/echo_server.py',
parent_image... | nilq/baby-python | python |
from flask_security_bundle import FlaskSecurityBundle
class SecurityBundle(FlaskSecurityBundle):
pass
| nilq/baby-python | python |
from .parse_html_index import parse_html_index
from .parse_html_raceindex import parse_html_raceindex
from .parse_html_racelist import parse_html_racelist
from .parse_html_oddstf import parse_html_oddstf
from .parse_html_oddsk import parse_html_oddsk
from .parse_html_odds2tf import parse_html_odds2tf
from .parse_html_o... | nilq/baby-python | python |
from .common import * # NOQA
import pytest
HUAWEI_CCE_ACCESS_KEY = os.environ.get('RANCHER_HUAWEI_CCE_ACCESS_KEY', "")
HUAWEI_CCE_SECRET_KEY = os.environ.get('RANCHER_HUAWEI_CCE_SECRET_KEY', "")
HUAWEI_CCE_PROJECT = os.environ.get('RANCHER_HUAWEI_CCE_PROJECT', "")
HUAWEI_CCE_AMI = os.environ.get('RANCHER_HUAWEI_CCE_A... | nilq/baby-python | python |
from jewelry import Jewelry
class Necklace(Jewelry):
DEFAULT_METAL : str = "gold"
DEFAULT_GEM : str = "diamond"
def __init__(self, metal : str = DEFAULT_METAL, gem : str = DEFAULT_GEM):
super(Necklace,self).__init__(polished = True)
self._metal = metal
self._gem = gem
@propert... | nilq/baby-python | python |
# Copyright (c) 2013 Shotgun Software Inc.
#
# CONFIDENTIAL AND PROPRIETARY
#
# This work is provided "AS IS" and subject to the Shotgun Pipeline Toolkit
# Source Code License included in this distribution package. See LICENSE.
# By accessing, using, copying or modifying this work you indicate your
# agreement to t... | nilq/baby-python | python |
import functools
from collections import OrderedDict, namedtuple
from http import HTTPStatus
from types import FunctionType
from typing import Callable, Iterable, Optional
from werkzeug.routing import Map, MethodNotAllowed, NotFound, RequestRedirect, Rule
from PythonPlug import Conn
from PythonPlug.plug import Plug
... | nilq/baby-python | python |
import unittest
from test_support import run_unittest, TESTFN
import glob
import os
def mkdirs(fname):
if os.path.exists(fname) or fname == '':
return
base, file = os.path.split(fname)
mkdirs(base)
os.mkdir(fname)
def touchfile(fname):
base, file = os.path.split(fname)
mkdirs(base)
... | nilq/baby-python | python |
from selenium import webdriver
import os
import subprocess
driver = webdriver.Chrome(service_log_path=os.path.devnull)
driver.set_window_size(1500, 900)
fname = "file://" + os.getcwd() + "/opcodes.html"
driver.get(fname)
driver.save_screenshot("../images/opcode_map.png")
driver.quit()
subprocess.check_output([
"c... | nilq/baby-python | python |
# 增加的一个类属性用于统计Student的数量,每创建一个实例,该属性自动加一
class Student(object):
count = 0
def __init__(self, name, score):
Student.name = name
Student.score = score
if Student.name != []:
Student.count += 1
# 测试:
if Student.count != 0:
print('测试失败!')
else:
bart = Student('Bart', 90... | nilq/baby-python | python |
#User function Template for python3
class Solution:
#Function to find if there exists a triplet in the
#array A[] which sums up to X.
def find3Numbers(self,A, n, X):
# Your Code Here
A.sort()
for i in range(n-2):
start=i+1
end=n-1
sum1=0
... | nilq/baby-python | python |
# Created: 17.05.2019
# Copyright (c) 2019, Manfred Moitzi
# License: MIT License
from typing import TYPE_CHECKING, Iterable, List, Mapping, Set
import json
from ezdxf.sections.tables import TABLENAMES
from ezdxf.lldxf.tags import Tags
if TYPE_CHECKING:
from ezdxf.eztypes import Insert, MText, LWPolyline, Polylin... | nilq/baby-python | python |
from astropy.coordinates import Angle
from neclib.parameters import PointingErrorData
class TestPointingErrorData:
expected = {
"dAz": Angle("5314.2466754691195arcsec"),
"de": Angle("382arcsec"),
"chi_Az": Angle("-27.743114809726713arcsec"),
"omega_Az": Angle("-10.004233550100272... | nilq/baby-python | python |
import pyglet.resource
import pyglet.sprite
import pyglet.graphics
def get_room_wall_image(room):
filename = 'res/rooms/walls/{}.jpg'.format(room.wall_variant)
return pyglet.resource.image(filename)
def get_forniture_image(forniture):
filename = 'res/forniture/{}.png'.format(forniture.name)
return... | nilq/baby-python | python |
# UNDER CONSTRUCTION !
light_metadata = {
"name": {
"type": "string"
},
"version": {
"type": "string"
},
"data_preparation": {
"type": "object",
"properties": {
"accepted_margin_of_error": {
"type": "number"
},
"total_row_count": {
"type": "nu... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 20 22:56:12 2019
@author: Suman
JaipurRentals
Jaipur’s Real Estate Market is experiencing an incredible resurgence, with property prices soaring by double-digits on an
yearly basis since 2013. While home owne... | nilq/baby-python | python |
import data as tours_data
def data_html():
ret = "<h1>Все туры:</h1>"+"\n"
for i in tours_data.tours.keys():
ret = ret + "<p>"+\
tours_data.tours[i]["country"]+\
': <a href="/data/tours/'+str(i)+'/">'+\
tours_data.tours[i]["title"]+\
"</a></p>"
... | nilq/baby-python | python |
# The MIT License (MIT)
#
# Copyright (c) 2019 Melissa LeBlanc-Williams for Adafruit Industries
#
# 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 limita... | nilq/baby-python | python |
__author__ = 'yinjun'
#@see http://www.jiuzhang.com/solutions/longest-common-subsequence/
class Solution:
"""
@param A, B: Two strings.
@return: The length of longest common subsequence of A and B.
"""
def longestCommonSubsequence(self, A, B):
# write your code here
x = len(A)
... | nilq/baby-python | python |
import sys
from typing import Any, Collection, Dict, List, Optional, Union
from pydantic import BaseModel
from rest_api.config import DEFAULT_TOP_K_READER, DEFAULT_TOP_K_RETRIEVER
MAX_RECURSION_DEPTH = sys.getrecursionlimit() - 1
class Question(BaseModel):
questions: List[str]
filters: Optional[Dict[str, O... | nilq/baby-python | python |
from hyperadmin.links import LinkPrototype
class FormStepLinkPrototype(LinkPrototype):
def get_link_kwargs(self, **kwargs):
link_kwargs = {'on_submit':self.handle_submission,
'method':'POST',
'url':self.get_url(),
'form_class': self.get_... | nilq/baby-python | python |
from tests import PMGLiveServerTestCase
from mock import patch
import unittest
from pmg.models import db, User
from tests.fixtures import dbfixture, UserData, RoleData, OrganisationData
class TestAdminUsersPage(PMGLiveServerTestCase):
def setUp(self):
super(TestAdminUsersPage, self).setUp()
self.... | nilq/baby-python | python |
from model import db, Product, Accounts
def deleteUser(rowid)
user = db.session.query(User).filter(User.id == user_id).first()
if user:
db.session.query(User).filter(User.id==user_id).delete()
db.session().commit()
def deleteProduct(rowid):
user = db.session.query(User).filter(... | nilq/baby-python | python |
"""Hata Yönetimi - Raise Deyimi."""
# Python dili kırmızı yazılar ile kendine has hata mesajları yayınlamaktadır
# Bizde bir hata meydana geldiğinde bu şekilde mesajlar yayınlayabiliriz.
# Bunun için Raise deyimi kullanılır.
sayi = 5
try:
if sayi == 5:
raise Exception('Sayı 5\'e eşit olamaz!')
else:
... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
import copy
__author__ = "Grant Hulegaard"
__copyright__ = "Copyright (C) Nginx, Inc. All rights reserved."
__license__ = ""
__maintainer__ = "Grant Hulegaard"
__email__ = "grant.hulegaard@nginx.com"
def collect_cache_size(collector, data, stamp):
collector.object.statsd.gauge('plus.cach... | nilq/baby-python | python |
from abc import ABCMeta
import numpy as np
from falconcv.decor import typeassert
import logging
logger = logging.getLogger(__name__)
class ApiModel(metaclass=ABCMeta):
def train(self, *args, **kwargs):
return self
def freeze(self, *args, **kwargs):
return self
def eval(self, *args, **k... | nilq/baby-python | python |
import sqlite3
CREATE_QUERY = """
CREATE TABLE IF NOT EXISTS chat_table (
chat_id INT PRIMARY KEY
)
"""
SELECT_ALL_QUERY = """
SELECT chat_id from chat_table
"""
INSERT_ONE_QUERY = """
INSERT INTO chat_table (chat_id)
VALUES (%s)
"""
def execute_query(query):
try:
sqlite_con... | nilq/baby-python | python |
import pandas
from openpyxl import load_workbook
from openpyxl.utils.dataframe import dataframe_to_rows
wb = load_workbook('data/regions.xlsx')
ws = wb.active
df = pandas.read_excel('data/all_shifts.xlsx')
df1 = df[['Sales Rep', 'Cost per', 'Units Sold']]
df1['Total'] = df1['Cost per'] * df1['Units Sold']
rows = data... | nilq/baby-python | python |
from __future__ import unicode_literals, print_function, division
import os
import matplotlib.pyplot as plt
from compute_scores import compute_scores
# Draw figures in Figure 2.
for rel in ['mirgene', 'ppi', 'ploc']:
# Heuristic of trigger words.
scores = compute_scores(rel, 'h2')
precisions = [s[2] for ... | nilq/baby-python | python |
#You are given a data structure of employee information, which includes the employee's unique id, his importance value and his direct subordinates' id.
# For example, employee 1 is the leader of employee 2, and employee 2 is the leader of employee 3. They have importance value 15, 10 and 5, respectively. Then employee... | nilq/baby-python | python |
import copy
import cv2
# import torch
from mindspore import Tensor
import numpy as np
from PIL import Image
from util.config import config as cfg
from util.misc import find_bottom, find_long_edges, split_edge_seqence, \
norm2, vector_sin, split_edge_seqence_by_step, sample, fourier_transform, \
clockwise, find_... | nilq/baby-python | python |
#!/usr/bin/python
import broker
import select
## demo receiver that is subscribed to the topic "demo/select_fd"
ep = broker.Endpoint()
subscriber = ep.make_subscriber("demo/select_fd")
ep.listen("127.0.0.1", 9999)
while(True):
## this will block until we have read-readiness on the file descriptor
# print("... | nilq/baby-python | python |
#
# @lc app=leetcode.cn id=275 lang=python3
#
# [275] H 指数 II
#
# https://leetcode-cn.com/problems/h-index-ii/description/
#
# algorithms
# Medium (41.25%)
# Likes: 139
# Dislikes: 0
# Total Accepted: 39K
# Total Submissions: 85.6K
# Testcase Example: '[0,1,3,5,6]'
#
# 给定一位研究者论文被引用次数的数组(被引用次数是非负整数),数组已经按照 升序排列 。... | nilq/baby-python | python |
from twotest.fixtures import client, django_client
from wheelcms_axle.tests.fixtures import localtyperegistry, localtemplateregistry, root
| nilq/baby-python | python |
resposta = 'S'
soma = count = maior = menor = 0
while resposta in 'Ss':
num = int(input('Digite um numero: '))
soma += num
count += 1
if count == 1:
maior = menor = num
else:
if num > maior:
maior = num
else:
menor = num
resposta = str(input('Quer... | nilq/baby-python | python |
#!/usr/bin/env python
# to be used with 'rps_pico_client.py'
# Example to illustrate RPS feature to run tiny (pico) services, such as reading sensor data or
# controlling a device; here, time at server is requested. In this example a new service task is
# created to serve a request. Compare this to 'task_pico_service... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__doc__ = """
hgvs.edit -- representation of edit operations in HGVS variants
NARefAlt and AARefAlt are abstractions of several major variant
types. They are distinguished by whether the ref and alt elements
of... | nilq/baby-python | python |
#!/usr/bin/env python
""""Downloads and unzips the KITTI tracking data.
Warning: This can take a while, and use up >100Gb of disk space."""
#ref from https://github.com/utiasSTARS/pykitti/blob/master/pykitti/downloader/tracking.py
from __future__ import print_function
import argparse
import os
import sys
from subpro... | nilq/baby-python | python |
from collections.abc import Iterable
from enum import Enum
import json
import logging
import subprocess
from typing import Union, Any, Optional
from pathlib import Path
from scipy import sparse
import scipy
from typer.models import NoneType
logger = logging.getLogger(__name__)
def expand_paths(path_or_pattern):
... | nilq/baby-python | python |
#----------------------------------------------------------------------
# This programme provides a simple example of how to use "approach control"
# for colour light (and to improve the automation of semaphore signals.
#
# For Colour Light Signals - this can be used where it is necessary to slow
# a train down to take... | nilq/baby-python | python |
import subprocess
import json
from datetime import datetime
from pydruid.client import PyDruid
from pydruid.utils.aggregators import (longmax,
doublemax)
from pydruid.utils.filters import Dimension
from kafka import KafkaProducer
from iso8601utils import validators
class KafkaAc... | nilq/baby-python | python |
import getpass
import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr
import urllib.request, urllib.parse, urllib.error
import ssl
import json
import time
import re
import os
import sys
# Email setting for notification
def Email(sender, password, recipient, emailsub, emailmsg, smtpsever... | nilq/baby-python | python |
import unittest
from buscasrc.core.analyzer import Analyzer
class TestAnalyzer(unittest.TestCase):
def setUp(self):
self.analyzer = Analyzer()
def test_prepare_text(self):
text = "Conan, the barbarian is a great HQ. Conan, #MustRead!"
self.assertListEqual(self.analyzer.prepare_text(... | nilq/baby-python | python |
import yaml
from functools import lru_cache
from flask import current_app as app
from atst.utils import getattr_path
class LocalizationInvalidKeyError(Exception):
def __init__(self, key, variables):
self.key = key
self.variables = variables
def __str__(self):
return "Requested {key} a... | nilq/baby-python | python |
from .validate import Validate
__all__ = ["Valdate"]
| nilq/baby-python | python |
"""Application tests."""
| nilq/baby-python | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
import inselect
REQUIREMENTS = [
# TODO How to specify OpenCV? 'cv2>=3.1.0',
'numpy>=1.11.1,<1.12',
'Pillow>=3.4.2,<3.5',
'python-dateutil>=2.6.0,<2.7',
'pytz>=2016.7',
'PyYAML>=3.12,<3.2',
'schematics>=1.1.1,<1.2',
'scikit-lea... | nilq/baby-python | python |
# get camera list
import logging
from datetime import datetime
from typing import Any
from typing import List
import requests
from protect_archiver.dataclasses import Camera
def get_camera_list(session: Any, connected: bool = True) -> List[Camera]:
cameras_uri = f"{session.authority}{session.base_... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 26 15:15:55 2018
@author: Madhur Kashyap 2016EEZ8350
"""
import os
import sys
import logging
import numpy as np
from functools import partial
from keras.optimizers import Adadelta
from sklearn.metrics import confusion_matrix
prog = os.path.basename(__file... | nilq/baby-python | python |
from connect4 import Connect4Board
from connect4 import GameState
from connect4 import Player
def test_win_condition():
# check vertical
for row in range(6-3):
for col in range(7):
game = Connect4Board()
for i in range(row, row+4):
game.board[i][col] = Player.PLAYER_1
if not game.chec... | nilq/baby-python | python |
import urllib
import os
import threading
import time
import errno
from functools import partial
import weakref
import base64
import json
import socket
from socketserver import ThreadingMixIn
from http.server import SimpleHTTPRequestHandler, HTTPServer
from urllib.parse import unquote
from urllib.parse import urlparse
... | nilq/baby-python | python |
from twisted.trial import unittest
from twisted.internet import defer
from nodeset.core import config
from nodeset.common.twistedapi import NodeSetAppOptions
class ConfigurationTest(unittest.TestCase):
def setUp(self):
cfg = NodeSetAppOptions()
cfg.parseOptions(['-n', '--listen', 'localhost:4... | nilq/baby-python | python |
acceptable_addrs = ["192.168.0.16"]
| nilq/baby-python | python |
# Generated by Django 2.1.5 on 2019-01-27 00:11
from django.db import migrations, models
import django.db.models.deletion
import simplemde.fields
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = []
operations = [
migrations.CreateModel(
name="Event",... | nilq/baby-python | python |
from .operator_bot import main
main()
| nilq/baby-python | python |
from episerver.vanir.configuration import Configuration
from azure.common.client_factory import get_client_from_json_dict
from azure.mgmt.resource import ResourceManagementClient
class AddEnvironmentCommand:
def __init__(self):
config = Configuration()
self.resource_client = get_client_from_json_di... | nilq/baby-python | python |
from tensorize import *
class InceptionResnetV1(Model):
def inference(self, inputs, output):
stem(inputs, outputs)
for x in xrange(4):
inceptionA()
reductionA()
for x in xrange(7):
inceptionB()
reductionB()
for x in xrange(3):
... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
import trello.checklist as checklist
class Checklist(checklist.Checklist):
pass
| nilq/baby-python | python |
import os
import unittest
from skidl import *
class UnitTestsElectronicDesignAutomationSkidlExamples(unittest.TestCase):
def test_introduction(self):
print("test_introduction")
# Create input & output voltages and ground reference.
vin, vout, gnd = Net('VI'), Net('VO'), Net('GND')
... | nilq/baby-python | python |
# Copyright Contributors to the Pyro project.
# SPDX-License-Identifier: Apache-2.0
import contextlib
import importlib
import itertools
import numbers
import operator
from collections import OrderedDict, namedtuple
from functools import reduce
import numpy as np
import opt_einsum
from multipledispatch import dispatch... | nilq/baby-python | python |
import unittest
import torch.cuda as cuda
from inferno.utils.model_utils import MultiscaleModelTester
class TestUnetMultiscale(unittest.TestCase):
def test_unet_multiscale_2d(self):
from neurofire.models import UNet2DMultiscale
input_shape = (1, 1, 512, 512)
output_shape = ((1, 1, 512, 512... | nilq/baby-python | python |
from .linear_growth_class import CosmoLinearGrowth
from .linear_growth_functions import a2z
from .linear_growth_functions import z2a
from .linear_growth_functions import get_Hz
from .linear_growth_functions import get_Dz
from .linear_growth_functions import get_r
from .linear_growth_functions import get_omega_m_z
fro... | nilq/baby-python | python |
#!/usr/bin/python
#-*- coding: utf-8 -*-
# >.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.
# Licensed under the Apache License, Version 2.0 (the "License")
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# --- File Name: loss_uneven.py
# --- Creation Date: 19-04-2021
# --- Last Modified: Sat 2... | nilq/baby-python | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
from pathlib import Path
from wildfires.utils import handle_array_job_args
try:
# This will only work after the path modification carried out in the job script.
from specific import (
CACHE_DIR,
SimpleCache,
get_model,
da... | nilq/baby-python | python |
import aiohttp
import asyncio
import json
import time
from pydigitalstrom.client import DSClient
from pydigitalstrom.log import DSLog
class DSWebsocketEventListener:
def __init__(self, client: DSClient, event_name: str):
self._client = client
self._event_name = event_name
self._callbacks ... | nilq/baby-python | python |
from django.core.exceptions import ObjectDoesNotExist
from django.db import models
class OrderField(models.PositiveIntegerField):
def __init__(self, for_fields=None, *args, **kwargs):
self.for_fields = for_fields
super().__init__(*args, **kwargs)
def pre_save(self, model_instance, add):
... | nilq/baby-python | python |
# Copyright 2020 Lynn Root
"""Functional tests for interrogate/coverage.py."""
import os
import sys
import pytest
from interrogate import config
from interrogate import coverage
HERE = os.path.abspath(os.path.join(os.path.abspath(__file__), os.path.pardir))
SAMPLE_DIR = os.path.join(HERE, "sample")
FIXTURES = os.p... | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.