content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
from textwrap import dedent
endc = "\033[0m"
bcolors = dict(
blue="\033[94m",
green="\033[92m",
orange="\033[93m",
red="\033[91m",
bold="\033[1m",
underline="\033[4m",
)
def _color_message(msg, style):
return bcolors[style] + msg + endc
def _message_box(msg, color="green", border="=" * ... | nilq/baby-python | python |
import sys
import subprocess
import gzip
from tqdm import tqdm
def get_lines_count(file_path):
if file_path[-3:] == ".gz":
ps = subprocess.Popen(
f"gzip -cd {file_path} | wc -l", shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
return int(ps.communicate()[0])
else:
... | nilq/baby-python | python |
# convert ERAiterim data from (Claudia Wekerle's) netcdf files to ieee-be
# compute specific humidity from dew point temperature
# unfortunately precipitation and downward radiation are only available
# as daily averages, I don't know why
import numpy as np
import matplotlib.pyplot as plt
from netCDF4 import Dataset
i... | nilq/baby-python | python |
"""
Conversion functions between corresponding data structures.
"""
import json
import logging
from collections import Hashable, OrderedDict # pylint: disable=E0611,no-name-in-module # moved to .abc in Python 3
from copy import deepcopy
from tempfile import TemporaryDirectory
from typing import TYPE_CHECKING
from ur... | nilq/baby-python | python |
# This source code is part of the Biotite package and is distributed
# under the 3-Clause BSD License. Please see 'LICENSE.rst' for further
# information.
__name__ = "biotite.sequence.graphics"
__author__ = "Patrick Kunzmann"
__all__ = ["plot_dendrogram"]
import numpy as np
def plot_dendrogram(axes, tree, orientatio... | nilq/baby-python | python |
import boto3
from trp import Document
# Document
s3BucketName = "ki-textract-demo-docs"
documentName = "expense.png"
# Amazon Textract client
textract = boto3.client('textract')
# Call Amazon Textract
response = textract.analyze_document(
Document={
'S3Object': {
'Bucket': s3BucketName,
... | nilq/baby-python | python |
from itertools import chain
import attr
@attr.s(slots=True, cmp=False)
class KmerDataCollection(object):
_kmers_data = attr.ib()
num_colors = attr.ib(init=False)
_coverage = attr.ib(None)
_edges = attr.ib(None)
raw_kmer = attr.ib(None)
def __attrs_post_init__(self):
assert len(self._... | nilq/baby-python | python |
__author__ = "Frédéric BISSON"
__copyright__ = "Copyright 2022, Frédéric BISSON"
__credits__ = ["Frédéric BISSON"]
__license__ = "mit"
__maintainer__ = "Frédéric BISSON"
__email__ = "zigazou@protonmail.com"
from dietpdf.info.decode_objstm import decode_objstm
def create_stream():
return b"""11 0 12 54 13 107
<</... | nilq/baby-python | python |
import json
import os
from unittest.mock import patch
from django.conf import settings
from django.utils import timezone as djangotime
from model_bakery import baker
from autotasks.models import AutomatedTask
from tacticalrmm.test import TacticalTestCase
class TestAPIv3(TacticalTestCase):
def setUp(self):
... | nilq/baby-python | python |
"""
Copyright 2020 Vitaliy Zarubin
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, softwar... | nilq/baby-python | python |
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use ... | nilq/baby-python | python |
class dtype:
def __eq__(self, other):
return self.__name__ == other.__name__
class complex128(dtype):
precedence = 10
class complex64(dtype):
precedence = 9
class float64(dtype):
precedence = 8
class float32(dtype):
precedence = 7
class float16(dtype):
precedence = 6
# class ... | nilq/baby-python | python |
"""
Global mail object used to send notification emails.
"""
from flask_mail import Mail, Message
from flask import current_app
mail = Mail()
def send_mail(email, output):
"""sends email"""
header = "Your analysis is ready"
content = '''<div style='font-size:14px;'>\
Your requested analysis is r... | nilq/baby-python | python |
import argparse
import sys
from typing import Callable
from typing import List
from typing import Optional
from . import audit
from . import baseline
from . import filters
from . import plugins
from . import scan
from ...settings import get_settings
from .common import initialize_plugin_settings
from detect_secrets.__... | nilq/baby-python | python |
# Copyright 2020 Huawei Technologies Co., Ltd
#
# 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... | nilq/baby-python | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed May 9 02:35:02 2018
@author: elvex
"""
"""Boite à outils de manipulation des base de données de tweets. """
#import json
import pandas as pd
import txt_analysis as TA
from math import log10
from glob import glob
from os.path import abspath
from re im... | nilq/baby-python | python |
from jmetal.algorithm.singleobjective.simulated_annealing import SimulatedAnnealing
from jmetal.operator import PolynomialMutation
from jmetal.problem.bbob import bbob
from jmetal.util.observer import ProgressBarObserver
from jmetal.util.termination_criterion import StoppingByEvaluations
if __name__ == '__main__':
... | nilq/baby-python | python |
"""
Packaging setup for ledcontroller
"""
# pylint: disable=line-too-long
import os.path
from codecs import open as codecs_open
from setuptools import setup
with codecs_open(os.path.join(os.path.abspath(os.path.dirname(__file__)), 'README.rst'), encoding='utf-8') as f:
LONG_DESCRIPTION = f.read()
setup(
na... | nilq/baby-python | python |
'''
实验名称:RTC实时时钟
版本:v1.0
日期:2020.12
作者:01Studio
说明:在LCD上显示时间
社区:www.01studio.org
'''
#导入相关模块
import pyb
from tftlcd import LCD43M
#定义常用颜色
RED = (255,0,0)
GREEN = (0,255,0)
BLUE = (0,0,255)
BLACK = (0,0,0)
WHITE = (255,255,255)
########################
# 构建4.3寸LCD对象并初始化
########################
d = LCD43M(portrait=1)... | nilq/baby-python | python |
from __future__ import division, absolute_import, print_function
from .jdx import jdx_reader, jdx_file_reader, JdxFile
__all__ = ["jdx"]
| nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Copyright (c) 2015, shakeel vaim and Contributors
# See license.txt
from __future__ import unicode_literals
import frappe
import unittest
# test_records = frappe.get_test_records('Add New Properties')
class TestAddNewProperties(unittest.TestCase):
pass
| nilq/baby-python | python |
from datetime import datetime
from city_scrapers_core.spiders import CityScrapersSpider
from dateutil.parser import parse as dateparse
from city_scrapers.mixins.wayne_commission import WayneCommissionMixin
class WayneBuildingAuthoritySpider(WayneCommissionMixin, CityScrapersSpider):
name = "wayne_building_autho... | nilq/baby-python | python |
"""Base segment definitions.
Here we define:
- BaseSegment. This is the root class for all segments, and is
designed to hold other subsegments.
- RawSegment. This is designed to be the root segment, without
any children, and the output of the lexer.
- UnparsableSegment. A special wrapper to indicate that th... | nilq/baby-python | python |
"""客户端查询排行榜"""
from upload import uploading
def rank():
pass | nilq/baby-python | python |
#!/usr/bin/env python
#pylint: disable=C0103
"""
This module provides business object class to interact with
DATASET_ACCESS_TYPES table.
"""
from WMCore.DAOFactory import DAOFactory
from dbs.utils.dbsExceptionHandler import dbsExceptionHandler
class DBSDatasetAccessType:
"""
DatasetAccessType business object ... | nilq/baby-python | python |
# Open3D: www.open3d.org
# The MIT License (MIT)
# See license file or visit www.open3d.org for details
# examples/python/ReconstructionSystem/sensors/realsense_recorder.py
# pyrealsense2 is required.
# Please see instructions in https://github.com/IntelRealSense/librealsense/tree/master/wrappers/python
import pyreal... | nilq/baby-python | python |
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^job-meta/',views.job_meta, name='job_meta'),
url(r'^job-success-failure',views.job_success_failure_ratio, name='job_success_failure_ratio'),
url(r'^$',views.dashboard, name='dashboard'),
] | nilq/baby-python | python |
# Copyright 2008-2018 Univa Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in... | nilq/baby-python | python |
import tweepy # To consume Twitter's API
import pandas as pd # To handle data
import numpy as np # For number computing
from textblob import TextBlob # for sentimental
import re
# For plotting and visualization:
from IPython.display import display
# for display use only import matplotlib.pyplot as... | nilq/baby-python | python |
from sqlalchemy import Column, Integer, String, DateTime, ForeignKey, Table
from sqlalchemy.orm import relationship, backref
from models import db_base as base
import os
import json
__author__ = "zadjii"
class Issue(base):
__tablename__ = "issue"
"""
Represents a single issue
"""
... | nilq/baby-python | python |
port = 8888
logging = 'info'
log_file_prefix = "tivid-error.log"
redis_host = 'localhost'
redis_port = 6379
redis_db = 0
java_source = "http://www.importnew.com/all-posts"
python_source = "http://python.jobbole.com/all-posts/"
| nilq/baby-python | python |
from threading import Thread
def async_func(f):
def wrapper(*args, **kwargs):
thr = Thread(target = f, args = args, kwargs = kwargs)
thr.start()
return wrapper | nilq/baby-python | python |
from __future__ import unicode_literals
from django.apps import AppConfig
class SequencerConfig(AppConfig):
name = 'sequencer'
| nilq/baby-python | python |
import os
import sys
import datetime
from glob import iglob
from skimage import io
import cv2
import tensorflow as tf
import numpy as np
import utils as ut
import training as tr
class VAE2predict:
def __init__(self, use_sampling=False):
self.use_sampling = use_sampling
self._build_model()
def... | nilq/baby-python | python |
from django import template
register = template.Library()
from urlparse import urlparse
def domain_only(full_url):
parsed = urlparse(full_url)
return parsed.netloc.lstrip("www.")
register.filter('domain_only', domain_only) | nilq/baby-python | python |
print('spam = 40')
spam = 40
print('eggs = 2')
eggs = 2
print('spam + eggs')
a = spam + eggs
print(a)
# Variable naming convention
# small then capital or sparated by _
# varA
| nilq/baby-python | python |
#
# This file is part of m.css.
#
# Copyright © 2017, 2018, 2019 Vladimír Vondruš <mosra@centrum.cz>
#
# 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... | nilq/baby-python | python |
from django.apps import AppConfig
class MagiclinkConfig(AppConfig):
name = 'magiclink'
| nilq/baby-python | python |
from flask import Flask
import os
app = Flask(__name__)
healthy = True
@app.route('/')
def hello():
global healthy
if healthy:
return f"Hello from {os.environ['HOST']}!\n"
else:
return "Unhealthy", 503
@app.route('/healthy')
def healthy():
global healthy
healthy = True
retur... | nilq/baby-python | python |
'''
Integration tests for states.
'''
import unittest as ut
import numpy as np
import dynamite_test_runner as dtr
from dynamite.states import State
class RandomSeed(dtr.DynamiteTestCase):
def test_generation(self):
'''
Make sure that different processors get the same random seed.
'''
... | nilq/baby-python | python |
import requests
import os
from dotenv import load_dotenv
from datetime import datetime
load_dotenv()
def send_to_slack(msg: str) -> None:
URL = os.getenv("SLACK_WEBHOOK")
headers = {"content-type": "application/json"}
payload = {
"attachments": [
{
"fallback": "Plain-t... | nilq/baby-python | python |
from flask import abort, request
from . import app
from .helpers import render_error_template
import logging
# Catch all route for everything not matched elsewhere
@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def catch_all(path): # pragma: no cover
abort(404, "Not Found")
@app.errorhandler... | nilq/baby-python | python |
'''
Created on Jun 21, 2016
@author: MarcoXZh
'''
import sys, re
import xml.etree.ElementTree as ET
from colormath.color_objects import sRGBColor, LabColor
from colormath.color_conversions import convert_color
from colormath.color_diff import delta_e_cie2000
from PIL import Image
from ImageComparison import calcSSIM
... | nilq/baby-python | python |
#!/usr/bin/env python3
# Xilinx CoolRunner II XC2C64A characteristics
bits_of_address = 7
bits_of_data = 274
bytes_of_data = (bits_of_data + 7) // 8
bits_in_program_row = bits_of_address + bits_of_data
address_sequence = (0x00, 0x40, 0x60, 0x20, 0x30, 0x70, 0x50, 0x10, 0x18, 0x58, 0x78, 0x38, 0x28, 0x68, 0x48, 0x08, ... | nilq/baby-python | python |
# Copyright 2020 reinforced_scinet (https://github.com/hendrikpn/reinforced_scinet)
#
# 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.... | nilq/baby-python | python |
#!/usr/bin/env python
import os
import sys
from chromedriver_py import binary_path
print(
"""This command will fail if you have not run the setup.py script AND "source environment/env.sh" first.\n\n\nIt is installing a headless chrome web browser driver to allow making an image out of the big demo script session... | nilq/baby-python | python |
import unittest
from users import User
class TestUser(unittest.TestCase):
'''
Test class that defines test cases for the contact class behaviours.
Args:
unittest.TestUser: TestUser class that helps in creating test cases
'''
# Items up here .......
def setUp(self):
'''
... | nilq/baby-python | python |
import random
import time
import os
import discord
import triggers
import data
import cmd
import tools
################################################################################
lurker_data = dict()
lurker_data['emoji'] = '👀'
lurker_data['min_chance'] = 1
lurker_data['max_chance'] = 10
data.NewGuildEnvAdd('l... | nilq/baby-python | python |
from enum import auto
from mstrio.utils.enum_helper import AutoName
class RefreshPolicy(AutoName):
ADD = auto()
DELETE = auto()
UPDATE = auto()
UPSERT = auto()
REPLACE = auto()
| nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab
from __future__ import unicode_literals, division, absolute_import, print_function
# to work around tk_chooseDirectory not properly returning unicode paths on Windows
# need to use a dialog that can be hacked up to actually... | nilq/baby-python | python |
from django.apps import AppConfig
class EsgConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'esg'
| nilq/baby-python | python |
from .base import * # noqa: F403,F401
DEBUG = True
INSTALLED_APPS += [ # noqa ignore=F405
'debug_toolbar',
]
MIDDLEWARE += [ # noqa ignore=F405
'debug_toolbar.middleware.DebugToolbarMiddleware',
]
ALLOWED_HOSTS = [
'0.0.0.0',
'127.0.0.1',
'art-backend.herokuapp.com'
]
INTERNAL_IPS = [
'0... | nilq/baby-python | python |
# Version 3.1; Erik Husby; Polar Geospatial Center, University of Minnesota; 2019
from __future__ import division
import math
import os
import sys
import traceback
from warnings import warn
import numpy as np
from osgeo import gdal_array, gdalconst
from osgeo import gdal, ogr, osr
gdal.UseExceptions()
class Rast... | nilq/baby-python | python |
import random
print('====================== \033[35mBEM-VINDO AO JOGO DA ADIVINHAÇÃO\033[m ======================')
print('Tente adivinhar o número entre 0 e 10 que eu estou pensando')
computador = random.randint(0, 10)
palpites = 0
acertou = False
while not acertou:
jogador = int(input('Qual é a sua tentativa? '))... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Imports
import json
import discord
import random
import datetime
import asyncio
client = discord.Client()
# Readiness Indicator
@client.event
async def on_ready():
print("The bot is ready!")
await client.change_presence(game=discord.Game(name="roulette with your money"))
# Remind... | nilq/baby-python | python |
import re
from django import template
from django.template.defaultfilters import stringfilter
from django.utils.safestring import mark_safe
from markdown import markdown
register = template.Library()
@register.filter("markdown")
@stringfilter
def markdown_filter(value):
return mark_safe(markdown(value))
@regi... | nilq/baby-python | python |
"""
This file is part of Advent of Code 2019.
Coded by: Samuel Michaels (samuel.michaels@protonmail.com)
11 December 2019
NO COPYRIGHT
This work is dedicated to the public domain. All rights have been
waived worldwide under copyright law, including all related and
neighboring rights, to the extent allowed by law.
Y... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from flask import Flask
from flask_restful import Resource, Api
from controller.TestSuit import TestSuit
from model.TestSuit import db as TestSuitDB
app = Flask(__name__)
api = Api(app)
api.add_resource(TestSuit, '/testsuit')
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///example.sqlit... | nilq/baby-python | python |
# Compact version
# ---------------
rule = (('0'*8 + bin(30)[2:])[-8:])[::-1]
cells = list('0'*40 + '1' + '0'*40)
for epoch in range(40):
print(''.join(cells).replace("0"," ").replace("1","█"))
cells = [cells[0]] + [rule[eval('0b' + cells[i-1]+cells[i]+cells[i+1])]
for i in range(1,len... | nilq/baby-python | python |
import io
import os
from google.cloud import vision
from google.cloud.vision import types
from google.protobuf.json_format import MessageToJson
class GoogleVisionApi:
def __init__(self):
# Instantiates a client
self.client = vision.ImageAnnotatorClient()
self.requestsCache = {}
def request(self, imagePath):... | nilq/baby-python | python |
from os import getenv, \
path
class Config(object):
API_KEY = getenv('API_KEY')
DEBUG = getenv('DEBUG', False)
SQLALCHEMY_DATABASE_URI = getenv('DATABASE_URL', 'sqlite:///' + path.dirname(__file__) + '/app/app.db').replace('mysql2:', 'mysql:')
SQLALCHEMY_ECHO = getenv('SQLALCHEMY_ECHO', ... | nilq/baby-python | python |
import numpy as np
import argparse
parser = argparse.ArgumentParser(description='main', formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('--dataset', default='mag', choices=['mag', 'amazon'])
parser.add_argument('--num_motif', default=50, type=int)
parser.add_argument('--eta', default=2.0, t... | nilq/baby-python | python |
from infi.pyutils.lazy import cached_method
from ..inquiry import InquiryException
from logging import getLogger
logger = getLogger(__name__)
class InfiniBoxVolumeMixin(object):
@cached_method
def _is_volume_mapped(self):
"""In race condition between a rescan and volume unmap operation, the device may... | nilq/baby-python | python |
import discord
from discord.ext import commands
import random, string
from asyncio import sleep
class Fun(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def ascii(self, ctx, amount: int=1):
await ctx.message.delete()
for i in range(amount):
text=''
for i in... | nilq/baby-python | python |
import requests
import lib.RModule as rmodule
import lib.RAudiostream as raudiostream
import lib.RAtmosphere as ratmosphere
import lib.RMonitoring as rmonitoring
class Project:
project_id = None
switchboards = []
neopixels = []
audiostream = None
monitoring = None
def __init__(self, projec... | nilq/baby-python | python |
# coding: utf-8
import numpy as np
import matplotlib.pyplot as plt
from sklearn import ensemble, svm,datasets
import brica1
# Randomforest Component Definition
class RandomForestClassifierComponent(brica1.Component):
def __init__(self, n_in):
super(RandomForestClassifierComponent, self).__init__()
... | nilq/baby-python | python |
""" Parent class to inception models """
import tensorflow as tf
from . import TFModel
from .layers import conv_block
class Inception(TFModel):
""" The base class for all inception models
**Configuration**
body : dict
layout : str
a sequence of blocks in the network:
- ... | nilq/baby-python | python |
# Generated by Django 3.0.4 on 2020-03-20 04:53
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('places', '0024_submittedplace'),
]
operations = [
migrations.RemoveField(
model_name='submittedplace',
name='website... | nilq/baby-python | python |
"""Tests for claim_line model and the associated functions."""
from claims_to_quality.analyzer.models import claim_line
def test_str_method():
"""Test that claim lines are represented in a readable format."""
line = claim_line.ClaimLine(
{'clm_line_hcpcs_cd': 'code', 'mdfr_cds': ['GQ'], 'clm_pos_code'... | nilq/baby-python | python |
#!/usr/bin/env python3
"""
Script to preprocess OCR output for Tesseract
Usage:
python3 preprocess.py /path/to/input/dir \
/path/to/output/dir
"""
from glob import glob
import os
import shutil
import sys
import cv2
import numpy as np
def preprocess(img):
"""Takes a given image and retu... | nilq/baby-python | python |
from .davis import vis
| nilq/baby-python | python |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2019 CERN.
# Copyright (C) 2019 Northwestern University.
#
# Invenio App RDM is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Invenio Records Permissions API."""
from elasticsearch_dsl.query... | nilq/baby-python | python |
#! python3
# aoc_13.py
# Advent of code:
# https://adventofcode.com/2021/day/13
# https://adventofcode.com/2021/day/13#part2
#
def part_one(input) -> int:
nmap =[]
ymap = []
coords = []
with open(input, 'r') as inp:
lines = inp.readlines()
for line in lines:
line.strip()
... | nilq/baby-python | python |
# Copyright (C) 2018 Shriram Bhat
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... | nilq/baby-python | python |
"""Implements the Projection extension.
https://github.com/stac-extensions/projection
"""
from typing import Any, Dict, Generic, List, Optional, Set, TypeVar, cast
import pystac
from pystac.extensions.hooks import ExtensionHooks
from pystac.extensions.base import (
ExtensionManagementMixin,
PropertiesExtensi... | nilq/baby-python | python |
from django.http import HttpResponse
from django.shortcuts import render
# Create your views here.
def home_view(request, *args, **kwargs):
# return HttpResponse("<h1>Hello World</h1>")
return render(request,"home.html", {})
| nilq/baby-python | python |
import re
import utils as u
with open(__file__ + ".input.txt", "r+") as file:
input_str = file.read()
regex = re.compile(r"(?P<from>\d+)-(?P<to>\d+)\s(?P<letter>\w):\s(?P<password>\w+)")
def is_valid_password(input_str):
nb_from, nb_to, letter, password = regex.search(input_str).groups()
return int(nb_... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# libfv.py────────────────────────────────────────────────────────────────┐
# │ │
# │ A Python library module that supports read/modification/write of .otf │
# │ and .ttf font version str... | nilq/baby-python | python |
import sys
def test_python_path():
paths = sys.path
workspace = '/workspaces/bestbot'
assert workspace in paths
| nilq/baby-python | python |
def foo(x = []):
return x.append("x")
def bar(x = []):
return len(x)
foo()
bar()
class Owner(object):
@classmethod
def cm(cls, arg):
return cls
@classmethod
def cm2(cls, arg):
return arg
#Normal method
def m(self):
a = self.cm(0)
return a.cm2(1)
| nilq/baby-python | python |
import hqm
import socket
class HQMBot():
def __init__(self, host, port, team, name):
self.team = team
self.host = host
self.port = port
self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.session = hqm.HQMClientSession(name, 55)
self.syncing = True... | nilq/baby-python | python |
import os
import random
check = """<input type="checkbox" id="{}" name="chord" value="{}">
<label for="{}"> {}</label><br>\n"""
def s(note):
t = note.lower()
return t[0] + "_" + t[2:5]
to_print = ""
for note in os.listdir("./Chords"):
to_print += check.format(note[:-4], note, s(note), note[... | nilq/baby-python | python |
import unittest
from app import db
from app.crypto.pw_hashing import global_salt_hash, indiv_salt_hash
from app.data_access.db_model.user import User
from app.data_access.user_controller import create_user, user_exists, delete_user, activate_user, \
store_pdf_and_transfer_ticket, find_user, check_idnr, check_dob
f... | nilq/baby-python | python |
from django.conf import settings
from django.conf.urls import url
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import include, path
from wrappr_backend.detection.api import urlpatterns as api_urls
urlpatterns = [
path('admin/', admin.site.urls),
url(r'^api-auth/'... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'GUI_try.ui'
#
# Created by: PyQt4 UI code generator 4.11.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
... | nilq/baby-python | python |
from flask import jsonify, request, Response
from jsonschema import RefResolutionError
from sqlalchemy.orm import Session
from flexget.api import APIResource, api
from flexget.api.app import NotFoundError
from flexget.config_schema import resolve_ref, schema_paths
schema_api = api.namespace('schema', description='Con... | nilq/baby-python | python |
"""
Compare two integers given as strings.
Example
For a = "12" and b = "13", the output should be
compareIntegers(a, b) = "less";
For a = "875" and b = "799", the output should be
compareIntegers(a, b) = "greater";
For a = "1000" and b = "1000", the output should be
compareIntegers(a, b) = "equal".
"""
def compare... | nilq/baby-python | python |
# This file is part of the faebryk project
# SPDX-License-Identifier: MIT
import faebryk.library.core
import faebryk.library.kicad
import faebryk.library.library
import faebryk.library.traits
| nilq/baby-python | python |
from datetime import datetime
from .api import ApiObject
class Trigger(ApiObject):
"""
https://www.xibbaz.com/documentation/3.4/manual/api/reference/trigger/object
"""
DEFAULT_SELECTS = ('Items', 'Functions', 'Dependencies', 'DiscoveryRule', 'LastEvent', 'Tags')
RELATIONS = ('hosts', 'groups')
... | nilq/baby-python | python |
################################################################### #
# Basic plot for two-strain SIR model:
# Bifurcation diagram for one parameter
####################################################################
import sys
import numpy as np
import pylab as plt
from matplotlib.font_manager impo... | nilq/baby-python | python |
import tweepy , tkinter, datetime, os, sys, random, time, pytz
from keys import *
from tweepy import TweepError
#Create oauth handler for tokens setting
auth = tweepy.OAuthHandler(consumer_token, consumer_secret)
auth.set_access_token(key,secret)
api = tweepy.API(auth)
random_lyrics = 'Lyrics.txt'
t... | nilq/baby-python | python |
from mycroft import MycroftSkill, intent_file_handler
class Prepararrefeicoes(MycroftSkill):
def __init__(self):
MycroftSkill.__init__(self)
@intent_file_handler('prepararrefeicoes.intent')
def handle_prepararrefeicoes(self, message):
self.speak_dialog('prepararrefeicoes')
def create_sk... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: ibc/core/commitment/v1/commitment.proto
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _refl... | nilq/baby-python | python |
import operator
from typing import Any, Callable, List, Optional, Type, Union
from sqlalchemy.inspection import inspect
from sqlalchemy.orm.attributes import InstrumentedAttribute
from sqlalchemy.orm.decl_api import DeclarativeMeta
from sqlalchemy.orm.relationships import RelationshipProperty
from sqlalchemy.sql impor... | nilq/baby-python | python |
'''
*File: domain_restriction.py
*Author: Nicholas Mattei (nicholas.mattei@nicta.com.au)
*Date: March 18, 2014
*
* Copyright (c) 2014, Nicholas Mattei and NICTA
* All rights reserved.
*
* Developed by: Nicholas Mattei
* NICTA
* http://www.nickmattei.net
* ... | nilq/baby-python | python |
import tensorflow as tf
from storage import run_dir
from train import train
from model import model
from predict import predict
model = model()
train(model)
| nilq/baby-python | python |
import os
import re
import codecs
from setuptools import setup, find_packages
current_path = os.path.abspath(os.path.dirname(__file__))
def read_file(*parts):
with codecs.open(os.path.join(current_path, *parts), 'r', 'utf8') as reader:
return reader.read()
def get_requirements(*parts):
with codecs.... | nilq/baby-python | python |
##!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
import math
import random
from hashlib import sha256
from pathlib import Path
from typing import Optional, Tuple, Union
import aiohttp
import fsspec
from fsspec.core import url_to_fs
########################################################################... | nilq/baby-python | python |
from subprocess import call
import glob
dirnames = glob.glob("samples/*")
for d in dirnames:
images = glob.glob(d+"/*.png")
print("")
print("### "+d)
images.sort()
for image in images:
print("")
print("")
| nilq/baby-python | python |
import kivy
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.button import Button
from kivy.uix.image import Image
from kivy.uix.label import Label
# from kivy.garden
from kivy.uix.textinput import TextInput
import time
from Code.Scripts.predi... | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.