content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
# -*- coding: utf-8 -*-
"""
Created on Wed May 27 20:06:01 2015
@author: Thomas
"""
# Python standard library imports
import csv
import os
def main():
costs = []
for file in os.listdir("reformatted/"):
print 'getting data from.. ' + file
cost_total = []
cost_2000 = []
... | nilq/baby-python | python |
class SveaException(Exception):
pass
class MissingFiles(SveaException):
pass
class DtypeError(SveaException):
pass
class PathError(SveaException):
pass
class PermissionError(SveaException):
pass
class MissingSharkModules(SveaException):
pass
| nilq/baby-python | python |
from __future__ import print_function
import yaml
from cloudmesh.common.util import path_expand
from cloudmesh.shell.command import PluginCommand
from cloudmesh.shell.command import command, map_parameters
from cloudmesh.openapi3.function.server import Server
from cloudmesh.common.console import Console
from cloudmes... | nilq/baby-python | python |
#! /usr/bin/env python
"""
Author: Scott H. Hawley
Based on paper,
A SOFTWARE FRAMEWORK FOR MUSICAL DATA AUGMENTATION
Brian McFee, Eric J. Humphrey, and Juan P. Bello
https://bmcfee.github.io/papers/ismir2015_augmentation.pdf
"""
from __future__ import print_function
import numpy as np
import librosa
from random impo... | nilq/baby-python | python |
text = input()
for index, letter in enumerate(text):
if letter == ":":
print(letter + text[index + 1])
| nilq/baby-python | python |
class Node:
def __init__(self, val):
self.val = val
self.left = left
self.right = right
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
| nilq/baby-python | python |
import argparse
import datetime
import fnmatch
import os
import pickle
import re
from time import time
from typing import List
import tensorflow.keras
import numpy
import numpy as np
from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint, ReduceLROnPlateau, TensorBoard
from tensorflow.keras.preprocessin... | nilq/baby-python | python |
lst = ["A","guru","sabarish","kumar"]
last=lst[-1]
length=0
for i in lst:
length=length+1
if i == last:
break
print("The length of list :",length)
| nilq/baby-python | python |
def dp(n, k):
if | nilq/baby-python | python |
# Copyright (c) nexB Inc. and others. All rights reserved.
# http://nexb.com and https://github.com/nexB/vulnerablecode/
# The VulnerableCode software is licensed under the Apache License version 2.0.
# Data generated with VulnerableCode require an acknowledgment.
#
# You may not use this software except in compliance ... | nilq/baby-python | python |
#!/usr/bin/env python3
# encoding: utf-8
import re
import torch.nn.functional as F
import torch.utils.model_zoo as model_zoo
from collections import OrderedDict
import torch
import torch.nn as nn
import math
import numpy as np
import time
import os
import sys
import torchvision
#__all__ = ['DenseNet121','DenseNet169... | nilq/baby-python | python |
from django.apps import AppConfig
class BizcontactsConfig(AppConfig):
name = 'bizcontacts'
| nilq/baby-python | python |
'''
--- Day 9: Encoding Error ---
With your neighbor happily enjoying their video game, you turn your attention to an open data port on the little screen in the seat in front of you.
Though the port is non-standard, you manage to connect it to your computer through the clever use of several paperclips. Upon conn... | nilq/baby-python | python |
import os
import subprocess
import unittest
from fs import open_fs
from celery import Celery, group
import magic
from fs.copy import copy_file
from parameterized import parameterized
app = Celery('test_generators')
app.config_from_object('unoconv.celeryconfig')
app.conf.update({'broker_url': 'amqp://guest:guest@local... | nilq/baby-python | python |
from .base import BaseDocument
import markdown
import html_parser
class MarkdownDocument(BaseDocument):
def __init__(self, path):
self.path = path
def read(self):
self.document = open(self.path, "r")
text = self.document.read()
html = markdown.markdown(text)
return html_parser.html_to_text(html)
def c... | nilq/baby-python | python |
while True:
try:
string = input()
print(string)
except EOFError:
break | nilq/baby-python | python |
# Eerst met PCA. Deze resulteert nu in 3 coponenten, waarvoor je dus twee plot nodig hebt
pca = PCA()
pcas = pca.fit_transform(X)
fig = plt.figure(figsize=(15, 8))
ax = fig.add_subplot(121)
plt.scatter(pcas[:, 0], pcas[:, 1], c=color, cmap=plt.cm.Spectral)
ax = fig.add_subplot(122)
plt.scatter(pcas[:, 2], pcas[:, 1], c... | nilq/baby-python | python |
# Copyright (c) 2019 Dan Ryan
# MIT License <https://opensource.org/licenses/mit>
from __future__ import absolute_import, unicode_literals
import collections
import csv
import io
import pathlib
import sqlite3
import tempfile
import uuid
from typing import Any, Dict, Generator, List, Optional, Set, Tuple, Union
impor... | nilq/baby-python | python |
import abc
import flask
from flask import jsonify, make_response
from ..app.swagger_schema import Resource, Schema
from ..extensions.audit import AuditLog
from ..logger.app_loggers import logger
from ..swagger import AfterResponseEventType, BeforeRequestEventType, BeforeResponseEventType
class ResourceResponse:
... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
Module for common converters settings and functions
"""
import os
from config import log, root_directory, DEFAULT_LANGUAGE
def db_get_statistic(models_list):
"""
:return:
"""
log.info("Start to get statistic of imported items:")
[log.info("%s: %s", model.__name__, mode... | nilq/baby-python | python |
from django.conf.urls import url
from django.contrib.auth.views import logout
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^change_city/$', views.change_city, name='change_city'),
url(r'^parse/$', views.parse, name='parse'),
url(r'^logout/$', logout, {'next_page': ... | nilq/baby-python | python |
max_n1 = int(input())
max_n2 = int(input())
max_n3 = int(input())
for num1 in range(2, max_n1 + 1, 2):
for num2 in range(2, max_n2 + 1):
for num3 in range(2, max_n3 + 1, 2):
if num2 == 2 or num2 == 3 or num2 == 5 or num2 == 7:
print(f"{num1} {num2} {num3}") | nilq/baby-python | python |
from typing import Callable, Dict, Tuple, Any
__all__ = ['HandlerResponse', 'Handler']
HandlerResponse = Tuple[int, Dict[str, str], str]
Handler = Callable[[Dict[str, Any], Dict[str, str]], HandlerResponse]
| nilq/baby-python | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2020 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless requi... | nilq/baby-python | python |
import sys
# cyheifloader allows specifying the path to heif.dll on Windows
# using the environment variable LIBHEIF_PATH.
from cyheifloader import cyheif
from PIL import Image
from PIL.ExifTags import TAGS
# Print libheif version
print(f'LibHeif Version: {cyheif.get_heif_version()}')
file_name = sys.ar... | nilq/baby-python | python |
from bibliopixel.animation.matrix import Matrix
try:
from websocket import create_connection
except ImportError:
create_connection = None
import threading
import numpy as np
WS_FRAME_WIDTH = 640
WS_FRAME_HEIGHT = 480
WS_FRAME_SIZE = WS_FRAME_WIDTH * WS_FRAME_HEIGHT
def clamp(v, _min, _max):
... | nilq/baby-python | python |
import os
import json
from pathlib import Path
import yaml
import unittest
import click
from click.testing import CliRunner
os.environ['QA_TESTING'] = 'true'
# Missing:
# - tests with --share
# - tests with CI=ON CI_COMMIT=XXXXXX
class TestQaCli(unittest.TestCase):
@classmethod
def setUpClass(self):
self.p... | nilq/baby-python | python |
ASCII_MAZE = """
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
S | | | | | |
+-+ + +-+-+ + + + + +-+ + + +-+-+-+ + + +
| | | | | | | | | | | | | | |
+ + +-+ + +-+ + +-+-+ +-+-+ +-+-+ + + + +
| | | | | | | |
+-+-+-+-+-+ +-+-+ +-+ +-+-+ +-+-+-+-+-+ +
| | ... | nilq/baby-python | python |
from Instruments.devGlobalFunctions import devGlobal
class CounterClass(devGlobal):
# Human readable name for the gui, note: Needs to be unique
name = "Counter"
def __init__(self, *args):
devGlobal.__init__(self, *args)
self.func_list = self.func_list + [
self.C... | nilq/baby-python | python |
from . import config
from .genome import Genome
class Population():
def __init__(self, default=True):
self.genomes = []
self.speciesRepresentatives = []
self.species = 0
if default:
self.initialize()
def initialize(self):
for i in range(config.populationSiz... | nilq/baby-python | python |
from __future__ import print_function
import setuptools
import sys
# Convert README.md to reStructuredText.
if {'bdist_wheel', 'sdist'}.intersection(sys.argv):
try:
import pypandoc
except ImportError:
print('WARNING: You should install `pypandoc` to convert `README.md` '
'to reSt... | nilq/baby-python | python |
# Module to describe all the potential commands that the Renogy Commander
# supports.
#
# Author: Darin Velarde
#
#
from collections import namedtuple
# I typically don't like import * but I actually need every symbol from
# conversions.
from conversions import *
# Register
# ** immutable data type **
# Represents ... | nilq/baby-python | python |
# 视觉问答模型
from keras.layers import Conv2D, MaxPooling2D, Flatten
from keras.layers import Input, LSTM, Embedding, Dense
from keras.models import Model, Sequential
import keras
# First, let's define a vision model using a Sequential model.
# This model will encode an image into a vector.
vision_model = Sequential()
visi... | nilq/baby-python | python |
# Generated by Django 3.1.3 on 2020-12-07 23:51
from django.db import migrations, models
import django.db.models.deletion
import django_update_from_dict
class Migration(migrations.Migration):
initial = True
dependencies = [
('users', '0003_auto_20201206_1634'),
]
operations = [
mig... | nilq/baby-python | python |
from django.contrib.auth import logout, authenticate, login
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.core.paginator import Paginator
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import redirect, get_object_or_40... | nilq/baby-python | python |
from typing import Any # NOQA
import optuna
from optuna._experimental import experimental
from optuna._imports import try_import
with try_import() as _imports:
from catalyst.dl import Callback
if not _imports.is_successful():
Callback = object # NOQA
@experimental("2.0.0")
class CatalystPruningCallback(... | nilq/baby-python | python |
#!/usr/bin/python
"""Copyright 2016 Google Inc. 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 l... | nilq/baby-python | python |
import pygame
from Clock import Clock
from Timer import Timer
class TileManager(object):
# Call constructor
def __init__(self, screenWidth, screenHeight, tileWidth, tileHeight, tileImage, tileType):
self.tiles = []
self.tileWidth = tileWidth
self.tileHeight = tileHeight
self.scr... | nilq/baby-python | python |
"""In this module are all SuperCollider Object related classes"""
| nilq/baby-python | python |
# Crie um programa que peça um número ao usuário e retorne se antecessor e o seu sucessor.
print('=-'*7 'DESAFIO 7' ''=-'*7)
n = int(input('Digite um número: '))
print('Analisando o número {}, seu antecessor é {} e seu sucessor é {} '.format(n, n - 1, n + 2))
| nilq/baby-python | python |
import pygame
from pygame.locals import QUIT, K_ESCAPE, K_a, K_d, K_s, K_SPACE
from time import time
from os.path import dirname, realpath
def main():
running, settings = load()
while running:
settings = update(settings)
draw(settings)
running = check_exit(settings)
pygame.quit()
de... | nilq/baby-python | python |
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under... | nilq/baby-python | python |
from vplot import GetOutput
import subprocess as sub
import numpy as np
import os
cwd = os.path.dirname(os.path.realpath(__file__))
import warnings
import h5py
import multiprocessing as mp
import sys
import bigplanet as bp
def test_bpstats():
#gets the number of cores on the machine
cores = mp.cpu_count()
... | nilq/baby-python | python |
import cv2
import pickle
import face_recognition
class recognize:
def __init__(self):
self.data = pickle.loads(open("./encodings.pickle", "rb").read())
self.detector = cv2.CascadeClassifier("./haarcascade_frontalface_default.xml")
def recognize_face(self, frame):
gray = cv2.cv... | nilq/baby-python | python |
token = 'BOT-TOKEN'
initial_extensions = ['cogs.general', 'cogs.groups', 'cogs.lights', 'cogs.scenes']
prefix = '>'
owner_only = True
owner_id = DISCORD-USER-ID
bridge_ip = 'BRIDGE-IP' | nilq/baby-python | python |
# --------------
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# code starts here
df = pd.read_csv(path)
total_length = len(df)
print(total_length)
fico = 0
for i in df['fico'] > 700:
fico += i
print(fico)
p_a = fico/total_length
print(round(p_a, 2))
debt = 0
for i in df['purpose'] ==... | nilq/baby-python | python |
import requests, zipfile
import os
import pandas as pd
def gdpimporter(url, filename=None, filetype='csv'):
"""Download the zipped file, unzip, rename the unzipped files, and
outputs a dataframe along with the title from meta data.
This function downloads the zipped data from URL to the local path,
un... | nilq/baby-python | python |
from functools import partial
from typing import Callable, Union
import jax
import jax.numpy as np
from rbig_jax.transforms.histogram import get_hist_params
from rbig_jax.transforms.inversecdf import (
invgausscdf_forward_transform,
invgausscdf_inverse_transform,
)
from rbig_jax.transforms.kde import get_kde_... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
import csv
from collections import defaultdict, namedtuple
from datetime import datetime, timedelta
import pkg_resources
import re
from zipfile import ZipFile
from enum import Enum, unique
from io import TextIOWrapper
Train = namedtuple("Train", ["name", "kind", "direction", "stops", "service_... | nilq/baby-python | python |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
raise Exception('this code should never execute')
| nilq/baby-python | python |
skills = [
{
"id" : "0001",
"name" : "Liver of Steel",
"type" : "Passive",
"isPermable" : False,
"effects" :
{
"maximumInebriety" : "+5",
},
},
{
"id" : "0002",
"name" : "Chronic Indigestion",
"type" : "Combat",
... | nilq/baby-python | python |
from netmiko import ConnectHandler, file_transfer
from getpass import getpass
ios_devices = {
"host": "cisco3.lasthop.io",
"username": "pyclass",
"password": "88newclass",
"device_type": "cisco_ios",
}
source_file = "testTofu.txt"
dest_file = "testTofuBack.txt"
direction = "get"
file_... | nilq/baby-python | python |
#!/usr/bin/env python3
# coding: utf-8
from threading import Thread
from queue import Queue
class TaskQueue(Queue):
def __init__(self, num_workers=1):
super().__init__()
self.num_workers = num_workers
self.start_workers()
def add_task(self, task, *args, **kwargs):
args = args ... | nilq/baby-python | python |
#!/usr/bin/env python
import logging
import os
import shutil
import sys
import tempfile
from io import BytesIO
from itertools import groupby
from subprocess import Popen,PIPE, check_output
import requests
from KafNafParserPy import *
from lxml import etree
from lxml.etree import XMLSyntaxError
from .alpino_dependenc... | nilq/baby-python | python |
import os
import pytest
from packaging import version
from unittest import TestCase
from unittest.mock import patch
from osbot_utils.utils.Dev import pprint
from osbot_utils.utils.Files import temp_folder, folder_files, folder_delete_all, folder_create, file_create_bytes, \
file_contents_as_bytes, file_contents, ... | nilq/baby-python | python |
# Generated by Django 3.1.4 on 2021-11-13 12:20
import datetime
from django.db import migrations, models
from django.utils.timezone import utc
import uuid
class Migration(migrations.Migration):
dependencies = [
('library_app', '0007_auto_20211113_1319'),
]
operations = [
migrations.Alte... | nilq/baby-python | python |
# Original script acquired from https://github.com/adafruit/Adafruit_Python_MCP3008
# Import SPI library (for hardware SPI) and MCP3008 library.
import Adafruit_GPIO.SPI as SPI
import Adafruit_MCP3008
import time
# Hardware SPI configuration:
SPI_PORT = 0
SPI_DEVICE = 0
mcp = Adafruit_MCP3008.MCP3008(spi=SPI.SpiDev... | nilq/baby-python | python |
"""
This component provides basic support for the Philips Hue system.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/hue/
"""
import asyncio
import json
import ipaddress
import logging
import os
import async_timeout
import voluptuous as vol
from homea... | nilq/baby-python | python |
import re
import sys
import boa3
from boa3 import neo
from boa3.constants import SIZE_OF_INT32, SIZE_OF_INT160, DEFAULT_UINT32
from boa3.neo import cryptography
from boa3.neo.utils.serializer import Serializer
from boa3.neo.vm.type.Integer import Integer
class NefFile:
"""
The object encapsulates the informa... | nilq/baby-python | python |
"""
@author: Skye Cui
@file: layers.py
@time: 2021/2/22 13:43
@description:
"""
import tensorflow as tf
class ConvAttention(tf.keras.layers.Layer):
def __init__(self, l, h, w, c, k):
super(ConvAttention, self).__init__()
self.reshape = tf.keras.layers.Reshape((l, w * h * c))
self.layer1 =... | nilq/baby-python | python |
start_case_mutation = """\
mutation startCase($case: StartCaseInput!) {
startCase(input: $case) {
case {
id
}
}
}\
"""
intervalled_forms_query = """\
query allInterForms {
allForms (metaHasKey: "interval") {
pageInfo {
startCursor
endCursor
}
edges {
node {
met... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# pylint: disable=no-self-use, too-many-locals, too-many-arguments, too-many-statements, too-many-instance-attributes
"""Invite"""
import string
import time
import json
from configparser import ConfigParser
import requests
from flask import request
from library.couch_database import Co... | nilq/baby-python | python |
from __future__ import annotations
from dataclasses import dataclass
from dataclasses import field
import boto3
from ..ec2api.vpcs import VPCs
from ..ec2common.ec2exceptions import *
# See vpc notes at the end of this file.
@dataclass
class VPCAttributes:
CidrBlock: str = None
DhcpOptionsId: str = None
... | nilq/baby-python | python |
# coding=utf-8
from particles import Particle
class RectParticle(Particle):
def __init__(self, l):
Particle.__init__(self, l)
# super(RectParticle, self).__init__(l)
rectMode(CENTER)
self.rota = PI/3
def display(self):
stroke(0, self.lifespan)
fill(204... | nilq/baby-python | python |
import pytest
from detect_secrets.core.potential_secret import PotentialSecret
from testing.factories import potential_secret_factory
@pytest.mark.parametrize(
'a, b, is_equal',
[
(
potential_secret_factory(line_number=1),
potential_secret_factory(line_number=2),
T... | nilq/baby-python | python |
"""
Basic shared function to read input data for each problem; the data file
must be in the subdirectory 'input' and with the name '<prog_name>.txt',
where '<prog_name>.py' is the name of the program being run
"""
import inspect
import pathlib
def get_input():
"""
Get input data for currently running program... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Holds fixtures for the smif package tests
"""
from __future__ import absolute_import, division, print_function
import json
import logging
import os
from copy import deepcopy
import numpy as np
import pandas as pd
from pytest import fixture
from smif.data_layer import S... | nilq/baby-python | python |
import os
import sys
from setuptools import setup
if sys.argv[-1] == 'publish':
os.system('python setup.py sdist bdist_wheel')
os.system('python -m twine upload dist/*')
sys.exit()
setup()
| nilq/baby-python | python |
#!/usr/bin/env python3
# Copyright (c) 2020-2022, NVIDIA CORPORATION. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification, are permitted
# provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice... | nilq/baby-python | python |
# Based on https://www.geeksforgeeks.org/get-post-requests-using-python/
# importing
import requests
import time
# defining the api-endpoint
API_ENDPOINT = "https://api.gfycat.com/v1/gfycats"
# your API key here
# API_KEY = "XXXXXXXXXXXXXXXXX"
# your source code here
external_url = input("Please input the externa... | nilq/baby-python | python |
import unittest
from datetime import datetime
from models import *
class Test_UserModel(unittest.TestCase):
"""
Test the user model class
"""
def setUp(self):
self.model = User()
self.model.save()
def test_var_initialization(self):
self.assertTrue(hasattr(self.model, "ema... | nilq/baby-python | python |
"""
Configuration file
"""
__author__ = 'V. Sudilovsky'
__maintainer__ = 'V. Sudilovsky'
__copyright__ = 'ADS Copyright 2014, 2015'
__version__ = '1.0'
__email__ = 'ads@cfa.harvard.edu'
__status__ = 'Production'
__license__ = 'MIT'
SAMPLE_APPLICATION_PARAM = {
'message': 'config params should be prefixed with the... | nilq/baby-python | python |
import asyncio
class ClientServerProtocol(asyncio.Protocol):
metrics = {}
def __init__(self):
# self.metrics = {}
self.spliter = '_#_'
self.ok_message = 'ok\n'
self.error_message = 'error\nwrong command\n\n'
def connection_made(self, transport):
self.transport = t... | nilq/baby-python | python |
__author__ = 'Thomas Rueckstiess, ruecksti@in.tum.de'
from scipy import random, asarray, zeros, dot
from pybrain.structure.modules.neuronlayer import NeuronLayer
from pybrain.tools.functions import expln, explnPrime
from pybrain.structure.parametercontainer import ParameterContainer
class StateDependentLayer(Neuron... | nilq/baby-python | python |
#!/usr/bin/env python
import sys
import time
from ansible.module_utils.forward import *
try:
from fwd_api import fwd
except:
print('Error importing fwd from fwd_api. Check that you ran ' +
'setup (see README).')
sys.exit(-1)
# Module documentation for ansible-doc.
DOCUMENTATION = '''
---
module:... | nilq/baby-python | python |
from django.db.models import ForeignKey
from graphene.utils.str_converters import to_camel_case
# https://github.com/graphql-python/graphene/issues/348#issuecomment-267717809
def get_selected_names(info):
"""
Parses a query info into a list of composite field names.
For example the following query:
... | nilq/baby-python | python |
"""Constants for integration_blueprint tests."""
from custom_components.arpansa_uv.const import CONF_NAME, CONF_LOCATIONS, CONF_POLL_INTERVAL
# Mock config data to be used across multiple tests
MOCK_CONFIG = {CONF_NAME: "test_arpansa", CONF_LOCATIONS: ['Brisbane','Sydney','Melbourne','Canberra'], CONF_POLL_INTERVAL: 1... | nilq/baby-python | python |
import json
from datetime import datetime, timedelta
from email import utils as email_utils
import pytest
from flask.testing import FlaskClient
from sqlalchemy.orm import Session
from app.models.exceptions import NotFound
from app.models.products import Brand, Category, Product, FEATURED_THRESHOLD
def create_basic_... | nilq/baby-python | python |
print('domain.com'.endswith('com'))
| nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Batch-create ownCloud users
"""
__author__ = "Constantin Kraft <c@onstant.in>"
import sys
import argparse
import owncloud
from owncloud.owncloud import HTTPResponseError
import csv
API_URL = ''
# User needs Admin permissions
OC_USER = ''
OC_PASS = ''
oc = owncloud.C... | nilq/baby-python | python |
from chipclock.display import ModeDisplay
from chipclock.modes.clock import ClockMode
from chipclock.renderers.time import render_ascii, render_chip
from chipclock.renderers.segment import setup_pins, render_segment
seconds_pins = [
['LCD-D5', 'LCD-D11'],
['LCD-D4', 'LCD-D10'],
['LCD-D3', 'LCD-D7'],
['LCD-D20'... | nilq/baby-python | python |
from typing import NoReturn, TypeVar, Type
import six
from .avrojson import AvroJsonConverter
TC = TypeVar('TC', bound='DictWrapper')
class DictWrapper(dict):
__slots__ = ['_inner_dict']
def __init__(self, inner_dict=None):
super(DictWrapper, self).__init__()
self._inner_dict = {} if inner_... | nilq/baby-python | python |
"""Functions to simplify interacting with database."""
import datetime as dt
from math import ceil
from bson.objectid import ObjectId
from bson import SON
from motor.motor_asyncio import AsyncIOMotorClient
from pymongo import WriteConcern, IndexModel, ASCENDING, ReturnDocument
def init_db(config, loop):
"""Initi... | nilq/baby-python | python |
#! /usr/bin/env python
#
def timestamp ( ):
#*****************************************************************************80
#
## TIMESTAMP prints the date as a timestamp.
#
# Licensing:
#
# This code is distributed under the GNU LGPL license.
#
# Modified:
#
# 06 April 2013
#
# Author:
#
# John Burkardt
... | nilq/baby-python | python |
"""
Tests for the :module`regression_tests.parsers.c_parser.module` module.
"""
import io
import re
import sys
from textwrap import dedent
from unittest import mock
from regression_tests.utils.list import NamedObjectList
from tests.parsers.c_parser import WithModuleTests
class ModuleTests(WithModuleTests):
... | nilq/baby-python | python |
import types
from operator import add
import sys
from common.functions import permutations, pick_from
COMMON_ENGLISH_WORDS = ['of', 'the', 'he', 'she', 'when', 'if', 'was']
ALPHABET = map(chr, range(ord('a'), ord('z') + 1) + range(ord('A'), ord('Z') + 1))
NUMBERS = set(map(str, range(0, 10)))
SPECIAL_CHARACTERS = {'... | nilq/baby-python | python |
# File name: SIM_SolarSys.py
# Author: Nawaf Abdullah
# Creation Date: 9/October/2018
# Description: numerical simulation of the n-body problem of a solar system
from classicalMech.planet import Planet
import matplotlib.pyplot as plt
# Constants
PI = 3.14159
class System:
def __init__(self, i_ms, i_pla... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
import json
from jinja2.ext import Extension
from jinja2 import nodes
from watson.assets.webpack import exceptions
from watson.common.decorators import cached_property
__all__ = ['webpack']
class WebpackExtension(Extension):
tags = set(['webpack'])
cached_stats = None
@cached_pr... | nilq/baby-python | python |
#:coding=utf8:
import logging
from django.test import TestCase as DjangoTestCase
from django.conf import settings
from jogging.models import Log, jogging_init
class DatabaseHandlerTestCase(DjangoTestCase):
def setUp(self):
from jogging.handlers import DatabaseHandler, MockHandler
import logging... | nilq/baby-python | python |
"""Defines preselections. Currently implements 'loose' and 'tight' strategies."""
from __future__ import annotations
__all__ = ["preselection_mask", "cut_vars"]
from functools import singledispatch
import awkward as ak
import numpy as np
from uproot.behaviors.TTree import TTree
def cut_vars(strength: str) -> list[... | nilq/baby-python | python |
from tutils import Any
from tutils import Callable
from tutils import List
from tutils import Tuple
from tutils import cast
from tutils import concat
from tutils import reduce
from tutils import lmap
from tutils import splitstriplines
from tutils import load_and_process_input
from tutils import run_tests
""" END H... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import __future__
import sys
print("===" * 30)
print("SAMPLE INPUT:")
print("===" * 30)
print(open("./input14.txt", 'r').read())
sys.stdin = open("./input14.txt", 'r')
#print(open("./challenge_sample_input", 'r').read())
#sys.stdin = open("./challenge_sample_input", 'r')
... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
import io
import time
import queue
import socket
import select
import functools
from quickgui.framework.quick_base import time_to_die
class DisconnectedException(Exception):
'''Socket was disconnected'''
pass
class QueueClient():
'''
TCP client for queue-based communication... | nilq/baby-python | python |
import xml4h
import os
import re
import spacy
#doc = xml4h.parse('tests/data/monty_python_films.xml')
#https://xml4h.readthedocs.io/en/latest/
class getData:
def __init__(self, name, path):
self.name = name
self.path = path
self.files = []
# test
self.testfile = None
... | nilq/baby-python | python |
import os
import logging
"""
Provide a common interface for all our components to do logging
"""
def basic_logging_conf():
"""Will set up a basic logging configuration using basicConfig()"""
return basic_logging_conf_with_level(
logging.DEBUG if "MDBRAIN_DEBUG" in os.environ else logging.INFO)
def ... | nilq/baby-python | python |
#!/usr/bin/env python
# coding: utf-8
# This notebook was prepared by [Donne Martin](http://donnemartin.com). Source and license info is on [GitHub](https://github.com/donnemartin/interactive-coding-challenges).
# # Solution Notebook
# ## Problem: Implement a linked list with insert, append, find, delete, length, an... | nilq/baby-python | python |
#!/usr/bin/env python3
import json
import os
import random
random.seed(27)
from datetime import datetime
import sqlalchemy.ext
import traceback
import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
import connexion
impo... | nilq/baby-python | python |
#!/usr/bin/env python2
"""Create GO-Dag plots."""
__copyright__ = "Copyright (C) 2016-2018, DV Klopfenstein, H Tang. All rights reserved."
__author__ = "DV Klopfenstein"
import sys
sys.path.append("/dfs/scratch2/caruiz/code/goatools/")
from goatools.cli.gosubdag_plot import PlotCli
def run():
"""Create GO-Dag ... | nilq/baby-python | python |
# Always prefer setuptools over distutils
from setuptools import setup, find_packages
# To use a consistent encoding
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
# Get the long description from the README file
with open(path.join(here, 'README.rst'), encoding='utf-8') as f:
... | nilq/baby-python | python |
import pytest
from . import constants
from pybible import pybible_load
from pybible.classes.bible import Bible
from pybible.classes.bible_without_apocrypha import BibleWithoutApocrypha
from pybible.classes.book import Book
from pybible.classes.chapter import Chapter
from pybible.classes.verse import Verse
@pytest.fix... | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.