content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
'''
Entry point for gunicorn to serve REST API
'''
import falcon
import worker
application = falcon.API()
api = application
worker = worker.Resource()
api.add_route('/worker', worker)
| nilq/baby-python | python |
from output.models.ms_data.particles.particles_da002_xsd.particles_da002 import (
A,
Doc,
Foo,
)
__all__ = [
"A",
"Doc",
"Foo",
]
| nilq/baby-python | python |
# -*- coding:utf-8 -*-
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
channel = connection.channel()
channel.queue_declare(queue='helloQueue')
def callback(ch, method, properties, body):
print(" [>>>]Receive %r" % body)
channel.basic_consume(callback, queue='hello... | nilq/baby-python | python |
# Copyright 2018 (c) Herbert Shin https://github.com/initbar/sipd
#
# This source code is licensed under the MIT license.
import logging
import threading
import time
from collections import deque
from src.rtp.server import SynchronousRTPRouter
# from multiprocessing import Queue
try:
from Queue import Queue
exc... | nilq/baby-python | python |
class Solution(object):
def partitionLabels(self, S):
"""
:type S: str
:rtype: List[int]
"""
dictionary = {}
index = -1
counter = []
for char in S:
if char not in dictionary:
index += 1
dictionary[char] = i... | nilq/baby-python | python |
from functools import reduce
from pathlib import Path
import pytoml as toml
def get_sphinx_configuration(project_dir):
"""Read the Sphinx configuration from ``pyproject.toml```."""
try:
project = toml.loads((Path(project_dir) / 'pyproject.toml').read_text())
return reduce(lambda a, b: a[b], '... | nilq/baby-python | python |
import os
import uuid
from django.utils import timezone
from django.db import models
from django.utils.deconstruct import deconstructible
# from main.models import User
from api.models import path_and_rename_image_share
from projects.models import Projects
from django.utils.translation import gettext_lazy as _
@dec... | nilq/baby-python | python |
#!/usr/local/bin/python
# encoding: utf-8
"""
Documentation for crowdedText can be found here: http://crowdedText.readthedocs.org/en/stable
Usage:
crowdedText [-s <pathToSettingsFile>]
-h, --help show this help message
-s, --settings the settings file
"""
################# GLOBAL IMPORTS... | nilq/baby-python | python |
import random
class RandomList(list):
def get_random_element(self):
element = random.choice(self)
self.remove(element)
return element | nilq/baby-python | python |
for _ in range(int(input())):
basic = int(input())
if basic < 1500:
print(basic + (basic * 0.10) + (basic * 0.90))
elif basic >= basic:
print(basic + 500 + (basic * 0.98)) | nilq/baby-python | python |
# Copyright (c) 2019 PaddlePaddle 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 appli... | nilq/baby-python | python |
import os
import time
from random import choice
from typing import Optional
from .paths import VERIFY_DIR
# 声明验证码取字范围
chars = "ABDEFGHJKLMNPQRTUYabdefghjkmnpqrty123456789"
EXPIRE_LIMIT_MINUTE = 5
def gen_code(length: int = 4) -> str:
code = ""
for _ in range(length):
code += choice(chars)
return... | nilq/baby-python | python |
import numpy as np
from pydrake.all import (InverseKinematics, RotationMatrix, MultibodyPlant,
PiecewiseQuaternionSlerp, PiecewisePolynomial)
from pydrake.solvers import mathematicalprogram as mp
def calc_iwa_trajectory_for_point_tracking(plant: MultibodyPlant,
... | nilq/baby-python | python |
#!/usr/bin/python3
from testlib import *
if __name__ == '__main__':
"""
Checker with points
Answer scored to the size of the intersection divided by the size of the union of the sets of options,
checked by used and correct choices. More info: https://en.wikipedia.org/wiki/Jaccard_index
This ... | nilq/baby-python | python |
import csv
import io
from urllib.request import urlopen
from django.core.management.base import BaseCommand
from web.foi_requests import models
ESICS_URL = 'https://raw.githubusercontent.com/vitorbaptista/dataset-sics-brasil/master/data/sics-brasil.csv' # noqa: E501
class Command(BaseCommand):
help = 'Load n... | nilq/baby-python | python |
from setuptools import setup
# The text of the README file
with open('README.md') as f:
rm = f.read()
# This call to setup() does all the work
setup(
name="boaf",
version="0.0.1",
description="Birds Of A Feather - Clustering in Python",
long_description=rm,
long_description_content_type="text... | nilq/baby-python | python |
from wallaby import *
import constants as c
import actions as a
import servos as s
def drive(lPer, rPer, dTime):
motor(c.lMotor, lPer)
motor(c.rMotor, rPer)
msleep(dTime)
ao()
def freezeBoth(): # Careful when using this function in a loop, as we saw. That last msleep() causes some confusion. -LMB
... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
import ctypes
EnumWindows = ctypes.windll.user32.EnumWindows
EnumWindowsProc = ctypes.WINFUNCTYPE(ctypes.c_bool, ctypes.POINTER(ctypes.c_int), ctypes.POINTER(ctypes.c_int))
GetWindowText = ctypes.windll.user32.GetWindowTextW
GetWindowTextLength = ctypes.windll.user32.GetWindowTextLengthW
IsWind... | nilq/baby-python | python |
"""
Sample plugin for locating stock items / locations.
Note: This plugin does not *actually* locate anything!
"""
import logging
from plugin import InvenTreePlugin
from plugin.mixins import LocateMixin
logger = logging.getLogger('inventree')
class SampleLocatePlugin(LocateMixin, InvenTreePlugin):
"""
A ... | nilq/baby-python | python |
from django.shortcuts import render
from django.db.models import Q
from api.v1.tools.paginator import customPagination
# serializers imports
from django.utils import timezone
from datetime import datetime
from django.db import DatabaseError, transaction
from django.db import IntegrityError, transaction
from django.con... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import random
import time
import unittest
from mock import call
from mock import patch
from mock import MagicMock as Mock
import pyrax
from pyrax.manager import BaseManager
from pyrax.clouddns import assure_domain
from pyrax.clouddns import CloudDNSClient
from pyrax.clou... | nilq/baby-python | python |
#!/usr/bin/env python
# encoding: utf-8
"""
=========================================================================================
Implementation of Sideways Information Passing graph (builds it from a given
ruleset)
"""
import itertools
# import os
# import sys
# import unittest
from hashlib import md5
from FuXi... | nilq/baby-python | python |
"""Base configuration.
Attributes:
config_yaml (str): Base configuration as YAML code.
config_dict (dict): Base configuration as Python dictionary.
Here is the complete base configuration present as a string in the
:obj:`config_yaml` attribute::
{}
"""
import textwrap
import yaml
config_yaml = """# Base ... | nilq/baby-python | python |
from django.contrib.contenttypes.models import ContentType
from waldur_core.core.utils import DryRunCommand
from waldur_mastermind.marketplace.models import Resource
from waldur_mastermind.marketplace_openstack import utils
from waldur_openstack.openstack.models import Tenant
class Command(DryRunCommand):
help =... | nilq/baby-python | python |
import sys
import os
node_block = []
file = open("profile_node.xml", 'r')
line = file.readline()
while line:
node_block.append(line)
line= file.readline()
file.close()
open("profile_output.xml", 'w+')
header = '<rspec xmlns="http://www.geni.net/resources/rspec/3" xmlns:emulab="http://www.protogeni.net/resou... | nilq/baby-python | python |
from django import forms
from django.utils.translation import gettext_lazy as _
from .models import CustomUser
class SignUpForm(forms.ModelForm):
password = forms.CharField(
label=_('Password'),
widget=forms.PasswordInput
)
confirm_password = forms.CharField(
label=_('Repeat pass... | nilq/baby-python | python |
import os
import sys
from sklearn.externals import joblib
import json
import numpy as np
DIR_CS231n = '/Users/clement/Documents/MLearning/CS231/assignment2/'
conf = {}
# Model instance
conf['input_dim'] = (3, 32, 32)
conf['num_filters'] = [16, 32, 64, 128]
conf['filter_size'] = 3
conf['hidden_dim'] = [500, 500]
conf... | nilq/baby-python | python |
#!/usr/bin/env python3
# Copyright (c) 2019 Stephen Farrell, stephen.farrell@cs.tcd.ie
#
# 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 th... | nilq/baby-python | python |
#!/usr/bin/python
import sys
# a brittle XML parser, with the advantage that memory consumption is constant.
class XMLParser:
def __init__(self):
self.tagstate=""
self.currenttag=""
def parse(self, buf):
events=[]
for c in buf:
if c=="<":
self.tagst... | nilq/baby-python | python |
# encoding: utf-8
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..utils import (
ExtractorError,
HEADRequest,
unified_strdate,
url_basename,
qualities,
)
class CanalplusIE(InfoExtractor):
IE_DESC = 'canalplus.fr, piwiplus.fr and d8.tv'
_VALID_UR... | nilq/baby-python | python |
import tweepy
import pandas as pd
from flask import Flask, render_template, request
from config import CONFIG
CONSUMER_KEY = CONFIG["CONSUMER_KEY"]
CONSUMER_SECRET = CONFIG["CONSUMER_SECRET"]
ACCESS_TOKEN = CONFIG["ACCESS_TOKEN"]
ACCESS_SECRET = CONFIG["ACCESS_SECRET"]
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUME... | nilq/baby-python | python |
from youtube_dl import YoutubeDL
from youtubesearchpython import VideosSearch
from colorama import Fore
from multiprocessing import Process
from pyfiglet import figlet_format
import base64,json,random,os
playlists = {}
songs = {}
pla_l = []
son_l = []
alldata = {}
config = {}
def search(content,limit):
return_di... | nilq/baby-python | python |
"""*****************
Cadastral Parcels
*****************
Definition
==========
Areas defined by cadastral registers or equivalent.
Description
===========
The INSPIRE Directive focuses on the geographical part of cadastral data. In the INSPIRE context, cadastral
parcels will be mainly used as locators for geo-inform... | nilq/baby-python | python |
# Generated by Django 3.0.2 on 2020-01-09 14:57
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('club', '0029_question'),
]
operations = [
migrations.AlterField(
model_name='question',
name='answer',
f... | nilq/baby-python | python |
import asyncio
import dataclasses
import enum
from typing import Dict, Optional, Set, Tuple
from supriya.clocks import AsyncTempoClock, Moment
from ..bases import Event
from .bases import ApplicationObject
from .parameters import ParameterGroup, ParameterObject
class Transport(ApplicationObject):
### CLASS VAR... | nilq/baby-python | python |
import string
import random
import sympy as sp
import math
chars = string.ascii_lowercase + string.ascii_uppercase + string.digits + "{}_"
nr_per_page = 7
nr_st = len(chars) ** nr_per_page
m = sp.nextprime(nr_st)
def n2st(n, amount_of_digits = nr_per_page):
if amount_of_digits == 0:
return ""
ch = c... | nilq/baby-python | python |
from django.contrib.auth.models import User
from django.db.models import Q
from django.test import TestCase
from django.urls import reverse_lazy
from model_mommy import mommy
from gear.models import Weapon
from player.models import Player
class TestRoutes(TestCase):
"""Integration tests."""
def setUp(self):... | nilq/baby-python | python |
#!/bin/python
from roomai.algorithms.crm import CRMPlayer
from roomai.algorithms.crm import CRMAlgorithm | nilq/baby-python | python |
import os
import hyperopt
import pandas as pd
from hyperopt import fmin, tpe, STATUS_OK, Trials
from hyperopt import hp
from hyperopt.pyll import scope
from sklearn.linear_model import LinearRegression
from xgboost import XGBRegressor
from src.utils.memory_managment import save_object
def trainXGBoost(train_x, trai... | nilq/baby-python | python |
import unittest
import mock
import requests_cache
from ddt import ddt, data
from nose.tools import assert_equals
from nose.tools import assert_false
from nose.tools import assert_is_not_none
from nose.tools import assert_not_equals
from nose.tools import assert_true
import pub
from app import logger
from open_locatio... | nilq/baby-python | python |
#!/usr/bin/env python3
from ev3dev.ev3 import *
import time
m1 = LargeMotor('outC')
m2 = LargeMotor('outD')
arq = open("Dados.txt", "w")
arq.write(" Leituras: \n\n")
arq.close()
def salvar(x):
arq = open("Dados.txt", "a")
s = "%d, %d\n" %(x[0], x[1])
arq.write(s)
arq.close()
m1.run_forever(speed_sp=... | nilq/baby-python | python |
"""
This :mod: `features` module includes methods to generate, select new features for the dataset.
"""
from .feature_generation import GoldenFeatures
from .feature_generation import FeatureInteraction
from .feature_selection import TreeBasedSelection
from .feature_selection import forward_step_selection
from .helpers... | nilq/baby-python | python |
"""
A collection of utility functions and classes. Originally, many
(but not all) were from the Python Cookbook -- hence the name cbook.
This module is safe to import from anywhere within matplotlib;
it imports matplotlib only at runtime.
"""
import collections
import collections.abc
import contextlib
import functoo... | nilq/baby-python | python |
#!/usr/bin/python
import os
import sys
import traceback
sys.path.append(os.path.join(os.path.dirname(__file__), ".."))
from django.core import mail
from travelist import models
try:
task = models.BackgroundTask.objects.filter(frequency=models.BackgroundTaskFrequency.HOURLY).order_by('id')[0]
except IndexError:... | nilq/baby-python | python |
"""Stores helper functions of the routes.py module
Author: Matthias van den Belt
"""
def format_size(size: int) -> str:
"""Formats the size of a file into MB
Input:
- size: size of a file in bytes
Output:
- formatted string showing the size of the file in MB
"""
return "%3.1f MB"... | nilq/baby-python | python |
class Config(object):
pass
class ProdConfig(Config):
pass
class DevConfig(Config):
DEBUG = True
class DevConfig(Config):
debug = True
SQLALCHEMY_DATABASE_URI = "YOUR URI"
#SQLALCHEMY_ECHO = True.
| nilq/baby-python | python |
#%%
import os
import glob
import numpy as np
import scipy as sp
import pandas as pd
import re
import git
# Import libraries to parallelize processes
from joblib import Parallel, delayed
# Import matplotlib stuff for plotting
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import matplotlib as mpl
# Seabor... | nilq/baby-python | python |
import six
from django.contrib.admin.options import InlineModelAdmin
from baya import RolesNode as g
from baya.admin.sites import NestedGroupsAdminSite
from baya.permissions import requires
from baya.permissions import ALLOW_ALL
from baya.tests.admin import BlagEntryInline
from baya.tests.admin import ProtectedPhotoBl... | nilq/baby-python | python |
#!/usr/bin/env python3
from pathlib import Path
import cv2
import depthai as dai
import numpy as np
import time
import glob
import os
from lxml import etree as ET
from tqdm import tqdm
def to_planar(arr: np.ndarray, shape: tuple) -> list:
return [val for channel in cv2.resize(arr, shape).transpose(2, 0, 1) for y_... | nilq/baby-python | python |
#open images, subprocess, irfan view
#Author: Todor
import os
print (os.curdir)
f = open("termlist.txt", 'rt')
list = f.readlines()
f.close()
print(list)
import subprocess
cwdNow = r"S:\Code\Python\\";
for n in list: subprocess.call([r"C:\Program Files\IrfanView\i_view32.exe", n.strip()], cwd=cwdNow)
... | nilq/baby-python | python |
from PIL import Image
from scipy import fftpack
import numpy
from bitstream import BitStream
from numpy import *
import huffmanEncode
import sys
zigzagOrder = numpy.array([0,1,8,16,9,2,3,10,17,24,32,25,18,11,4,5,12,19,26,33,40,48,41,34,27,20,13,6,7,14,21,28,35,42,
49,56,57,50,43,36,29,22,... | nilq/baby-python | python |
import base64
code="CmltcG9ydCBweW1vbmdvCmltcG9ydCByYW5kb20KaW1wb3J0IHJlCmltcG9ydCBzdHJpbmcKaW1wb3J0IHN5cwppbXBvcnQgZ2V0b3B0CmltcG9ydCBwcHJpbnQKCiMgQ29weXJpZ2h0IDIwMTIKIyAxMGdlbiwgSW5jLgojIEF1dGhvcjogQW5kcmV3IEVybGljaHNvbiAgIGFqZUAxMGdlbi5jb20KIwojIElmIHlvdSBhcmUgYSBzdHVkZW50IGFuZCByZWFkaW5nIHRoaXMgY29kZSwgdHVybiBiYWNr... | nilq/baby-python | python |
def sc_kmeans(input_dict):
"""
The KMeans algorithm clusters data by trying to separate samples in n groups of equal variance,
minimizing a criterion known as the inertia <inertia> or within-cluster sum-of-squares.
This algorithm requires the number of clusters to be specified. It scales well to large ... | nilq/baby-python | python |
from nltk.corpus import movie_reviews
from nltk.corpus import stopwords
from nltk import FreqDist
import string
sw = set(stopwords.words('english'))
punctuation = set(string.punctuation)
def isStopWord(word):
return word in sw or word in punctuation
review_words = movie_reviews.words()
filtered = [w.lower() fo... | nilq/baby-python | python |
# Dwolla Secret Stuff
apiKey = ''
apiSecret = ''
token = ''
pin = ''
| nilq/baby-python | python |
# coding: utf-8
import yaml
from os.path import dirname, join
from unittest import TestCase, main
from hamcrest import assert_that, equal_to
from graph_matcher import Isomorphic
from utils import cached_method
from patterns import (
AbstractFactory as AbstractFactoryPattern,
Decorator as DecoratorPattern,
... | nilq/baby-python | python |
from mock import mock
from tests.base import BaseTestCase, MockRequests
from mod_home.models import CCExtractorVersion, GeneralData
from mod_test.models import Test, TestPlatform, TestType
from mod_regression.models import RegressionTest
from mod_customized.models import CustomizedTest
from mod_ci.models import Blocked... | nilq/baby-python | python |
from rest_framework import serializers
from todos.models import TodoList, Task
class TaskSerializer(serializers.ModelSerializer):
class Meta:
model = Task
fields = ("id", "description", "deadline", "completion_date", "assignee",)
class TaskCreateSerializer(serializers.ModelSerializer):
class ... | nilq/baby-python | python |
import json
import requests
class CollecTorFile:
def __init__(self, path, size, last_modified):
self.path = path
self.size = size
self.last_modified = last_modified
def __repr__(self):
return (f"<CollecTorFile path={self.path} size={self.size} "
f"last_modified... | nilq/baby-python | python |
import numpy as np
from mapel.main.objects.Instance import Instance
class Graph(Instance):
def __init__(self, experiment_id, instance_id, alpha=1, model_id=None, edges=None):
super().__init__(experiment_id, instance_id, alpha=alpha, model_id=model_id)
self.edges = edges
self.num_nodes... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
Dummy backend for unsupported platforms.
"""
# system imports
import uuid
from typing import Optional
# local imports
from .base import Notification, DesktopNotifierBase
class DummyNotificationCenter(DesktopNotifierBase):
"""A dummy backend for unsupported platforms"""
def __ini... | nilq/baby-python | python |
def search(nums: list, target: int) -> int:
l = len(nums)
middle = l // 2
if l == 1:
if nums[0] == target:
return 0
else:
return -1
while l >= 1:
if middle == 0:
middle = 1
if nums[middle - 1] == target:
return middle - 1
... | nilq/baby-python | python |
def test():
# Test
assert("True == False" in __solution__ or "True==False" in __solution__ or "True ==False" in __solution__ or "True== False" in __solution__
), "اجابة خاطئة: في النقطة الاولى لم تقم بعملية المقارنة بشكل صحيح"
assert("-2*10 != 20" in __solution__ or "-2*10!=20" in __solution__ o... | nilq/baby-python | python |
import math
class Solution:
def findComplement(self, num):
"""
:type num: int
:rtype: int
"""
result = ~num
if result < 0:
result = result + int(math.pow(2, math.ceil(math.log2(-result))))
return result
if __name__ == '__main__':
sol = Solu... | nilq/baby-python | python |
from ..broker import Broker
class DevicePropertyBroker(Broker):
controller = "device_properties"
def show(self, **kwargs):
"""Shows the details for the specified device property.
**Inputs**
| ``api version min:`` None
| ``api version max:`` None
| ... | nilq/baby-python | python |
#!/usr/bin/python3
import sys
try:
import weasyprint
print("0")
sys.exit(0)
except ImportError:
print("1")
sys.exit(1)
| nilq/baby-python | python |
# import the necessary packages
import numpy as np
import argparse
import cv2
# construct the argument parse and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", help = "path to the image")
args = vars(ap.parse_args())
# load the image
image = cv2.imread(args["image"])
# define the... | nilq/baby-python | python |
from protocol_utils import ndict
__all__ = [
ndict,
]
| nilq/baby-python | python |
'''
randomize my own dataset for 2d training with respect to the same data of choy.
'''
import os, sys
import yaml
nowpath = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.dirname(nowpath))
from common.dataset import ShapeNetV2, Sun2012pascal
from common.geometry import View, Camera
sys.path.append(... | nilq/baby-python | python |
# Adafruit IO HTTP API - Group Interactions
# Documentation: https://io.adafruit.com/api/docs/#groups
# adafruit_circuitpython_adafruitio with an esp32spi_socket
import board
import busio
from digitalio import DigitalInOut
import adafruit_esp32spi.adafruit_esp32spi_socket as socket
from adafruit_esp32spi import adafrui... | nilq/baby-python | python |
from FreeTAKServer.model.SpecificCoT.SendRoute import SendRoute
from FreeTAKServer.controllers.configuration.LoggingConstants import LoggingConstants
from FreeTAKServer.controllers.CreateLoggerController import CreateLoggerController
from FreeTAKServer.model.RestMessages.RestEnumerations import RestEnumerations
import ... | nilq/baby-python | python |
"""empty message
Revision ID: 99f650dc0924
Revises: b4c1dfa70233
Create Date: 2019-03-23 19:02:35.328537
"""
# revision identifiers, used by Alembic.
revision = '99f650dc0924'
down_revision = 'b4c1dfa70233'
from alembic import op
import sqlalchemy as sa
def upgrade():
# ### commands auto generated by Alembic ... | nilq/baby-python | python |
from arm.logicnode.arm_nodes import *
class WorldVectorToLocalSpaceNode(ArmLogicTreeNode):
"""Transform world coordinates into object local coordinates.
@seeNode Vector to Object Orientation
@seeNode Get World Orientation
@seeNode Vector From Transform
"""
bl_idname = 'LNWorldVectorToLocalSpac... | nilq/baby-python | python |
from django import forms
from django.core.exceptions import ValidationError
from django.utils.translation import gettext_lazy as _
from .models import Block, BlocklistSubmission
from .utils import splitlines
def _get_matching_guids_and_errors(guids):
error_list = []
matching = list(Block.objects.filter(guid_... | nilq/baby-python | python |
from django.contrib.auth import get_user_model
from rest_framework import serializers
from phonenumber_field.serializerfields import PhoneNumberField
User = get_user_model()
class PhoneNumberSerializer(serializers.Serializer):
phone_number = PhoneNumberField(required=True)
confirmation_code = serializers.Int... | nilq/baby-python | python |
#!/usr/bin/env python3
import sys
import csv
import time
import random
import curses
import signal
import pickle
import datetime
import argparse
import subprocess
from enum import Enum
from copy import deepcopy as copy
State = Enum('State', 'pick watch getready draw countdown check roll')
class GameTerminated(Excep... | nilq/baby-python | python |
text = """
//------------------------------------------------------------------------------
// Explicit instantiation.
//------------------------------------------------------------------------------
#include "computeGenerators.cc"
namespace Spheral {
template void computeGenerators<Dim< %(ndim)s >,
... | nilq/baby-python | python |
import requests
import json
import datetime
import pprint
class FlightTicketPriceNotificationFromSkyscanner():
SkyscannerApiKey = "sk-----"
MailgunApiKey = "key------"
MailgunSandbox = "sandbox-----"
MailgunEmail = "-----@-----"
conditions = [{
"country": "PL",
"currency": "PLN",
... | nilq/baby-python | python |
import sys
import typing
import numpy as np
def solve(
x: np.array,
y: np.array,
) -> typing.NoReturn:
n = x.size
ord = np.argsort(x, kind='mergesort')
x, y = x[ord], y[ord]
mn = np.minimum.accumulate(y)
mx = np.maximum.accumulate(y)
def possible(d):
j = np.searchsorted(x, x -... | nilq/baby-python | python |
try:
import sys
from cv2 import cv2
import numpy as np
import time
import math
import utils.hand_tracking as ht
except ModuleNotFoundError:
sys.path.append("../")
finally:
import utils.hand_tracking as ht
def main(show_fps=False, video_src=0):
# Capture the video stream Webcam
... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
TencentBlueKing is pleased to support the open source community by making 蓝鲸智云-权限中心(BlueKing-IAM) available.
Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in compliance with th... | nilq/baby-python | python |
#!/usr/bin/env ruby
# usage:
# ruby all-releases ipython jupyter jupyterlab jupyterhub
# dependencies:
# gem install netrc octokit activesupport faraday-http-cache
# attribution: minrk
require "rubygems"
require "octokit"
require "faraday-http-cache"
require "active_support"
# enable caching
stack = Faraday::Ra... | nilq/baby-python | python |
from time import sleep
import copy
import logging
import os
from disco.bot.command import CommandError
from disco.types.base import BitsetMap, BitsetValue
from sqlalchemy import (
create_engine as spawn_engine, PrimaryKeyConstraint,
Column, exc, ForeignKey,
)
from sqlalchemy.dialects.mysql import (
TEXT, ... | nilq/baby-python | python |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from . import ... | nilq/baby-python | python |
from typing import Tuple
import jax
import jax.numpy as jnp
from jaxrl.datasets import Batch
from jaxrl.networks.common import InfoDict, Model, Params, PRNGKey
def target_update(critic: Model, target_critic: Model, tau: float) -> Model:
new_target_params = jax.tree_multimap(
lambda p, tp: p * tau + tp *... | nilq/baby-python | python |
import os
import pytest
import flask
from flask_dance.contrib.github import make_github_blueprint, github
from flask_dance.consumer.storage import MemoryStorage
betamax = pytest.importorskip("betamax")
GITHUB_ACCESS_TOKEN = os.environ.get("GITHUB_OAUTH_ACCESS_TOKEN", "fake-token")
current_dir = os.path.dirname(__file... | nilq/baby-python | python |
import numpy as np
import scipy as sp
import scipy.stats
def gaussian_loglik(obs, mu, sigma):
return sp.stats.multivariate_normal.logpdf(obs, mean=mu, cov=sigma) / mu.shape[0]
def gaussian_entropy(sigma):
return 0.5 * (len(sigma) + np.log(np.linalg.det(sigma)) + np.log(2 * np.pi))
def r2_score(obs, pred):
... | nilq/baby-python | python |
from pydantic import BaseSettings
class Settings(BaseSettings):
APP_NAME: str = "FastAPI Boilerplate"
EMAIL_SENDER: str = "no-reply@app.com"
SMTP_SERVER: str = "your_stmp_server_here"
POSTGRES_USER: str = "app"
POSTGRES_PASSWORD: str = "app"
POSTGRES_SERVER: str = "db"
POSTGRES_DB: str = ... | nilq/baby-python | python |
import json
import logging
import random
import time
import traceback
from ceph.rados_utils import RadosHelper
log = logging.getLogger(__name__)
def run(ceph_cluster, **kw):
"""
CEPH-9311 - RADOS: Pyramid erasure codes (Local Repai rable erasure codes):
Bring down 2 osds (in case of k=4) from 2 lo... | nilq/baby-python | python |
import numpy as np
import cv2
import re
import torch
import torch.nn as nn
from torchvision import transforms
from marsh_plant_dataset import MarshPlant_Dataset
N_CLASSES = 7
output_columns = ['Row', 'Img_ID', 'Section', 'Sarcocornia', 'Spartina', 'Limonium', 'Borrichia', 'Batis', 'Juncus', 'None']
THRESHOLD_SIG = 0.5... | nilq/baby-python | python |
from glob import glob
from config import BOARD_HEIGHT, BOARD_WIDTH, N_IN_ROW
from utils import get_model_path
from config import globalV
from game import Board, Game
from mcts_alphaZero import MCTSPlayer
from policy_value_net_pytorch import PolicyValueNet
"""
input location as '3,3' to play
"""
class Human:
""" h... | nilq/baby-python | python |
import json
import urllib2
import uuid
import random
import string
# send api call, must have NXT server running
def nxtapi(typ):
return json.load(urllib2.urlopen('http://jnxt.org:7876/nxt', typ));
| nilq/baby-python | python |
# ************************************************
# (c) 2019-2021 Nurul-GC. *
# - BSD 3-Clause License *
# ************************************************
from secrets import token_bytes
from typing import Tuple
def encrypt(text: str) -> Tuple[int, int]:
"""Functi... | nilq/baby-python | python |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import... | nilq/baby-python | python |
import mipow
bulb = mipow.mipow("70:44:4B:14:AC:E6")
bulb.connect()
bulb.off()
bulb.disconnect()
| nilq/baby-python | python |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | nilq/baby-python | python |
#!/usr/bin/env python
# vim: expandtab:tabstop=4:shiftwidth=4
'''
Prune images/builds/deployments
'''
#
# Copyright 2016 Red Hat Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License ... | nilq/baby-python | python |
from django.apps import AppConfig
class BlastNew(AppConfig):
name = 'blast_new'
| nilq/baby-python | python |
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
import frappe.utils
import os
from frappe import _
from frappe.website.doctype.website_route.website_route impo... | nilq/baby-python | python |
size(960, 240)
background(0)
fill(205)
ellipse(264, 164, 400, 400)
fill(150)
ellipse(456, -32, 400, 400)
fill(49)
ellipse(532, 236, 400, 400)
| nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.