content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
from ModelCreator import get_proportions_model
from ModelEvaluator import plot, show_images
from CustomDataProcessor import get_processed_data
import keras.models as models
import tensorflow as tf
import argparse
import os
import numpy as np
tf.config.experimental.list_physical_devices('GPU')
def train(directory, ima... | nilq/baby-python | python |
from pyalgotrade.barfeed import ibfeed
import datetime
class Parser(object):
def parse(self, filename):
slashIndex = filename.rfind('/')
if (slashIndex > -1):
filename = filename[slashIndex + 1:]
underscoreIndex = filename.rfind('_')
hyphenIndex = filename.rfind('-')
... | nilq/baby-python | python |
# !/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Filename: __init__.py
# Project: helpers
# Author: Brian Cherinka
# Created: Monday, 19th October 2020 5:49:35 pm
# License: BSD 3-clause "New" or "Revised" License
# Copyright (c) 2020 Brian Cherinka
# Last Modified: Monday, 19th October 2020 5:49:35 pm
# Modified By:... | nilq/baby-python | python |
from flask_bcrypt import generate_password_hash, check_password_hash
from sqlalchemy import Column, ForeignKey, Integer, String, Time, UniqueConstraint, text, Float, Index, Boolean, \
DateTime, CHAR
from sqlalchemy.dialects.postgresql import BIT
from sqlalchemy.ext.declarative import declarative_base
from sqlalchem... | nilq/baby-python | python |
"""Typical Queueing Theory Processes"""
from math import erf, exp, log, pi, sqrt
from nc_arrivals.arrival_distribution import ArrivalDistribution
from utils.exceptions import ParameterOutOfBounds
class DM1(ArrivalDistribution):
"""Corresponds to D/M/1 queue."""
def __init__(self, lamb: float, n=1) -> None:
... | nilq/baby-python | python |
from .swear_handler import swear
from .error_handler import VKErrorHandler, DefaultErrorHandler
| nilq/baby-python | python |
def prime2(a):
if a == 2: return True
if a < 2 or a % 2 == 0: return False
return not any(a % x == 0 for x in range(3, int(a**0.5) + 1, 2))
| nilq/baby-python | python |
# -*- coding: utf-8 -*-
from datetime import datetime
import threading
import time
from logger import logger
LOCK_POOL_WORKERS = threading.RLock()
POOL_WORKERS = {}
def _register_new_worker(worker_id, host, port, datetime_now, ttl=600):
""" Нельзя использовать без блокировки LOCK_POOL_WORKERS """
worker = {... | nilq/baby-python | python |
import re
import sys
fileName = sys.argv[1]
with open('./'+fileName+'.g', 'r') as rf:
with open('./'+fileName+'-format.g', 'w') as wf:
line = rf.readline()
while line:
infos = re.split(r'[\s]', line)
if infos[0] == 'v':
wf.write('v {} {}\n'.format(int(infos[... | nilq/baby-python | python |
import numpy as np
import scipy.sparse as sp
## sc-pml and the nonuniform grid are both examples of diagonal scaling operators...we can symmetrize them both
def create_symmetrizer(Sxf, Syf, Szf, Sxb, Syb, Szb):
'''
input Sxf, Syf, etc. are the 3D arrays generated by create_sc_pml in pml.py
#usage ... | nilq/baby-python | python |
# -*- coding:UTF-8 -*-
# Author:Tiny Snow
# Date: Wed, 24 Feb 2021, 00:50
# Project Euler # 055 Lychrel numbers
#=================================================Solution
lychrel_numbers = 0
for n in range(1, 10000):
flag = True
str_n = str(n)
reverse_n = ''.join(reversed(str_n))
for _ in range(50):
... | nilq/baby-python | python |
"""Apps for cms"""
from django.apps import AppConfig
class CMSConfig(AppConfig):
"""AppConfig for cms"""
name = "cms"
def ready(self):
"""Application is ready"""
import cms.signals # pylint:disable=unused-import, unused-variable
| nilq/baby-python | python |
import abc
import logging
from typing import Optional
from ..defaults import Defaults, Key
from ..errors import MenuConfigError
from ..helpers import Utils
logger = logging.getLogger(__name__)
class AbstractMenu(abc.ABC):
def __init__(self, **config):
self._config = config
self.validate__conf... | nilq/baby-python | python |
import os
import sys
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
probes = (
('pEN1', 100423573, 100433412, 'Linx'),
('pEN2', 100622909, 100632521, 'Xite'),
('pLG1', 100456274, 100465704, 'Linx'),
('pLG10', 100641750, 100646253, 'Dxpas34'),
('pLG11', 10... | nilq/baby-python | python |
features_dict = {
"Name":{
"Description":"String",
"Pre_Action":'''
''',
"Post_Action":'''
''',
"Equip":'''
''',
"Unequip":'''
'''
},
"Dual Wielding":{
"Description":"You can use this weapon in your Off Hand (if availab... | nilq/baby-python | python |
import os
import subprocess
import pytest
from app.synspec import wrapper
def test_synspecwrapper_remove_spectrum(mocker):
syn = wrapper.SynspecWrapper(teff=20000, logg=4, wstart=4400, wend=4600)
mocker.patch("os.remove")
syn._remove_spectrum()
os.remove.assert_called_once()
def test_synspecwra... | nilq/baby-python | python |
# curl -i -X GET 'http://192.168.0.146:8000/v2/projects'
import requests
SERVER_IP = '192.168.0.146'
SERVER_PORT = '8000'
r = requests.get('http://'+SERVER_IP+':'+SERVER_PORT+'/v2/projects')
#print(r.status_code)
#print(r.headers['content-type'])
#print(r.encoding)
#print(r.text)
#print(type(r.json()))
ALL_PROJECT... | nilq/baby-python | python |
import cx_Oracle
import log
import define_data_type as DTF
class Cache:
def __init__(self):
self._results = {}
def execute(self, conn, table, param, value):
sql_request = f"SELECT * FROM {table} WHERE {param}='{value}'"
try:
return self._results[sql_request]
except... | nilq/baby-python | python |
import requests
no = input("enter your no")
r = requests.get('https://get.geojs.io/')
ip_request = requests.get('https://get.geojs.io/v1/ip.json')
ipadd = ip_request.json()['ip']
url = 'https://get.geojs.io/v1/ip/geo/' + ipadd + '.json'
geo_request = requests.get(url)
geo_data = geo_request.json()
msg = f"latitude: {ge... | nilq/baby-python | python |
# encoding: utf-8
from .usstock_interface import * | nilq/baby-python | python |
from SimPEG import Survey, Utils, Problem, np, sp, mkvc
from simpegMT.Utils import rec2ndarr
import simpegMT
from scipy.constants import mu_0
import sys
from numpy.lib import recfunctions as recFunc
############
### Data ###
############
class DataMT(Survey.Data):
'''
Data class for MTdata
:param SimPEG ... | nilq/baby-python | python |
import itertools
from aoc_cqkh42 import BaseSolution
class Solution(BaseSolution):
def part_a(self):
return self.data.count('(') - self.data.count(')')
def part_b(self):
instructions = (1 if item == '(' else -1 for item in self.data)
return list(itertools.accumulate(instructions)).in... | nilq/baby-python | python |
from .core import core
from .task_parser import TaskParser, UnexpectedDayName
from .wrapper import GoogleTasksWrapper, NoSuchTaskList | nilq/baby-python | python |
class PulldownButtonData(ButtonData):
"""
This class contains information necessary to construct a pulldown button in the Ribbon.
PulldownButtonData(name: str,text: str)
"""
@staticmethod
def __new__(self,name,text):
""" __new__(cls: type,name: str,text: str) """
pass
| nilq/baby-python | python |
import numpy as np
import os
from pyspark.sql import SparkSession
import cluster_pack
from cluster_pack.spark import spark_config_builder
if __name__ == "__main__":
package_path, _ = cluster_pack.upload_env()
ssb = SparkSession.builder \
.appName("spark_app") \
.master("yarn") \... | nilq/baby-python | python |
from django.db import models
from django.db import migrations
import django.db.models.deletion
import swapper
class Migration(migrations.Migration):
dependencies = [
('imagestore_cms', '0001_initial'),
]
operations = [
migrations.AlterField(
'imagestorealbumptr',
... | nilq/baby-python | python |
# pylint: disable=duplicate-code
"""
Authentication example
======================
.. Copyright:
Copyright Wirepas Ltd 2019 licensed under Apache License, Version 2.0
See file LICENSE for full license details.
"""
from utils import get_settings, setup_log
from connections import Connections... | nilq/baby-python | python |
#
# PySNMP MIB module FR-MFR-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/FR-MFR-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:15:59 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:... | nilq/baby-python | python |
import torch
import numpy as np
from utils import vocab, pos_vocab, ner_vocab, rel_vocab
class Example:
def __init__(self, input_dict):
self.id = input_dict['id']
self.passage = input_dict['d_words']
self.question = input_dict['q_words']
self.choice = input_dict['c_words']
... | nilq/baby-python | python |
import pygame
pygame.init()
SCREEN_WIDTH = 800
SCREEN_HEIGHT = int(SCREEN_WIDTH * 0.8)
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption('Shooter')
#set framerate
clock = pygame.time.Clock()
FPS = 60
#define player action variables
moving_left = False
moving_right = False
... | nilq/baby-python | python |
# -*- coding: utf8 -*-
from django.contrib.auth import get_user_model
from django.core import mail
from django.test import TestCase
from rest_framework.authtoken.models import Token
from nopassword.models import LoginCode
class TestRestViews(TestCase):
def setUp(self):
self.user = get_user_model().objec... | nilq/baby-python | python |
# see https://www.codewars.com/kata/559a28007caad2ac4e000083/solutions/python
fibonacci_cache = {}
def fib(n):
if n in fibonacci_cache:
return fibonacci_cache[n]
if n == 1: return 0
if n == 2: return 1
else:
value = fib(n-1) + fib(n-2)
fibonacci_cache[n] = value
return value
def perimeter(n... | nilq/baby-python | python |
import warnings
import numpy as np
import scipy.sparse as sp
class Graph:
"""
A container to represent a graph. The data associated with the Graph is
stored in its attributes:
- `x`, for the node features;
- `a`, for the adjacency matrix;
- `e`, for the edge attributes;
-... | nilq/baby-python | python |
from __future__ import annotations
from typing import List, Tuple
def check_conflicts(path1: Path, path2: Path) -> bool:
"""
Checks if two paths have either an edge conflict or a vertex conflict
:param path1: The first path
:param path2: The second path
:return: True if paths are confl... | nilq/baby-python | python |
from collections import defaultdict
from itertools import cycle, count
# Python 3 got rid of itertools.izip because zip now does it (but not in Python 2)
try: from itertools import izip
except: izip = zip
def spiral_directions():
dirs = cycle([(1,0), (0,-1), (-1,0), (0,1)]) # R, U, L, D, ...
dists = (n >> 1 f... | nilq/baby-python | python |
import requests
from .progressbar import SimpleProgressBar
def download(url, dst):
r = requests.get(
url,
stream=True,
)
bar = SimpleProgressBar(int(r.headers['Content-Length']))
with open(dst, 'wb') as f:
CHUNK_SIZE = 256 * 1024
for chunk in r.iter_content(chunk_size=C... | nilq/baby-python | python |
from barcode import EAN13
from barcode.writer import ImageWriter
from io import BytesIO
# print to a file-like object:
rv = BytesIO()
EAN13(str(100000902922), writer=ImageWriter()).write(rv)
# or sure, to an actual file:
with open('somefile.jpeg', 'wb') as f:
EAN13('100000011111', writer=ImageWriter()).write(f) | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# @Author: YangZhou
# @Date: 2017-06-03 20:02:55
# @Last Modified by: YangZhou
# @Last Modified time: 2017-06-03 20:07:13
from ase import io
atoms=io.read('POSCAR')
filter=atoms.positions[:,0]<atoms.positions[:,0].max()-5.17286
del atoms[filter]
atoms.cell[0,0]=5.17286
atoms.cente... | nilq/baby-python | python |
# Copyright 2019 The ROBEL Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wr... | nilq/baby-python | python |
a = {
'x' : 1,
'y' : 2,
'z' : 3
}
b = {
'w' : 10,
'x' : 11,
'y' : 2
}
#find keys in common
print( a.keys() & b.keys() )
#find keys in a not in b, no + operator
print(a.keys() - b.keys() )
#find (key,value) pairs in common !!not values
print(a.items() & b.items() )
c = {key:a[key] for key in a.keys() & b.keys() }
pr... | nilq/baby-python | python |
"""
Простое приложение, которое показывает импорт функций.
"""
from library.services import delay_function
if __name__ == "__main__":
delay_function(10)
| nilq/baby-python | python |
tup1 = ("aws",'azur',1988,2050,50,57)
tup2 = (1,2,3,4,5,6,7)
print(tuple(enumerate(tup1)),type(tup1),id(tup1),len(tup1))
print(tuple(enumerate(tup2)),type(tup2),id(tup2),len(tup2))
print(tup1[3:])
print(tup1[-3])
print(tup2[:4])
print(tup2[0:])
#del(tup1[0]) #tuple object doesnot support item deletion
tup = (1,2,[1... | nilq/baby-python | python |
from .database import *
from acq4.util import DataManager
from acq4.pyqtgraph.widgets.ProgressDialog import ProgressDialog
import acq4.util.debug as debug
from acq4.Manager import logExc, logMsg
class AnalysisDatabase(SqliteDatabase):
"""Defines the structure for DBs used for analysis. Essential features are:
... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
Created Aug 11, 2020
author: Mark Panas
"""
def OpenAirBeam2(filename):
import numpy as np
import pandas as pd
with open(filename) as fp:
out = fp.readlines()
#print(out[0].rstrip().split(','))
if out[0].rstrip().split(',')[0] != "":
#pr... | nilq/baby-python | python |
import requests
import os
import json
import logging
from logging.handlers import TimedRotatingFileHandler
import time
from kafka import KafkaProducer
import psycopg2
from datetime import datetime, timezone
import datetime
import pytz
from psycopg2.extras import Json
from psycopg2.sql import SQL, Literal, Identifier
f... | nilq/baby-python | python |
"""
Copyright (C) 2004-2015 Pivotal Software, Inc. All rights reserved.
This program and the accompanying materials are made available under
the terms of the 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
... | nilq/baby-python | python |
from PIL import Image
import math
import sys
import eleksdrawpy as xy
def create_paths(im):
f = (255 * 255 * 3) ** 0.5
paths = []
w, h = im.size
for m in [-2, -1, 0, 1, 2]:
for radius in range(0, w, 8):
path = []
for a in range(1800):
a = math.radians(a /... | nilq/baby-python | python |
"""
Satellite6Version - file ``/usr/share/foreman/lib/satellite/version.rb``
========================================================================
Module for parsing the content of file ``version.rb`` or ``satellite_version``,
which is a simple file in foreman-debug or sosreport archives of Satellite 6.x.
Typical ... | nilq/baby-python | python |
def main():
# input
N = int(input())
# compute
l_0, l_1 = 2, 1
if N == 1:
print(l_1)
else:
for _ in range(N-1):
l_i = l_0 + l_1
l_0, l_1 = l_1, l_i
print(l_i)
# output
if __name__ == '__main__':
main()
| nilq/baby-python | python |
"""
Qxf2 Services: Utility script to compare images
* Compare two images(actual and expected) smartly and generate a resultant image
* Get the sum of colors in an image
"""
from PIL import Image, ImageChops
import math, os
def rmsdiff(im1,im2):
"Calculate the root-mean-square difference between two images"
h ... | nilq/baby-python | python |
from requests import get
def myip():
return get('http://checkip.amazonaws.com/').text.strip()
| nilq/baby-python | python |
#Tres personas deciden invertir su dinero para fundar una empresa. Cada una de ellas invierte una cantidad distinta.
#Obtener el porcentaje que cada quien invierte con respecto a la cantidad total invertida.
primera_inversion = float(input("Ingrese la primera inversion \n"))
segunda_inversion = float(input("Ingrese l... | nilq/baby-python | python |
import os
with open('locationsCOMSAT.csv') as f:
header = f.readline()
g = [l.rstrip().split(',') for l in f.readlines()]
## all information in string, not numerics
cmda = 'python createjobscriptsnora10a.py'
cmd = 'python createjobscriptsnora10.py'
ncdir = '/work/users/kojito/nora10/nc'
start = '2011'
end... | nilq/baby-python | python |
import speech_recognition as sr
import pyttsx3
from datetime import datetime
import webbrowser
from subprocess import Popen, CREATE_NEW_CONSOLE
import random
import sys
speech = 0
commands = {}
scripts = {}
responses = {}
active = True
def audio_to_text(recognizer, mic):
if not isinstance(recognizer, sr.Recogniz... | nilq/baby-python | python |
'''1. 编写 Demo 类,使得下边代码可以正常执行:
>>> demo = Demo()
>>> demo.x
'FishC'
>>> demo.x = "X-man"
>>> demo.x
'X-man'
'''
class Demo:
def __getattr__(self , name):
return 'FishC'
| nilq/baby-python | python |
import os
import torch
import torch.nn as nn
import unittest
from fusion.architecture.projection_head import LatentHead
os.environ['KMP_DUPLICATE_LIB_OK']='True'
class TestLatentHead(unittest.TestCase):
def test_forward(self):
dim_in = 32
dim_l = 64
latent_head = LatentHead(dim_in, dim_... | nilq/baby-python | python |
import balanced
balanced.configure('ak-test-2eKlj1ZDfAcZSARMf3NMhBHywDej0avSY')
debit = balanced.Debit.fetch('/debits/WD5SwXr9jcCfCmmjTH5MCMFD')
dispute = debit.dispute | nilq/baby-python | python |
import mcprot
import asyncio
import logging
logging.basicConfig(level = logging.INFO)
stream = mcprot.PacketStream('localhost', 25565)
loop = asyncio.get_event_loop()
result = loop.run_until_complete(stream.get_status())
print(result)
| nilq/baby-python | python |
from typing import Any, Dict, List
from electionguard.types import BALLOT_ID
from .base import BaseResponse, BaseRequest, Base
from .election import CiphertextElectionContext
from .tally import CiphertextTally
__all__ = [
"CiphertextTallyDecryptionShare",
"DecryptTallyShareRequest",
"DecryptionShareReque... | nilq/baby-python | python |
import pandas as pd
import streamlit as st
import numpy as np
df = pd.read_csv('data/raw/ames_housing_data.csv')
max_price = df['SalePrice'].max()+50
min_price = df['SalePrice'].min()
bins = np.linspace(min_price, max_price, 60)
inds = np.digitize(df['SalePrice'], bins)
price_groups = [bins[inds[i]] for i in ... | nilq/baby-python | python |
import os
from typing import Dict
from allennlp.interpret.attackers import Attacker, Hotflip
from allennlp_demo.common import config, http
class MaskedLmModelEndpoint(http.ModelEndpoint):
def __init__(self):
c = config.Model.from_file(os.path.join(os.path.dirname(__file__), "model.json"))
super(... | nilq/baby-python | python |
import os
import unittest
import warnings
from flask import json
import webapp
from config import TestingConfig, Config
class HomeViewTest(unittest.TestCase):
#@unittest.skip
def setUp(self):
self.app = webapp.app.test_client()
self.app.testing = True
#@unittest.skip
def test_home_pa... | nilq/baby-python | python |
import pydub
import pytube
output_path = "C:/Users/epics/Music"
segments = []
playlist = pytube.Playlist("https://youtube.com/playlist?list=PL3PHwew8KnCl2ImlXd9TQ6UnYveqK_5MC")
for i in range(0,16):
segments.append(pydub.AudioSegment.from_file(f"{output_path}/.ytmp3_cache/{i}.mp3",format="mp4"))
sum(segments).ex... | nilq/baby-python | python |
import mapping
import struct
import types
#import logging
#log = logging.getLogger('util.primitives.structures')
class enum(list):
'''
>>> suits = enum(*'spades hearts diamonds clubs'.split())
>>> print suits.clubs
3
>>> print suits['hearts']
1
'''
def __init__(self, *... | nilq/baby-python | python |
from __future__ import absolute_import
from __future__ import print_function
import os
import yaml
import argparse
import sys
import numpy as np
from flask import Flask, request, jsonify
import json
import os
import io
from werkzeug.utils import secure_filename
import subprocess
AUDIO_STORAGE = os.path.join("/content"... | nilq/baby-python | python |
import tensorflow as tf
import numpy as np
x_data = np.random.rand(100).astype(np.float32)
y_data = 0.1*x_data + 0.3
W = tf.Variable(tf.random_uniform([1],-1.0,1.0))#产生均匀分布的随机张量
b = tf.Variable(tf.zeros([1]))
y = W*x_data + b
loss = tf.reduce_mean(tf.square(y-y_data))
optimizer = tf.train.GradientDescen... | nilq/baby-python | python |
output = input['fields']
| nilq/baby-python | python |
from functools import reduce
from typing import List
import numpy as np
__all__ = [
"ABCDElement", "Media", "FreeSpace", "ThinLens",
"FlatInterface", "CurvedInterface", "ABCDCompositeElement",
"ThickLens", "PlanoConvexLens"]
class ABCDElement:
@property
def length(self) -> float:
ret... | nilq/baby-python | python |
class StatusHost:
hostname: str
device_id: str
uptime: int
power_time: int
time: str
timestamp: int
fwversion: str
devmodel: str
netrole: str
loadavg: float
totalram: int
freeram: int
temperature: int
cpuload: float
height: int
def __init__(self, data):
... | nilq/baby-python | python |
from __future__ import division
import numpy as np
import os
import pandas as pd
import itertools
import matplotlib.pyplot as plt
## required in 3D plot
from mpl_toolkits.mplot3d import Axes3D
import xml.etree.ElementTree as ET
import time
import pylab as pl
from IPython import display
import sys
import time
import c... | nilq/baby-python | python |
import flask
import requests
import sqlalchemy
from sqlalchemy import orm
_HAS_PSYCOPG2 = False
try:
import psycopg2
_HAS_PSYCOPG2 = True
except ImportError:
pass
from .base import ExceptionConverter
class ArgumentErrorConverter(ExceptionConverter):
@classmethod
def convert(cls, exc):
i... | nilq/baby-python | python |
from troposphere import Template
from troposphere.iot import (
Certificate,
Policy,
PolicyPrincipalAttachment,
Thing,
ThingPrincipalAttachment,
TopicRule,
TopicRulePayload,
Action,
LambdaAction,
)
t = Template()
certificate = Certificate(
'MyCertificate',
CertificateSignin... | nilq/baby-python | python |
import sys, math
code = {
"TTT": "F","TTC": "F", "TTA":"L", "TTG":"L",
"CTT":"L", "CTC":"L", "CTA":"L", "CTG":"L",
"ATT":"I", "ATC":"I", "ATA":"I", "ATG":"M",
"GTT":"V", "GTC":"V", "GTA":"V", "GTG":"V",
"TCT":"S", "TCC":"S", "TCA":"S", "TCG": "S",
"CCT":"P", "CCC":"P", "CCA":"P", "CCG":"P",
"ACT":"T", "ACC":"T", ... | nilq/baby-python | python |
"""Class to infer with the model."""
from pathlib import Path
import torch
from PIL import Image
from torch.cuda.amp import autocast
from torch.nn import DataParallel
from torch.utils.data import DataLoader
from tqdm import tqdm
from .config import Config
from .data import INPUT_CHANNELS, OUTPUT_CHANNELS, TestDataset... | nilq/baby-python | python |
from django.shortcuts import redirect
from django.views.generic import UpdateView
from ...models.survey import Survey, Question, Choice
from ...models.answer import SurveyAnswer
from ...forms.surveys import AnswerSurveyQuestionsForm
from ..helper import get_ip, get_next_question
from ..error import permission_user_u... | nilq/baby-python | python |
import unittest
from pathlib import Path
import colab_transfer
class TestTransferMethods(unittest.TestCase):
def get_dummy_data_root(self):
data_root_folder_name = 'dummy_data_for_unit_test/'
return data_root_folder_name
def create_dummy_data(self):
input_data_folder_name = self.ge... | nilq/baby-python | python |
"""Differential Evolution Optimization
:Author: Robert Kern
Copyright 2005 by Robert Kern.
"""
import numpy as np
# Licence:
# Copyright (c) 2001, 2002 Enthought, Inc.
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the fo... | nilq/baby-python | python |
from PyQt5.QtWidgets import QApplication, QWidget, QComboBox, QGroupBox, \
QVBoxLayout, QRadioButton, QLabel, QSlider, QPushButton, QMessageBox
from Windows.Templates.SimplePerfOptionsTemplate import Ui_Dialog
from Windows.GeneralPerf import GeneralPerf
import re
import numpy as np
from util_tools.PopUp... | nilq/baby-python | python |
# Autogenerated from KST: please remove this line if doing any edits by hand!
import unittest
from type_ternary import _schema
class TestTypeTernary(unittest.TestCase):
def test_type_ternary(self):
r = _schema.parse_file('src/term_strz.bin')
self.assertEqual(r.dif.value, 101)
| nilq/baby-python | python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from builtins import range
import sys
import os
import ntpath # equivalent to os.path when running on windows
def run(id, gtotool, config, debug):
try:
gtomain = gtotool.gtomain
# read config
module_name = ... | nilq/baby-python | python |
# encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import absolute_import
import abc
class TargetNotFoundError(Exception):
@abc.abstractproperty
def _target_type(self):
return None
def __init__(self, *args, **kwargs):
self._target ... | nilq/baby-python | python |
# Copyright 2019 The TensorFlow Authors. 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 applica... | nilq/baby-python | python |
from django.db import models
import uuid
from django.contrib.auth.models import User
# Create your models here.
TIPOS_USUARIOS = (
('admin', 'Admin'),
('estudiante', 'Estudiante'),
('docente', 'Docente'),
('administrativo', 'Personal administrativo')
)
TIPOS_UNIVERSIDADES = (
('unfv', 'Universida... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
import abjad
class ScoreTemplate(object):
def __call__(self):
# Violin
violin_staff = abjad.Staff(
[abjad.Voice(name='Violin Voice')],
name='Violin Staff',
lilypond_type='ViolinStaff',
)
violin_tag = abjad.LilyPondLi... | nilq/baby-python | python |
def setup():
size(500,500)
smooth()
background(50)
strokeWeight(2)
stroke(250)
counter= 0
mcolor=0
cx = 250
cy = 250
R = 200
def draw():
global cx,cy, R, counter, mcolor
y1 = cos(counter)*R + cy
x1 = sin(counter)*R + cx
mcolor=mcolor+1
stroke(mcolor)
... | nilq/baby-python | python |
#!/usr/bin/env python
"""
synopsis:
Paranoid Pirate queue
Original author: Daniel Lundin <dln(at)eintr(dot)org>
Modified for async/ioloop: Dave Kuhlman <dkuhlman(at)davekuhlman(dot)org>
usage:
python ppqueue.py
notes:
To test this, use the lazy pirate client. To run this, start any number of
p... | nilq/baby-python | python |
""" Core abstract rendering abstractions. This includes the main drivers of
execution and the base clases for shared data representations.
"""
from __future__ import print_function, division, absolute_import
from six.moves import range
import numpy as np
import abstract_rendering.geometry as geometry
import abstract_r... | nilq/baby-python | python |
from .core.protocol import Range
from .core.protocol import Request
from .core.registry import get_position
from .core.registry import LspTextCommand
from .core.sessions import method_to_capability
from .core.typing import Any, Dict, Optional, List, Tuple
from .core.views import range_to_region
from .core.views import ... | nilq/baby-python | python |
from haystack.preprocessor.cleaning import clean_wiki_text
from haystack.preprocessor.utils import convert_files_to_dicts, fetch_archive_from_http
from haystack.reader.farm import FARMReader
from haystack.reader.transformers import TransformersReader
from haystack.utils import print_answers
from haystack.document_store... | nilq/baby-python | python |
from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
class Profile(models.Model):
user = models.OneToOneField(User, on_delete = models.CASCADE, related_name = 'auth_user')
wms_id = models.IntegerField(default = 0)
is_grp = models.BooleanField(defaul... | nilq/baby-python | python |
from setuptools import setup, find_packages
from os import path
import io
import versioneer
here = path.abspath(path.dirname(__file__))
with io.open(path.join(here, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='knitty',
version=versioneer.get_version(),
cmdclass=vers... | nilq/baby-python | python |
#!/usr/bin/env python3
# Copyright (c) 2020-2021 Dimitrios-Georgios Akestoridis
#
# 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 righ... | nilq/baby-python | python |
"""Define setup for installing the repository as a pip package."""
from setuptools import find_packages, setup
setup(
name="ikshana",
packages=find_packages(),
version="0.1.1",
description="Python package for computer vision",
author="ikshana.ai",
license="MIT",
url="https://github.com/iksh... | nilq/baby-python | python |
from django.http import HttpResponseBadRequest
from django.http import HttpResponseBadRequest
from django.core.exceptions import ValidationError
from django.core.exceptions import SuspiciousOperation
import json
import logging
logger = logging.getLogger(__name__)
class validation:
def __init__(self, data):
... | nilq/baby-python | python |
import asyncio
import pydash
import math
from rocon_client_sdk_py.virtual_core.path_planner import PathPlanner
class Actuator(): #metaclass=SingletonMetaClass):
def __init__(self, context):
pass
async def change_position(self, context, destination_point, destination_map=None):
worker = context... | nilq/baby-python | python |
import logging
from django.core.management.base import BaseCommand
from parliament.models import PoliticalParty
from openkamer.parliament import create_parties
logger = logging.getLogger(__name__)
class Command(BaseCommand):
def handle(self, *args, **options):
parties = create_parties(update_votes=Fal... | nilq/baby-python | python |
import cython
import threading
class PWM:
_port: object
_pin: object
_duty_cycle: cython.longdouble
cycle_time: cython.longdouble
_pwm_thread: object
def __init__(self, gpio_port: object, pwm_pin: object, duty_cycle: cython.longdouble = 0, cycle_time: cython.longdouble = 0.02):
se... | nilq/baby-python | python |
from autolens.pipeline.phase.imaging.analysis import Analysis
from autolens.pipeline.phase.imaging.result import Result
from .phase import PhaseImaging
| nilq/baby-python | python |
from piccolo.apps.migrations.auto import MigrationManager
from piccolo.columns.column_types import Date
from piccolo.columns.column_types import Varchar
from piccolo.columns.defaults.date import DateNow
from piccolo.columns.indexes import IndexMethod
ID = "2021-09-26T17:01:33:631238"
VERSION = "0.50.0"
DESCRIPTION = ... | nilq/baby-python | python |
from .SRW_RWF_ISRW import SRW_RWF_ISRW
from .Snowball import Snowball, Queue
from .ForestFire import ForestFire
from .MHRW import MHRW
from .TIES import TIES
| nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.