text stringlengths 8 6.05M |
|---|
# Basics of Python
# No need to declare a data type
my_name = "Naima"
print(my_name)
# Variables are case sensitive and use Snake case; Pascal case is used for classes
My_name = "Not Naima"
print(My_name)
# Can assign a variable with the value of another
name = "Jennifer"
jennifer = name
print(jennifer)
# Print mul... |
class Priority:
def __init__(self, higher_priority=[], lower_priority=[], non_colliding=[]):
self.higher_priority = higher_priority
self.lower_priority = lower_priority
self.non_colliding = non_colliding
def get_higher_priority(self):
return self.higher_priority
def get_low... |
# Generated by Django 2.2.13 on 2020-07-17 15:27
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accounts', '0012_auto_20200717_2055'),
]
operations = [
migrations.AlterField(
model_name='userprofile',
name='Imag... |
from django.shortcuts import render, redirect, get_object_or_404
from django.core.urlresolvers import reverse
from django.http import HttpResponse, Http404, HttpResponseRedirect
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.views import... |
#!/usr/bin/python3
import argparse
import json
import re
import platform
import os
import sys
parser = argparse.ArgumentParser()
parser.add_argument('--skip-arch', nargs=1, action='append', default=[])
parser.add_argument('--parse-only', action='store_true')
parser.add_argument('--push', action='store_true')
parser.ad... |
from django.contrib.auth.base_user import BaseUserManager
from django.contrib.auth.hashers import make_password
from rest_framework.utils import json
from rest_framework.views import APIView
from rest_framework.response import Response
import requests
from rest_framework_simplejwt.tokens import RefreshToken
from django... |
import os
os.environ['SPARK_HOME'] = "/application/hadoop/app/spark_on_yarn/"
os.environ['JAVA_HOME'] = "/application/hadoop/app/jdk/"
os.environ['HADOOP_CONF_DIR'] = "/application/hadoop/app/hadoop/etc/hadoop"
import findspark
findspark.init()
from pyspark import SparkConf
from pyspark import SparkContext
if __name_... |
from django.contrib.auth.models import User
from products.models import Reviews
from django import forms
class AllProductDetailes(forms.ModelForm):
class Meta:
model = User
fields = '__all__'
class ReviewForm(forms.ModelForm):
class Meta:
model = Reviews
fields = '__all__'
|
# Fibonacci Sequence Code In Python
# Copyright © 2019, Sai K Raja, All Rights Reserved
x = input("What iteration/root in the fibonacci seqeunce do you want?")
print("0") #Starting Fibonacci Sequence with a zero (optional)
def fibonacci_sequence(a): #Creating Fibonacci Sequence Function
if a == 1: #Starting... |
import pandas as pd
from test_grades import test_grades
# author: Kaiwen Liu
'''q4'''
def test_restaurant_grades(df_resturant,camis_id):
# this function returns value for each resturant with function test_grades
df_eachresturant=df_resturant.ix[camis_id]
df = list(df_eachresturant['GRADE'])
return ... |
def dig_pow(n, p):
total = sum(int(a) ** i for i, a in enumerate(str(n), start=p))
quo, rem = divmod(total, n)
return quo if rem == 0 else -1
|
import sys
sys.setrecursionlimit(2000)
def simpleSolve(A, st, en, K, sym):
symCount = 0
for c in A[st:en]:
if c == sym:
symCount += 1
if (symCount == 0):
return 0
elif (symCount == K):
return 1
return -1
def flipFromLast(A, st, en, K):
a = list(A)
for i in range(en-K, en):
if i < 0:
continue
pri... |
# 数据准备
#初步处理照片,识别照片中的人脸,规范化成220*220jpg文件。
import cv2
XX="CM"#类型 AF AM CF CM
cascPath = "haarcascade_frontalface_default.xml"
faceCascade = cv2.CascadeClassifier(cascPath)
for i in range(1,751):
print(i)
#Read the image anf BGR to GRAY
imagePath = "E:\\daxue\\graduation\\SCUT-FBP5500_v2\\Images\\"+XX+str(... |
# Generated by Django 2.2 on 2020-01-29 11:50
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('home', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='banner',
name='image',
field=m... |
import pytest
from flask.testing import FlaskClient
from ajdb.structure import ActSet
def test_act_valid(client: FlaskClient, fake_db: ActSet) -> None:
response = client.get('/act/2020. évi XD. törvény')
response_str = response.data.decode('utf-8')
act = fake_db.act('2020. évi XD. törvény')
assert ac... |
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
from dataclasses import dataclass
from pants.backend.codegen.thrift.apache.python import subsystem
from pants.backend.codegen.thrift.apache.python.addi... |
import json
from django.contrib import messages
from django.core.urlresolvers import reverse_lazy
from django.views.generic import FormView, ListView, UpdateView
from djofx import models
from djofx.forms import CategoriseTransactionForm, CategoryForm
from djofx.utils import qs_to_monthly_report
from djofx.views.base ... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.3 on 2017-11-04 03:44
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('adminapp', '0026_delete_parametrizacion'),
]
operations = [
migrations.Crea... |
import heapq
def solution(jobs):
answer, time, end, count = 0, 0, -1, 0
hq = []
n= len(jobs)
while count < n:
for job in jobs:
if end < job[0] <= time:
heapq.heappush(hq, job[1])
answer += time - job[0]
if hq:
answer += hq[0] * len... |
import sys
import os
thisdir = os.path.dirname(os.path.abspath(__file__))
benchdir = os.path.join(thisdir, "benchmarks")
sys.path.append(benchdir)
import datetime
import argparse
import time
import benchutil
TIMEOUT = 60 * 60.0 # one hour
def add_benchmarks(jobs, interpreter, args):
for name in ["jittest", "py... |
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, SubmitField
from wtforms import (widgets, SelectMultipleField, IntegerField,
TextAreaField, SelectField)
from wtforms.validators import DataRequired, ValidationError, Email, EqualTo
from app.models import ... |
import re
import PIL.Image
import pytest
import torch
from common_utils import assert_equal
from prototype_common_utils import make_label
from torchvision.prototype import transforms, tv_tensors
from torchvision.transforms.v2._utils import check_type, is_pure_tensor
from torchvision.transforms.v2.functional import c... |
# Generated by Django 3.0.1 on 2019-12-22 17:30
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('teams', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Mat... |
# --------------------------------------------------------
# --------------------------------------------------------
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import _init_paths
from torch.utils.data import Dataset, DataLoader
from torchv... |
# Generated by Django 3.1.7 on 2021-04-01 00:18
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Persona',
fields=[
('id', models.AutoField(... |
/Users/ccummings/.pyenv/versions/2.7.13/lib/python2.7/_weakrefset.py |
import dice
import gspread
import pygsheets
import pandas as pd
from tabulate import tabulate
from oauth2client.service_account import ServiceAccountCredentials
#########
# Öffne Worksheet in gspread
#########
scope = [
'https://spreadsheets.google.com/feeds',
'https://www.googleapis.com/auth/drive'
]
creden... |
from X import B
b1 = B()
b1.c()
|
from django import forms
from .models import CashWithrawal, RefCreditTransfer, C2BTransaction, CashTransfer,Checkout
from paypal.pro.forms import PaymentForm
class CashWithrawalForm(forms.ModelForm):
class Meta:
model = CashWithrawal
fields = (
"user",
"amount",
)
... |
from time import sleep
num = int(input('Digite um número: '))
print('Analisando o valor...')
sleep(2)
print('Antecessor: {}'.format(num-1))
print('Sucessor: {}'.format(num+1))
|
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 10 16:30:18 2014
@author: ayush488
"""
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 10 08:25:21 2014
@author: ayush488
"""
import math
import urllib #needed for web calls
import operator #needed for sorting dictionary
N=5000000000 #assuming the number of web pages to... |
import numpy as np
from blob_mask import blob_mask, blob_mask_dim
from constants import feature_size, anchor_size, real_image_width, real_image_height
statuses = {
"normal": 0,
"hat": 1,
"ghost": 2,
}
s = 6
y_offset = 3 # The blob picture is not centered vertically around it's position
def get_localizat... |
import RPi.GPIO as GPIO
import time
import matplotlib.pyplot as plt
comparator_value = 4
troyka = 17
dac = [26, 19, 13, 6, 5, 11, 9, 10]
leds = [21, 20, 16, 12, 7, 8, 25, 24]
bits = len(dac)
levels = 2**bits
maxvoltage = 3.3
listofnums =[]
temp=0
def decimal2binary(dec):
return[int(bin) for bin in bin(dec)[2:... |
import numpy as np
import pandas as pd
import tensorflow as tf
import pickle
import copy
from scipy.stats import wasserstein_distance
from spyro.builders import build_mlp_regressor, build_distributional_dqn
from spyro.core import BaseAgent
from spyro.losses import quantile_huber_loss
from spyro.utils import progress
... |
from pylab import *
import numpy
ncores = numpy.arange(1,128,1)
plot(ncores, 1.0/(0.1+0.9/ncores))
show()
plot(ncores, (1.0/(0.1+0.9/ncores))/ncores)
show()
|
f = open("./dangan:ot-1228.csv")
count = 0
for line in f:
k = line.split(",")
for i in k:
count += 1
print count
|
#This program uses nested for loop to identify which meals have and don't have spam.
#Lists each ingredients in either and calculates a spam score for the relevant meal.
menu = [
["egg", "bacon"],
["egg", "sausage", "bacon"],
["egg", "spam"],
["egg", "bacon", "spam"],
["egg", "bacon", "saus... |
total = 0
final_total = 0
final_depth_level = 10
current_depth = 1
print "Gimme a number less than 10 "
#x = int(raw_input('> '))
x=8
print "Gimme another number less than 10 "
#y = int(raw_input('> '))
y=9
def recursion_depth(depth):
if (current_depth == 1):
print "at depth of "+str(dep... |
import random
import math
def generatelots(n):
l = []
for x in xrange(1,n+1):
k = []
for y in xrange(0,16):
k.extend([random.randrange(0,10)])
l.append(k)
return l
def strangedistance(n,m):
count = 0
for i in xrange(0,len(m[0])):
if n[i] == m[0][i]:
count += 1
return (count-m[1])**2
def repro... |
from django.shortcuts import render
from visitations import models
from django.urls import reverse_lazy
from django.views.generic.list import ListView
from patients.models import Patient
from django.views.generic.detail import DetailView
from django.views.generic.edit import UpdateView, CreateView, DeleteView
from djan... |
#!/usr/bin/python
class Solution(object):
def canWinNim(self, n):
if n%4 == 0:
return False
return True |
import numpy as np
import sys
import math
import time
def partition(lista,inicio,fim):
pivo = lista[inicio]
i = inicio + 1
j = fim
while (i <= j):
if(lista[i] <= pivo):
i += 1
elif(lista[j] > pivo):
j -= 1
elif(i <= j):
lista[i... |
import serial
import time
# can be easily replaced with a file name for testing without servos
#ser = serial.Serial('/dev/ttyACM0', 9600)
ser = serial.Serial('COM4', 9600)
#ser = open("servo_output.txt", "w")
# tested and functional
def add_zeros_to_int(int_val):
if(len(str(int_val)) == 1):
return "00" + str(int_v... |
num = 0 #초기값
while num <= 3: #조건식
print("num = %d"%num)
num += 1 #증감식(증가 또는 감소하는 식)
print("""어제 호텔 델루나 봤어?
꼭 봐라 두 번 봐라!!""")
count = 2
while count: #숫자는 0이 거짓
print("재방송을 시작합니다.")
count -= 1
print("두 번 다봤어")
print("열 번 찍어 안넘어가는 나무 없다.")
hit = 0
while hit < 10:
hit += 1
print... |
# Copyright 2017 datawire. 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 law or agr... |
import os
import json
import urllib
import urllib2
import cPickle
import codecs
import time
import datetime
import sys
reload(sys)
sys.setdefaultencoding("latin-1")
from xml2dict import XML2Dict
from unicodedata import normalize
from sets import Set
import pdb
from django.utils.timesince import timeuntil
class Ponto:
... |
def odder(listValues):
'''
this vill filter odds
'''
return [o for o in listValues if o%2!=0] |
class Node:
def __init__(self,data):
self.data = data
self.left = None
self.right = None
class Tree:
def __init__(self):
self.head=None
def insert(self,data):
new_node=Node(data)
if self.head is None:
self.head=new_node
return
... |
'''
栈:先进后出
压栈:添加元素
出栈:删除元素
'''
'''
队列:先进先出
进队
出对
'''
import collections
queue = collections.deque()
# 进队
queue.append("A")
queue.append("B")
queue.append("C")
# 出队
data1 = queue.popleft()
print(data1)
data2 = queue.popleft()
print(data2)
data3 = queue.popleft()
print(data3)
print(queue)
|
# Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'targets': [
{
'target_name': 'my_bundle',
'type': 'shared_library',
'mac_bundle': 1,
'sources': [ 'bundle.c' ],
'mac_bundle_r... |
import dash_bootstrap_components as dbc
carousel = dbc.Carousel(
items=[
{
"key": "1",
"src": "/static/images/slide1.svg",
"header": "With header ",
"caption": "and caption",
},
{
"key": "2",
"src": "/static/images/slid... |
from pyswagger import App
from datetime import datetime
from email._parseaddr import mktime_tz
from email.utils import parsedate_tz
cached_api: App = None
def header_to_datetime(header) -> datetime:
return datetime.fromtimestamp(mktime_tz(parsedate_tz(header)))
def get_api() -> App:
global cached_api
... |
import random
from enum import Enum
import mysql.connector
import math
playableRaces = []
selectableSubraces = []
abilitiesList = []
classesList = []
selectableClassSpecs = []
skillsList = []
backgroundsList = []
armoursList = []
weaponsList = []
numProf = 18
numStat = 6
selectedRace = {}
select... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.core.management.base import BaseCommand
from django.utils.timezone import now
from ...models import AccessToken, Grant, RefreshToken
class Command(BaseCommand):
help = 'Cleans up expires oauth2 rows'
def handle(self, *args, **optio... |
# import random
# print(dir(random))
#
# x = random.randrange(1, 100)
# print(x)
import turtle
scr = turtle.Screen()
scr.screensize(720, 720)
trt = turtle.Turtle()
trt.seth(0)
trt.color("red")
trt.begin_fill()
trt.circle(100)
trt.end_fill()
trt.back(100)
trt.color("blue")
trt.begin_fill()
trt.circle(200)
trt.end_fil... |
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 24 10:02:31 2020
@author: Kaja Amalie
"""
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
tf.executing_eagerly()
from sklearn.model_selection import train_test_split
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import Mi... |
# Configuracion de la base de datos a utilizar.
import settings
from sqlalchemy.engine.url import URL
from sqlalchemy.orm import relationship, backref
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine, Column, Integer, String, ForeignKey
db = declarative_base()
# Tablas... |
from django.contrib import auth
from django.template import RequestContext
from django.shortcuts import render_to_response, get_object_or_404
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.contrib.auth.forms import UserCreationForm
from django import forms
from dj... |
def duplicate_count(text):
output = 0
seen = []
for x in text.lower():
if x not in seen and text.lower().count(x) > 1:
seen.append(x)
output += 1
return output
'''
Count the number of Duplicates
Write a function that will return the count of distinct case-insensitive
a... |
def func(n):
if n == 1:
return 1
if n == 2:
return 2
if arr[n] != -1:
return arr[n]
else:
return func(n-1)+func(n-2)
n = int(input())
arr = [-1]*1000
print(func(n))
def fibonacci(n):
# Taking 1st two fibonacci nubers as 0 and 1
... |
# -*- Mode: python; py-indent-offset: 4; indent-tabs-mode: nil; coding: utf-8; -*-
#
# Copyright (c) 2014, Regents of the University of California
#
# GPL 3.0 license, see the COPYING.md file for more information
from waflib import Logs, Configure
def options(opt):
opt.add_option('--debug', '--with-debug', action... |
print('\033[7;31;40mOlá mundo!\033[m')
print('\033[7;30mOlá Mundo!\033[m')
a = 5
b = 8
print('Os valores são \033[1;36;40m{}\033[m e \033[1;31;45m{}\033[m!!!'.format(a, b))
nome = 'Danilo'
print('Muito prazer em te conhecer, {}{}{}'.format('\033[4;32m', nome, '\033[m'))
# \033[(0, 1, 4, 7);(30 à 37);(40 à 47)m
# \033... |
n =int(input())
alist =[]
blist=[]
for i in range(n):
alist.append(list(map(str,input().split())))
low =int(input())
high =int(input())
for i in alist:
cut = int(i[1][-3:])
if low<=cut<=high:
blist.append(tuple(i))
print(blist)
|
from flask import Flask, render_template, make_response, url_for, redirect
app = Flask(__name__)
@app.route('/')
def index():
resp = make_response(render_template('index.html'))
resp.set_cookie('username', 'the username')
return resp
@app.route('/redirect')
def redirect1():
return redirect(url_for('... |
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
from dataclasses import dataclass
from textwrap import dedent
import pytest
from pants.backend.go.util_rules.coverage import GoCoverMode
from pants.bac... |
import ais.stream
import csv
import os
import sys
from tqdm import tqdm
def data_src():
data_dir = "../data"
filename = "CCG_AIS_Log_2018-05-01.csv"
path = os.path.join(data_dir, filename)
return path
def verify_datasrc(path: str):
with open(path) as f:
try:
for msg in tqdm(enu... |
import boto3
import json
# Resource access manager(ram)
def get_ram_info():
"""
A function that gives ram resource shares info and resource associations
"""
conn = boto3.client('ec2')
regions = [region['RegionName'] for region in conn.describe_regions()['Regions']]
shares_info = []
share_p... |
from _base.downloadAndInstall import DownloadAndInstall
from _feature_objects.feature_popup import *
from _feature_objects.feature_screen import *
from _feature_objects.feature_left_menu import *
from _test_suites._variables.variables import Variables
class MainPage(BaseActions):
def check_main_page_loaded(self)... |
import os
import sys
import shutil
def remove_file(file):
""" Remove file path is local from working dir """
try:
os.remove(file)
except Exception:
pass
def before_tag(context, tag):
if tag.startswith('before.clean') or tag.startswith('clean'):
remove_file('site.conf')
... |
# from __future__ import print_function
# import argparse
# import os
# import random
# import torch
# import torch.nn as nn
# import torch.nn.parallel
# import torch.backends.cudnn as cudnn
# import torch.optim as optim
# import torch.utils.data
# import torchvision.transforms as transforms
# import torchvision.utils ... |
import paho.mqtt.client as mqtt
import time
from threading import Thread
def on_message(client, userdata, message):
# print(message)
print('Recver>> Received message')
def sender(host, port, payload):
print('Sender>> Starting...')
client = mqtt.Client('measure_sender')
client.connect(host, port)... |
from __future__ import annotations
import enum
import textwrap
from typing import (
Iterable,
Sequence,
Union,
)
import uuid
from ai.backend.client.auth import AuthToken, AuthTokenTypes
from ai.backend.client.request import Request
from ai.backend.client.session import api_session
from ai.backend.client.o... |
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from pants.backend.docker.goals.tailor import rules as tailor_rules
from pants.backend.docker.rules import rules as docker_rules
from pants.backend.docker.target_types import DockerImageTa... |
"""-----------------------------------------------------------------
The user is asked to enter one or more keywords.
Input: none
Output: a list containing all the keywords that the user has entered (where each keyword is a string)
-----------------------------------------------------------------"""
def user_keyword... |
import os
import sys
import unittest
try:
sys.path.append(os.environ.get('PY_DEV_HOME'))
from webTest_pro.common.mysqlKit import sqlOperating
from webTest_pro.common.logger import logger,T_INFO
from webTest_pro.common.initData import init
except ImportError as e:
print e
host = init.db_conf['hos... |
from datetime import datetime
import random
from pie_logger import get_logger
log = get_logger()
# socket.emit('callback', {action: 'oven', unique_pie_id: pie.unique_pie_id, heat_time: game.time.now})
# socket.emit('callback', {action: 'bake', baketype: 'apple'});
# socket.emit('callback', {action: 'bake', bakety... |
import sys
sys.path.append('../')
from BDA import stats
stats.binom_test(x = 10, n = 30, p = 0.5, alternative = "greater")
stats.binom_test(x = [10, 20], p = 0.5, alternative = "greater")
#binom.test(x = 10, n = 30, p = 0.5, alternative = "greater") ## R
stats.binom_test(x = 10, n = 30, p = 0.5, alternative = "les... |
def oddOrEven(arr):
if sum(arr) % 2 == 0:
return "even"
else:
return "odd" |
# to run this script type
# python3 hello_world.py
def hello_world():
"""
This is a function which
returns the greeting 'hello world'
"""
greeting = "hello world!"
print(greeting)
return greeting
def whatever():
return (20 + 10)
if __name__ == '__main__':
hello_world() |
# web评分服务端
# -*-coding:utf-8-*-
from flask import Flask, render_template, request
import os
import base64
import cv2
from keras.models import Sequential
from keras.models import load_model
import numpy as np
import time
def sc(imagePath, current):
global model
# imagePath=q.get()
frame = cv2.imread(imagePa... |
from pprint import pformat
from contextlib import contextmanager
import numpy as np
import signal
import time
import re
import os
import traceback
import pdb
from collections.abc import MutableMapping
import subprocess
import copy
import datetime
import psutil
import resource
import sys
import shutil
import errno
impor... |
print("enter correct user name and password combo to continue")
count=0
username=bhavanagadde
password=bhavana#1995
while password!="bhavana#1995" and username!="bhavanagadde" and count<3:
username=input('enter username=') and password=input('enter password=')
if username==bhavanagadde and password==bhavana#1995... |
#!/usr/bin/env python
#-*- coding: UTF-8 -*_
import os
import shutil
import sys
from Bio import SeqIO
#Importar the function in other script
import Find_domains
import funtion_blast
import make_tres
#Informatatio for teh program help
if len(sys.argv)<2:
print("""\n --------------Welcome to the program help-----... |
from django.apps import AppConfig
class CourseManagementAppConfig(AppConfig):
name = 'course_management_app'
|
from hypothesis import given
import hypothesis.strategies as st
import numpy as np
from nonlinear import NonLinearSolver
@given()
# @example([])
def test_NonLinearSolver(s):
pass
|
import struct
padding = 'A' * 76
return_address = struct.pack('I', 0xb7ec60c0)
win_address = struct.pack('I', 0x080483f4)
print padding + win_address + return_address
|
from enum import Enum
from pygame.locals import K_UP, K_DOWN, K_LEFT, K_RIGHT
Color = {
"RED": (255, 0, 0),
"BLUE": (0, 0, 255),
"GREEN": (0, 255, 0),
"YELLOW": (255, 255, 0),
"CYAN": (0, 255, 255),
"WHITE": (255, 255, 255),
"GRAY": (50, 50, 50)
}
RED = Color["RED"]
BLUE = Color["BLUE"]
GR... |
from PIL import Image
import base64
import numpy as np
import requests
import json
import cv2
import dlib
import sys
from random import randint
from random import uniform
from random import choice
import time
from PyQt5 import QtGui
from PyQt5.QtWidgets import QWidget, QApplication, QLabel, QVBoxLayout
from PyQt5.QtGui... |
import json
from channels.db import database_sync_to_async
from channels.generic.websocket import AsyncWebsocketConsumer
import messaging.models
from messaging.utils import Firebase
class MessageConsumer(AsyncWebsocketConsumer):
async def websocket_connect(self, event):
self.user = self.retrieve_user(... |
from django.contrib import admin
from architect.inventory.models import Inventory, Resource
@admin.register(Inventory)
class InventoryAdmin(admin.ModelAdmin):
list_display = ('name', 'engine', 'status')
list_filter = ('status', 'engine')
@admin.register(Resource)
class ResourceAdmin(admin.ModelAdmin):
... |
# http://www.practicepython.org/exercise/2014/03/05/05-list-overlap.html
from random import randint
def estaDentroDe(num, lista):
for i in lista:
if (i == num):
return True
a = []
b = []
res = []
for i in range(20): #GENERAR DOS LISTAS ALEATORIAS
numa = randint(0,20)
numb = randint(0... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from SAAS_UI_TEST.framework.readconfig import config,LOG_PATH
import logging
import os.path
from SAAS_UI_TEST.framework.browser_engine import BrowserEngine
from SAAS_UI_TEST.framework.logger import Logger
'''
level = logging.DEBUG
logger = logging.getLogger('browserEngine'... |
import unittest
from katas.kyu_7.return_the_closest_number_multiple_of_10 import \
closest_multiple_10
class ClosestMultipleOf10TestCase(unittest.TestCase):
def test_equal_1(self):
self.assertEqual(closest_multiple_10(54), 50)
def test_equal_2(self):
self.assertEqual(closest_multiple_10(... |
import sys
import random
from PyQt5.QtGui import QPainter, QColor
from PyQt5 import uic
from PyQt5.QtWidgets import QApplication
from PyQt5.QtWidgets import QMainWindow, QTableWidgetItem
import sqlite3
class MyWidget(QMainWindow):
def __init__(self):
super().__init__()
uic.loadUi("addEditCoffeeFor... |
import tweepy as tw
from config import TWITTER_CONFIG
class TwitterConsumer:
def __init__(self):
auth = tw.OAuthHandler(TWITTER_CONFIG["consumer_key"], TWITTER_CONFIG["consumer_secret"])
auth.set_access_token(TWITTER_CONFIG["key"], TWITTER_CONFIG["secret_key"])
self.__api = tw.API(auth, wa... |
import json
import boto3
from pytube import YouTube
import botocore.vendored.requests.packages.urllib3 as urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
def lambda_handler(event, context):
ACCESS_KEY_ID = 'AKIAIP7E6DYJUA6FZXEQ'
ACCESS_SECRET_KEY = 'w0YKEuAGC7gxxeYfL6Ouj/QDwQ4xHZK4V... |
from crontab import CronTab
"""
Here the object can take two parameters one for setting
the user cron jobs, it defaults to the current user
executing the script if ommited. The fake_tab parameter
sets a testing variable. So you can print what could be
written to the file onscreen instead or writting directly
into the c... |
from nastran.analysis import Subcase
from typing import Dict
import numpy as np
from pyNastran.bdf.bdf import BDF
from nastran.aero.superpanels import SuperAeroPanel5, SuperAeroPanel1
from nastran.aero.analysis.flutter import FlutterSubcase, FlutterAnalysisModel
class PanelFlutterSubcase(FlutterSubcase):
def ... |
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from __future__ import absolute_import, division, print_function, unicode_literals
from wadebug.config import Config
class Result:
def t... |
from copy import deepcopy
from unittest.mock import patch
from mybib.graphql.access_layer import EntityAlreadyExistsError
@patch("mybib.web.api.papers.insert_paper", autospec=True)
def test_post_inserts(
insert_paper_mock, authenticated_post, bibtex_json_multiple_authors
):
bibtex_multiple_authors, json_mult... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.