content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
num = 1
num = 2
num=- 3
num=4
num = 5
| nilq/baby-python | python |
"""
Purpose: Stackoverflow answer
Date created: 2021-01-09
URL: https://stackoverflow.com/questions/65643483/bokeh-plot-is-empty/65643667#65643667
Contributor(s):
Mark M.
"""
import re
import pandas as pd
import bokeh
sample = """
2018-10-22 7468.629883 2.282400e+09 0.263123 NASDAQ
2018-10-23 7437.540039... | nilq/baby-python | python |
import os
import traceback
from copy import deepcopy
from time import sleep
import django_rq
import kubernetes.stream as stream
import websocket
from django.utils import timezone
from kubernetes import client, config
from rq import get_current_job
from api.models import KubePod, ModelRun
from master.settings import M... | nilq/baby-python | python |
# email_outbound/models.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
from django.core.mail import EmailMultiAlternatives
from django.apps import apps
from django.db import models
from wevote_functions.functions import extract_email_addresses_from_string, generate_random_string, \
positive_value... | nilq/baby-python | python |
from django.urls import path, include
urlpatterns = [
path('launches/', include('api_spacex.launches.urls'))
]
| nilq/baby-python | python |
# TRAINS - Keras with Tensorboard example code, automatic logging model and Tensorboard outputs
#
# Train a simple deep NN on the MNIST dataset.
# Gets to 98.40% test accuracy after 20 epochs
# (there is *a lot* of margin for parameter tuning).
# 2 seconds per epoch on a K520 GPU.
from __future__ import print_function
... | nilq/baby-python | python |
from data.db.db import *
async def GivePlayerGold(interaction,arg1,arg2,owner_id):
if interaction.user.id==owner_id:
execute(f"SELECT Gold FROM PlayerEconomy WHERE UserID = ?",arg1)
reply = cur.fetchall()
Gold = reply[0][0]
Gold = int(Gold) + int(arg2)
execute("UPDATE Pla... | nilq/baby-python | python |
from .mongodbRepositorio import conexaoBanco, inserirDocumento
import datetime
from bson import ObjectId
import re
def salvarDoadorBD(registro, nome, dt_cadastro, cidade,
bairro, grupoabo, fatorrh, fone, celular, sexo,
dt_nascimento, dt_ultima_doacao, dt_proximo_doacao, mongodb):
... | nilq/baby-python | python |
import zof
APP = zof.Application(__name__)
FLOW_MOD = zof.compile('''
type: FLOW_MOD
msg:
table_id: $table
command: ADD
match: []
instructions:
- instruction: APPLY_ACTIONS
actions:
- action: OUTPUT
port_no: $port
''')
@APP.message('CHANNEL_UP')
def channel_up... | nilq/baby-python | python |
#!/usr/bin/python3
# Grab data from the Riff.CC MySQL service and render it to the Curator's PostgreSQL database
# Credits:
# - https://stackoverflow.com/questions/10195139/how-to-retrieve-sql-result-column-value-using-column-name-in-python
# - https://github.com/PyMySQL/PyMySQL
# - https://stackoverflow.com/questi... | nilq/baby-python | python |
#!/usr/bin/env python
# Copyright (C) 2015 Dmitry Rodionov
# This software may be modified and distributed under the terms
# of the MIT license. See the LICENSE file for details.
from ..dtrace.apicalls import apicalls
import inspect
from sets import Set
from os import sys, path
def choose_package_class(file_type, fi... | nilq/baby-python | python |
from PIL import Image, ImageDraw
from vk_bot.config import *
import io, requests, random, os
from vk_bot.core.modules.basicplug import BasicPlug
from vk_bot.core.modules.upload import Upload
class Quote(BasicPlug, Upload):
doc = "Фильтр Вьетнам"
command = ("вьетнам",)
def main(self):
url = self.even... | nilq/baby-python | python |
from data import Data
from projects.job import Job
import json
from .service import Service
import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore
class Firestore(Service):
def __init__(self, service_account_path_file, timestamp_name='timestamp', collection='default'):
... | nilq/baby-python | python |
"""Prepare a lexical data file for spacy train."""
import gzip
import json
import math
import sys
import typer
from itertools import islice
from pathlib import Path
def main(
full_vocabulary_path: Path = typer.Argument(..., help='Path to the full vocabulary'),
input_vocabulary_path: Path = typer.Argument(...... | nilq/baby-python | python |
# coding=utf-8
"""
Singular Value Decomposition Based Collaborative Filtering Recommender
[Rating Prediction]
Literature:
Badrul Sarwar , George Karypis , Joseph Konstan , John Riedl:
Incremental Singular Value Decomposition Algorithms for Highly Scalable Recommender Systems
Fifth I... | nilq/baby-python | python |
#!/usr/bin/python
import numpy
from pylab import *
from numpy import *
from scipy import *
from scipy.stats import mode
from scipy.misc.common import factorial
from scipy.spatial.distance import correlation,euclidean
from math import log
import os
path=os.getenv('P_Dir')
#Mutual information
'''
Definition:
... | nilq/baby-python | python |
from app import db
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
login = db.Column(db.String(64), index=True, unique=True)
email = db.Column(db.String(120), index=True, unique=True)
password = db.Column(db.String(120))
last_login = db.Column(db.TIMESTAMP)
def get_id(self):... | nilq/baby-python | python |
import tensorflow as tf
def sample_gumbel(shape, eps=1e-20):
"""Sample from Gumbel(0, 1)"""
U = tf.random_uniform(shape,minval=0,maxval=1)
return -tf.log(-tf.log(U + eps) + eps)
def gumbel_softmax_sample(logits, temperature):
""" Draw a sample from the Gumbel-Softmax distribution"""
y = logits + s... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
'''
Tests neo_utils.core.
@author: Pierre Thibault (pierre.thibault1 -at- gmail.com)
@license: MIT
@since: 2010-11-10
'''
__docformat__ = "epytext en"
import unittest
from neo_utils.core import count
from neo_utils.core import every
from neo_utils.core import inverse_linked_list
from neo_ut... | nilq/baby-python | python |
###############################################################################
#
# The MIT License (MIT)
#
# Copyright (c) Tavendo GmbH
#
# 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 with... | nilq/baby-python | python |
#!/usr/bin/env python3
"""
Created on Fri Sep 20 12:37:07 2019
@author: mikhail-matrosov
"""
from pycoercer.basic_validator import BasicValidator
class Options():
def __init__(self,
allow_unknown=True,
purge_unknown=False,
require_all=False,
br... | nilq/baby-python | python |
""" owns all PlaybackController AVS namespace interaction
https://developer.amazon.com/public/solutions/alexa/alexa-voice-service/reference/playbackcontroller
"""
from __future__ import unicode_literals
class PlaybackController(object):
""" owns all PlaybackController AVS namespace interaction """
def _... | nilq/baby-python | python |
import logging
import json
import jsonpickle
from tqdm.autonotebook import tqdm
from seml.database import get_collection
from seml.settings import SETTINGS
States = SETTINGS.STATES
__all__ = ['get_results']
def parse_jsonpickle(db_entry):
import jsonpickle.ext.numpy as jsonpickle_numpy
jsonpickle_numpy.re... | nilq/baby-python | python |
from airflow.decorators import dag
from airflow.providers.airbyte.operators.airbyte import AirbyteTriggerSyncOperator
from airflow.providers.airbyte.sensors.airbyte import AirbyteJobSensor
from airflow.utils.dates import days_ago
@dag(start_date=days_ago(1), schedule_interval=None, tags=["example"])
def airbyte():
... | nilq/baby-python | python |
class Solution:
def partitionLabels(self, S):
"""
:type S: str
:rtype: List[int]
"""
idxes = dict(zip(S, range(len(S))))
ans, left, right = [], 0, 0
for i, ch in enumerate(S):
right = max(right, idxes[ch])
if right == i:
... | nilq/baby-python | python |
from typing import AnyStr
from typing import Union
from typing import Type
from nezzle.graphics.edges.baseedge import BaseEdge
from nezzle.graphics.edges.edgefactory import EdgeClassFactory
class EdgeConverter(object):
@staticmethod
def convert(edge: BaseEdge, edge_type: Union[Type, AnyStr]):
if is... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
import re
import os
class Config:
src = 'src/WS101.md'
dest = 'WS101.md'
pattern = '{{import\((.+)\)}}'
def import_resource(match):
if not match:
return ''
path = match.groups()[0]
return ('# file: ' + path + '\n' +
'# ' + ('-' * (6 + len(path)... | nilq/baby-python | python |
"""Public API for yq"""
load("//lib/private:yq.bzl", _is_split_operation = "is_split_operation", _yq_lib = "yq_lib")
_yq_rule = rule(
attrs = _yq_lib.attrs,
implementation = _yq_lib.implementation,
toolchains = ["@aspect_bazel_lib//lib:yq_toolchain_type"],
)
def yq(name, srcs, expression = ".", args = []... | nilq/baby-python | python |
"""The output package contains the various output modules."""
from pathlib import Path
from typing import Any, Optional, Tuple
from tunable import Selectable, Tunable
from ..simulation.simulator import World
ShapeType = Tuple[int, int]
def ensure_path(path: str) -> str:
"""
Ensures that the parent director... | nilq/baby-python | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
##
# Copyright (C) Benjamin D. McGinnes, 2013-2018
# ben@adversary.org
# OpenPGP/GPG key: 0x321E4E2373590E5D
#
# Version: 0.1.2
#
# BTC: 1KvKMVnyYgLxU1HnLQmbWaMpDx3Dz15DVU
#
#
# Requirements:
#
# * Python 3.4 or later.
# * GPGME 1.10.0 or later with Python bindings.
#... | nilq/baby-python | python |
# temp.py
import os
import time
import RPi.GPIO as GPIO
import Adafruit_DHT as dht
sensor = dht.DHT11
temp_pin =4
red= 17
green= 27
GPIO.setmode(GPIO.BCM)
GPIO.setup(green, GPIO.OUT, initial=GPIO.LOW)
GPIO.setup(red,GPIO.OUT,initial=GPIO.LOW)
GPIO.setwarnings(False)
def printTemp():
h, t = dht.r... | nilq/baby-python | python |
import re
from datetime import datetime
from unittest.mock import patch
import pytest
from requests import Response
from requests.exceptions import RequestException
from http_nudger.monitor import url_check
URL = "https://google.com"
@pytest.fixture
def http_response():
resp = Response()
resp.status_code =... | nilq/baby-python | python |
import numpy as np
from itertools import combinations
from sklearn import gaussian_process
from from_fits import create_image_from_fits_file
from simulations import simulate
# First find best NCLEAN using cv_cc.py
# Plot covariance matrix of the residuals (not difmap, but, probably, AIPS?)
# Plot covariogramm, GP f... | nilq/baby-python | python |
def app_data_preparation(file_list, lock_period, impute):
'''
recieves file list of data file names/paths in a certain order:
1) icp das
2) metering devices
3) SVO
4) VDNH
5) COVID
6) self-isolation index
lock_period - can be specified as tuple (start date, edn date)in case new lock... | nilq/baby-python | python |
"""
Boronic Acid Factory
====================
"""
from ..functional_groups import BoronicAcid
from .functional_group_factory import FunctionalGroupFactory
from .utilities import _get_atom_ids
class BoronicAcidFactory(FunctionalGroupFactory):
"""
Creates :class:`.BoronicAcid` instances.
Creates function... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
Created on Sat Feb 2 10:36:23 2019
@author: Bahman
"""
import csv
import math
import numpy as np
import random
from matplotlib import pyplot as plt
def readMyCSVData(fileName):
with open(fileName, 'r') as csvfile:
reader = csv.reader(csvfile, delimiter=',')
... | nilq/baby-python | python |
from opendc.models.scenario import Scenario
from opendc.models.portfolio import Portfolio
from opendc.util.rest import Response
def GET(request):
"""Get this Scenario."""
request.check_required_parameters(path={'scenarioId': 'string'})
scenario = Scenario.from_id(request.params_path['scenarioId'])
... | nilq/baby-python | python |
from pdb_util import get_interatomic_distance
from gcd_pdb import read_pdb
from pdb_parsing_tools import get_resname, get_atom, isatom
# rename atoms of a particular residue according to a pair of templates
def rename_atoms_of_selected_residue(
pdbfile, resname, template_pdb_start, template_pdb_target, newfilename):... | nilq/baby-python | python |
__author__ = "Alex Rudy"
__version__ = "0.6.0"
| nilq/baby-python | python |
from datetime import datetime
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore
from apscheduler.executors.pool import ProcessPoolExecutor
from .models import Timelapse
from . import appbuilder
import cv2
import os
HOST_URL = appbuilder.ap... | nilq/baby-python | python |
# Given a string and a pattern, find all anagrams of the pattern in the given string.
# Anagram is actually a Permutation of a string.
# Example:
# Input: String="ppqp", Pattern="pq"
# Output: [1, 2]
# Explanation: The two anagrams of the pattern in the given string are "pq" and "qp".
# Input: String="abbcabc", Patte... | nilq/baby-python | python |
import numpy as np
import imageio
import cv2
import sys, os
#Processing Original Image
def process_img(location_img):
image = imageio.imread(location_img)
image = image.astype(np.float32)/255
return image
#Load and construct Ground Truth
def read_gt(location_gt):
entries = os.listdir(location_gt... | nilq/baby-python | python |
import os
import urllib
from google.appengine.api import users
from google.appengine.ext import ndb
import jinja2
import webapp2
JINJA_ENVIRONMENT = jinja2.Environment(
loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),
extensions=['jinja2.ext.autoescape'],
autoescape=True)
class HomePageHandler(webapp... | nilq/baby-python | python |
import typing as t
from dataclasses import (
InitVar,
dataclass,
field,
)
from .container import (
DIContext,
get_di_container,
)
from .errors import (
ConfigError,
DIErrors,
)
@dataclass(frozen=True)
class Inject:
"""
A class that can serve as:
* a descriptor for a `Comp... | nilq/baby-python | python |
#!/usr/bin/env python
import sys
from os import path, makedirs
from argparse import ArgumentParser
import pickle
import math
from random import sample
import numpy as np
from time import time
from scipy.signal import gaussian
from skimage import io
from skimage.feature import ORB, match_descriptors, plot_matches
fro... | nilq/baby-python | python |
from typing import List, Dict
from .exceptions import ProductsNotFound
from .interfaces import CartProduct
from ...repositories.interfaces import AbstractRepository
def dict_to_products(
requested_products: List[Dict], product_repository: AbstractRepository
) -> List[CartProduct]:
requested_ids = {p["id"] fo... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# <nbformat>3.0</nbformat>
# <codecell>
from pandas import *
import os, os.path
import sys
sys.path.append('/home/will/HIVReportGen/AnalysisCode/')
# <codecell>
store = HDFStore('/home/will/HIVReportGen/Data/SplitRedcap/2013-01-16/EntireCohort.hdf')
# <codecell>
redcap_data = store['redc... | nilq/baby-python | python |
# Copyright (c) 2017 Niklas Rosenstein
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, ... | nilq/baby-python | python |
from __future__ import annotations
import toolsql
contract_creation_blocks_schema: toolsql.DBSchema = {
'tables': {
'contract_creation_blocks': {
'columns': [
{
'name': 'address',
'type': 'Text',
'primary': True,
... | nilq/baby-python | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from argparse import ArgumentParser
from gspread import authorize
from json import dumps
from oauth2client.service_account import ServiceAccountCredentials
from copy import deepcopy
prefix_github = 'https://github.com/'
prefix_mirror = 'FIWARE-GEs/'
scope = ['https://spr... | nilq/baby-python | python |
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
import models.spiking_util as spiking
"""
Relevant literature:
- Zenke et al. 2018: "SuperSpike: Supervised Learning in Multilayer Spiking Neural Networks"
- Bellec et al. 2020: "A solution to the learning dilemma for recurrent networks ... | nilq/baby-python | python |
################################################################################
# Project : AuShadha
# Description : Surgical History Views
# Author : Dr.Easwar T.R
# Date : 16-09-2013
# License : GNU-GPL Version 3,Please see AuShadha/LICENSE.txt for details
##################################... | nilq/baby-python | python |
"""First_Django_Project URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home'... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
""" ADDL: Alzheimer's Disease Deep Learning Tool
Preprocess Pipeline:
Required arguments:
-P, --preprocess Data preprocess pipeline flag
--P_input_data_dir P_INPUT_DATA_DIR
Input directory containing original NIfTI files
--P_t... | nilq/baby-python | python |
from .serverless import ServerlessHandler
| nilq/baby-python | python |
#!/usr/bin/env python
#Script in dev for send commands to multiple switches at once through Telnet.
import telnetlib
import time
TELNET_PORT = 23
TELNET_TIMEOUT = 6
def send_command(remote_conn, cmd):
cmd = cmd.rstrip()
remote_conn.write(cmd + '\n')
time.sleep(6)
return remote_conn.read_very_eager()... | nilq/baby-python | python |
# Importar librería
import os
# Declaracion de variables
clientes = []
numCuentas = 0
opcion = 0
# Declaración de métodos
def crearCuenta(clientes):
global numCuentas
# Con este método se crea una cuenta bancaria
nombre = input('Introduzca nombre: ')
apellido = input('Introduzca apellido: ')
# Se crea lista ... | nilq/baby-python | python |
from kedro.pipeline import Pipeline
from kedro_mlflow.pipeline.pipeline_ml import PipelineML
def pipeline_ml(
training: Pipeline, inference: Pipeline, input_name: str = None,
) -> PipelineML:
pipeline = PipelineML(
nodes=training.nodes, inference=inference, input_name=input_name
)
return pipe... | nilq/baby-python | python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#http://www.cnblogs.com/way_testlife/archive/2011/04/17/2019013.html
import Image
im = Image.open("a.jpg")
#分别打印图片的原格式,高和宽的数组、颜色模式
print im.format, im.size, im.mode
#显示图片
im.show()
| nilq/baby-python | python |
# ----------------------------------
# CLEES DirectControl
# Author : Tompa
# ----------------------------------
# --- General libs
import json
# --- Private Libs
import clees_mqtt
# VAR ---
Dircntl = []
Repmsg = []
def init():
global Dircntl
global Repmsg
with open... | nilq/baby-python | python |
from flask import Flask, request, jsonify
import json
import requests
import shutil
import logging
import boto3
from botocore.exceptions import ClientError
import os
from flask_sqlalchemy import SQLAlchemy
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
from datetime import datetime
... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
Created on Tue May 29 11:23:10 2018
@author: eemeg
"""
def ICASAR(n_comp, spatial_data = None, temporal_data = None, figures = "window",
bootstrapping_param = (200,0), ica_param = (1e-4, 150), tsne_param = (30,12), hdbscan_param = (35,10),
out_folder = '... | nilq/baby-python | python |
#!/usr/bin/env python3
"""
Aggregate machine ads into time bins by site
"""
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
import elasticsearch
import elasticsearch_dsl as edsl
import datetime
import dateutil
import re
import logging
import time
from urllib.parse import urlparse, urlunparse
def ... | nilq/baby-python | python |
# file: asynchronous-inquiry.py
# auth: Albert Huang <albert@csail.mit.edu>
# desc: demonstration of how to do asynchronous device discovery by subclassing
# the DeviceDiscoverer class
# $Id: asynchronous-inquiry.py 405 2006-05-06 00:39:50Z albert $
#
# XXX Linux only (5/5/2006)
import bluetooth
import select
c... | nilq/baby-python | python |
#!/usr/bin/env python
from pyspark.sql import SparkSession
from pyspark.sql.functions import col, window, asc, desc, lead, lag, udf, hour, month, stddev, lit
from pyspark.sql.window import Window
from pyspark.sql.types import FloatType, IntegerType, DateType
from pyspark import SparkConf
import yaml
import datetime
imp... | nilq/baby-python | python |
from django.core.exceptions import ValidationError
from cyder.base.tests import ModelTestMixin
from cyder.core.ctnr.models import Ctnr
from cyder.core.system.models import System
from cyder.cydhcp.constants import STATIC
from cyder.cydhcp.interface.static_intr.models import StaticInterface
from cyder.cydhcp.network.mo... | nilq/baby-python | python |
"""
This file is part of the opendrive-beamng project.
--------------------------------------------------------------------------------
Server class - deals with initialization, configuring of the environment, sim
launch and socket comms.
Notes:
- Set `BNG_HOME` env variable to beamNG.tech path
TODO:
- Swit... | nilq/baby-python | python |
import discord
import gspread
from discord.ext import commands
from oauth2client.service_account import ServiceAccountCredentials
from gspread.exceptions import CellNotFound
class Gsheets:
@classmethod
def start(cls):
"""Starts gsheets API instance."""
scope = ['https://spreadsheets.google.com... | nilq/baby-python | python |
import sys
import os
import numpy as np
import time
from PIL import Image
APS = 100;
TileFolder = sys.argv[1] + '/';
heat_map_out = 'patch-level-color.txt';
def whiteness(png):
wh = (np.std(png[:,:,0].flatten()) + np.std(png[:,:,1].flatten()) + np.std(png[:,:,2].flatten())) / 3.0;
return wh;
def blackness(p... | nilq/baby-python | python |
# see: https://github.com/gabrielfalcao/HTTPretty/issues/242#issuecomment-160942608
from httpretty import HTTPretty as OriginalHTTPretty
try:
from requests.packages.urllib3.contrib.pyopenssl \
import inject_into_urllib3, extract_from_urllib3
pyopenssl_override = True
except:
pyopenssl_override = Fa... | nilq/baby-python | python |
import contextlib
import random
import time
from sorting import (
bubble_sort,
selection_sort,
insertion_sort,
merge_sort,
)
@contextlib.contextmanager
def timeit(name):
start = time.time()
yield
end = time.time()
took = end - start
print(f"The {name} took {took:.4f}s")
def near... | nilq/baby-python | python |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
from TreeNode import *
class Solution:
def recoverFromPreorder(self, S: str) -> TreeNode:
s = S.split("-") # s = ['1... | nilq/baby-python | python |
# Generated by Django 3.0.2 on 2020-01-12 12:02
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('newshows', '0002_setting_profile'),
]
operations = [
migrations.AddField(
model_name='setting',
name='... | nilq/baby-python | python |
import requests
import json
#Assignment Object
#Properties: TOKEN, id, name, description, created_at, updated_at, due_at
#Functions:
class Assignment:
def __init__(self, TOKEN, assignment_id, assignment_name, assignment_description, assignment_created_at, assignment_updated_at, assignment_due_at):
self.TO... | nilq/baby-python | python |
""" Cisco_IOS_XR_ethernet_lldp_oper
This module contains a collection of YANG definitions
for Cisco IOS\-XR ethernet\-lldp package operational data.
This module contains definitions
for the following management objects\:
lldp\: Link Layer Discovery Protocol operational data
Copyright (c) 2013\-2016 by Cisco Syste... | nilq/baby-python | python |
from flask import json
from tests.test_case import *
from app import constants
from app.events.dao import users_dao as ud
from app.events.dao import applications_dao as ad
class AppsTestCase(TestCase):
def setUp(self):
super(AppsTestCase, self).setUp()
Application.query.delete()
db_session_commit()
de... | nilq/baby-python | python |
#!/usr/bin/env python
# -*-coding:utf-8-*-
from os.path import expanduser
home = expanduser("~")
orig_content = file(home + "/github/luiti/luiti/README.markdown").read()
layout_content = """
---
layout: default
title: Home
note: This file is auto generated by /tools/generate_document_guide_page.py, dont modify this f... | nilq/baby-python | python |
#In this problem we have to state the count of rotations a sorted array has
#gone through.
# For Ex:
# 4 5 6 1 2 3 4
# The above array has gone through 3 rotations
n=int(input("Enter the length of the array:\n"))
arr=[]
#taking input
for i in range(0,n):
print("Element",i+1)
ele = int(input(... | nilq/baby-python | python |
from .Common import *
from .chars import (
Header,
InitStrFormat,
InitStrFormatContainDummy,
GoalStrFormat,
InitActionStateUpdateFormat,
InitActionTimesUpdateFormat,
HandsPosition,
EndPose,
InitState,
SpecialDomainHeadStr,
SpecialFuncAndPreStr,
SpecialActionStr,
initA... | nilq/baby-python | python |
import logging
import os
from faucetconfrpc.faucetconfrpc_client_lib import FaucetConfRpcClient
from poseidon_core.helpers.config import yaml_dump
class EmptyFaucetConf(Exception):
pass
class FaucetRemoteConfGetSetter:
DEFAULT_CONFIG_FILE = ''
def __init__(self, client_key=None, client_cert=None,
... | nilq/baby-python | python |
import json
import logging
import re
import sys
from pathlib import Path
from typing import List, Optional
import requests
from slugify import slugify
from kadenze_dl.models import Session, Video
logger = logging.getLogger("utils")
logger.addHandler(logging.StreamHandler(sys.stdout))
logger.setLevel(logging.INFO)
f... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.29 on 2020-07-20 00:14
from __future__ import unicode_literals
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
... | nilq/baby-python | python |
# """Test Classification Manager Module."""
# import pytest
# from geniepy.errors import ClassifierError
# import geniepy.datamgmt.daos as daos
# import geniepy.datamgmt.repositories as dr
# from geniepy.datamgmt.tables import PUBMED_PROPTY, CTD_PROPTY, CLSFR_PROPTY
# from geniepy.datamgmt import DaoManager
# from geni... | nilq/baby-python | python |
from flask import render_template
from app import app
from .request import get_sources,get_news
# from .models import Source,Article
# from .request import get_news
@app.route('/')
def index():
'''
View root page function that returns the index page and its data
'''
# Getting popular news
tit... | nilq/baby-python | python |
"""Run a system command in its own working directory."""
# =============================================================================
# CONTENTS
# -----------------------------------------------------------------------------
# phlsys_workingdircommand
#
# Public Classes:
# CommandWithWorkingDirectory
#
# ---------... | nilq/baby-python | python |
"""Retrieve the path of the parent module to dynamically build the name of FastAPI app."""
import pathlib
parent_module = pathlib.Path(__file__).parent.name
| nilq/baby-python | python |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
import dials_data
import dials_data.datasets
import dials_data.download
import mock
def test_all_datasets_can_be_parsed():
assert dials_data.datasets.definition
def test_repository_location():
rl = dials_data.datasets... | nilq/baby-python | python |
# Generated from IEC61131Parser.g4 by ANTLR 4.9.1
from antlr4 import *
from io import StringIO
from typing.io import TextIO
import sys
def serializedATN():
with StringIO() as buf:
buf.write("\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\2\u0118")
buf.write("\u0a1a\b\1\4\2\t\2\4\3\t\3\4\4\t\4... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_quickD3map
----------------------------------
Tests for `quickD3map` module.
"""
import nose.tools as nt
from nose.tools import raises
import pandas as pd
import numpy as np
from itertools import combinations
import geojson
from quickD3map import PointMap, LineM... | nilq/baby-python | python |
# Copyright Contributors to the Packit project.
# SPDX-License-Identifier: MIT
from enum import Enum
from logging import getLogger
logger = getLogger(__name__)
class TaskName(str, Enum):
copr_build_start = "task.run_copr_build_start_handler"
copr_build_end = "task.run_copr_build_end_handler"
copr_build ... | nilq/baby-python | python |
from collections import Mapping
from colorama import Fore, Style
def log(msg):
print("{}{}".format(Style.RESET_ALL, msg))
def log_highlight(msg):
print("{}{}".format(Fore.GREEN, msg))
def info(msg):
print("{}[INFO] {}".format(Fore.CYAN, msg))
def warn(msg):
print("{}[WARN] {}".format(Fore.YELLOW, msg))
de... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from openelevationservice import SETTINGS
from openelevationservice.server.api import api_exceptions
from openelevationservice.server.utils import logger, convert, codec
from openelevationservice.server.api import querybuilder, validator
from openelevationservice.server.api.response import Resp... | nilq/baby-python | python |
from bs4 import BeautifulSoup
import requests
#
def parse_a_website(url) -> BeautifulSoup:
response = requests.get(url)
data = response.text
soup = BeautifulSoup(data, 'html.parser')
return soup
| nilq/baby-python | python |
from sqlalchemy.sql.functions import func
from model.db import db
import json
from controller.logicTopoBasin import LogicTopoBasin
from controller.logicTopoLivingArea import LogicTopoLivingArea
from controller.logicTopoAgricultureArea import LogicTopoAgricultureArea
from controller.logicTopoWaterwork import LogicTopoWa... | nilq/baby-python | python |
# coding: utf-8
# In[3]:
import cv2
import numpy as np
import sys
sys.path.append('../')
from Mod.utils import *
from tqdm import tqdm
# In[4]:
def py_nms(dets,thresh):
'''剔除太相似的box'''
x1 = dets[:, 0]
y1 = dets[:, 1]
x2 = dets[:, 2]
y2 = dets[:, 3]
scores = dets[:, 4]
areas = (x2 -... | nilq/baby-python | python |
from flask import render_template
from flask_login import login_required
from .blueprint import web
@web.route("/")
def index():
return render_template("index.html")
@web.route("/customer")
@login_required
def customer():
return render_template("customer.html")
| nilq/baby-python | python |
from peewee import *
from cdm_souffleur.model.baseModel import BaseModel
class mapped_concept(BaseModel):
id = AutoField()
name = CharField()
codes_and_mapped_concepts = TextField()
username = CharField()
created_on = DateTimeField() | nilq/baby-python | python |
#coding=utf-8
'''
Created on 2016年3月3日
'''
import zmq
from exception import UnimplementedException, Zmqf404
import logging
import json
__author__ = 'chenjian'
class ZmqfPattern(object):
'''
'''
MPBS = 'MPBS'# Multi Publisher -- Broker -- Multi Subscriber
class ZmqfApplication(object):
'''
cla... | nilq/baby-python | python |
from django import forms
from . import models
from ..base.forms import SentryProjectInput
from ..checklists.forms import TagInput
from ..repos.forms import RepoInput
class ServiceForm(forms.ModelForm):
class Meta:
model = models.Service
fields = [
"owner",
"name",
... | nilq/baby-python | python |
from functools import partial
from itertools import chain
from typing import (Optional,
Sequence)
from clipping.planar import (complete_intersect_multisegment_with_polygon,
complete_intersect_polygons,
complete_intersect_regions,
... | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.