content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
"""
MIT License
Copyright (c) 2021 Defxult#8269
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, copy, modify, merge, publish, ... | nilq/baby-python | python |
# Generated by Django 2.2.10 on 2020-04-06 06:28
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('items', '0002_item_whereabouts'),
]
operations = [
migrations.AddField(
model_name='item',
name='sale_type',
... | nilq/baby-python | python |
# Copyright 2021 IBM Corporation
#
# 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 wri... | nilq/baby-python | python |
import os
import shutil
import unittest
from xbrr.tdnet.client.document_client import DocumentClient
from xbrr.edinet.reader.reader import Reader
from xbrr.tdnet.reader.doc import Doc
import pandas as pd
class TestReader(unittest.TestCase):
@classmethod
def setUpClass(cls):
_dir = os.path.join(os.path... | nilq/baby-python | python |
from noise import pnoise2
from time import sleep
from threading import Thread
import os
import color
import platform
import socket
try: from pynput import keyboard
except ImportError: keyboard = None
# unused ports: 26490-26999
port = 26969
address = "192.168.50.172"
s = socket.socket(socket.AF_INET, socket.SOCK_STRE... | nilq/baby-python | python |
expected_output = {
"vrf": {
"User": {
"iid": 4100,
"number_of_entries": 2186,
"eid": {
"0.0.0.0/0": {
"uptime": "1w6d",
"expire": "never",
"via": [
"static-send-map-reques... | nilq/baby-python | python |
import random
from environment import TicTacToe, X, O
class Agent:
def __init__(self, plays=X, episodes=10_000):
"""
Initialise the agent with all the possible board states in a look up table.
Winning states have a value of 1, losing states have -1. All else are 0
"""
... | nilq/baby-python | python |
import random
import uuid
LOGGED_IN_DATA = {
'host': 'https://app.valohai.com/',
'user': {'id': 'x'},
'token': 'x',
}
PROJECT_DATA = {
'id': '000',
'name': 'nyan',
'description': 'nyan',
'owner': 1,
'ctime': '2016-12-16T12:25:52.718310Z',
'mtime': '2017-01-20T14:35:02.196871Z',
... | nilq/baby-python | python |
#!/usr/bin/env python
from distutils.core import setup
LONG_DESCRIPTION = \
'''Convert DNA structural variants in VCF files into BED format'''
setup(
name='svdistil',
version='0.1.0.0',
author='Bernie Pope',
author_email='bjpope@unimelb.edu.au',
packages=['svdistil'],
package_dir={'svdistil'... | nilq/baby-python | python |
import h5py
import numpy as np
import pandas as pd
import lightgbm as lgb
class HDFSequence(lgb.Sequence):
def __init__(self, hdf_dataset, batch_size):
"""
Construct a sequence object from HDF5 with required interface.
Parameters
----------
hdf_dataset : h5py.Dataset
... | nilq/baby-python | python |
import json
from src.main import ReadFile
if __name__ == '__main__':
path_to_annotell_annotation = 'annotell_1.json'
with open(path_to_annotell_annotation, 'r') as content:
json_body = json.load(content)
result = ReadFile().convert(json_body)
print(result) | nilq/baby-python | python |
import httpretty
import pytest
from h_matchers import Any
@pytest.fixture
def pyramid_settings():
return {
"client_embed_url": "http://hypothes.is/embed.js",
"nginx_server": "http://via.hypothes.is",
"via_html_url": "https://viahtml.hypothes.is/proxy",
"checkmate_url": "http://loca... | nilq/baby-python | python |
#! /usr/bin/env python
from metadata_file import MetadataFile
import json
class FalseJSONMetadataFile(MetadataFile):
"""A metadata file type for files that claim to be JSON files but aren't """
category_name = 'FALSE_JSON';
def collect_metadata(self):
print('not parsing json from %s' % self.path)... | nilq/baby-python | python |
"""
# FRACTION TO RECURRING DECIMAL
Given two integers representing the numerator and denominator of a fraction, return the fraction in string format.
If the fractional part is repeating, enclose the repeating part in parentheses.
If multiple answers are possible, return any of them.
It is guaranteed that the leng... | nilq/baby-python | python |
from youtube_search import YoutubeSearch as YS
from config import TOKEN
from aiogram import Bot,types,Dispatcher,utils
from aiogram.utils import executor
from aiogram.types import InputTextMessageContent,InlineQueryResultArticle, ReplyKeyboardMarkup,KeyboardButton
import hashlib
async def on_startup(_):
... | nilq/baby-python | python |
# do imports
import matplotlib.pyplot as plt
import logomaker as logomaker
# load ARS enrichment matrix
ars_df = logomaker.get_example_matrix('ars_enrichment_matrix',
print_description=False)
# load wild-type ARS1 sequence
with logomaker.open_example_datafile('ars_wt_sequence.txt... | nilq/baby-python | python |
"""Portfolio Helper"""
__docformat__ = "numpy"
from datetime import datetime
from dateutil.relativedelta import relativedelta
import yfinance as yf
import pandas as pd
# pylint: disable=too-many-return-statements
BENCHMARK_LIST = {
"SPDR S&P 500 ETF Trust (SPY)": "SPY",
"iShares Core S&P 500 ETF (IVV)": "IVV... | nilq/baby-python | python |
import json
from testtools.matchers import raises, Not
import falcon.testing as testing
import falcon
class FaultyResource:
def on_get(self, req, resp):
status = req.get_header('X-Error-Status')
title = req.get_header('X-Error-Title')
description = req.get_header('X-Error-Description')
... | nilq/baby-python | python |
from django import forms
from .models import AVAILABLE_SLOTS_LEVELS, Spell, Spellbook
class SpellbookForm(forms.ModelForm):
class Meta:
model = Spellbook
fields = ['name']
class SpellbookSlotsForm(forms.Form):
spellbook_pk = forms.IntegerField(label="spellbook")
slot_level_field_names =... | nilq/baby-python | python |
# terrascript/provider/vcd.py
# Automatically generated by tools/makecode.py (24-Sep-2021 15:30:19 UTC)
#
# For imports without namespace, e.g.
#
# >>> import terrascript.provider.vcd
#
# instead of
#
# >>> import terrascript.provider.vmware.vcd
#
# This is only available for 'official' and 'partner' providers.
fr... | nilq/baby-python | python |
import re
import jsonschema
import json
import copy
from anchore_engine.services.policy_engine.engine.policy.exceptions import (
RequiredParameterNotSetError,
ValidationError,
ParameterValidationError,
)
from anchore_engine.subsys import logger
class InputValidator(object):
__validator_description__ ... | nilq/baby-python | python |
from django.http import HttpResponse
from django.db.models import Q
from apiApp.models import Profile, Comment, Tag, User, Group, Post
from apiApp.serializers import ProfileSerializer, CommentSerializer, UserSerializer, TagSerializer, GroupSerializer, PostSerializer
from apiApp.permissions import IsOwnerOrReadOnly
... | nilq/baby-python | python |
from bson.objectid import ObjectId
from app.models.domain.training_data_set import TrainingDataSet
from tests.stubs.models.domain.feature_extraction_data import get_feature_extraction_data_stub_5_1, get_feature_extraction_data_stub_4_2
def get_training_data_set_stub():
return TrainingDataSet(
last_modifi... | nilq/baby-python | python |
"""Slack platform for notify component."""
import asyncio
import logging
import os
from urllib.parse import urlparse
from aiohttp import BasicAuth, FormData
from aiohttp.client_exceptions import ClientError
from slack import WebClient
from slack.errors import SlackApiError
import voluptuous as vol
from homeassistant.... | nilq/baby-python | python |
from main import notion
from commands.run_daily_reset import run_daily_reset
from commands.run_update_duration import run_update_duration
if notion.UPDATE_DURATION:
print("UPDATE_DURATION : ", run_update_duration())
if notion.DAILY_RESET:
print("DAILY_REST : ", run_daily_reset())
| nilq/baby-python | python |
{% extends "_common/main.py" %}
{% set typeStep = "Delete" %}
| nilq/baby-python | python |
#! /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',
... | nilq/baby-python | python |
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... | nilq/baby-python | python |
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... | nilq/baby-python | 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | nilq/baby-python | python |
# 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]]
... | nilq/baby-python | python |
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)]
| nilq/baby-python | python |
#!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... | nilq/baby-python | python |
#!/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 ... | nilq/baby-python | python |
# 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))
| nilq/baby-python | python |
#!/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... | nilq/baby-python | python |
# -*- 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... | nilq/baby-python | python |
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... | nilq/baby-python | python |
"""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'):
... | nilq/baby-python | python |
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... | nilq/baby-python | python |
#!/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 <... | nilq/baby-python | python |
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 ... | nilq/baby-python | python |
"""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... | nilq/baby-python | python |
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]]
| nilq/baby-python | python |
from .script import test
def main():
test()
| nilq/baby-python | python |
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 = ... | nilq/baby-python | python |
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 = [
... | nilq/baby-python | python |
from Pluto.Libraries.Libraries.GLM import *
| nilq/baby-python | python |
""" 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... | nilq/baby-python | python |
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)
... | nilq/baby-python | python |
#!/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.
# ---------------------... | nilq/baby-python | python |
# 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... | nilq/baby-python | python |
# 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 ... | nilq/baby-python | python |
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])
| nilq/baby-python | python |
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... | nilq/baby-python | python |
""" 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
... | nilq/baby-python | python |
import app.api.point
import app.api.track
import app.api.tracker
import app.api.user
| nilq/baby-python | python |
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)
... | nilq/baby-python | python |
#!/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
""" | nilq/baby-python | python |
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 >... | nilq/baby-python | python |
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... | nilq/baby-python | python |
# -*- 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... | nilq/baby-python | python |
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._... | nilq/baby-python | python |
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... | nilq/baby-python | python |
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... | nilq/baby-python | python |
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... | nilq/baby-python | python |
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),\
... | nilq/baby-python | python |
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... | nilq/baby-python | python |
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... | nilq/baby-python | python |
##################################################################################
#
# 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 ... | nilq/baby-python | python |
#!/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... | nilq/baby-python | python |
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... | nilq/baby-python | python |
# -*- 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... | nilq/baby-python | python |
# 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... | nilq/baby-python | python |
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... | nilq/baby-python | python |
#! /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,... | nilq/baby-python | python |
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'
... | nilq/baby-python | python |
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... | nilq/baby-python | python |
#!/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: 路径文... | nilq/baby-python | python |
"""
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... | nilq/baby-python | python |
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: ... | nilq/baby-python | python |
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... | nilq/baby-python | python |
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 = ... | nilq/baby-python | 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 writing, software
# distribu... | nilq/baby-python | python |
# -*- 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... | nilq/baby-python | python |
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... | nilq/baby-python | python |
# 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... | nilq/baby-python | python |
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
| nilq/baby-python | python |
# -*- 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
... | nilq/baby-python | python |
# 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... | nilq/baby-python | python |
# -*- 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... | nilq/baby-python | python |
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 __... | nilq/baby-python | python |
#!/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 # ... | nilq/baby-python | python |
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 | nilq/baby-python | python |
#!/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... | nilq/baby-python | python |
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(... | nilq/baby-python | python |
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
... | nilq/baby-python | python |
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... | nilq/baby-python | python |
#-----------------------------------------------------------------------------
# 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... | nilq/baby-python | python |
#!/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.... | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.