content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
# Copyright (C) NVIDIA CORPORATION. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... | nilq/baby-python | python |
from yahoo_finance import Currency
file= open("Currency_update.txt", 'r')
x=file.readlines()
for y in x:
L=map(str, y.split())
res=''
for z in L[:-1]:
res+=z+' '
print '%30s %s'%(res,L[-1])
first_currency=raw_input("enter first currency: ")
second_currency=raw_input("enter second curren... | nilq/baby-python | python |
#!/usr/bin/env python3
#encoding=utf-8
#-----------------------------------------------------
# Usage: python3 timer3.py
# Description: timer function with keywordonly argument
#-----------------------------------------------------
'''
Same usage as timer2.py, but uses 3.X keyword-only default arguments
instead of... | nilq/baby-python | python |
"""
Generate a autoencoder neural network visualization
"""
# Changing these adjusts the size and layout of the visualization
FIGURE_WIDTH = 16
FIGURE_HEIGHT = 9
RIGHT_BORDER = 0.7
LEFT_BORDER = 0.7
TOP_BORDER = 0.8
BOTTOM_BORDER = 0.6
N_IMAGE_PIXEL_COLS = 64
N_IMAGE_PIXEL_ROWS = 48
N_NODES_BY_LAYER = [10, 7, 5, 8]
... | nilq/baby-python | python |
from kafka import KafkaConsumer
from kafka.errors import KafkaError
import logging
import sys
BOOTSTRAP_SERVERS = ['3.209.55.41:9092']
KAFKA_TOPIC = 'fledge-testing'
_LOGGER = logging.getLogger(__name__)
_LOGGER.setLevel(logging.DEBUG)
handler = logging.StreamHandler(sys.stdout)
handler.setLevel(logging.DEBUG)
forma... | nilq/baby-python | python |
import os
from shutil import copy2
from datetime import datetime
from PIL import Image
from sys import argv
username = argv[1]
dest = argv[2]
source = "C:/Users/" + username + "/AppData/Local/Packages/Microsoft.Windows.ContentDeliveryManager_cw5n1h2txyewy/LocalState/Assets"
currentImgs = []
for filename in os.listdir(... | nilq/baby-python | python |
class HabitatError(Exception):
_msg = 'Unhandled Error'
def __init__(self, *args, **kwargs):
return super().__init__(self._msg%args, **kwargs)
class InvalidBiomeError(HabitatError):
_msg = '%s is not a valid biome!'
class AmbiguousProvidesError(HabitatError):
_msg = '%s and %s both provide %s... | nilq/baby-python | python |
import random
# Easy to read representation for each cardinal direction.
N, S, W, E = ('n', 's', 'w', 'e')
class Cell(object):
"""
Class for each individual cell. Knows only its position and which walls are
still standing.
"""
def __init__(self, x, y, walls):
self.x = x
self.y = y
... | nilq/baby-python | python |
import numpy as np
import pandas as pd
from sklearn.linear_model import lasso_path
from lassoloaddata import get_folds
# define the grid of lambda values to explore
alphas = np.logspace(-4, -0.5, 30)
def get_lasso_path(X_train, y_train, alphas=alphas):
"""
compute the lasso path for the given data
Args:
... | nilq/baby-python | python |
""""
Settings:
pos_id
second_key
client_id
client_secret
"""
import hashlib
import json
import logging
from collections import OrderedDict
from decimal import Decimal
from typing import Optional, Union
from urllib.parse import urljoin
from django import http
from django.conf import settings
from django... | nilq/baby-python | python |
from redbot.core import commands
class Tutorial_Cog(commands.Cog):
"""Minimal tutorial bot"""
def __init__(self, bot):
self.bot = bot
@commands.group()
async def simple_cog(self, ctx):
pass
@simple_cog.command()
async def hello(self, ctx, *, message):
"""Says something... | nilq/baby-python | python |
from IPython.display import HTML
import IPython
import htmlmin
def _format_disqus_code(page_url: str, page_identifier: str, site_shortname: str) -> str:
"""This function formats the necessary html and javascript codes needed to be
inserted into the jupyter notebook
Args:
page_url (str): your page'... | nilq/baby-python | python |
DEBUG = True
# Make these unique, and don't share it with anybody.
SECRET_KEY = "c69c2ab2-9c58-4013-94a6-004052f2583d40029806-a510-4c48-a874-20e9245f55f70394cbad-48b5-4945-9499-96c303d771e6"
NEVERCACHE_KEY = "9fb86bbb-51a2-494d-b6ca-1065c0f1f58ee6d757ec-85b0-4f66-9003-ff57c8a3d9d8b37a8b11-19a9-4c03-8596-ba129af542ed"... | nilq/baby-python | python |
from setuptools import setup, find_packages
setup(
name="componentsdb",
version="0.1",
packages=find_packages(exclude=['tests']),
package_data={
'componentsdb': [
'ui/templates/*.html',
'ui/static/*',
],
},
install_requires=[
'enum34',
'fl... | nilq/baby-python | python |
#!/usr/bin/env python3
# https://leetcode.com/problems/ugly-number/
import unittest
class Solution:
def isUgly(self, num: int) -> bool:
if num <= 0:
return False
if num == 1:
return True
original = num
while num % 2 == 0:
num //= 2
while... | nilq/baby-python | python |
import unittest
from unittest import mock
from easybill_rest import Client
from easybill_rest.resources.resource_attachments import ResourceAttachments
from easybill_rest.tests.test_case_abstract import EasybillRestTestCaseAbstract
class TestResourceAttachments(unittest.TestCase, EasybillRestTestCaseAbstract):
... | nilq/baby-python | python |
#########
#IMPORTS#
#########
from tensorflow.keras.losses import binary_crossentropy
from tensorflow.keras.models import Model
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.layers import *
class Unet2D:
def __init__(self):
c1 = Conv2D(32, (3, 3), activation='relu', padding='s... | nilq/baby-python | python |
async def get_value():
return "not-none"
<caret>if await get_value():
print("Not none")
else:
print("None") | nilq/baby-python | python |
import sys
from bson.objectid import ObjectId, InvalidId
from girder import logger
from girder.constants import AccessType
from girder.models.model_base import AccessControlledModel
from girder.models.model_base import ValidationException
from girder.models.user import User as UserModel
from girder.utility.model_import... | nilq/baby-python | python |
from .model import DeepUNet
| nilq/baby-python | python |
from flask import Blueprint, redirect, url_for, render_template, request, abort, Flask
from flask import current_app
from website import db
from website.main.forms import SearchForm
from website.main.utils import db_reset, build_destination, make_parks, miles_to_meters, seconds_to_minutes
from website.models import Res... | nilq/baby-python | python |
import pytest
import os
import time
import projects.sample.sample as sample
from tests.backgroundTestServers import BackgroundTestServers
from rtCommon.clientInterface import ClientInterface
from tests.common import rtCloudPath
test_sampleProjectPath = os.path.join(rtCloudPath, 'projects', 'sample')
test_sampleProject... | nilq/baby-python | python |
from . import meta_selector # noqa
from .pg import PatternGenerator
from .selector import Selector
PatternGenerator('')
Selector('')
| nilq/baby-python | python |
def binc(n,m):
bc = [[0 for i in range(1000)] for j in range(1000)];
for x in range(m+1):
bc[0][x] = 1;
bc[1][0] = 1;
for i in range(1,n):
for j in range(i+1):
print("I", i, "J", j);
bc[i][j] = bc[i-1][j-1] + bc[i-1][j];
... | nilq/baby-python | python |
# coding: utf-8
# Python libs
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
import os
import shutil
import tempfile
import time
# Salt libs
import salt.utils.files
from salt.beacons import watchdog
from salt.ext.six.moves import range
# Salt test... | nilq/baby-python | python |
# PART 1
def draw_stars(x):
for count in range(0, len(x)):
print '*' * x[count]
x = [1, 2, 4, 8, 16, 32]
draw_stars(x)
# PART 2
def draw_star(x):
for count in range(0, len(x)):
if(isinstance(x[count], str)):
print x[count].lower()[:1] * len(x[count])
else:
print '*' * x[count] | nilq/baby-python | python |
from influence_module.interface import IInfluencer
from music_module.interface import IMusic
from graphics_module.interface import IVisuals
from parse_module.interface import parse_config
from timeit import default_timer as timer
import numpy as np
configs = None
i_visuals = None
i_influencer = None
i_music = None
de... | nilq/baby-python | python |
"""
This file stores a subclass of DistanceSolver, UPGMA. The inference procedure is
a hierarchical clustering algorithm proposed by Sokal and Michener (1958) that
iteratively joins together samples with the minimum dissimilarity.
"""
from typing import Callable, Dict, List, Optional, Tuple, Union
import abc
from col... | nilq/baby-python | python |
from pathlib import Path
from unittest import mock
from credsweeper.file_handler.patch_provider import PatchProvider
class TestPatchProvider:
def test_load_patch_data_p(self) -> None:
"""Evaluate base load diff file"""
dir_path = Path(__file__).resolve().parent.parent
file_path = dir_pat... | nilq/baby-python | python |
import md5
i = 0
while 1:
key = 'ckczppom' + str(i)
md = md5.new(key).hexdigest()
if md[:5] == '00000':
break
i+=1
print i | nilq/baby-python | python |
from django.contrib import admin
# Register your models here.
from .models import Item
class ItemAdmin(admin.ModelAdmin):
list_display = ['item_id', 'price', 'type', 'seller',
'customer_id', 'quantity_per_item', 'total_price' ]
admin.site.register(Item, ItemAdmin) | nilq/baby-python | python |
import sys
from base64 import b64encode
from nacl import encoding, public
"""
This script is used to encrypt the github secrets for the
Debricked login, since the bindings for golang suck.
"""
def encrypt(public_key: str, secret_value: str) -> str:
"""Encrypt a Unicode string using the public key."""
public_k... | nilq/baby-python | python |
from qgis.core import *
import psycopg2
QgsApplication.setPrefixPath("/usr", True)
qgs = QgsApplication([], False)
qgs.initQgis()
uri = QgsDataSourceURI()
uri.setConnection("192.168.50.8", "5432", "pub", "ddluser", "ddluser")
try:
conn = psycopg2.connect("dbname='soconfig' user='ddluser' host='192.168.50.8' pas... | nilq/baby-python | python |
from django.conf.urls import include, url
from olympia.reviews.feeds import ReviewsRss
from . import views
# These all start with /addon/:id/reviews/:review_id/.
review_detail_patterns = [
url('^$', views.review_list, name='addons.reviews.detail'),
url('^reply$', views.reply, name='addons.reviews.reply'),
... | nilq/baby-python | python |
#!/usr/bin/env python3
import json
import urllib.request
import mirrorz
import config
def fetch_json(url):
print(f"fetching {url}")
response = urllib.request.urlopen(url)
data = response.read()
return json.loads(data)
def main():
for name, cfg in config.sites.items():
values=[]
for... | nilq/baby-python | python |
from pprint import pprint # noqa
from datetime import datetime
from normality import stringify
REMOVE = [
"Shape.STArea()",
"Shape.STLength()",
"Shape.len",
"SHAPE.len",
"SHAPE.fid" "FullShapeGeometryWKT",
"Shape__Length",
]
RENAME = {
"SDELiberiaProd.DBO.MLMELicenses_20160119.Area": "Ar... | nilq/baby-python | python |
from jsonrpc11base.errors import APIError
from src import exceptions
class UnknownTypeError(APIError):
code = 1000
message = 'Unknown type'
def __init__(self, message):
self.error = {
'message': message
}
class AuthorizationError(APIError):
code = 2000
message = 'Aut... | nilq/baby-python | python |
from django.contrib import admin
from .models import Tag, Category, Article, About
# Register your models here.
admin.site.register(Tag)
admin.site.register(Category)
admin.site.register(About)
@admin.register(Article)
class PostAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ('title',)}
| nilq/baby-python | python |
# import the necessary package
from functools import wraps
from flask import request
from PIL import Image
from io import BytesIO
from app.main import config
import numpy as np
import base64
import cv2
import os
def token_required(f):
@wraps(f)
def decorated(*args, **kwargs):
data, status = Auth.get_l... | nilq/baby-python | python |
import time
from typing import Union
import pyglet
from kge.core import events
from kge.core.constants import DEFAULT_FPS
from kge.core.system import System
class Updater(System):
def __init__(self, engine=None, time_step=1 / (DEFAULT_FPS), **kwargs):
super().__init__(engine, **kwargs)
... | nilq/baby-python | python |
NUMBERS = [
".",
"0",
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
]
OPERATIONS = [
"+",
"-",
"=",
"×",
"÷",
]
FUNCTIONS = [
"%",
"(",
")",
"⁺⁄₋",
"¹⁄ₓ",
"10ˣ",
"2ⁿᵈ",
"²√x",
"³√x",
"AC",
"cos",
"cosh",
... | nilq/baby-python | python |
import json
from collections import OrderedDict
from raven_preprocess.np_json_encoder import NumpyJSONEncoder
from ravens_metadata_apps.utils.basic_response import \
(ok_resp, err_resp)
def json_dump(data_dict, indent=None):
"""Dump JSON to a string w/o indents"""
if indent is not None and \
not is... | nilq/baby-python | python |
__author__ = 'Govind Patidar'
class Locator(object):
# open page locator All ID
logo = "//img[@alt='Mercury Tours']"
btn_skip = "com.flipkart.android:id/btn_skip"
banner_text = "com.flipkart.android:id/banner_text"
mobile_no = "com.flipkart.android:id/mobileNo"
btn_msignup = "com.flipkart.andr... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from datetime import datetime, date, timedelta
from functools import reduce
from django.db.models import Count
from rest_framework import serializers
from common.consts import CFEI_TYPES, PARTNER_TYPES
from common.mixins.views import PartnerIdsMixin
fro... | nilq/baby-python | python |
import base64
import mimetypes
from io import BytesIO
from time import time
from typing import Any, Dict, List, TypedDict
from PyPDF2 import PdfFileReader
from PyPDF2.utils import PdfReadError
from ....models.models import Mediafile
from ....permissions.permissions import Permissions
from ....shared.exceptions import... | nilq/baby-python | python |
# Copyright 2022 Google LLC
#
# 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 io
import os
from unittest.mock import MagicMock, patch
from uuid import uuid4
from django.core.files.uploadedfile import SimpleUploadedFile
from django.template.exceptions import \
TemplateSyntaxError as DjangoTemplateSyntaxError
from django.test import TestCase
from jinja2 import TemplateSyntaxError
from ... | nilq/baby-python | python |
#python3 Steven 12/05/20,Auckland,NZ
#pytorch backbone models
import torch
from commonTorch import ClassifierCNN_NetBB
from summaryModel import summaryNet
from backbones import*
def main():
nClass = 10
net = ClassifierCNN_NetBB(nClass, backbone=alexnet)
summaryNet(net, (3,512,512))
#net = Class... | nilq/baby-python | python |
from fastapi import FastAPI
app = FastAPI()
@app.get("/keyword-weights/", response_model=dict[str, float])
async def read_keyword_weights():
return {"foo": 2.3, "bar": 3.4}
| nilq/baby-python | python |
"""Submodule providing embedding lookup layer."""
from typing import Tuple, Dict
import tensorflow as tf
from tensorflow.keras.layers import Flatten, Layer # pylint: disable=import-error,no-name-in-module
class EmbeddingLookup(Layer):
"""Layer implementing simple embedding lookup layer."""
def __init__(
... | nilq/baby-python | python |
import sys
import os
import numpy as np
from numpy import array
import datetime
import calendar
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from matplotlib.ticker import FuncFormatter
from swaty.swaty_read_model_configuration_file import swat_read_model_configuration_file
from swaty.classes... | nilq/baby-python | python |
class Solution:
cache = {0: 0, 1: 1}
def fib(self, N: int) -> int:
if N in self.cache:
return self.cache[N]
self.cache[N] = self.fib(N - 1) + self.fib(N - 2)
return self.cache[N]
# Contributed by LeetCode user mereck.
class Solution2:
def fib(self, N: int) -> in... | nilq/baby-python | python |
import unittest
from src.command.shutter_command import ShutterCommand, ShutterCommandType
class TestShutterCommand(unittest.TestCase):
def test_parse(self):
self.assertEqual(ShutterCommand.parse(" Up "), ShutterCommand(ShutterCommandType.POSITION, 0))
self.assertEqual(ShutterCommand.parse(" ... | nilq/baby-python | python |
#
# Photo Fusion
#
# Peter Turney, February 8, 2021
#
# Read a fusion pickle file (fusion_storage.bin) and
# make photos of the fusion events.
#
import golly as g
import model_classes as mclass
import model_functions as mfunc
import model_parameters as mparam
import numpy as np
import time
import pickle
... | nilq/baby-python | python |
from subprocess import call
import re
import json
# cache for `dependencies`
dependencies = dict()
# parses and represents a carthage dependency
class Dependency(object):
def __init__(self, line, origin):
self.line = line
self.origin = origin
match = re.match(r"^(?P<identifier>(github|git|... | nilq/baby-python | python |
#!/usr/bin/env python3
import argparse
import gzip
import logging
import hashlib
from glob import glob
from json import load
from inscriptis import get_text
from inscriptis.model.config import ParserConfig
from collections import defaultdict
from harvest import posts
from harvest.extract import extract_posts
from url... | nilq/baby-python | python |
#!/usr/bin/python
import timeit
from graphtheory.structures.edges import Edge
from graphtheory.structures.graphs import Graph
from graphtheory.structures.factory import GraphFactory
from graphtheory.traversing.bfs import BFSWithQueue
from graphtheory.traversing.bfs import SimpleBFS
V = 10
#V = 1000000 # OK
graph_fa... | nilq/baby-python | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import colorsimple as cs
entry_dict = {
"A (Rhodopsin)" : { "shape" : 7, "ps" : 1.5, "clr" : "#FFB8B8" },
"B1 (Secretin)" : { "shape" : 7, "ps" : 1.5, "clr" : "#00A600" },
"C (Glutamate)" : { "shape" : 7, "ps" : 1.5, "clr" ... | nilq/baby-python | python |
from typing import Dict, Optional, Tuple
from datadog import initialize, statsd
from .base import BaseClient
class DogstatsdClient(BaseClient):
def __init__(self, agent_host: str, port: int) -> None:
initialize(statsd_host=agent_host, statsd_port=port)
def increment_counter(
self, name: str... | nilq/baby-python | python |
symbols = ["DOLLAR SIGN", "BANANA", "CHERRY", "DIAMOND", "SEVEN", "BAR"]
import random
reel_1 = random.choice(symbols)
reel_2 = random.choice(symbols)
reel_3 = random.choice(symbols)
if reel_1 == reel_2 and reel_2 == reel_3:
print("%s! %s! %s! LUCKY STRIKE! YOU WIN £10"% (reel_1, reel_2, reel_3))
elif reel_1... | nilq/baby-python | python |
from tkinter import Canvas
class GraphicItem:
itemType: str
coords: list
config: dict
def __init__(self, cnv: Canvas):
self.cnv = cnv
self.uid = None
def update(self):
if self.uid is None:
self.uid = self.cnv._create(
itemType=self.itemType,
... | nilq/baby-python | python |
class cel:
def __init__(self):
self.temp = 1234567890
| nilq/baby-python | python |
import datetime
import dateutil.parser
import pytz
import pytz.exceptions
from django.contrib import messages
from django.core.exceptions import ObjectDoesNotExist
from django.http import HttpResponseNotFound
from django.shortcuts import redirect, render
from django.utils import timezone, translation
from django.utils.... | nilq/baby-python | python |
from operator import attrgetter
import pyangbind.lib.xpathhelper as xpathhelper
from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType, RestrictedClassType, TypedListType
from pyangbind.lib.yangtypes import YANGBool, YANGListType, YANGDynClass, ReferenceType
from pyangbind.lib.base import PybindBase
from d... | nilq/baby-python | python |
from collections import OrderedDict
class Decision:
def __init__(self, id, name):
self.id = id
self.name = name
self.decisionTables = []
class DecisionTable:
def __init__(self, id, name):
self.id = id
self.name = name
self.inputs = []
self.outputs = [... | nilq/baby-python | python |
#!/usr/bin/env python
from __future__ import absolute_import, print_function
import numpy as np
import math
import random
import time
import rospy
import tf
from geometry_msgs.msg import Point, Pose, Twist
from utils import generatePoint2D, bcolors, close2Home
WHEEL_OFFSET = 0
class Wanderer():
"""
Super class... | nilq/baby-python | python |
"""Quantum Inspire library
Copyright 2019 QuTech Delft
qilib is available under the [MIT open-source license](https://opensource.org/licenses/MIT):
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 Softwar... | nilq/baby-python | python |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from contextlib import contextmanager
from datetime import datetime
import os
import tensorflow as tf
def batch_size_from_env(default=1):
"""Get batch size from environment variable SALUS_BATCH_SIZE"""
... | nilq/baby-python | python |
import logging
import redis
import time
import iloghub
iloghub = iloghub.LogHub()
iloghub.config()
# create logger
logger = logging.getLogger('simple_example')
#formater = logging.Formatter(style=" %(message)s")
fmt = "%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s"
datefmt = "%H:%M:%S"
formatte... | nilq/baby-python | python |
from os.path import exists
import speech_recognition as sr
import mss
import numpy as np
import os
from PIL import Image
path, dirs, files = next(os.walk("D:/Document/3INFO/BDD/Demon/"))
monitor =2
i = len(files)
import glob
def record_volume(path,i):
fichier=open(path[0:-3]+".txt","a")
r = sr.Recognizer()
... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""SymptomSuggestion.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1TCme3BRC34OqIgLUca6GkivYK-1HFs-j
"""
# !git clone https://github.com/rahul15197/Disease-Detection-based-on-Symptoms
# cd Disease-Detection-b... | nilq/baby-python | python |
#!/usr/bin/python3
"""
TXFMTrackService
(C) 2015
David Rieger
"""
import bottle
from bottle import route, run, response
from storagemanager import StorageManager
sm = StorageManager()
@route('/api/get/all')
def get_all_songs():
response.headers['Access-Control-Allow-Origin'] = '*'
return sm.get_songs()
@r... | nilq/baby-python | python |
from domain.Contest.database.contest_repository import ContestRepository
from domain.Contest.usecase.contest_interactor import ContestInteractor
from infrastructure.database.postgres.sqlhandler import SqlHandler
class ContestController:
def __init__(self, sqlhandler: SqlHandler):
self.interactor = Contest... | nilq/baby-python | python |
# dht11_serial.py - print humidity and temperature using DHT11 sensor
# (c) BotBook.com - Karvinen, Karvinen, Valtokari
import time
import serial # <1>
def main():
port = serial.Serial("/dev/ttyACM0", baudrate=115200, timeout=None) # <2>
while True:
line = port.readline() # <3>
arr = line.split() # <4>
if len... | nilq/baby-python | python |
corruptionValues = {
"Glimpse_of_Clarity_1": 15,
"Crit_DMG_1": 10,
"Crit_DMG_2": 15,
"Crit_DMG_3": 20,
"Flash_of_Insight_1": 20,
"Lash_of_the_Void_1": 25,
"Percent_Crit_1": 10,
"Percent_Crit_2": 15,
"Percent_Crit_3": 20,
"Percent_Haste_1": 10,
"Percent_Haste_2": 15,
"Perc... | nilq/baby-python | python |
from enum import Enum, auto
from fastapi import Request
from fastapi.responses import JSONResponse
class ErrCode(Enum):
NO_ERROR = 0
EMAIL_DUPLICATED = auto()
NO_ITEM = auto()
ErrDict = {
ErrCode.NO_ERROR: "정상",
ErrCode.EMAIL_DUPLICATED: "동일한 이메일이 존재합니다.",
ErrCode.NO_ITEM: "해당 항목이 존재하지 않습니다. "... | nilq/baby-python | python |
import numpy as np
from sklearn.model_selection import TimeSeriesSplit
from sklearn.utils import indexable
from sklearn.utils.validation import _num_samples
import backtrader as bt
import backtrader.indicators as btind
import datetime as dt
import pandas as pd
import pandas_datareader as web
from pandas import Series, ... | nilq/baby-python | python |
import argparse
parser = argparse.ArgumentParser(prog='build_snp_map_for_neale_lab_gwas.py', description='''
Build the SNP map table: phased genotype variant <=> Neale's lab GWAS
''')
parser.add_argument('--genotype-pattern', help='''
In the form: prefix{chr}suffix.
Will load 1..22 chromosomes (no X).
''')
... | nilq/baby-python | python |
def hello_world():
return "hi" | nilq/baby-python | python |
import filecmp
import os
import subprocess
import unittest
from clockwork import gvcf
from cluster_vcf_records import vcf_record
modules_dir = os.path.dirname(os.path.abspath(gvcf.__file__))
data_dir = os.path.join(modules_dir, "tests", "data", "gvcf")
def lines_from_vcf_ignore_file_date(vcf):
with open(vcf) as... | nilq/baby-python | python |
from torch.utils.data import dataloader
from torchvision.models.inception import inception_v3
from inception_v4 import inceptionv4
import torch
import torch.distributed as dist
import argparse
import torch.nn as nn
import torch.backends.cudnn as cudnn
import torch.optim
import torch.utils.data
import torch.utils.data.d... | nilq/baby-python | python |
# Generated by Django 2.1.3 on 2018-11-02 08:18
from django.db import migrations, models
import django.db.models.deletion
import mptt.fields
class Migration(migrations.Migration):
dependencies = [
('pages', '0007_language_code'),
]
operations = [
migrations.AlterField(
model... | nilq/baby-python | python |
from enum import Enum, unique
@unique
class BrowserType(Enum):
"""Class to define browser type, e.g. Chrome, Firefox, etc."""
CHROME = "Chrome"
EDGE = "Edge"
FIREFOX = "Firefox"
INTERNET_EXPLORER = "Internet Explorer"
OPERA = "Opera"
SAFARI = "Safari"
| nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""End to end test of running a job.
:copyright: Copyright (c) 2019 RadiaSoft LLC. All Rights Reserved.
:license: http://www.apache.org/licenses/LICENSE-2.0.html
"""
from __future__ import absolute_import, division, print_function
import pytest
import os
# TODO(e-carlin): Tests that need to b... | nilq/baby-python | python |
n = int(input())
suma = 0
dif = []
for i in range(n):
a , b = map(int, input().split())
suma += b*(n-1)
dif.append(a-b)
dif = sorted(dif, reverse = True)
for j in range(n):
suma+= j*dif[j]
print(suma)
| nilq/baby-python | python |
"""Tools for converting model parameter from Caffe to Keras."""
import numpy as np
import os
import sys
import shutil
import h5py
import collections
import pickle
def dump_weights(model_proto, model_weights, weight_output, shape_output=None, caffe_home='~/caffe'):
"""Helper function to dump caffe model weithts i... | nilq/baby-python | python |
import logging
from typing import List
from homeassistant.helpers.entity import Entity
from gehomesdk.erd import ErdCode, ErdApplianceType
from .base import ApplianceApi
from ..entities import GeErdSensor, GeErdBinarySensor
_LOGGER = logging.getLogger(__name__)
class DryerApi(ApplianceApi):
"""API class for dr... | nilq/baby-python | python |
import re
m = re.search(r'([a-zA-Z0-9])\1+', input().strip())
print(m.group(1) if m else -1)
| nilq/baby-python | python |
import logging
import sys, os
import datetime
import eons, esam
import pandas as pd
#Class name is what is used at cli, so we defy convention here in favor of ease-of-use.
class in_excel(esam.DataFunctor):
def __init__(self, name=eons.INVALID_NAME()):
super().__init__(name)
self.requiredKWArgs.app... | nilq/baby-python | python |
from django.test import Client, TestCase
from django.urls import reverse
from django.contrib.auth import get_user_model
from posts.forms import PostForm
from posts.models import Post
User = get_user_model()
class TaskCreateFormTests(TestCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
... | nilq/baby-python | python |
from abc import ABC, abstractmethod
import asyncio
from typing import Callable
class AbstractConnectSignal(ABC):
def __init__(self) -> None:
self.targets = set()
def connect(self, target: Callable):
if target not in self.targets:
self.targets.add(target)
@abstractmethod
... | nilq/baby-python | python |
#pip install pdfplumber
import pdfplumber
pdf = pdfplumber.open('./Relação')
paginas = len(pdf.pages) #quantidade de paginas
text = ""
for i in range(paginas):
page = pdf.pages[i]
text += page.extract_text()
print(text)
| nilq/baby-python | python |
import logging
import json
logger = logging.getLogger(__name__)
def __virtual__():
'''
Only load if jenkins_common module exist.
'''
if 'jenkins_common.call_groovy_script' not in __salt__:
return (
False,
'The jenkins_smtp state module cannot be loaded: '
'j... | nilq/baby-python | python |
from django.contrib.auth import get_user_model
from django.contrib.auth.forms import UserChangeForm, UserCreationForm
CustomUser = get_user_model()
# TODO: are we using this form now that we have django-allauth?
class CustomUserCreationForm(UserCreationForm):
class Meta:
model = CustomUser
fields... | nilq/baby-python | python |
from fairseq.tasks import register_task
from fairseq.tasks.translation import TranslationTask
from fairseq import utils, search
from glob import glob
import os
from morphodropout.binarize import SRC_SIDE, TGT_SIDE
from morphodropout.dataset import build_combined_dataset
from morphodropout.seq_gen import SequenceGener... | nilq/baby-python | python |
name = "pip_test_package"
| nilq/baby-python | python |
#!/usr/bin/env python
import os, os.path, sys
import socket
if __name__ == "__main__":
PROJECT_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), '..',))
print "PROJECT_ROOT=", PROJECT_ROOT
sys.path.append(PROJECT_ROOT)
# Add virtualenv dirs to python path
host = socket.gethostn... | nilq/baby-python | python |
import glob
import os
import re
import requests
from Bio.SeqIO import SeqRecord
from Bio import SeqIO
from .utils import is_fasta
class PrimerDesigner:
"""Class for designing primers from FASTA files.
It will send a FASTA alignment to `primers4clades`_ in order to design
degenerate primers. Input data ... | nilq/baby-python | python |
#!/bin/env python3
import random
import sys
import os
import time
from collections import defaultdict
from typing import Dict, Tuple, Union, Set
import requests
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
import expand_utilities as eu
from expand_utilities import QGOrganizedKnowledgeGraph
sys.path.app... | nilq/baby-python | python |
import pprint
import cyok
bit_file = 'foobar.bit'
# load DLL
cyok.load_library()
# check version
print('FrontPanel DLL built on: %s, %s' % cyok.get_version())
# connect to device
dev = cyok.PyFrontPanel()
print('Opening device connection.')
dev.open_by_serial()
print('Getting device information.')
dev_info = dev... | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.