text stringlengths 38 1.54M |
|---|
class PlaceholderInput(forms.widgets.Input):
template_name = 'about/placeholder.html'
input_type = 'text'
def get_context(self, name, value, attrs):
context = super(PlaceholderInput, self).get_context(name, value, attrs)
context['widget']['attrs']['maxlength'] = 50
context['widget']... |
from django.template.loader import render_to_string
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext_lazy as _
class Widget(object):
name = "widget"
label = "Widget"
template = "widget.html"
color = None
context_errors = _('No data')
icon = "icon-user"... |
#!/usr/bin/python
#
# misc-funcs.py: time, collections, and parser related helper methods
# author stephenb
#
from logger import *
# Do hash replacement / string interpolation of a heredoc
def interpolate(msg, inhash=locals()):
import StringIO
outstr = StringIO.StringIO()
# print str(inhash)
print >> outstr,... |
# DB Connector for ZODB
import base64
import ZODB
import ZODB.FileStorage
import transaction
from BTrees.OOBTree import OOBTree
from ZODB.FileStorage import FileStorage
from persistent import Persistent
from base_connector import ConnectorBase
from common.consts import DEFAULT_DB_NAME, DEFAULT_TABLE_NAME
... |
import numpy as np
radius = 1
total_dots = 100000
inner_dots = 0
# Using loop
# for dot in range(total_dots):
# x = np.random.uniform(0, radius)
# y = np.random.uniform(0, radius)
#
# distance = np.sqrt(x**2 + y**2)
# if distance <= radius:
# inner_dots += 1
#
# print(4 * inner_dots / total_do... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# baseフォルダのファイルを加工して問題に変換する
"""
重要:適当に問題を生成しています。
大体100近いファイルを一気に作成します。
※lv=レベル
※加工ファイル名はプログラムに埋め込んでいる(make_quiz関数)
※自分にできるところから始める
基本的にはlv が大きいほど消えている量が多くて難しくなる。
lvが違うけど、同じ結果になっていたりするかもしれない。
基本的に自分のやりやすいレベルから始める。
... |
import numpy as np
import torch
import torch.utils.data
from scipy.stats import entropy
from torch import nn
from torch.autograd import Variable
from torch.nn import functional as F
from torchvision.models.inception import inception_v3
from tqdm import tqdm
# Inception score code adapted from https://github.com/sbarr... |
#!/usr/bin/python
import sys
for line in sys.stdin:
if("medallion" in line):
continue
try:
data = line.strip().split(",")
if(len(data)<3):
continue
lc = data[1]
datetime = data[3]
date = datetime.split("-")
month = date[1]
except:
... |
# encoding: utf-8
"""
__init__.py
Created by David Farrar on 2012-02-08.
Copyright (c) 2011-2013 Exa Networks. All rights reserved.
"""
|
import sys
from bs4 import BeautifulSoup
import requests
#from apps.rgl.spider_html_render import SpiderHtmlRender
import execjs
import json
import demjson
import csv
import urllib
from apps.rgl.seph_spider import SephSpider as SephSpider
from apps.rgl.website_stats import WebsiteStats as WebsiteStats
class SteamDb(ob... |
import os
import queue
import threading
import traceback
threadpool = []
work_queue = queue.Queue()
def init_threadpool():
global threadpool
threadpool = [threading.Thread(target=worker_thread, daemon=True, name=f'Worker-{idx}') for idx in range(16)]
[t.start() for t in threadpool]
def worker_thread():... |
"""
Code that watches for fishy behavior and swings the BANHAMMER.
"""
class Warden(object):
def report_connection(self):
pass |
# python3
import sys
def compute_min_refills(distance, tank, stops):
# write your code here
count = 0
start = 0
stops = [0]+ stops + [distance]
final = len( stops) - 1
i = 0
base = tank
while i < final:
if stops[i + 1] - stops[i] > tank:
return -1
i += 1
... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-05-03 23:18
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import django_extensions.db.fields
import mptt.fields
import uuid
class Migration(migrations.Migration):
initial = True
de... |
#REST FRAMEWORK Core
from rest_framework import serializers
#INTERNAL Components
from followprocess.process.models import Process, UserProcess, RestrictProcess
from .utils import raise_error_message
class ProcessSerializer(serializers.ModelSerializer):
class Meta:
model = Process
fields = ['pk', ... |
import os
from datetime import datetime
import logging
from django.core.management.base import BaseCommand
from .utilities import import_data, import_v1_data, export_data, delete_data
logger = logging.getLogger(__name__)
default_file_uri = os.path.join(
os.path.dirname(os.path.realpath(__file__)), 'geocontext... |
from utils import *
def compute_SIFT_ckp(img1, img2, save_flag):
gray1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
gray2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
sift = cv2.xfeatures2d.SIFT_create()
kp1, des1 = sift.detectAndCompute(gray1, None)
kp2, des2 = sift.detectAndCompute(gray2, None)
img1 = cv2.drawKey... |
# -*- coding: utf-8 -*-
#########################################################################
#
# Copyright (C) 2012 OpenPlans
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either versio... |
# 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 u... |
'''
Script: Get Calander By Pincode(s)
By: CrazyKID (GitHub: @crazykiid)
'''
from os import system
import requests, time
system('clear')
script = '## Script: Get Calander By Pincode(s) ##\n'
print(script)
pins = input('Enter pincode(s):')
pincodes = pins.split(',')
given_date = input('Enter date (dd-mm-yyyy):')
gap = ... |
from setuptools import setup, Extension
# Compile *mysum.cpp* into a shared library
setup(
#...
ext_modules=[Extension('yuv2rgb', ['yuv2rgb.cpp'],),],
)
|
import numpy as np
import pyopencl
import pyopencl.array
import pyopencl.tools
from ... import interface
from .ndarray import ndarray
def array_wrap(arr):
"""coerce object to be a wrapped array"""
arr.__class__ = ndarray
return arr
class Context(interface.Context):
"""
wh... |
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
result=[]
for i in range(2**len(nums)):
temp=[]
i1=i
for j in range(len(nums)):
if i1%2==1:
temp.append(nums[j])
i1=i1//2
result.... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'orleven'
import os
import sys
import argparse
# import uvloop
import asyncio
import sys
import glob
from lib.common import banner
from lib.core import run
from lib.data import logger
from lib.data import debug
from lib.data import conf
from lib.log import CUS... |
# -*- coding: utf-8 -*-
"""
@author: Lukas Sandström
"""
import logging
from connect_instrument import connect_znb
logging.basicConfig()
znb_ip = "localhost"
znb = connect_znb(znb_ip)
znb.preset()
znb.INITiate.CONTinuous.ALL.w("OFF")
ch = znb.get_channel(1)
ch.name = "SP_ch_1"
dia1 = znb.get_diagram(1)
ch.config... |
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import path, include
from accounts import views
urlpatterns = [
path('', views.HomePageView.as_view(), name='home'),
path('admin/', admin.site.urls),
path('accounts/', include('acc... |
import six
class RpcError(Exception):
def __repr__(self):
return '<%s: %s>' % (self.__class__.__name__, self)
class RpcRequestError(RpcError):
def __init__(self, request, *args, **kwargs):
self.request = request
super(RpcError, self).__init__(*args, **kwargs)
class Timeout(RpcReque... |
# -*- python -*-
# This software was produced by NIST, an agency of the U.S. government,
# and by statute is not subject to copyright in the United States.
# Recipients of this software assume all responsibilities associated
# with its operation, modification and maintenance. However, to
# facilitate maintenance we as... |
import random
class DieRoller:
'''
A class that allows one to simulate dice rolls of even sides > 1
'''
def roll(self, sides):
if sides % 2 != 0 or sides < 2:
return -1
else:
return random.randrange(1, sides+1)
def rolltwo(self, sides):
if sides % 2 != 0 or sides < 2:
return (-1,-1)
else:
ret... |
#! /usr/bin/env python3
import roslib
roslib.load_manifest('basic_tutorials')
import rospy
from basic_tutorials.srv import *
def handle_add_two_ints(req):
"""
Returns the value req.sum as a result od req.a+req.b
AddTwoIntsRequest and AddTwoIntsResponse are formed when making the custom srv
AddTwoInts... |
from RESTAPI.ChatBotLibrary import ChatBot
class ChatBotResponse:
def WeatherResponse(self, text):
pass
def BotResponse(self, text):
result = ChatBot.response(text)
return result
|
'''
Spiral Matrix II
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n = 3,
You should return the following matrix:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
https://oj.leetcode.com/problems/spiral-matrix-ii/
'''
class Solution:
# @return a ... |
from ._sinAction import *
from ._sinActionFeedback import *
from ._sinActionGoal import *
from ._sinActionResult import *
from ._sinFeedback import *
from ._sinGoal import *
from ._sinResult import *
|
import os
image_dirs = ["training", "tuning", "evaluation"]
for image_dir in image_dirs:
filenames = os.listdir(image_dir)
for filename in filenames:
if filename[:8] == "download":
i_left = filename.find("(")
i_right = filename.find(")")
if i_left > 0:
... |
import numpy as np
import seaborn as sb
import matplotlib.pyplot as plt
import pandas as pd
from mpl_toolkits import mplot3d
from sklearn.cluster import KMeans
sb.set()
sb.set_style("darkgrid")
# This code is for viewing a lot of information on the console
desired_width = 320
pd.set_option('display.width', desired_wid... |
#if and else if
"""
number = 23
guess = int(input("Enter an interger:"))
if guess == number:
print("Congratulation, u guess it.")
print("But u do not win any prizes!")
elif guess < number:
print("No its a little higher ")
else:
print("No , its a little lower")
print("Done")
"""
#while loop
"""
num... |
from django.db import models
from django.core.validators import MinLengthValidator
# Create your models here.
class Cats(models.Model):
nickname = models.CharField(max_length=30)
weight = models.PositiveIntegerField()
foods = models.CharField(max_length = 100)
breed = models.ForeignKey('Breeds', on_del... |
# -*- coding: utf-8 -*-
# Copyright (c) 2011, National Film Board of Canada - Office National du Film du Canada
from django.test import TestCase
from django.core.exceptions import ObjectDoesNotExist
from django.contrib.auth.models import User
from django.test.client import Client
from django.conf import settings
from... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('firestation', '0022_firedepartment_twitter_handle'),
]
operations = [
migrations.RenameField(
model_name='staffi... |
from sqlalchemy import *
from migrate import *
from migrate.changeset import schema
pre_meta = MetaData()
post_meta = MetaData()
contracts = Table('contracts', post_meta,
Column('id', Integer, primary_key=True, nullable=False),
Column('description', String(length=140)),
Column('start_date', Date),
Col... |
from _21_rpg import Character, encounter, simulate_battle
def test_encounter():
player = Character(8, 5, 5)
boss = Character(12, 7, 2)
assert encounter(player, boss) is None
assert boss.hit_points == 9
assert player.hit_points == 6
assert encounter(player, boss) is None
assert boss.hit_p... |
def main():
'''
Показывает механизм работы continue и break
'''
while True:
a = int(input())
if a < 10:
continue
elif a > 100:
break
else:
print(a)
if __name__ == '__main__':
main()
|
from multiprocessing import Pool
from typing import Union, Tuple
import numpy as np
from batchgenerators.utilities.file_and_folder_operations import *
from nnunetv2.configuration import default_num_processes
from nnunetv2.paths import nnUNet_results
from nnunetv2.utilities.dataset_name_id_conversion import maybe_conve... |
# CCC 2021 Junior 4: Arranging Books
#
# Author: Charles Chen
#
# This solution is inspired by a formula described by Aaron He on YouTube. The
# formula is:
#
# minSwaps = (# misplaced books in L) + (# misplaced books in M)
# - MIN((# of M books in L), (# of L books in M))
#
# For the reasoning behind this formula and... |
name = 'tictactoe'
print('Compiling ' + name)
env = Environment()
env.Append(LIBS = [
'sfml-window',
'sfml-system',
'sfml-graphics'
]);
VariantDir("build", "source", duplicate = 0)
program = env.Program(name, Glob('build/*.cpp'))
env.Install("..", program)
|
import ubinascii
import machine
from machine import Pin, PWM
client_id = ubinascii.hexlify(machine.unique_id())
|
from common import service
from shared.models import player_privacy
from sqlalchemy.sql import select
from sqlalchemy.dialects.mysql import insert
privacy_fields = (
# (name, default)
("names", False),
("soulmate", False),
("tribe", False),
("look", False),
("activity", False),
("badges", True),
("titles", T... |
from keras.models import Model, Sequential, load_model, model_from_config
from keras.layers import Input, concatenate,InputSpec, Activation, Embedding, LSTM, Dense, Dropout, Lambda, Flatten, Bidirectional
from keras.engine.topology import Layer
from keras.optimizers import Adam
from keras.callbacks import EarlyStopping... |
import sys
import boto3
from datetime import datetime
from awsglue.transforms import *
from awsglue.utils import getResolvedOptions
from pyspark.context import SparkContext
from awsglue.context import GlueContext
from awsglue.dynamicframe import DynamicFrame
from awsglue.job import Job
from pyspark.sql.functions import... |
from PyQt4 import QtGui, QtCore
from vmedian import vmedian
import numpy as np
import cv2
from matplotlib.pylab import cm
class QFabFilter(QtGui.QFrame):
def __init__(self, video):
super(QFabFilter, self).__init__()
self.video = video
self.init_filters()
self.init_ui()
def in... |
"""ResNet50 model for Keras, just copy this code, and try to get a better understanding of this model.
# Reference:
- [Deep Residual Learning for Image Recognition](
https://arxiv.org/abs/1512.03385)
Adapted from code contributed by BigMoyan.
"""
from __future__ import print_function
import numpy as np
import ... |
chart = {}
n = int(input())
for i in range(n):
x = int(input())
if x in chart:
chart[x] += 1
else:
chart[x] = 1
vals = sorted(chart.values())
used = []
used1 = 0
# case 1 only 2 1s
if vals[-1] == vals[-2] and vals[-1] != vals[-3]:
for name, val in chart.items():
if val == vals[-... |
import string
import random
from . import cpf as cpf_module
from . import cnpj as cnpj_module
def cpf():
cpf_ramdom = ''.join(random.choice(string.digits) for i in range(11))
while not cpf_module.validate(cpf_ramdom):
cpf_ramdom = ''.join(random.choice(string.digits) for i in range(11))
return cpf... |
import tkinter as tk
from tkinter import *
import tkinter.font as tkFont
import datetime
# from PIL import ImageTk
#調色盤
rgb1 = (92, 128, 188) #rgb顏色設定
bgcolor1 = '#%02x%02x%02x'% rgb1 #將rgb格式轉成hex格式
rgb2 = (46, 196, 182)
bgcolor2 = '#%02x%02x%02x'% rgb2
rgb3 = (216, 247, 147)
bgcolor3 = '#%02x%02x%02x'% rgb3
rgb4... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
python wifi share in windows
:author:
yehuohan, 550034086@qq.com, yehuohan@gmail.com
"""
#===============================================================================
# import
#========================================================================... |
# -*- coding: utf-8 -*-
import sqlite3
try:
from . import create_table as ct
from . import ls as li
except:
import create_table as ct
import ls as li
from pathlib import Path
def del_todo():
home_dir = str(Path.home())
conn = sqlite3.connect(home_dir + "/task.db")
cur = conn.cursor()
slct_data = "select * fro... |
from typing import List
class Solution:
def binary_recursive_search(self, nums: List[int], target: int, low=0) -> int:
if len(nums) < 1:
return None
elif len(nums) is 1 and nums[0] != target:
return None
else:
middle = (len(nums) - 1) // 2
if ... |
def team_comp(heroes):
if len(set(heroes)) != len(heroes) or len(heroes) != 6:
raise InvalidTeam()
tank,damage,support = 0,0,0
for x in heroes:
if x in TANK:
tank+=1
elif x in DAMAGE:
damage+=1
elif x in SUPPORT:
support+=1
return [t... |
import selenium
import time
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import ElementClickInterceptedException
path_of_driver = "C:\development\chromedriver.exe"
from selenium import webdriver
from bs4 import BeautifulSoup
import requests
import time
import lxml
my_form = "https://... |
# -*- coding: utf-8 -*-
"""
Created on Sat Sep 24 10:52:54 2016
@author: ahada
"""
import xml.etree.cElementTree as ET
from collections import defaultdict
import re
import pprint
osmfile = "data/sample.osm"
street_type_re = re.compile(r'\b\S+\.?$', re.IGNORECASE) #pulls out or matches the very last word in street na... |
import numpy as np
import torch
import torch.nn as nn
from . import debug as db
import torch.nn.functional as F
from collections import OrderedDict
from scanrepro import SimCLRModel
import scancuda
from torchvision import models
import pytorch_lightning as pl
class SCANModelPT(nn.Module):
def __init__(
sel... |
from django.shortcuts import render, redirect
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login, logout
from authentication.models import UserType
def auth_login(request):
if request.method == 'POST':
user = authenticate(username=request.POST['login'], password... |
#!/usr/bin/env python3
from operator import eq
if __name__ == "__main__":
n = int(input())
for _ in range(n):
a = input()
b = input()
res = []
for aa, bb in zip(a, b):
if aa == bb:
res.append(".")
else:
res.append("*")
... |
from six import add_metaclass
from abc import ABCMeta
from abc import abstractmethod
from abc import abstractproperty
from pacman.model.abstract_classes.abstract_has_constraints \
import AbstractHasConstraints
from pacman.model.abstract_classes.abstract_has_label import AbstractHasLabel
@add_metaclass(ABCMeta)
c... |
#!/usr/bin/env python
# coding: UTF-8
import re, sys
class codewriter():
debug = 1 # 0:off, 1:print debug message
lfcode = "\r\n" #line feed code dos="\r\n", unix="\n"
labelnum = 0
def __init__(self, filename):
self.asmfile = open(filename, "a")
self.nextpc = 0 # fo... |
import vwo
import threading
import json
import os
from flask import (
Flask, g, render_template, session, redirect, url_for
)
from vwo import UserStorage, GOAL_TYPES
from os.path import join, dirname
from dotenv import load_dotenv
from flaskr.utils import user
from flaskr.models import home_model, history_model, ... |
import os
my_object = 'test1'
obj_path = os.path.abspath(os.path.join('..', my_object))
print(obj_path)
if os.path.exists(obj_path):
if os.path.isfile(obj_path):
size = os.path.getsize(obj_path)
print(f'Это файл. Размер {size} байт')
elif os.path.isdir(obj_path):
print('Это директория')... |
import unittest
import numpy as np
from data_structure import Graph, GraphNode, GraphEdge
class TestGraph(unittest.TestCase):
@classmethod
def setUpClass(self):
# 0 ---> 1 7
# | \ |\
# | \ | \
# | \ | \
... |
import unittest
import numpy as np
from lsst.ts.wep.ctrlIntf.AstWcsSol import AstWcsSol
from lsst.ts.wep.ctrlIntf.WcsData import WcsData
class TestAstWcsSol(unittest.TestCase):
"""Test the AstWcsSol class."""
def setUp(self):
self.astWcsSol = AstWcsSol()
def testSetWcsData(self):
wcsC... |
from matplotlib import pyplot as plt
import pandas as pd
import numpy as np
import os
def readData(label,feature):
suffix = '.csv'
filename = os.path.join('Data/csv/',label,feature+suffix)
dataframe = pd.read_csv(filename,header=None)
dataframe.columns = ['id','x','y','z','a','label']
return dataframe
def grap... |
import requests
inputs = {
"patient_id": "2",
"attending_email": "erica.skerrett@duke.edu",
"user_age": 67,
}
r = requests.post("http://vcm-7311.vm.duke.edu:5000/api/new_patient",
json=inputs)
inputs2 = {
"patient_id": "2",
"heart_rate": 67, # need to get time stamped heart rat... |
# Generated by Django 3.2.5 on 2021-07-27 19:21
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0006_auto_20210727_1804'),
]
operations = [
migrations.AddField(
model_name='produto',
name='capa',
... |
import re
#import nagisa
import MeCab
from my_utils import __PAD__, __SOS__, __EOS__, __UNK__, __PAD_ID__, __SOS_ID__, __EOS_ID__, __UNK_ID__
class LimitedLang():
"""
単語数を制限したLang
"""
def __init__(self, lang_obj, maxcount):
self.name = lang_obj.name
self.word2index = {__PAD__: __PAD_I... |
from LSP.plugin.core.collections import DottedDict
from LSP.plugin.core.protocol import Diagnostic
from LSP.plugin.core.protocol import DocumentUri
from LSP.plugin.core.protocol import Error
from LSP.plugin.core.protocol import TextDocumentSyncKind
from LSP.plugin.core.sessions import get_initialize_params
from LSP.plu... |
#from lib.instascrapper import Instascrapper
from lib.imgur import Imgur
class Huachiapi:
description = "description"
default_msg = "Holis aún estoy bajo construcción!"
def __init__(self):
pass
# saldazo method
def saldazo(self, *args):
return f"{self.default_msg}"
# shop me... |
import threading
import time
import random
class Counter():
def __init__(self, start=0):
self.lock = threading.Lock()
self.value = start
def increment(self):
print "[Counter.increment()] waiting to acquire lock"
self.lock.acquire()
try:
print "[Counter.incre... |
# Copyright (c) 2017-2022 The Molecular Sciences Software Institute, Virginia Tech
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this l... |
#!/home/lubuntu/miniconda2/bin/python
import pyglet
from pyglet.window import mouse
import sys
import looky_config
from pyglet.window import key
from math import sqrt
def writeCalibrationFile(xs,ys):
dx = xs[1] - xs[0]
dy = ys[1] - ys[0]
dist = sqrt(dx**2.0 + dy**2.0)
dpi = round(dist/3.0)
fid = o... |
N,M = map(int, input().split())
Answer=[]
Package, Solo = 10000, 10000
for _ in range(M):
i1, i2 = map(int, input().split())
if Solo>i2: Solo=i2
if Package>i1 and i2>i1/6: Package=i1
print(min((N//6+1)*Package, (N//6)*Package + (N%6)*Solo, N*Solo))
|
import tensorflow as tf
def conv(inputs, ksize, kchannel, kstride=1, name='conv'):
'''2D convolution.
Args:
inputs: An input tensor in NHWC.
ksize: The size of filter.
kchannel: The number of filter channel.
kstride: The stride interval.
Returns:
The output te... |
from sqlalchemy import Column, ForeignKey, String, Integer
from sqlalchemy.orm import relationship
from application import db
from application.domain.model.base_model import BaseModel
class Post(BaseModel, db.Model):
__tablename__ = 'posts'
PER_PAGE = 10
user_id = Column(Integer, ForeignKey("users.id"),... |
#!/usr/bin/python3
import argparse
import i3ipc
import os
import re
from dataclasses import dataclass
from typing import List, Any
def flatten(l):
return [item for sl in l for item in sl]
@dataclass(frozen=True)
class Windows:
windows: List[Any]
def window_class(self, window_class: str):
retur... |
'''
绘图API:绘制文本
1. 文本
2. 各种图形(直线、点、椭圆、弧、扇形、多边形等)
3. 图像
QPainter
调用画板:painter.begin()
painter.end() 绘制结束
必须在paintEvent事件方法中绘制各种元素
'''
import sys
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtGui import QPainter, QColor, QFont, QPen
from PyQt5.QtCore import Qt
class DrawText(QWidget):
def __init__(s... |
# Quick Sort
# Function signature: quicksort(Array, Integer, Integer)
# The main function which starts the quick sort process. This functions splits the array into subarrays and calls
# quicksort on these two arrays. This is the divide part of divide and conquer strategy applied to sort the whole
# array.
# Initial ca... |
from sys import path
from os.path import dirname as dir
from shutil import rmtree
path.append(dir(path[0]))
from analizer import grammar
from analizer.reports import BnfGrammar
from analizer.interpreter import symbolReport
dropAll = 0
if dropAll:
print("Eliminando registros")
rmtree("data")
s = """
USE t... |
import sys
n = input().strip()
arr = [int(i) for i in input().strip().split(' ')]
#print(arr)
print(sum(arr)) |
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 23 00:55:57 2020
@author: Daniela G. Osuna
"""
import matplotlib.pyplot as plt
Estados = ['Coahuila', 'Chiapas','Zacatecas','Jalisco','Total']
defunciones = [1934,1090,752,3396,5439]
colores = ['red','green','blue','orange','yellow']
plt.title('Defunciones... |
from typing import Optional
def greeting(name: Optional[str] = None) -> str:
# Optional[str] means the same thing as Union[str, None]
if name is None:
name = 'stranger'
return 'Hello, ' + name
|
# Generated by Django 2.2.4 on 2019-11-03 21:32
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('crm', '0030_auto_20191103_2057'),
]
operations = [
migrations.AlterField(
model_name='templatec... |
from django.utils import timezone
from django.db import models
import random
from .models import BaseModel
from .company_data import Client, Vendor, CompanyDetail
from .employee_data import Employee
def random_string():
return str(random.randint(10000, 99999))
class DayBook(BaseModel):
number = models.Char... |
# Function used to find the minimum and maximum of each tiles
import argparse
import ee
from find_image import get_filter_collection, define_geometry
from constant.gee_constant import DICT_EVI_PARAM, GEE_S2_BAND, GEE_DRIVE_FOLDER, EVI_BAND, \
NDVI_BAND, DICT_TRANSLATE_BAND, NB_VI_CSV, CONVERTOR
from utils.image_fin... |
import numpy as np
from netCDF4 import Dataset
import sys
def direct():
# where the data file was output
return '../RunSimulation/'
def save_direct():
# where you want to save the summary data
return './'
def get_all_Vcs(Vcses_tot):
Vc_list = []
for Vcses in Vcses_tot:
... |
from utils import BigQueryClient
import matplotlib.pyplot as plt
query = """SELECT * FROM `revenue-manager-alphalabs.revenue_manager.hotels_table`"""
df = BigQueryClient().load_dataframe_from_bigquery(query=query)
room = df[df['room_name'] == 'Habitación estándar, vistas al mar'].reset_index(drop=True)
room_pivot =... |
n = int(input())
d = {'purple':'Power','green':'Time','blue':'Space','orange':'Soul','red':'Reality','yellow':'Mind'}
a,b = [],[]
for i in d.keys():
a.append(i)
for i in range(n):
b.append(input())
print(6-n)
for i in list(set(a)-set(b)):
print(d[i])
|
from astropy.io import fits
import sys
coadd = fits.open(sys.argv[1])
coadd[0].data = coadd[0].data[0:2048,0:2048]
coadd.writeto(sys.argv[1], overwrite=True)
|
from multiprocessing import Pool,Pipe,cpu_count,Manager
from pandas import DataFrame
import numpy as np
import operator
from STRATEGY.bk_strategy import *
import pymysql
import time
def pysql_connect():
db = pymysql.connect("localhost", "root", "12345678", "qtsm")
cursor = db.cursor()
return {'db':db,'cur... |
#!/usr/bin/python
from xbee import XBee, ZigBee
import serial
import time
import sqlite3
def get_temperature(data):
item = data['samples']
temperature = ((item[0].get('adc-0')*1.2/1023)-0.5)*100
print temperature
#if format=="F":
#convert to farenheit
#tempature = (tempature * 1.8) ... |
import random
# Your main() method accepts one argument. The value of the argument is stored in a variable called "balance" (See line 9)
def main(balance):
a=int(input(f'Your balance is {balance}. How much would you like to wager?'))
print(f'Your are betting {a}')
slot1=random.randint(0,9)
slot2=random.randint... |
from fractions import Fraction
# The float class is Python's default implementation for representing real numbers
# The Python (CPython) float is implemented using the <C double> type which (usually!) implements
# the <IEEE 754 double-precision binary float>, also called <binary64>
# The float uses a fixed number of b... |
__author__ = 'gbrewer'
############################################################################################
#
# Imported Definitions
#
############################################################################################
# import json
#import os
#import traceback
#import datetime
try:
import indigo
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.