content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
# Copyright 2020 Louis Richard
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | nilq/baby-python | python |
# import dependencies
import os
import json
import struct
import time
import requests
import numpy as np
import binascii
import datetime
import datetime as dt
from datetime import date
from flask import Flask, Response, request, redirect, url_for, escape, jsonify, make_response
from flask_mongoengine import MongoEngine... | 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
# d... | nilq/baby-python | python |
# vim:set et ts=4 sw=4:
import logging
class FileLogger(object):
"""
This becomes a File Like object that can be be written to. But
instead of actually writing to a file it writes to a logger object
Example:
#Redirect stdout and stderr to a logging object
import sys
from file_logger import ... | nilq/baby-python | python |
# Copyright 2014 - Rackspace
#
# 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, ... | nilq/baby-python | python |
import sys
from pathlib import Path
sys.path.append(str(Path(__file__).parent.parent))
from tksugar import Generator
count = 1
def button(button, tag):
global count
child = Generator(r"samples\yml\multiwindow_child.yml").get_manager()
ordinal = lambda n: "%d%s" % (n,"tsnrhtdd"[(n // 10 % 10 != 1) * (n % 10 < 4... | nilq/baby-python | python |
import numpy
from scipy.ndimage import shift
from skimage.exposure import rescale_intensity
from aydin.features.groups.translations import TranslationFeatures
from aydin.io.datasets import camera
def n(image):
return rescale_intensity(
image.astype(numpy.float32), in_range='image', out_range=(0, 1)
)... | nilq/baby-python | python |
numberlist = [1, 2, 3, 4, 5, 6, 7, 8, 9]
for number in numberlist:
if number == 1:
print("1st")
elif number == 2:
print("2nd")
elif number == 3:
print("3rd")
else:
print(str(number) + "th") | nilq/baby-python | python |
# -*- coding: utf-8 -*-
import inspect
import io
import os
import numpy as np
import pytest
import pytoshop
from pytoshop import enums
from pytoshop import layers
DATA_PATH = os.path.join(os.path.dirname(__file__), 'psd_files')
def test_futz_with_channel_image_data():
filename = os.path.join(DATA_PATH, 'g... | nilq/baby-python | python |
from abc import ABC, abstractmethod
from typing import List
from evobench import Benchmark
from evobench.model import Solution
class HillClimber(ABC):
def __init__(self, benchmark: Benchmark):
self.benchmark = benchmark
@abstractmethod
def __call__(self, solution: Solution, **kwargs) -> Solutio... | nilq/baby-python | python |
# coding=utf-8
from urllib2 import URLError, HTTPError
import urllib2
import json
import logging
from api_exception import APIError
from common.config import configs
from common.util import Util
# from appName.route.neutron_api import list_ports_by_nobind
# from appName.route.neutron_api import list_network
# from appN... | nilq/baby-python | python |
import os
import torch
import torchvision.transforms as transforms
import torchvision.datasets as datasets
def load_dataset(data_root, dataset_name, trans):
if dataset_name == 'mnist':
return datasets.MNIST(
root=data_root,
train=True,
transform=trans,
downl... | nilq/baby-python | python |
from typing import Union, Optional, List, Dict
from torch_geometric.typing import OptPairTensor, Adj, OptTensor, Size, PairTensor
import torch
from torch import Tensor
from torch_geometric.nn import GINEConv as BaseGINEConv, GINConv as BaseGINConv, LEConv as BaseLEConv
from torch.nn import Sequential, Linear, ReLU
fro... | nilq/baby-python | python |
import argparse, logging, math, filepattern, time, queue
from bfio import BioReader, BioWriter
import pathlib
from preadator import ProcessManager
logging.basicConfig(format='%(asctime)s - %(name)-8s - %(levelname)-8s - %(message)s',
datefmt='%d-%b-%y %H:%M:%S')
# length/width of the chunk each _m... | nilq/baby-python | python |
#!/usr/bin/env python
import os, sys
import string
import argparse
import re
parser = argparse.ArgumentParser(description="""
creates mut file from snpEFF vcf
""", formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument('--vcf', metavar = '<file.vcf>', required=True,
help="""VCF file. <REQUIRED>\n\n""")
... | nilq/baby-python | python |
"""
Django settings for Journal project.
Generated by 'django-admin startproject' using Django 3.0.3.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""
... | nilq/baby-python | python |
#!/usr/bin/env python
import os, sys, subprocess, argparse, re, logging, errno
import mymm
parser = argparse.ArgumentParser(description = "This program takes a .pqr file (MEAD format only for now, meaning no chain field!) and writes a CRG and PDB file from it.", prog = sys.argv[0])
parser.add_argument('--pqr', metav... | nilq/baby-python | python |
"""
This code was generated by Codezu.
Changes to this file may cause incorrect behavior and will be lost if
the code is regenerated.
"""
from mozurestsdk.mozuclient import default as default_client
from mozurestsdk.mozuurl import MozuUrl;
from mozurestsdk.urllocation import UrlLocation
from mozure... | nilq/baby-python | python |
import os
import os.path as osp
import pickle
import sys
import time
project_root = os.path.abspath ( os.path.join ( os.path.dirname ( __file__ ), '..', '..' ) )
if __name__ == '__main__':
if project_root not in sys.path:
sys.path.append ( project_root )
import coloredlogs, logging
logger = logging.getLog... | nilq/baby-python | python |
# ----------------------------------------------------------------------
# AdministrativeDomain REST API
# ----------------------------------------------------------------------
# Copyright (C) 2007-2021 The NOC Project
# See LICENSE for details
# ----------------------------------------------------------------------
... | nilq/baby-python | python |
import torchvision.transforms as transforms
import numpy as np
import h5py, os, random, math, torch
import os
import torch.utils.data as data
import cv2
from PIL import Image
import csv
def get_csv_content(path): #
if not path.endswith('.csv'):
raise ValueError(f"Wrong path, Got {path}")
... | nilq/baby-python | python |
# import the libraries
import googlemaps
import json
from GoogleMapsAPIKey import get_my_key
# Define the API Key.
API_KEY = get_my_key()
# Define the Client
gmaps = googlemaps.Client(key = API_KEY)
# Define Parameters
# Method One Place ID: 'place_id:ChIJ7-bxRDmr3oARawtVV_lGLtw'
... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# *****************************************************************************
# NICOS, the Networked Instrument Control System of the MLZ
# Copyright (c) 2009-2021 by the NICOS contributors (see AUTHORS)
#
# This program is free software; you can redistribute it and/or modify it under
# the t... | nilq/baby-python | python |
from internos.taskapp.celery import app
import json
import pytz
import httplib
import datetime
from django.utils import timezone
from time import mktime
from internos.backends.utils import get_data
@app.task
def sync_partner_data():
from internos.etools.models import PartnerOrganization
partners = get_data('... | nilq/baby-python | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import DomoticzAPI as dom
from test_all import (WIDTH_LABEL, FILE, TEST, H2, CRLF, SUFFIX)
def main():
print(FILE)
print("{:{}<{}}: {}".format("Test script", SUFFIX, WIDTH_LABEL, __file__))
print(FILE)
server = dom.Server()
print(CRLF)
print(TEST... | nilq/baby-python | python |
from unittest import TestCase
from algotrader.app.backtest_runner import BacktestRunner
from algotrader.trading.config import Config, load_from_yaml
from algotrader.trading.context import ApplicationContext
from tests import test_override
class StrategyPersistenceTest(TestCase):
start_date = 19930101
intrim_... | nilq/baby-python | python |
def ajuda(com):
help(com)
def titulo(msg, cor=0):
tam = len(msg) + 4
print('-' * tam)
print(f' {msg}')
print('-' * tam)
comando = ''
while True:
titulo('SISTEMA DE AJUDA PyHELP')
comando = str(input('Funca ou Biblioteca > '))
if comando.upper() == 'FIM':
break
else:
... | nilq/baby-python | python |
from src.core.models import TimestampedModel
from src.users.managers import UserManager
from src.users.validators import (
validate_unique_username,
validate_username_valid_characters_only,
)
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin
from django.db import models
from django.util... | nilq/baby-python | python |
from django import forms
from django.core.exceptions import ValidationError
from grandchallenge.publications.models import (
Publication,
identifier_validator,
)
from grandchallenge.publications.utils import get_identifier_csl
class PublicationForm(forms.ModelForm):
def clean_identifier(self):
id... | nilq/baby-python | python |
class MorseCode():
def __init__(self):
self.__dic_plain = { 'A':'.-', 'B':'-...',
'C':'-.-.', 'D':'-..', 'E':'.',
'F':'..-.', 'G':'--.', 'H':'....',
'I':'..', 'J':'.---', 'K':'-.-',
'L':'.-..', 'M':'--', 'N':'-.',
'O':'---', 'P':'.--.', 'Q':'-... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
############################################################################
#
# Copyright © 2013, 2014 OnlineGroups.net and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany th... | nilq/baby-python | python |
from .emojipedia import Emojipedia, Emoji
| nilq/baby-python | python |
import re
import ssl
from retrying import retry
import urllib.request
wordlist_re = re.compile(
r'<a href="/wordlist/(\w+.shtml)" target="_top">\w+</a><BR>')
wordlist_name_re = re.compile(
r'<h1 class=body-title__title>(.+?)</h1>')
words_re = re.compile(
r'<div class=wordlist-item>([\w -\\\']+?)</div>')
... | nilq/baby-python | python |
"""This module contains the general information for AdaptorHostEthIf ManagedObject."""
from ...imcmo import ManagedObject
from ...imccoremeta import MoPropertyMeta, MoMeta
from ...imcmeta import VersionMeta
class AdaptorHostEthIfConsts:
IF_TYPE_VIRTUAL = "virtual"
MAC_AUTO = "AUTO"
UPLINK_PORT_0 = "0"
... | nilq/baby-python | python |
from PyQt5.QtGui import QImage
from PIL import Image
import numpy as np
def numpyQImage(image):
qImg = QImage()
if image.dtype == np.uint8:
if len(image.shape) == 2:
channels = 1
height, width = image.shape
bytesPerLine = channels * width
qImg ... | nilq/baby-python | python |
#Copyright (c) 2014 Samsung Electronics Co., Ltd 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
#
# Unle... | nilq/baby-python | python |
from src import Camera, Tracer, World, Stereo
| nilq/baby-python | python |
import pygame
import random
import time
import sys
pygame.init()
# definicion de colores
blanco = pygame.Color(255,255,255)
negro = pygame.Color(0,0,0)
rojo = pygame.Color(255,0,0)
rojo_o = pygame.Color(100,0,0)
gris = pygame.Color(200,200,200)
verde = pygame.Color(0,250,100)
verde_o = pygame.Color(0,150,50)
morado = ... | nilq/baby-python | python |
# 要添加一个新单元,输入 '# %%'
# 要添加一个新的标记单元,输入 '# %% [markdown]'
# %%
import numpy as np
from matplotlib import pyplot as plt
import os
from matplotlib import font_manager
import matplotlib as mpl
zhfont1 = font_manager.FontProperties(fname='SimHei.ttf')
from mpl_toolkits.axes_grid1 import make_axes_locatable
import pandas as ... | nilq/baby-python | python |
# Corrigido
print('Exercício 010')
print()
# Bloco de entrada
carteira = float(input('Informe quanto você tem na sua carteira: '))
print()
# Bloco de cálculo
dólar = carteira / 5.47
# Bloco de saída
print('Você pode comprar $ {:.2f} dólares com R$ {} reais na carteira.'.format(
dólar, carteira))
print()
| nilq/baby-python | python |
"""
Write an iterative function iterPower(base, exp) that calculates the exponential baseexp by simply using successive multiplication. For example, iterPower(base, exp) should compute baseexp by multiplying base times itself exp times. Write such a function below.
This function should take in two values - base can be... | nilq/baby-python | python |
from SuperSafety.Utils.utils import limit_phi, load_conf
from SuperSafety.Supervisor.Dynamics import run_dynamics_update
import numpy as np
from matplotlib import pyplot as plt
import numpy as np
from numba import njit
class Modes:
def __init__(self, conf) -> None:
self.time_step = conf.kernel_time_st... | nilq/baby-python | python |
import math
import re
from threading import Thread
import serial
from ...LightSkin import ForwardModel, LightSkin, EventHook
class ArduinoConnectorForwardModel(ForwardModel):
""" Connects to an Arduino running the Arduino Connector Script on the given port with the given baudrate
Parses the input in a n... | nilq/baby-python | python |
# -------------------------------------------------------------------------------
# Copyright IBM Corp. 2016
#
# 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/licens... | nilq/baby-python | python |
import numpy as np
from numpy.testing import assert_equal
from terrapin.flow_direction import aread8, convert_d8_directions
test_sets = [
# source:
# http://resources.arcgis.com/en/help/main/10.1/index.html#//009z00000051000000
# lower right corner of flow accumulation array is 2 in url but it should be 1... | nilq/baby-python | python |
# Copyright 2019-2019 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" fil... | nilq/baby-python | python |
# Copyright 2019 Adobe
# All Rights Reserved.
#
# NOTICE: Adobe permits you to use, modify, and distribute this file in
# accordance with the terms of the Adobe license agreement accompanying
# it. If you have received this file from a source other than Adobe,
# then your use, modification, or distribution of it ... | nilq/baby-python | python |
import os
import sys
from time import sleep
# Logo do programa!
print('-' * 41)
print(' Calculadora Simples Version 1.0')
print('-' * 41)
print(' Seja bem-vindo!')
print('-' * 41)
sleep(3)
os.system('clear')
# Valores para usar na Opção!
n1 = int(input('1# Digite um valor: '))
n2 = int(input('2# Digit... | nilq/baby-python | python |
from __future__ import division
import os, time, scipy.io
import tensorflow as tf
import numpy as np
from PIL import Image
tf.logging.set_verbosity(tf.logging.INFO)
# os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
from dataset import SID_dataset as SID_dataset
from network import Netowrk as Netowrk
###############
## Data
#... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import argparse
from hoppy.timing.timing import EventFits
__author__ = 'Teruaki Enoto'
__date__ = '2020 September 5'
__version__ = '0.01'
def get_parser():
"""
Creates a new argument parser.
"""
usage = """
plot event fits file (PULSE_PHASE)
"""
pa... | nilq/baby-python | python |
from django.apps import AppConfig
class MainConfig(AppConfig):
name = 'main'
SOCIALS = {
'vk': 'https://vk.com/goto_msk',
'instagram': 'https://www.instagram.com/goto_goto_goto/',
'facebook': 'https://www.facebook.com/GoToCampPage/',
'telegram': 'https://t.me/goto_channel'
}
| nilq/baby-python | python |
'''
Based on https://stackoverflow.com/questions/44164749/how-does-keras-handle-multilabel-classification
'''
import warnings
try:
from keras.models import Sequential
from keras.layers import Dense, Dropout
from keras.optimizers import SGD
def keras_fit(T, Y, **kwargs):
if Y.ndim == 1:
... | nilq/baby-python | python |
from z3 import Implies
import numpy as np
from z3 import Implies
from quavl.lib.expressions.qbit import Qbits
from quavl.lib.models.circuit import Circuit, Method
from quavl.lib.operations.gates import Rx, Rz, V, CNOT, V_dag
def repair_toffoli():
# Initialize circuit
a, b, c = Qbits(['a', 'b', 'c'])
n =... | nilq/baby-python | python |
from . import Base
from sqlalchemy import Column, String, Integer, Enum as EnumCol, Date, ForeignKey
from sqlalchemy.orm import relationship
from enum import Enum
class TaskType(Enum):
Note = "Note"
Task = "Task"
class Task(Base):
__tablename__ = "task"
id = Column(Integer, primary_key=True, autoin... | nilq/baby-python | python |
"""Core Module
==============
This module includes the abstraction of a Simulation Model and the definition of a Path.
"""
from .base_model import BaseModel, ModelState
from .path import Path
| nilq/baby-python | python |
import pulp
from graphviz import Digraph
from discord import Embed, File
from tabulate import tabulate
import math
import ada.emoji
from ada.result_message import ResultMessage
from ada.breadcrumbs import Breadcrumbs
class HelpResult:
def __str__(self):
return """
ADA is a bot for the videogame Satisfact... | nilq/baby-python | python |
import numpy
import dask.dataframe as dd
import operator
import collections
import re
import logging
#logging.basicConfig(format='%(asctime)s %(levelname)s [%(filename)s:%(lineno)d] %(message)s', level=logging.NONE)
# build successor relation and edges among concepts
def successor(concepts,c1,c2):
return c1 < c2 an... | nilq/baby-python | python |
import io, csv
from flask import (
Blueprint,
render_template,
request,
redirect,
url_for,
make_response,
session,
)
from helpers.hubspot import create_client
from helpers.session import SessionKey
from auth import auth_required
from hubspot.crm import ObjectType
from hubspot.crm.contacts im... | nilq/baby-python | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import importlib
import os
import sys
from io import StringIO
from PySide2.QtCore import Qt
from PySide2.QtGui import QKeyEvent
from PySide2.QtWidgets import QWidget, QMessageBox
from tensorflow.keras.models import Model, load_model
from MnistClassifier.Ui_MainWidget im... | nilq/baby-python | python |
# DESCQA galaxy catalog interface. This defines the GalaxyCatalog base class
# and, on import, registers all of the available catalog readers. Convenience
# functions are defined that enable automatic detection of the appropriate
# catalog type.
# Note: right now we are working with galaxy properties as floats, with
#... | nilq/baby-python | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import getopt
import sys
from _datetime import datetime
from fmc_rest_client import FMCRestClient
from fmc_rest_client.resources import *
logging.basicConfig(level=logging.INFO)
fmc_server_url = None
username = None
password = None
obj_types = []
obj_name_prefix = None... | nilq/baby-python | python |
from django.shortcuts import render
from .models import Portfolio
def portfolio(request):
portfolios = Portfolio.objects
return render(request, 'portfolio/portfolio.html', {'portfolios': portfolios})
| nilq/baby-python | python |
from ...config import LennyBotSourceConfig
from .isource import ISource
from ..github import GitHubService
import re
import requests
class GithubSource(ISource):
def __init__(self, name, config: LennyBotSourceConfig, github: GitHubService) -> None:
self._name = name
self._github = github
... | nilq/baby-python | python |
# -*- coding: utf-8; -*-
"""
Gui implementation for gui created via qt-designer.
"""
__author__ = "Christoph G. Keller"
__copyright__ = "Copyright 2017"
__credits__ = [""]
__license__ = "MIT"
__version__ = "2.0.0"
__maintainer__ = "Christoph G. Keller"
__email__ = "christoph.g.keller@gmail.com"
__status__ ... | nilq/baby-python | python |
from flask_restful import Resource, reqparse, abort
from flask import request
from lista.models.service_model import ServiceModel
from lista.schemas.service_schema import ServiceSchema
class ServiceResource(Resource):
parser = reqparse.RequestParser()
parser.add_argument('name',
type=st... | nilq/baby-python | python |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import Dataset, DataLoader
from PIL import Image, ImageDraw
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.path import Path
import seaborn as sns
import tqdm
class DetectionDataset(Dataset)... | nilq/baby-python | python |
def _repr(mat,notes,dFrame):
from shutil import get_terminal_size as gts
old = None
d0,d1 = mat.dim
feats = mat.features
ind_level = mat.index.level
col_place_holder = mat.DISPLAY_OPTIONS["col_place_holder"]
row_place_holder = mat.DISPLAY_OPTIONS["row_place_holder"]
left_seperator ... | nilq/baby-python | python |
import numpy as np
import tensorflow as tf
tensor_2d = np.array([(1, 2, 3, 4), (4, 5, 6, 7), (8, 9, 10, 11), (12, 13, 14, 15)])
print(tensor_2d)
print(tensor_2d[2][3])
print(tensor_2d[0:2, 0:2])
matrix1 = np.array([(2, 2, 2), (2, 2, 2), (2, 2, 2)], dtype='int32')
matrix2 = np.array([(1, 1, 1), (1, 1, 1), (1, 1, 1)], ... | nilq/baby-python | python |
# Generated by Django 4.0.1 on 2022-01-06 14:01
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('verzelapp', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='modulo',
name='app_label',
),
... | nilq/baby-python | python |
from . HaarClassifierFunctions import faceFinder as fd
from . HaarClassifierFunctions import haarTraining as tr
from . HaarClassifierFunctions import boundingBoxes as bd
import cv2
import os
import numpy as np
def classifierceleb(path):
test_img = cv2.imread(path)
print(test_img)
face_detected,... | nilq/baby-python | python |
"""Simple watcher that prints wikipedia changes as they occur."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import json
import pprint
import argparse
import pywikibot
import requests
import sseclient
from googleapiclient import errors as google_api_er... | nilq/baby-python | python |
#programa ainda não finalizado
n = []
for c in range(0, 5):
valor = int(input('Digite um valor: '))
if c == 0 or valor > n[-1]:
n.append(valor)
print('Valor adicionado ao final da lista.')
else:
pos = 0
while pos < len(n):
if valor <= n[pos]: #TypeError
... | nilq/baby-python | python |
from collections import defaultdict
from typing import List, Any, Set, Tuple, Iterable
import pandas as pd
def printUniqueTokens(series: pd.Series):
unique_series = series.unique()
token_count = {}
for a in unique_series:
tokens = a.split(' ')
for t in tokens:
if t not in toke... | nilq/baby-python | python |
from django.conf import settings
import django.contrib.postgres.fields
import django.contrib.postgres.fields.jsonb
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('contenttypes', '0002_remove_content_type_name'),
('auth', '0011_update_proxy_permis... | nilq/baby-python | python |
from unittest import TestCase
from src.chunker import Chunker
class TestChunker(TestCase) :
def test_chunker_yields_list_with_buffered_size(self) :
chunks = Chunker(range(5), 3)
chunk = next(chunks)
self.assertEqual(len(chunk), 3)
self.assertListEqual(chunk, [0,1,2])
... | nilq/baby-python | python |
#!/usr/bin/env python3
import os
import sys
from setuptools import setup, find_packages
VERSION = os.environ.get('GITHUB_REF', '0.0.4').replace('refs/tags/v', '')
is_wheel = 'bdist_wheel' in sys.argv
_license = ""
if os.path.exists('LICENSE'):
with open('LICENSE') as lf:
_license = lf.readline().rstrip(... | nilq/baby-python | python |
import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.nn.functional as F
from torchvision import transforms
import numpy as np
import cv2
from models.single_track import SiamRPNPP as base_model
from dataset.util import generate_anchor
class SiamRPNPP(nn.Module):
def __init__(self, tra... | nilq/baby-python | python |
import argparse
from utils import levenshtein
import pdb
import re
def clean(label):
alphabet = [a for a in '0123456789abcdefghijklmnopqrstuvwxyz* ']
label = label.replace('-', '*')
nlabel = ""
for each in label.lower():
if each in alphabet:
nlabel += each
return nlabel
parse... | nilq/baby-python | python |
"""
Create a pedestal file from an event file using the target_calib Pedestal
class
"""
from targetpipe.io.camera import Config
Config('checs')
from matplotlib.ticker import MultipleLocator, FormatStrFormatter, \
FuncFormatter, AutoMinorLocator
from traitlets import Dict, List
from ctapipe.core import Tool, Compon... | nilq/baby-python | python |
import django_filters
import htmlgenerator as hg
from django import forms
from django.utils.html import mark_safe
from django.utils.translation import gettext as _
from django_countries.widgets import LazySelect
from .button import Button
from .notification import InlineNotification
class Form(hg.FORM):
@staticm... | nilq/baby-python | python |
import sys
import pytest
sys.path.append(".")
sys.path.append("..")
sys.path.append("../..")
from Hologram.Network import Network
class TestNetwork(object):
def test_create_network(self):
network = Network()
def test_get_invalid_connection_status(self):
network = Network()
with pytes... | nilq/baby-python | python |
from django.urls import path
from rest_framework_simplejwt import views as jwt_views
from . import views
from rest_framework_simplejwt.views import TokenRefreshView, TokenObtainPairView
urlpatterns = [
path('login/', views.loginView.as_view(), name='obtain_token'),
path('nlogin/', views.adminTokenObtainPairVie... | nilq/baby-python | python |
"""The managers for the models
"""
from django.contrib.auth.models import UserManager as BaseUserManager
class UserManager(BaseUserManager):
"""The user manager
"""
def create_user(self, username, email=None, password=None, **extra_fields):
"""Create a user.
:param username: The user nam... | nilq/baby-python | python |
"""
Project: RadarBook
File: ecef_to_lla.py
Created by: Lee A. Harrison
On: 3/18/2018
Created with: PyCharm
Copyright (C) 2019 Artech House (artech@artechhouse.com)
This file is part of Introduction to Radar Using Python and MATLAB
and can not be copied and/or distributed without the express permission of Artech House... | nilq/baby-python | python |
x,y=map(int,input().split())
z=0
for j in range(x,y):
z=j
a=0
for i in range(len(str(j))):
r=j%10
a=a+r**3
j=j//10
if a==z:
print(a,end=" ")
print()
| nilq/baby-python | python |
import os
from .base import *
API_DB_URL = os.environ.get("API_DB_URL", "sqlite+aiosqlite:///db.sqlite")
| nilq/baby-python | python |
# -*- coding: utf-8 -*-
from django.conf.urls import url, patterns
from django.contrib import admin
from .views import ChatRoomTokenView, ChatRoomView
admin.autodiscover()
urlpatterns = patterns(
'',
url(r'^room/(?P<token>\w{32})$', ChatRoomView.as_view(), name='chat-room'),
url(r'^new-room/$', ChatRoomT... | nilq/baby-python | python |
# coding=utf8
# Copyright 2018 JDCLOUD.COM
#
# 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 ... | nilq/baby-python | python |
from panflute import run_filter, Header
def increase_header_level(elem, doc):
if type(elem)==Header:
if elem.level < 6:
elem.level += 1
else:
return []
def main(doc=None):
return run_filter(increase_header_level, doc=doc)
if __name__ == "__main__":
main() | nilq/baby-python | python |
# -*- coding: utf-8 -*-
import time
import json
import requests
import logging
import pika
from config import PROXY
from twython import TwythonStreamer
class sampleStreamer(TwythonStreamer):
"""
Retrieve data from the Twitter Streaming API.
The streaming API requires
`OAuth 1.0 <http://en.wikipedia.... | nilq/baby-python | python |
""" Package for cookie auth modules. """
__author__ = "William Tucker"
__date__ = "2020-02-14"
__copyright__ = "Copyright 2020 United Kingdom Research and Innovation"
__license__ = "BSD - see LICENSE file in top-level package directory"
| nilq/baby-python | python |
"""
Tests scikit-learn's KNeighbours Classifier and Regressor converters.
"""
import unittest
from distutils.version import StrictVersion
import numpy
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsRegressor, KNeighborsClassifier
from sklearn.pi... | nilq/baby-python | python |
7
8
9
10
| nilq/baby-python | python |
import sys
# mode is one of 'left', 'right', 'center'
def horizontal_align_print(s, width, mode='left', offsetChar=' ', end='\n',
os=sys.stdout):
p = _print_to_file_func(os)
if mode[0] == 'l': # left
offset = width - len(s)
p(s, end='')
for _ in range(offs... | nilq/baby-python | python |
from os.path import join, dirname
import datetime
# import pandas as pd
# from scipy.signal import savgol_filter
# from bokeh.io import curdoc
# from bokeh.layouts import row, column
# from bokeh.models import ColumnDataSource, DataRange1d, Select
# from bokeh.palettes import Blues4
# from bokeh.plotting import figur... | nilq/baby-python | python |
#!/usr/bin/env python3
import requests
import os
import json
from requests.auth import HTTPBasicAuth
import requests_unixsocket
MFMODULE_RUNTIME_HOME = os.environ['MFMODULE_RUNTIME_HOME']
ADMIN_USERNAME = "admin"
ADMIN_PASSWORD = os.environ['MFADMIN_GRAFANA_ADMIN_PASSWORD']
GRAFANA_SOCKET = "%s/tmp/grafana.sock" % MF... | nilq/baby-python | python |
import os
from dotenv import load_dotenv
load_dotenv()
AV_API_KEY = os.getenv("AV_API_KEY", "value does not exist")
AV_API_KEY_2 = os.getenv("AV_API_KEY_2", "value does not exist")
BINANCE_KEY = os.getenv("BINANCE_KEY", "Binance key not found")
BINANCE_SECRET = os.getenv("BINANCE_SECRET", "Binance secret not found") | nilq/baby-python | python |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative wo... | nilq/baby-python | python |
# -*- coding: utf8 -*-
#
# 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 |
"""
Lab jack GUI
"""
import datetime
import lab_jack_lib as lj
import PySimpleGUI as sg
def logprint(message=''):
"""
printing ='on'
print and return None
"""
form = '[{}, {}]'.format(datetime.datetime.now(), message)
print(form)
def now_datetime(type=1):
"""
typ... | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.