text stringlengths 8 6.05M |
|---|
from django.shortcuts import render
from rest_framework import generics,viewsets
from .models import Estimates
from .serializer import EstimateSerializer
from django.http import JsonResponse
class EstimateViewSet(viewsets.ModelViewSet):
queryset = Estimates.objects.all()
serializer_class = EstimateSerializer
def esti... |
from flask import Flask,render_template,request,url_for,jsonify,json,session,redirect
import unirest
import httplib
from parse_rest.connection import register
register(<application_id>, <rest_api_key>[, master_key=None]) //parse credentials
from parse_rest.datatypes import Object
app=Flask(__name__)
class ngos(Object... |
# file io stuff
import os.path
import json
camID = 0
whiteBalance = 1
isFlipped = False
def getParams():
file = open('configs/camera.txt', 'r')
config = file.read()
params = json.loads(config)
return config
def getWhiteBalance():
return whiteBalance
def setParam(paramName, value, cameraParameters):
glo... |
from django.shortcuts import render
from django.http import HttpResponse, request
from .models import * |
from __future__ import absolute_import
import logging
import tensorflow as tf
from parser.constants import TrainVariables
class LatentAttentionNetwork(object):
"""The RNN underlying the implemented model for IFTTT domain.
This class replicates the network proposed in the following NIPS 2016 paper:
Ch... |
import hashlib, trans
import socket, os, codecs
import urllib2, urlparse
import sys
import re
from datetime import datetime
from uuid import uuid4
from copy import deepcopy
from django.contrib import auth
from django.core.files.base import ContentFile
from django.template import TemplateDoesNotExist
from django.templa... |
# coding=utf-8
from django.http import HttpResponseRedirect
from django.core.context_processors import csrf
from django.shortcuts import render_to_response, HttpResponse
from django.core.urlresolvers import reverse
from django.core.files.storage import FileSystemStorage
from models import *
from forms import *
from xl... |
# Compare Algorithms
import pandas as pd
import matplotlib.pyplot as plt
from sklearn import model_selection
from sklearn.ensemble import AdaBoostClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC
#from sklearn import prepr... |
import pandas as pd
import datetime
import numpy as np
import six
## filter PDF->Excel file; select Equi from listed securities
def filter(filename):
bdt_df = pd.read_excel(filename, 1, header=None, index_col=None)
bdt_df_mat = bdt_df.as_matrix()
bdt_equi_list = []
bdt_gdrs_list = []
for d in bdt_d... |
r"""PyTorch Detection Training.
To run in a multi-gpu environment, use the distributed launcher::
python -m torch.distributed.launch --nproc_per_node=$NGPU --use_env \
train.py ... --world-size $NGPU
The default hyperparameters are tuned for training on 8 gpus and 2 images per gpu.
--lr 0.02 --batch-... |
# Реализуйте reducer в задаче подсчета среднего времени, проведенного пользователем на странице.
# Mapper передает в reducer данные в виде key / value, где key - адрес страницы, value - число секунд, проведенных пользователем на данной странице.
# Sample Input:
# www.facebook.com 100
# www.google.com 10
# www.go... |
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from test_adds import adjustement
# from model.project import Project
def test_add_project(app, db, json_projects):
app.session.ensure_login("admi... |
from flask_wtf import FlaskForm as Form
from wtforms import TextField, TextAreaField, SubmitField, validators, ValidationError
# This is creating my form.
# Imported the module Flask_wTF, wtforms.
# Created each field I wanted to be on my contact form e.g. name, email, subject.
# Flask-WTF comes with built-in validato... |
"""
Script that takes in dual fragment merged paired end reads of AAFC Diptera CO1 amplicons and removes degenerate primers
Script expects very specific conditions, and currently does not support other primers or amplicons.
Author: Jackson Eyres
Copyright: Government of Canada
License: MIT
"""
from Bio import SeqIO
im... |
from pyVim.connect import SmartConnect
import ssl
gcontext = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
si=SmartConnect(host="",port=443,user="root",pwd="",sslContext=gcontext)
c = si.RetrieveContent()
rootfolder = c.rooFolder()
for datacenter in rootfolder.childEntity:
print datacenter.name
|
"""Fixes file permissions after the file gets written on import. Put something
like the following in your config.yaml to configure:
permissions:
file: 644
dir: 755
"""
import os
import stat
from beets import config
from beets.plugins import BeetsPlugin
from beets.util import ancestry, displ... |
#!/usr/bin/env python
# -*- coding=utf-8 -*-
__author__ = 'jimit'
__CreateAt__ = '2019\3\7 0007-8:57' |
import os
import cv2
import numpy as np
import tensorflow as tf
path = 'testimages/'
tf.reset_default_graph() # 重置计算图
sess = tf.Session()
# 导入保存好的计算图
saver = tf.train.import_meta_graph('model/softmax_model.meta')
# 导入计算图中的所有参数
saver.restore(sess, 'model/softmax_model')
graph = tf.get_default_graph() # 获取当前计算图
inpu... |
from _typeshed import Incomplete
STATUS: Incomplete
EMOJI_DATA: Incomplete
|
import logging
from telegram.ext import Updater, CommandHandler, InlineQueryHandler
import scryfall_telegram.actions as actions
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
def main():
with open('./token.txt') as f:
token = f.read().strip()
... |
from flask import Flask, request, redirect
import cgi
import os
import jinja2
template_dir = os.path.join(os.path.dirname(__file__), 'templates')
jinja_env = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir), autoescape = True)
app = Flask(__name__)
app.config['DEBUG'] = True
tasks = []
@app.route... |
import serial
import time
with open('port_config.txt', 'r') as f:
text = f.readlines()
SIM900devicePort = '/dev/' + text[0].split('\n')[0]
print 'SIMinterface port =', SIM900devicePort
#devicePort = '/dev/ttyUSB0' #USB to serial device
escapeString = 'xYzZyX' #some random string of letters that won't ever loo... |
import pickle
import pandas as pd
from sklearn.cluster import KMeans
print("Loading data set...")
beer_reviews = pd.read_csv("beer_reviews.csv")
data = beer_reviews.copy() # create copy of original data set
# drop unnecessary columns
data.drop(["brewery_id", "brewery_name", "review_time", "review_profilename", "bee... |
import yaml
def config():
data = yaml.load(open("db.yaml", "r", encoding="utf8"))
data_list = [{
"name": data[k].get("name"),
"host": data[k].get("master").get("host"),
"port": data[k].get("master").get("port"),
"user": data[k].get("master").get("user"),
"pass": data[k]... |
from .UQAnalysis import UQAnalysis
from .RawDataAnalyzer import RawDataAnalyzer
from .Common import Common
class UncertaintyAnalysis(UQAnalysis):
def __init__(self, ensemble, output):
self.moments = None
super(UncertaintyAnalysis, self).__init__(ensemble, output, UQAnalysis.UNCERTAINTY)
def s... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-08-23 20:11
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('api_', '0001_initial'),
]
operations = [
m... |
import math
import random
def leer_numero(ini, fin, mensaje):
while True:
try:
valor = int( input(mensaje) )
except TypeError as ex:
print(type(ex).__name__,'- {}'.format("Tipo de dato no valido"))
else:
if valor >= ini and valor <= fin:
break
return valor
def generador():
numeros = leer_numero... |
def hw(s) -> bool:
length = len(s)
for i in range(0, int(length / 2)):
if s[i] != s[length - i - 1]:
return False
return True
class Solution:
s = ""
catch = {}
catcha = {}
def countSubstrings(self, s: str) -> int:
self.s = s
return self.dfs(0, len(s))
... |
# import the libraries
import numpy as np
import pandas as pd
import torch
# for neural networks
import torch.nn as nn
# for parallel computations
import torch.nn.parallel as parallel
# for the optimizer
import torch.optim as optim
# for some utilities
import torch.utils.data
# for stochasitic gradient descent
from tor... |
from google.appengine.ext import db
from usermeta import UserMeta
from game import Game
import math
import random
from ..utilities import *
class League(db.Model):
def createLeague(self,teams):
league_teams=[]
for t in teams:
team=LeagueTeam(user=t)
t.league=True
save_user(t)
team.pu... |
<<<<<<< HEAD
Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, 22:44:40) [MSC v.1600 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> """
This is a commit
written in
more than just one line
"""
'\nThis is a commit\nwritten in\nmore than just one line\n'
>>> print("hello world"... |
import sys
r = sys.stdin.readline
N = int(r())
arr = []
sum = 0
for i in range(N) :
arr.append(int(r()))
arr.sort() #정렬하고
arr.reverse() #내림차순으로 만듬
for i in range(N) :
temp = arr[i] - i
if temp < 0 :
break
else :
sum += temp
print(sum) |
#!/usr/bin/env python
'''
Basic script to initialize database with some test entries.
'''
__author__ = 'Aditya Viswanathan'
__email__ = 'aditya@adityaviswanathan.com'
import argparse
import os
import sys
from db import db
from flask_script import Manager as ScriptRunner
from flask_migrate import Migrate, MigrateComm... |
#!/bin/python3
import os
import sys
import datetime
#
# Complete the timeConversion function below.
#
#Sample Input 0
#07:05:45PM
#Sample Output 0
#19:05:45
def timeConversion(s):
#
# Write your code here.
#
isAm = s.find("AM")>-1
isPm = s.find("PM")>-1
s = s.replace("AM","")
s = s.repla... |
"""
pyjld.system.registry.base
"""
__author__ = "Jean-Lou Dupont"
__fileid = "$Id: base.py 37 2009-04-03 01:58:16Z jeanlou.dupont $"
__all__ = ['Registry', 'RegistryException']
import sys
class RegistryException(Exception):
"""
An exception class for Registry
"""
def __init__(self, value):
... |
import sys
'''
https://adventofcode.com/2020/day/1
'''
def parse(args):
input_nums = []
with open(args[1], mode='r') as f:
for line in f.readlines():
input_nums.append(int(line.strip()))
return input_nums
def find2(input_nums, target):
'''
Find 2 numbers (assumed positive ints)... |
# import env
Import('env')
if(env['PLATFORM'] == 'linux'):
env.ParseConfig( 'pkg-config --cflags --libs uuid ')
objs = env.SharedObject([Glob('*.cpp')])
Return('objs')
|
import toml
output_file = ".streamlit/secrets.toml"
with open("milkbar-326412-53ae838df218.json") as json_file:
json_text = json_file.read()
config = {"textkey": json_text}
toml_config = toml.dumps(config)
with open(output_file, "w") as target:
target.write(toml_config) |
__author__ = "Kavitha Yogaraj"
__status__ = "Development"
# -------------------------------------------------------------
# Import Packages required for Running Code
# -------------------------------------------------------------
import traceback
import os
import sys
from urllib.request import urlopen
import pandas ... |
import json
# DEVELOPER: https://github.com/undefinedvalue0103/nullcore-1.0/
logging = None
cfg = json.loads(open('config.json', 'r').read())
def __update__():
with open('config.json', 'w') as f:
f.write(json.dumps(cfg, indent=4))
def __reload__():
global cfg
try:
new_cfg = json.load(open('... |
lines = """LLLLLLL.LLLLLLLLLLLLLLL.LLL.LLLL.LLLLLLL.L.LLLLLLL.LLLLLL.LLLLLLLL.LLLLL..LLLLLLLLLLLLLLLLLL
LLLLLLL.LLLLLL.LLLL.LLL.LLLLLLLLLL.LLLLLLL.LLLLL.L.LLLLLLLLLLLLLLL.LLLLLLLLLLLLLLLLLLLLLLLLL
.LLLLLLLLLLLLLLL.LLLLLL.LLLLLL.LLLLLLLL.LL.LLLLLLL.LLL.LL.LLLLLLLLLLL.LLL..LLLLLLLL.LLLLLLLL
LLLLLLLLLLLLLLL..LLLLLL.LLLLLL... |
import sys,os
import gui
import core
import argparse
#この部分で定義
parser = argparse.ArgumentParser()
parser.add_argument("-gui","--gui", help="run core with gui",
action='store_true')
args = parser.parse_args()
#with gui
if args.gui:
gui.main()
else:
core.main()
|
from django.conf import settings
from django.db import models
from django_extensions.db.models import TimeStampedModel
from tickets.enums import Urgency,Location,Category
class Ticket(TimeStampedModel):
title = models.CharField(max_length=255)
location = models.CharField(choices=Location.choices(), default=L... |
import numpy as np
import torch
class NeighborFinder:
def __init__(self, adj_list, n_user, n_item, uniform=False, seed=None, use_mem=False):
self.node_to_neighbors = []
self.node_to_edge_idxs = []
self.node_to_edge_timestamps = []
adj_list_new = [[] for _ in range(n_user + n_item +... |
from django.contrib import admin
# Register your models here.
from api.models import Resource
from api.models import Location
admin.site.register(Resource)
admin.site.register(Location) |
age = 21
name = 'YanYu'
print '%s is %d years old'%(name, age)
print 'Why is %s is playing with python?'%name |
# print_count.py
def print_count(n):
yield "Hello World\n"
yield "\n"
yield "Look at me count to %d\n" % n
for i in xrange(n):
yield " %d\n" % i
yield "I'm done!\n"
# Example:
if __name__ == '__main__':
out = print_count(10)
print "".join(out)
# Route to a file
out = pr... |
a1 = int(input('Digite o primeiro termo: '))
r = int(input('Digite a Razão desse termo: '))
n = 1
for n in range(1,11):
an = a1 + (n-1)*r
print(an, end=' ')
|
from enum import Enum
Races = Enum('Races', 'DWARF, ELF, HALFLING, HUMAN, DRAGONBORN, GNOME, HALF-ELF, HALF-ORC, TIEFLING')
Skills = Enum('Skills', 'STRENGTH, DEXTERITY, CONSTITUTION, INTELLIGENCE, WISDOM, CHARISMA')
class Race():
def __init__(self, name, bonus1, bonus2):
self.name = name
... |
import datetime
from django.db import models
from django.core.validators import RegexValidator
from django.contrib.auth.models import User
from akun.models import Profil
Validator = RegexValidator(
regex='^[0-9]*$', message='Hanya Angka', code='NIK tidak valid')
class Kategori(models.Model):
nama_kategori =... |
import sys
import cv2
from vision.camera import load_camera
from vision.video import load_video_writer
from ml.model import load_yolo, load_detectron
import logging
import argparse
import tqdm
logger = logging.getLogger("root")
def yolo(args):
detector = load_detector(args)
video_writer_original = load_video... |
#! /usr/bin/env python
"""Module for interfacing with KARR's propeller chip
@author:Kristian Charboneau
"""
import serial
def move_x(value):
pass
def move_y(value):
pass
def move_z(value):
pass
def rot_x(value):
pass
def rot_y(value):
pass
def rot_z(value):
pass
def _light(value):
... |
import turtle
def draw_circle(x,y,r):
turtle.up()
turtle.goto(x,y)
turtle.stamp()
turtle.forward(r)
turtle.down()
turtle.left(90)
turtle.circle(r)
turtle.shape("turtle")
draw_circle(0,0,50)
draw_circle(200,200,100)
draw_circle(100,-100,50)
|
import connexion
import six
from swagger_server.models.exposures_bundle import ExposuresBundle # noqa: E501
from swagger_server import util
def get_exposures(coords_file, start_date=None, end_date=None): # noqa: E501
"""provided with list of lat,lons in a file (1 pair on each line) will return a bundle of expo... |
# Generated by Django 2.2.2 on 2019-07-07 19:55
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('listings', '0014_auto_20190707_1223'),
]
operations = [
migrations.RenameField(
model_name='listing',
old_name='Rules',
... |
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
import grpc
from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2
import settings_service_pb2 as settings__service__pb2
class SettingsServiceStub(object):
# missing associated documentation comment in .proto file
pass
... |
from django.shortcuts import render, HttpResponseRedirect, reverse
from django.views.decorators.csrf import ensure_csrf_cookie
from django.http import JsonResponse
from numpy.core.numeric import NaN
import pandas as pd
from django.contrib import messages
from .models import Consumer
from work.models import Site
from wo... |
#!/usr/bin/env python
PACKAGE = "vocus2_ros"
from dynamic_reconfigure.parameter_generator_catkin import *
gen = ParameterGenerator()
fusion_enum = gen.enum([ gen.const("Arithmetic_mean", int_t, 0, "Arithmetic mean"),
gen.const("Max", int_t, 1, "Max"),
gen.const(... |
from __future__ import unicode_literals
import frappe
from frappe.utils import flt, cstr, cint, time_diff_in_hours, now, time_diff, add_days, formatdate
from frappe import _
import json
import math
import re
@frappe.whitelist()
def get_global_search_suggestions(filters):
query = """ select name from `tabTraining` ... |
def solve(a):
even, odd = 0,0
for x in a:
if isinstance(x,int):
if x%2==0:
even+=1
else:
odd+=1
return even-odd
'''
Given an array, return the difference between the count of even numbers and the
count of odd numbers. 0 will be considered a... |
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def hello_world():
return render_template('index.html')
@app.route('/<name>')
def hello(name):
return "Hello " + name.capitalize()
if __name__ == '__main__':
app.run(debug = True)
# or
# app.debug = True
# app.run(... |
import plotly
import plotly.plotly as py
import plotly.graph_objs as go
import pandas as pd
plotly.tools.set_credentials_file(username='zz186', api_key='g7hnRhD8XruvpT3eKj1C')
data=pd.read_csv("FIFA19 - Ultimate Team players.csv")
df2=data[["quality","league"]]
df2["counts"]=1
df2=df2.groupby(['quality']).sum()
df2=... |
import logging
import fmcapi
def test__application_category(fmc):
logging.info("Testing ApplicationCategory class.")
obj1 = fmcapi.ApplicationCategories(fmc=fmc)
logging.info("All ApplicationCategories -- >")
result = obj1.get()
logging.info(result)
logging.info(f"Total items: {len(result['it... |
from .autoprotocol import *
from .behavior_specialization import *
from .markdown import *
from .opentrons import *
|
import os
#Comment this out to use your gpu
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"] = ""
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import *
from tensorflow.keras import metrics
from tensorflow.keras import optimizers
from tensorflow.keras.mod... |
import random
game = input("Do you want to play the game:")
while (game== "yes" or game== 'y' or game== "Yes" or game== 'Y'):
print(random.randrange(1,6,1))
game = input("Do you want to play the game again:")
print("end") |
from tkinter import *
root = Tk()
root.title("格子版面管理員")
text = Label(root, text="Hello World!",
width="30", height="5",
bg="black", fg="white")
text.grid(row=0, column=0)
root.mainloop()
# 檔名: tk_demo3.py
# 作者: Kaiching Chang
# 時間: May, 2018
|
from rest_framework import serializers
from django.contrib.auth.models import User
from backend.profiles.models import Profile
class ProfileSerializer(serializers.Serializer):
username = serializers.CharField(max_length=20)
nickname = serializers.CharField(max_length=20)
password = serializers.CharFie... |
with open('Day 4/data.dat', "r") as data:
input = [x for x in data]
input.sort()
watches = []
guards = {}
for line in input:
info = line.replace("[", "").replace(']','').split(" ")
if info[2] == 'Guard':
#number, date, time, list of times asleep, times fallen asleep, total min
... |
class TextHelper:
@staticmethod
def hide_sensitive_data(string: str, count: int = 4):
"""Replace sensitive data with asterisk, except last 4 symbols."""
return f"{'*' * (len(string) - count)}{string[-count:]}"
|
import numpy as np
import matplotlib.pyplot as plt
from pandas.core.common import flatten
from fourierMethods import *
from multipdesys import *
N=64
def g(x):
y=2+6*np.sin(6*x)-38*np.cos(6*x)
return y
x=np.linspace(0,2*np.pi,N)
G=g(x)
Fg=np.fft.fft(G)/N
FF=[]
K=findK(N)
for i in range(0,len(K)):
ff=(-F... |
import numpy as np
def activation(v):
# output 1 if v >=0, 0 otherwise
output = None
return output
def predict(x,w):
# calculate logit, v
v = None
# activate v
output = None
return output
def main():
#define input poitns
# the first column is for bias = 1
pointA = np.array... |
import cv2
import numpy as np
import utils.utils as utils
from net.inception import InceptionResNetV1
from net.mtcnn import mtcnn
import tensorflow as tf
physical_devices = tf.config.experimental.list_physical_devices('GPU')
assert len(physical_devices) > 0, "Not enough GPU hardware devices available"
tf.config.expe... |
import os
import matplotlib.pyplot as plt
from matplotlib.pyplot import xticks
import matplotlib.ticker as mtick
from utils import read_attack_stats, VICTIMS_COLORS, VICTIMS_LINESTYLES, \
COEFFS_COLORS, COEFFS_LINESTYLES, COEFFS_LABELS
import pandas as pd
xticks_short = False
LABELSIZE = 14
def attack_stats_agai... |
from kivy.core.window import Window
from kivy.app import App
from kivy.uix.label import Label
import re
from datetime import date
from kivy.uix.popup import Popup
# To Calculate The Age From Date Of Birth
def match(p_dob, p_age):
dob_pattern = r'(((0[1-9]|[12][0-9]|3[01])([/])(0[13578]|10|12)([/])(\d{4}))|(([0][1... |
import os
os.system("python3 generate_dimacs_gift_v2.py")
os.system("python3 main.py") |
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 4 15:38:54 2017
@author: zx621293
"""
def RefineData (protein,labelling): #(input data, labelled ground truth)
mydata=protein.values.astype("float64")
delrow= list()
delcolumn= list()
for column in np.linspace(0,mydata.shape[1]-1,mydata.shape[... |
salary = float(input('Please type your salary:'))
a = (10 / 100) * salary + salary
b = (15 / 100) * salary + salary
if salary <= 1250:
print('You have a salary increase of 15% new salary is £ {} '.format(b))
else:
print('You have a salary increase of 10% your new salary is £ {}'.format(a))
|
import matplotlib.image as mpimg
import numpy as np
import os,sys
import math
from skimage.morphology import opening, closing, white_tophat
from skimage.morphology import square
import postprocessing
from plots import *
from skimage.filters import gaussian
### Data extraction ###
def load_training_images(n):
... |
from .product import Product
class Category:
def __init__(self, category):
self._category = category
self._products = []
@property
def category(self) -> str:
return self._category
@category.setter
def category(self, value):
self._category = value
@property
... |
# Copyright (C) 2016 Cuckoo Foundation.
# This file is part of Cuckoo Sandbox - http://www.cuckoosandbox.org
# See the file 'docs/LICENSE' for copying permission.
import logging
import os.path
import subprocess
import _winreg
from lib.common.abstracts import Auxiliary
from lib.common.registry import set_regkey
from l... |
#!/usr/bin/env python3
import io
import csv
import utils
def download():
utils.download_file('http://astro.temple.edu/~tua87106/DDI_pred.csv', '../data/pmid_26196247/DDI_pred.csv')
def map_to_drugbank():
matched = set()
unmapped_names = set()
results = []
unmapped = 0
duplicated = 0
wi... |
# -*- coding:utf-8 -*-
from urllib import request,response,parse,error
import re
from bs4 import BeautifulSoup
class crawl:
def __init__(self,url):
self.url=url
#获取页面内容
def getPage(self,Num):
try:
url=self.url+str(Num)+'?o=2'
req=request.urlopen(url)
return ... |
import random
ord = ['', '', '', '']
aluno = [0, 1, 2, 3]
for x in range(4):
aluno[x] = input('Digite o {}º aluno: '.format(x + 1))
n = random.randint(0, 3)
while(ord[n] != ''):
n = random.randint(0, 3)
ord[n] = aluno[x]
print('A ordem será: {}, {}, {}, {}'.format(ord[0], ord[1], ord[2], ord[3... |
import numpy as np
def compute_dist(mat, # numpy array of shape (N, nx) and type 'float'
scl=None, # [usf] numpy array of shape (nx,) and type 'float'
wt=None, # [nusf] numpy array of shape (N,) and type 'float'
hist=[]):
if hist:
mat = np.concatenat... |
def sum(num1, num2):
num3 = num1 + num2
print("Sum of {0}, {1} is : {2}".format(num1, num2, num3))
def sum(num1, num2, num3):
num4 = num1 + num2 + num3
print("Sum of {0}, {1}, {2} is : {3}".format(num1, num2, num3, num4))
def main():
sum(3, 2, 3)
if __name__ == "__main__":
main()
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class FieldConstrains(object):
# Required
# Examples:
# ['allowEmpty']
#
# [+] - EmptinessValidator
#
# public function allowEmpty($value)
ALLOW_EMPTY = 'allowEmpty' # можно передать поля без значения, для пустых строк. Для удаления атр... |
from django.urls import path
from . import views as users_views
from django.contrib.auth.views import LoginView, LogoutView, PasswordResetView, PasswordResetDoneView, PasswordResetConfirmView, PasswordResetCompleteView
urlpatterns = [
path('signup/<uuid>/', users_views.SignupView.as_view(), name="signup"),
pat... |
print("This program makes usernames")
print("from a file of names")
infileName = input("What file is it in? ")
outfileName = input("Place username in this file: ")
infile = open(infileName, "r")
outfile = open(outfileName, "w")
for i in infile:
first, last = i.split()
uname = (first + last).upper()
prin... |
from .birds import Birds
|
import re, os, subprocess, mmap, sys, urllib2, pprint
REPO_PATH = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
URL_REGEX = r'https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,4}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)'
SOURCE_TYPE_URL = 'URL'
SOURCE_TYPE_FILE = 'file'
SOURCE_TYPE_STRING = 'string'
APPEN... |
from django.apps import AppConfig
class ClinicAppConfig(AppConfig):
name = 'clinic_app'
|
#!/usr/local/bin/python3
import re
from bs4 import BeautifulSoup
from discord.ext import commands
from utils import web
class MonsterHunter(commands.Cog):
"""Monster Hunter Skill list"""
def __init__(self, bot):
self.bot = bot
@commands.command()
async def mh(self, ctx):
"""[search... |
# -*- coding: utf-8 -*-
from __future__ import print_function
import time
import pygame
import OpenGL.GL as gl
import OpenGL.GLU as glu
import numpy as np
import itertools
import fractions
import copy
import numpy as np
#local imports
from common import COLORS, DEBUG, VSYNC_PATCH_HEIGHT_DEFAULT, VSYNC_PATCH_WIDTH_DE... |
import json
import requests
import uuid
response = requests.get("https://data.kcmo.org/resource/c46m-hv6s.json")
contracts = json.loads(response.text)
for x in contracts:
x['effective_date'] = x.pop('contract_date')
x['supplier'] = x.pop('vendor')
x.update({
'id' : str(uuid.uuid4()),
'type'... |
from random import Random
from goodstudy.settings import EMAIL_FROM
from django.core.mail import send_mail
from apps.user.models import EmailCaptcha
def random_num(randomlenth=8):
my_str = ''
chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789'
lenth = len(chars) - 1
random = Rand... |
def ask_for_int():
while True:
try:
age = int(input("enter your age = "))
except(ValueError):
print("Entered input is not a number")
continue
else:
if(age >= 18):
print("eligible to vote")
break
... |
import autodisc as ad
import plotly
import zipfile
import os
import numpy as np
from PIL import Image
import plotly.graph_objs as go
import warnings
import random
from autodisc.gui.jupyter.misc import create_colormap, transform_image_from_colormap
#def plot_discoveries_treemap(experiment_definitions=None, repetition_i... |
from flask import request
from flask_restful import Resource, marshal_with
from ..fields import Fields
from app.models.models import Category, db
from app.forms import CreateCategoryForm, UpdateCategoryForm
from app.utils import output_json
category_fields = Fields().category_fields()
class CategoryListAPI(Resource... |
from os.path import dirname
from os.path import join
from kivy.uix.button import Button
from kivy.uix.image import Image
class ButtonIcon(Button):
# def __init__(self, icon_name, **kwargs):
# super(ButtonIcon, self).__init__(**kwargs)
# icon_path = glob(join(dirname(__file__), "resources", icon_nam... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.