content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
from os import symlink
from os.path import join, realpath
from functools import wraps
from textwrap import dedent
from pprint import PrettyPrinter
from operator import itemgetter
from mock import Mock
from git import Repo
from jig.tests.testcase import JigTestCase
from jig.diffconvert import describe_diff, DiffType, ... | nilq/baby-python | python |
import rospy
import subprocess
from gazebo_msgs.srv import DeleteModel
from gazebo_msgs.srv import SetModelConfiguration
from gazebo_msgs.srv import SpawnModel
from std_srvs.srv import Empty as EmptySrv
from std_srvs.srv import EmptyResponse as EmptySrvResponse
class Experiment(object):
'''
Spawn objects
... | nilq/baby-python | python |
"""Define library examples."""
| nilq/baby-python | python |
import os
class RootDir:
HOME_DIR = os.path.expanduser('~')
DIR_NAME = '.stoobly'
_instance = None
def __init__(self):
if RootDir._instance:
raise RuntimeError('Call instance() instead')
else:
self.root_dir = os.path.join(self.HOME_DIR, self.DIR_NAME)
... | nilq/baby-python | python |
from django.contrib import admin
from .models import *
# Register your models here.
class ShortAdmin(admin.ModelAdmin):
list_display = ['website', 'slug', 'expired', 'creation_date', 'expiration']
actions = ['expire','unexpire']
def expire(self, request, queryset):
for link in queryset:
... | nilq/baby-python | python |
# Contents:
# Getting Our Feet Wet
# Make a List
# Check it Twice
# Custom Print
# Printing Pretty
# Hide...
# ...and Seek!
# You win!
# Danger, Will Robinson!!!
# Bad Aim
# Not Again!
# Play It, Sam
# Game Over
# A Real Win
print("### Getting Our Feet Wet ###")
board = []
print("### Make a List ###")
for i in range(... | nilq/baby-python | python |
import redis
r = redis.Redis()
def main():
print(r.info())
if __name__ == '__main__':
main()
| nilq/baby-python | python |
from selenium import webdriver
import multiprocessing as mp
import numpy as np
import parms
from webdriver_manager.firefox import GeckoDriverManager
from selenium.webdriver.firefox.options import Options
# Prepare driver
options = Options()
options.headless = True
driver = webdriver.Firefox(options=options... | nilq/baby-python | python |
# -*- coding: UTF-8 -*-
import unittest
import os.path
from typing import List
from wpydumps import parser
from wpydumps.model import Page
SAMPLE_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "sample.xml")
class TestParser(unittest.TestCase):
def test_parse(self):
pages: List[Page] = ... | nilq/baby-python | python |
import mimetypes
import time
from django.http import HttpResponse, Http404, HttpResponseNotModified
from django.utils.http import http_date
from django.views.static import was_modified_since
from django.conf import settings
from simplethumb.models import Image
from simplethumb.spec import Spec, ChecksumException, dec... | nilq/baby-python | python |
#!/usr/bin/python
import csv
import random
import numpy as np
import pandas as pd
inFile19 = "csvOdds/gameIDodds2019.csv"
iTrainFile19 = open(inFile19, "r")
readerTrain19 = csv.reader(iTrainFile19, delimiter=',', quotechar='"', quoting=csv.QUOTE_ALL)
inFile18 = "csvOdds/gameIDodds2018.csv"
iTr... | nilq/baby-python | python |
import struct
import telnetlib
def p(x):
return struct.pack('<L', x)
get_flag2 = 0x804892b
setup_get_flag2 = 0x8048921
# Flag 2
payload = ""
payload += "P"*112 # Add the padding leading to the overflow
payload += p(setup_get_flag2)
payload += p(get_flag2)
print(payload) | nilq/baby-python | python |
# coding: utf-8
import sys
from codecs import open
from urllib2 import urlopen
from simplejson import loads as load_json
url = urlopen("http://www.example.com/wp-admin/admin-ajax.php?action=externalUpdateCheck&secret=ABCDEFABCDEFABCDEFABCDEFABCDEFAB")
res = url.read()
if res == "0":
sys.exit(0)
updates... | nilq/baby-python | python |
# Services plugin for bb exporter
# 2020 - Benoît Leveugle <benoit.leveugle@sphenisc.com>
# https://github.com/oxedions/bluebanquise - MIT license
from pystemd.systemd1 import Unit
from prometheus_client.core import GaugeMetricFamily
class Collector(object):
services = {}
services_status = []
def __ini... | nilq/baby-python | python |
import setuptools
import os
import sys
# Get Version
sys.path.append(os.path.dirname(__file__))
import versioneer
__VERSION__ = versioneer.get_version()
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
version=__VERSION__,
cmdclass=versioneer.get_cmdclass(),
name="pu... | nilq/baby-python | python |
# adds the results to s3
import boto3
import os
import io
import scraperwiki
import time
import simplejson as json
import gzip
import pandas as pd
def upload(test):
AWS_KEY = os.environ['AWS_KEY_ID']
AWS_SECRET = os.environ['AWS_SECRET_KEY']
queryString = "* from aus_ads"
queryResult = scraperwiki.sqlite.selec... | nilq/baby-python | python |
from typing import List
from typing import Union
from pyspark.sql import DataFrame
from pyspark.sql import functions as F
from pyspark.sql.window import Window
def filter_all_not_null(df: DataFrame, reference_columns: List[str]) -> DataFrame:
"""
Filter rows which have NULL values in all the specified column... | nilq/baby-python | python |
from __future__ import absolute_import
from builtins import object
import numpy as np
import logging
from relaax.common import profiling
from relaax.server.common import session
from relaax.common.algorithms.lib import utils
from relaax.common.algorithms.lib import observation
from .. import dqn_config
from .. impo... | nilq/baby-python | python |
__all__ = [
"__version__",
"spotify_app",
"SpotifyAuth",
"SpotifyClient",
"SpotifyResponse",
]
from .aiohttp_spotify_version import __version__
from .api import SpotifyAuth, SpotifyClient, SpotifyResponse
from .app import spotify_app
__uri__ = "https://github.com/dfm/aiohttp_spotify"
__author__ = ... | nilq/baby-python | python |
from . import views
from rest_framework.routers import SimpleRouter
from django.urls import path
router = SimpleRouter()
router.register("posts", views.PostViewSet, "posts")
urlpatterns = [
path('upload_file/', views.FileUploadView.as_view()),
]
urlpatterns += router.urls | nilq/baby-python | python |
import getpass
message = 'hello {}'.format(getpass.getuser())
| nilq/baby-python | python |
from django.core.urlresolvers import resolve
from django.urls import reverse
from django.template.loader import render_to_string
from django.test import TestCase
from django.http import HttpRequest
from unittest import skip
from users.views import home_visitor, display_signup
from users.models import University, Facult... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File : LiarDie.py
@Time : 2021/11/15 00:08:33
@Author : yanxinyi
@Version : v1.0
@Contact : yanxinyi620@163.com
@Desc : Applying algorithm of Fixed-Strategy Iteration Counterfactual Regret Minimization
(FSICFR) to Liar Die.
java code str... | nilq/baby-python | python |
import numpy as np
import pandas as pd
import pickle
from sklearn.neighbors import NearestNeighbors
from flask import Flask, render_template, request, redirect, jsonify
"""
To run on windows with powershell:
1. Navigate to the directory where apsapp.py is located.
2. Enter: $env:FLASK_APP = "apsapp.py"
3. Enter: pytho... | nilq/baby-python | python |
class RLEIterator:
def __init__(self, A: List[int]):
def next(self, n: int) -> int:
# Your RLEIterator object will be instantiated and called as such:
# obj = RLEIterator(A)
# param_1 = obj.next(n)
| nilq/baby-python | python |
# 입력으로 하나씩 받아서 아이디랑 이름이랑 매치시키자.
import collections
def solution(record) :
result = collections.defaultdict(str)
for rec in record :
_, uid, name = rec.split(' ')
result[uid] = name
print(result)
answer = []
return answer
answer =solution(["Enter uid1234 Muzi", "Enter uid4567 Prod... | nilq/baby-python | python |
from typing import Dict, Tuple
from libp2p.typing import StreamHandlerFn, TProtocol
from .exceptions import MultiselectCommunicatorError, MultiselectError
from .multiselect_communicator_interface import IMultiselectCommunicator
from .multiselect_muxer_interface import IMultiselectMuxer
MULTISELECT_PROTOCOL_ID = "/mu... | nilq/baby-python | python |
# bbc micro:bit + bit:commander (4tronix)
# use joystick to command robot kitronik :move
from microbit import *
import radio
# setup
radio.on()
#radio.config(group=0)
s_forward, s_right = 0, 0
# main loop
while True:
# read joystick and scale it
# -100 is full reverse forward / 0 is stop / +100% is full for... | nilq/baby-python | python |
# Generated by Django 3.2 on 2021-05-19 04:25
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('Sentiment', '0003_auto_20210517_1332'),
]
operations = [
migrations.CreateModel(
name='CSVResult'... | nilq/baby-python | python |
from collections import defaultdict
from aocd import data
from p09 import Boost
class Cabinet(Boost):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.screen = defaultdict(int)
self.x = None
self.y = None
self.score = None
self.ball_x = ... | nilq/baby-python | python |
rna_trans = {'G':'C', 'C':'G', 'T':'A', 'A':'U'}
def to_rna(dna):
rna = ''
for n in dna:
if n not in rna_trans:
return ''
rna += rna_trans[n]
return rna
| nilq/baby-python | python |
#!/usr/bin/env python2.7
"""Facilitates the measurement of current network bandwidth."""
import collections
class Bandwidth(object):
"""Object containing the current bandwidth estimation."""
def __init__(self):
self._current = 0
self._previous = 0
self._trend = collections.deque(max... | nilq/baby-python | python |
import gmsh
# init gmsh
gmsh.initialize()
gmsh.option.setNumber("General.Terminal", 1)
gfile="03032015J_H2-HR.brep"
volumes = gmsh.model.occ.importShapes(gfile)
gmsh.model.occ.synchronize()
print(volumes)
pgrp = gmsh.model.addPhysicalGroup(3, [1])
gmsh.model.setPhysicalName(2, pgrp, "Cu")
"""
gmsh.model.mesh.setSiz... | nilq/baby-python | python |
from __future__ import division
import re
from math import sqrt, sin, cos, log, tan, acos, asin, atan, e, pi
from operator import truediv as div
from operator import add, sub, mul, pow
from .numbers import NumberService
class MathService(object):
__constants__ = {
'e': e,
'E': e,
'EE': e,... | nilq/baby-python | python |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import subprocess
import sys
import ipaddress
from ansible.errors import AnsibleFilterError
from ansible.module_utils.common.process import get_bin_path
from ansible.module_utils._text import to_text
from ansible.module_utils.six... | 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
# ... | nilq/baby-python | python |
import sqlite3
class Database:
def __init__(self, dbname):
self.conn = sqlite3.connect(dbname)
self.conn.execute("CREATE TABLE IF NOT EXISTS shotmeter (" \
"id INTEGER PRIMARY KEY, " \
"groupname TEXT not null , " \
"sh... | nilq/baby-python | python |
#/*
# * Player - One Hell of a Robot Server
# * Copyright (C) 2004
# * Andrew Howard
# *
# *
# * This library is free software; you can redistribute it and/or
# * modify it under the terms of the GNU Lesser General Public
# * License as published by the Free Software Foundation; either
# ... | nilq/baby-python | python |
from math import *
import math
from .math_eval import *
one_arg_mathfuncs = {}
for funcname in dir(math):
func = globals()[funcname]
try:
func(2) # if this works, the function accepts one arg
one_arg_mathfuncs[funcname] = func
except Exception as ex:
# this is most likely either b... | nilq/baby-python | python |
# Copyright (c) 2015, Scott J Maddox. All rights reserved.
# Use of this source code is governed by the BSD-3-Clause
# license that can be found in the LICENSE file.
import os
import sys
fpath = os.path.join(os.path.dirname(__file__), '../fdint/_nonparabolic.pyx')
templates_dir = os.path.join(os.path.dirname(__file__),... | nilq/baby-python | python |
import re
import traceback
import telegram
from telegram.ext.dispatcher import run_async
from mayday import LogConfig
from mayday.constants import TICKET_MAPPING, conversations, stages
from mayday.constants.replykeyboards import ReplyKeyboards
from mayday.controllers.request import RequestHelper
from mayday.helpers.u... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding:UTF-8 -*-
import dircache
from pprint import pprint
import os
path='../..'
contents=dircache.listdir(path)
annotated=contents[:]
dircache.annotate(path,annotated)
fmt='%25s\t%25s'
print fmt % ('ORIGINAL','ANNOTATED')
print fmt % (('-'*25,)*2)
for o,a in zip(contents,annotated):... | nilq/baby-python | python |
import asyncio
async def req1():
await asyncio.sleep(1)
return 1
async def req2():
return 2
async def main():
res = await asyncio.gather(req1(), req2())
print(res)
asyncio.get_event_loop().run_until_complete(main())
| nilq/baby-python | python |
from classes.AttackBarbarians import AttackBarbarians
attack = AttackBarbarians(level=36)
while True:
attack.start()
| nilq/baby-python | python |
constants = {
# --- ASSETS FILE NAMES AND DELAY BETWEEN FOOTAGE
"CALIBRATION_CAMERA_STATIC_PATH": "assets/cam1 - static/calibration.mov",
"CALIBRATION_CAMERA_MOVING_PATH": "assets/cam2 - moving light/calibration.mp4",
"COIN_1_VIDEO_CAMERA_STATIC_PATH": "assets/cam1 - static/coin1.mov",
"COIN_1_VIDEO... | nilq/baby-python | python |
def counter(T):
c = 0
l = 0
for i in T:
if len(set(i.lower())) > c:
l = len(i)
c = len(set(i.lower()))
elif (len(set(i.lower())) == c) & (len(i) > l):
l = len(i)
c = len(set(i.lower()))
return l | nilq/baby-python | python |
#!/usr/bin/env python
"""
Example application views.
Note that `render_template` is wrapped with `make_response` in all application
routes. While not necessary for most Flask apps, it is required in the
App Template for static publishing.
"""
import app_config
import json
import oauth
import static
import re
import s... | nilq/baby-python | python |
#!/usr/bin/python
#
# yamledit.py
# github.com/microtodd/yamledit
#
import os
import sys
import getopt
import ruamel.yaml
from ruamel import yaml
from ruamel.yaml.scalarstring import SingleQuotedScalarString, DoubleQuotedScalarString
__version__ = '0.5'
# TODO
#
# ) merge two yaml files capability
# ) Support input p... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from ..tre_elements import TREExtension, TREElement
__classification__ = "UNCLASSIFIED"
__author__ = "Thomas McCullough"
class XINC(TREElement):
def __init__(self, value):
super(XINC, self).__init__()
self.add_field('XINC', 's', 22, value)
class XIDC(TREElement):
de... | nilq/baby-python | python |
"""Extracts labels for each actionable widget in an abstract state."""
import math
class LabelExtraction:
"""Extracts labels for each actionable widget in an abstract state."""
@staticmethod
def extract_labels(abstract_state, page_analysis):
""" Extracts labels for each actionable widget in the ... | nilq/baby-python | python |
import darkdetect
def is_dark():
return darkdetect.isDark()
| nilq/baby-python | python |
import os
import HFSSdrawpy.libraries.example_elements as elt
from HFSSdrawpy import Body, Modeler
from HFSSdrawpy.parameters import GAP, TRACK
# import HFSSdrawpy.libraries.base_elements as base
pm = Modeler("hfss")
chip1 = Body(pm, "chip1")
track = pm.set_variable("20um")
gap = pm.set_variable("10um")
radius1 =... | nilq/baby-python | python |
# coding: utf-8
from django.db import models
class Jurado(models.Model):
"""
xxx
"""
nome = models.CharField(u'Nome completo', max_length=200)
def __str__(self):
return self.nome
class Meta:
db_table = 'tb_jurado'
verbose_name = 'Jurado'
verbose_name_plural =... | nilq/baby-python | python |
# Implementation of Kruskal's Algorithm
# this is a greedy algorithm to find a MST (Minimum Spanning Tree) of a given connected, undirected graph. graph
# So I am implementing the graph using adjacency list, as the user wont be
# entering too many nodes and edges.The adjacency matrix is a good implementation
# ... | nilq/baby-python | python |
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
import datetime
import boto3
import json
events_client = boto3.client("events")
sagemaker_client = boto3.client("sagemaker")
ssm_client = boto3.client("ssm")
class Metric:
_iam_permissions = [
{
... | nilq/baby-python | python |
from datetime import datetime
import pytest
@pytest.fixture(scope="module")
def setup_lab(lab, authenticated_client):
lab_obj = authenticated_client.api.create_lab(**lab)
yield lab_obj
authenticated_client.api.delete_lab(lab["path"] + lab["name"])
@pytest.fixture(scope="module")
def lab():
now = da... | nilq/baby-python | python |
#encoding: UTF-8
import urllib2
import re
import socket
import time
rfile = open('./ip.txt')
wfile = open('./result.csv', 'a+')
for line in rfile:
opener = urllib2.build_opener()
time.sleep(0.5)
opener.addheaders = [('User-Agent', 'Mozilla/6.0 (Linux 5.5; rv:6.0.2) Gecko/20140101 Firefox/6.0.0')]
... | nilq/baby-python | python |
from .sqlalchemy import SQLAlchemy
from .db import base
db = SQLAlchemy()
# db.register_base(base) | nilq/baby-python | python |
import mock
import testtools
from shakenfist.baseobject import DatabaseBackedObject, State
from shakenfist import exceptions
from shakenfist.tests import base
class DatabaseBackedObjectTestCase(base.ShakenFistTestCase):
@mock.patch('shakenfist.baseobject.DatabaseBackedObject._db_get_attribute',
s... | nilq/baby-python | python |
from .base import *
import scipy.io
from os import path as pth
class Food(BaseDataset):
def __init__(self, root, classes, transform = None):
BaseDataset.__init__(self, root, classes, transform)
img_dir = pth.join(root,"images")
category_path = pth.join(root,"categories.txt")
with o... | nilq/baby-python | python |
"""Get debug information."""
from googledevices.helpers import gdh_session
def debug(host, loop, test, timeout):
"""Get debug information."""
from googledevices.utils.debug import Debug
async def connectivity():
"""Test connectivity a Google Home unit."""
async with gdh_session():
... | nilq/baby-python | python |
from database.connect import DatabaseError
from flask import Flask, request, render_template, jsonify
import json
from database import Database
from src.predict import *
app = Flask(__name__)
def pipeline(ticker, years):
"""Converts user input to appropriate types"""
ticker = str(ticker)
years = int(yea... | nilq/baby-python | python |
import pandas as pd
import numpy as np
import config
import utils
import torch
import torch.nn as nn
import torch.nn.functional as F
from pathlib import Path
from tqdm.auto import tqdm
from sklearn.metrics import roc_auc_score
from datetime import datetime
from torch.utils.data import DataLoader, Dataset
from torch.u... | nilq/baby-python | python |
import graphene
from graphene import Argument
from graphene_django.types import DjangoObjectType
from ..models import Category, Product
class ProductType(DjangoObjectType):
class Meta:
model = Product
class Query(object):
all_products = graphene.List(ProductType)
product = graphene.Field(Produc... | nilq/baby-python | python |
import os
PROJECT_NAME = "fastapi sqlalchemy pytest example"
VERSION = "0.0.1"
BASE_DIR: str = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
API_PREFIX = "/api"
SQLALCHEMY_DATABASE_URL: str = os.getenv('DATABASE_URI', f"sqlite:///{BASE_DIR}/foo.db")
DEBUG=True | nilq/baby-python | python |
"""
MIT License
Copyright (c) 2018 Simon Olofsson
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 secrets import token_bytes
from coincurve import PublicKey
from sha3 import keccak_256
import os
private_key = keccak_256(token_bytes(32)).digest()
public_key = PublicKey.from_valid_secret(private_key).format(compressed=False)[1:]
addr = keccak_256(public_key).digest()[-20:]
def clear():
if os.name == 'nt':
... | nilq/baby-python | python |
#!/usr/bin/env python
""" Stackfuck Interpreter """
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
with open("README.md") as file_readme:
readme = file_readme.read()
setup(
name="Stackfuck",
version="0.0.1",
description="Interpreter for esoteric language... | nilq/baby-python | python |
import collections
from typing import List
class Solution:
def longestSubsequence(self, arr: List[int], difference: int) -> int:
longest = 0
while arr:
new_arr = []
curr = [arr[0]]
for j in arr[1:]:
if j == curr[-1] + difference:
... | nilq/baby-python | python |
from django.shortcuts import render
from utils.api_response import JsonResponse
from rest_framework.decorators import (api_view, authentication_classes,
permission_classes)
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework.permissions imp... | nilq/baby-python | python |
import re
import logging
import socket
import json
from urllib import request, error, parse
# 匹配合法 IP 地址
regex_ip = re.compile(
r"\D*("
+ r"(?:1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|[1-9])\."
+ r"(?:1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|\d)\."
+ r"(?:1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|\d)\."
+ r"(?:1\d{2}|2[0-4]\d... | nilq/baby-python | python |
from tkinter import *
from tkinter import filedialog
from pygame import mixer
import os
import stagger
class MusicPlayer:
filename = "MUSIC NAME"
def __init__(self, window):
window.geometry('500x400')
window.title('MP3 Player')
window.resizable(1, 1)
Load = Button(window, text... | nilq/baby-python | python |
import random
from time import sleep
lista = [0,1,2,3,4,5]
aleatorio = random.choice(lista)
print(20*'=')
print(" JOGO DA ADIVINHAÇÃO")
print(20*'=')
escolha = int(input("Digite um numero de 0 a 5: "))
print('PROCESSANDO...')
sleep(4)
if escolha == aleatorio:
print('O numero era {} e você escolheu corret... | nilq/baby-python | python |
import tensorflow as tf
from tensorflow.keras import Model
from . import enet_modules as mod
class ENet(Model):
"""
https://arxiv.org/pdf/1606.02147.pdf
"""
def __init__(self, classes,
kernel_initializer=tf.initializers.glorot_uniform(),
alpha_initializer=tf.initializ... | nilq/baby-python | python |
import pandas as pd
import networkx as nx
import numpy as np
from typing import Union
from pymarket.transactions import TransactionManager
from pymarket.bids import BidManager
from pymarket.mechanisms import Mechanism, MechanismReturn
RandomState = Union[np.random.RandomState, None]
def p2p_random(bids: pd.DataFrame... | nilq/baby-python | python |
SEP = "/"
def _splitnode(nodeid):
"""Split a nodeid into constituent 'parts'.
Node IDs are strings, and can be things like:
''
'testing/code'
'testing/code/test_excinfo.py'
'testing/code/test_excinfo.py::TestFormattedExcinfo::()'
Return values are lists e.g.
[]
... | nilq/baby-python | python |
print("Hell o' world.") | nilq/baby-python | python |
"""test_rest_api URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Cl... | nilq/baby-python | python |
from typing import Dict, List, Optional, Pattern, Type, TypedDict
# CONFIG ALIASES
from pyVmomi import vim
ResourceFilterConfig = TypedDict(
'ResourceFilterConfig', {'resource': str, 'property': str, 'type': str, 'patterns': List[str]}
)
MetricFilterConfig = Dict[str, List[str]]
InstanceConfig = TypedDict(
'... | nilq/baby-python | python |
#!/usr/bin/env python3
from setuptools import setup, find_packages
setup(
name = "ascii_py",
version = "2.0",
description = "Make ascii art",
# This is because shutil.get_terminal_size() was added in 3.3
python_requires=">=3.5",
author = "ProfOak",
author_email = "OpenProfOak@gmail.com",
... | nilq/baby-python | python |
# Use Modern Python
from __future__ import unicode_literals, absolute_import, print_function
# System imports
# Django imports
from django.forms import ValidationError, Field, TextInput
# External libraries
import six
# Local imports
import django_prbac.csv
class StringListInput(TextInput):
def render(self, n... | nilq/baby-python | python |
import os
import shutil
import tempfile
import unittest
import numpy as np
import cwepr.dataset
import cwepr.exceptions
import cwepr.io.magnettech
import cwepr.processing
ROOTPATH = os.path.split(os.path.abspath(__file__))[0]
class TestMagnettechXmlImporter(unittest.TestCase):
def setUp(self):
source =... | nilq/baby-python | python |
from django.apps import AppConfig
class BillingsConfig(AppConfig):
name = 'billings'
def ready(self):
import billings.signals # noqa
| nilq/baby-python | python |
from utils import parsing, mysql_module
config = parsing.parse_json('config.json')
mysql = mysql_module.Mysql()
def is_owner(ctx):
return ctx.message.author.id in config["owners"]
def is_server_owner(ctx):
return ctx.message.author.id == ctx.message.server.owner
def in_server(ctx):
return ctx.message.... | nilq/baby-python | python |
import jedi
from jedi.evaluate.recursion import ExecutionRecursionDetector
try:
from queue import Queue
except ImportError:
# Python 2 shim
from Queue import Queue
stop_execution_signal_queue = Queue(maxsize=1)
"""
Allows a controller thread to cause Jedi to abort execution.
`ExecutionRecursionDetector.pu... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from enum import Enum, auto
class TokenType(Enum):
"""
Types (categories) of tokens such as "number", "symbol" or "word".
"""
Unknown = 0,
Eof = auto()
Eol = auto()
Float = auto()
Integer = auto()
HexDecimal = auto()
Number = auto()
Symbol = auto()
... | nilq/baby-python | python |
from __future__ import absolute_import
default_app_config = 'project.jass.apps.JASSAppConfig'
| nilq/baby-python | python |
import pytest
@pytest.mark.functions
def test_fill_empty(null_df):
df = null_df.fill_empty(columns=["2"], value=3)
assert set(df.loc[:, "2"]) == set([3])
@pytest.mark.functions
def test_fill_empty_column_string(null_df):
df = null_df.fill_empty(columns="2", value=3)
assert set(df.loc[:, "2"]) == set... | nilq/baby-python | python |
# By Soham Koradia as a project for Khan Academy
'''
The process to user this is similar as that described at the top of the
total_infection module, and the onyl difference is that instead of running the
total_infection algorithm, you would use this one, like so (continuing from the
example users given in that module)... | nilq/baby-python | python |
import numpy as np
import matplotlib.pyplot as plt
data = np.loadtxt("intento.dat")
n_points = int(np.sqrt(len(data)))
grid = np.reshape(data.T, (201, 201))
plt.figure(figsize=(15,5))
plt.subplot(1,2,1)
plt.imshow(grid)
plt.xlabel("Indice X")
plt.ylabel("Indice T")
plt.colorbar(label="Temperatura")
T1=data[:,0]
T2... | nilq/baby-python | python |
from operator import attrgetter
import pyangbind.lib.xpathhelper as xpathhelper
from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType, RestrictedClassType, TypedListType
from pyangbind.lib.yangtypes import YANGBool, YANGListType, YANGDynClass, ReferenceType
from pyangbind.lib.base import PybindBase
from d... | nilq/baby-python | python |
#!/usr/bin/env python3
class DSHead():
def printTemplateHead(self):
templateHeader = "".join(open('tjgwebservices/views/static/dsheader.tpl','r').readlines())
templateHeader = templateHeader.replace("{website.title}","II Data School")
templateHeader = templateHeader.replace("{website.v... | nilq/baby-python | python |
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
self.sum += val... | nilq/baby-python | python |
a= int(input('Digite um numero: '))
print(f'{a*1}\n{a*2}\n{a*3}\n{a*4}\n{a*5}\n{a*6}\n{a*7}\n{a*8}\n{a*9}\n{a*10}') | nilq/baby-python | python |
class User(object):
def __init__(self, **args):
self.id = args.get('id')
self.name = args.get('name')
self.username = args.get('username')
self.email = args.get('email')
self.street = args.get('street')
self.suite = args.get('suite')
self.city = args.get('city... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from torchvision.models.resnet import BasicBlock, Bottleneck, ResNet, model_urls as imagenet_urls
from torchvision.models.utils import load_state_dict_from_url
from .utils import cnn_model
__all__ = ['resnet18', 'resnet34', 'resnet50', 'resnet101',
'resnet152', 'resnext50_32x4d', '... | nilq/baby-python | python |
def cockroach_speed(s):
return int(s * 27.7778) | nilq/baby-python | python |
from .dataset_processing import apply_mask, roi_array
| nilq/baby-python | python |
""" real_estate_in_korea trade check command line tool."""
from real_estate_in_korea.main import main
main(None)
| nilq/baby-python | python |
# 公主连接Re:Dive会战管理插件
# clan == クラン == 戰隊(直译为氏族)(CLANNAD的CLAN(笑))
from nonebot import on_command
from hoshino import R, Service, util
from hoshino.typing import *
from .argparse import ArgParser
from .exception import *
sv = Service('clanbattle')
SORRY = 'ごめんなさい!嘤嘤嘤(〒︿〒)'
_registry:Dict[str, Tuple[Callable, ArgParse... | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.