text stringlengths 38 1.54M |
|---|
from MySQLdb import *
import MySQLdb
from tkinter import CENTER, Entry, Tk, Button
from Menu_Eleccion import Menu
from tkinter import PhotoImage
from tkinter import Label
import os
import ctypes
direc = os.path.dirname(__file__)
icono = os.path.join(direc, 'imagenes/icono.png')
fondo = os.path.join(direc,... |
import sys
import os
import itertools
import copy
import math
import multiprocessing as mp
import Core.Solvers.MTSSP.M2S_item as M2S_item
from pyomo.environ import *
from pyomo.opt import SolverFactory
import Core.scenario_class as SC
from Core.Solvers.MSSP import defunction as MSSP
class Decision_Tree:
def __init__(... |
import keras
from sklearn.model_selection import train_test_split
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from keras.preprocessing.image import ImageDataGener... |
import hashlib
from django.utils.http import urlquote
TEMPLATE_FRAGMENT_KEY_TEMPLATE = 'template.cache.%s.%s'
def make_template_fragment_key(fragment_name, vary_on=None):
if vary_on is None:
vary_on = ()
key = ':'.join([urlquote(var) for var in vary_on])
args = hashlib.md5(key.encode('utf-8'))
... |
from datetime import datetime
from time import time
from PIL import Image
import os
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
from django.db import models
# Create your models here.
rice_CHOICES = (
('1', _('rice with meat and vegetables')),
... |
"""
Lines fo code counting
"""
import os
import shlex
import subprocess
from navio_tasks import settings as settings
from navio_tasks.cli_commands import check_command_exists, prepinform_simple
from navio_tasks.output import say_and_exit
from navio_tasks.settings import REPORTS_FOLDER
from navio_tasks.utils import inf... |
# !/usr/bin/env python
# encoding: utf-8
import os
import requests
import re
import hashlib
from bs4 import BeautifulSoup
from docx import Document
from docx.shared import Pt, Inches
from docx.oxml.ns import qn
from pathlib import Path
def getImage(image_url, md5_title, number):
image_request = requests.get(imag... |
#coding=utf-8
# 所有的id label都为int
import networkx as nx
class MCommunity:
'''
Modularity Community.
'''
def __init__(self, label):
self.label = label
self.members = list() # 待确定采用list还是set 假设输入的每个community不包含重复节点
def add_member(self, member):
self.members.app... |
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 14 18:19:32 2019
@author: ts-fernando.takada
"""
# Importing the Libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# Importing DataSet
dataset = pd.read_csv('50_Startups.csv')
x = dataset.iloc[:, :-1].values
y = dataset.iloc... |
# Exercício Python 014: Escreva um programa que converta uma temperatura digitando em graus Celsius e converta para graus Fahrenheit.
c = float(input("Qual a temperatura em Cº?"))
f = (c * 9/5) + 32
print("Cº {} Fº {} ".format(c, f)) |
def factors(n):
for i in range(1, n + 1):
if n % i == 0:
print(i)
return
n = int(input("Enter a number: "))
print("All factors of", n, "is")
factors(n)
|
from setuptools import setup, find_packages
with open('requirements.txt', 'r') as rf:
requirements = rf.readlines()
requirements = [x.replace('\n', '').replace('\r', '')
for x in requirements]
setup(
name='breakawayDiceMapper',
version='0.1',
python_requires='>=3.5',
packa... |
from django.contrib import admin
from .models import Track, Driver, TrackDriver, Bet
admin.site.register(Track)
admin.site.register(Driver)
admin.site.register(TrackDriver)
admin.site.register(Bet) |
def get_bool(_bytearray, byte_index, bool_index):
"""
Get the boolean value from location in bytearray
"""
index_value = 2 ** bool_index
byte_value = _bytearray[byte_index]
current_value = byte_value & index_value
return current_value == index_value
def set_bool(_bytearray, byte_index, b... |
from flask import Blueprint
blue_user = Blueprint("user", __name__, url_prefix="/user")
from . import view
|
#coding:UTF-8
from explatform.account.forms import UserRegisterForm
from django.template import loader, RequestContext
from django.shortcuts import render_to_response as rtr
from django.http import HttpResponse
def UserRegister(request):
if request.method == 'POST':
form = UserRegisterForm(request.POST)
... |
#COMMIT DAMN YOU
import sys, pygame
from Actor import *
pygame.init()
#print "Enter a player name: ",
#name=raw_input()
#print "Enter your starting health: ",
#health=int(raw_input())
#print "Enter your starting damage: ",
#damage=int(raw_input())
player=Player(0,0,'images/player.png','Brennan',100,10)
d... |
#@+leo-ver=5-thin
#@+node:ekr.20050328092641.4: * @file Library.py
#@+<< docstring >>
#@+node:ekr.20050912180445: ** << docstring >>
''' Stores Leo trees in database files.
This should help people develop templates that they want to reuse between Leo
projects. For example, I'd like a template of many Java interfaces t... |
from gurobipy import *
import numpy as np
def solve_with_gurobi(p):
def constraints(name_constr_pairs):
for name, cstr in name_constr_pairs:
model.addConstr(cstr, name)
try:
quality_consideration = hasattr(p, 'qlevels')
overtime_consideration = hasattr(p, 'zmax')
... |
import os
SECRET_KEY = os.urandom(24)
MAIL_DEBUG = True # 开启debug,便于调试看信息
MAIL_SUPPRESS_SEND = False # 发送邮件,为True则不发送
MAIL_SERVER = 'smtp.qq.com' # 邮箱服务器
MAIL_PORT = 465 # 端口
MAIL_USE_SSL = True # 重要,qq邮箱需要使用SSL
MAIL_USE_TLS = False # 不需要使用TLS
MAIL_USERNAME = '12572665... |
import requests,json,sys,random,datetime,pdb,re,urllib.request
import lxml.html as HTML
from dateutil import parser
import time
def loadJson(filename):
with open(filename) as f:
return json.load(f)
return None
def getGroupURLFromID(id):
return "http://coverartarchive.org/release-group/" + id + "/front"
def down... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'SumPrice.ui'
#
# Created by: PyQt5 UI code generator 5.15.1
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import QtCore, QtG... |
# -*- coding: utf-8 -*-
# Copyright 2014, Digital Reasoning
#
# 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 applica... |
def gcd(a,b):
while b!=0:
r = a%b
a = b
b = r
return a
T = int(input())
for t in range(T):
test_case = list(map(int,input().split()))
n = test_case[0]
nums = test_case[1:]
S = 0
for i,a in enumerate(nums[:-1]):
for b in nums[i+1:]:
S+=gcd(a,b)
print(S)
|
import os
import numpy as np
import cv2 as cv
from PIL import Image
import matplotlib.pyplot as plt
import pandas as pd
import torch
import torchvision
from torchvision import transforms
from torch.utils.data import DataLoader, Dataset
import sys
sys.path.insert(0, '..')
import header
###############################... |
from .dataset_mapper import *
from .tools import add_dataset_config, register_datasets
from .datasets import VisualGenomeTrainData |
#
# (name, isNumerical?)
#
feature_names = [
("MSSubClass", False),
("MSZoning", False),
("LotFrontage", True),
("LotArea", True), # Quadratically related to pool area?
("Street", False),
("Alley", False),
("LotShape", False),
("LandContour", False),
("Utilities", False),
... |
from django.urls import path
from .views import views
urlpatterns = [
path('', views.index, name='index'),
path('create-collection-point', views.createCollectionPoint, name='createCollectionPoint'),
path('collection-points', views.collectionPoints, name='collectionPoints'),
]
|
# WASTC notes
print ('even though we add .1 ten times, we do not get the answer one')
x = 0.0
x += .1
x += .1
x += .1
x += .1
x += .1
x += .1
x += .1
x += .1
x += .1
x += .1
if x == 1.0:
print ('x is one')
else:
print ('x is not one')
print ('x is', x)
print ('but we can get 1.25')
x = 0.0
x += .125
x += ... |
from decouple import config
# Spotify configs
SPOTIFY_CLIENT_ID = config("spotify_client_id")
SPOTIFY_CLIENT_SECRET = config("spotify_client_secret")
ARTIST_ID = config("frank_ocean_id")
# Twitter configs
TWITTER_API_KEY = config("twitter_api_key")
TWITTER_API_SECRET = config("twitter_api_secret")
TWITTER_TOKEN = con... |
import copy
def rotate_90():
global raw_map
ret = [[0] * square for _ in range(square)]
for c in range(square):
for d in range(square):
ret[d][square-1-c] = raw_map[c+startPoint[0]][d+startPoint[1]]
for c in range(square):
for d in range(square):
raw_map[c+startPo... |
from torch.nn import Module
class OutputLayerFactory:
def create(self, input_size: int) -> Module:
raise NotImplementedError
|
import os
from datetime import datetime
from flask import Flask, abort, request
from linebot import (
LineBotApi, WebhookHandler
)
from linebot.exceptions import (
InvalidSignatureError
)
from linebot.models import (
MessageEvent, TextMessage, TextSendMessage,
)
app = Flask(__name__)
line_bot_api = Line... |
import json
from random import randint
import pytest
from flask import url_for
from backend_tests.constans import UserData
from backend_tests.framework.asserts import assert_data_are_equal
from database.models import User, Role
from resources.auth import LoginApi, SignupApi
from resources.errors import EmailAlreadyEx... |
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 1 17:14:22 2017
@author: adhingra
"""
# Kernel Principal Component Analysis - Feature Extraction
# Dimensionality reduction
# importing libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# importing dataset
dataset = pd.read_csv('Social_Ne... |
total2 = 0 #contador
j = 1 #contaodr
while j < 5: # j parte con el valor 1 y el ciclo while lo que hace es que mienras se cumpla la condcion, el codigo correra.
total2 += j # esta condicion indica que por cada ciclo del while, la variable total2 se va modificando
j += 1 # lo mismo que en el comentario de la linea... |
# -*- coding: utf-8 -*-
class Book(object):
def __init__(self, name, height, width):
self.name = name
self.height = height
self.width = width
if __name__ == '__main__':
pass
|
from sklearn.model_selection import StratifiedKFold
import numpy as np
from sklearn.model_selection import train_test_split
X = []
y = []
for i in range(20):
X.append((i,i))
if i < 10:
y.append(0)
else:
y.append(1)
# print(X)
# print(y)
X = np.array(X)
y = np.array(y)
X_train, X_test, ... |
import os
import unittest
import siibra as sb
from test.get_token import get_token
token = get_token()
os.environ['HBP_AUTH_TOKEN'] = token["access_token"]
class TestRetrievalDownloadFile(unittest.TestCase):
def test_download_file(self):
sb.retrieval.download_file(
"https://object.cscs.ch/v1/... |
from django.urls import path
from . import views
app_name = 'Data'
urlpatterns = [
path('', views.index, name='index'),
path('CSV/',views.render_csv,name="csv"),
path('NewEntry/',views.add_data,name='add_data'),
path('ViewEntry/<int:id>/',views.view_data,name="view_data"),
path('EditEntry/<int:id>... |
##############################################
## test pour la concatenation d'un automate ##
##############################################
# les tests sont semblables aux tests pour la fonction union
from execution import *
from automate import *
from concatenation import *
import unittest
import random
longueur_m... |
import xlrd
import sqlite3
excel=xlrd.open_workbook("example.xlsx")
print excel.sheets()[1].name
table=excel.sheets()[1]
conn=sqlite3.connect('z.db')
cursor = conn.cursor()
cursor.execute('create table %s (%s %s primary key)' % (table.name,table.row_values(0)[0],table.row_values(1)[0]))
for (key1,key2) in (table.r... |
#一家商场在降价促销。如果购买金额50-100元(包含50元和100元)之间,会给10%的折扣,
# 如果购买金额大于100元会给20%折扣。
# 编写一程序,询问购买价格,再显示出折扣(%10或20%)和最终价格
def discount( price ):
if( price >= 50 and price <= 100 ):
print("10%的折扣")
return price * 0.9
if( price > 100 ):
print("20%的折扣")
return price * 0.8
print(discount(100)) |
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def home_page():
return render_template('home_page.html')
@app.route('/projects')
def projects_page():
return 'Hello, World!' |
'''
请求通话命令
'''
import struct
import struct
import os
import sys
sys.path.append(os.path.abspath("../tool"))
from typeProperty import typed_property
class ApplyForVoiceBean(object):
__slots__ = ['_usage', '_device_category', '_device_id']
usage = typed_property('usage', str)
device_category = typed_property... |
# -*- coding: utf-8 -*-
"""
Created on Fri May 28 14:29:29 2021
@author: Selim Arslan
Romberg Extrapolation
"""
import numpy as np
def romberg(f, a, b, n):
r = np.array( [[0] * (n+1)] * (n+1), float )
h = b - a
r[0,0] = 0.5 * h * ( f( a ) + f( b ) )
powerOf2 = 1
for i in rang... |
from tensorflow.keras.models import load_model
import os
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.optimizers import RMSprop
import pandas as pd
import numpy as np
import config
model = load_model(os.path.join(config.models_path, "my_model.h5"))
model.summary()
#Traini... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#-Imports----------------------------------------------------------------------
#--wxPython Imports.
import wx
#- wxPython Demo --------------------------------------------------------------
__wxPyOnlineDocs__ = 'https://wxpython.org/Phoenix/docs/html/wx.RadioBox.html'
... |
#!/usr/bin/env python
"""A simple test of PyTurtle with multiple turtles
"""
import pyturtle
def main():
"""The test program.
"""
tom = pyturtle.Turtle()
sam = pyturtle.Turtle(tom.board, tom.page)
# sam.color = 'blue'
sam.about_face()
pyturtle.help()
for _ in range(len(pyturtle.COLORS)... |
from method import *
# Map file types to their corresponding extensions.
file_extensions = {'psrfits':'.fits','filterbank':'.fil'}
def main(hotpotato):
print('\nCalculating suitable FFT length')
t_FFTlength_start = time.time()
# Get data directory, basename and filetype to generate glob string of data f... |
# Generated by Django 3.1.2 on 2020-10-22 16:04
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('discordbot', '0005_amongusgame_text_message_id'),
]
operations = [
migrations.AlterField(
model_name='amongusgame',
... |
#Este programa genera la multiplicacion de dos numeros
primer_numero = float(input('Ingrese el primer numero: '))
segundo_numero = float(input('INgrese el segundo numero: '))
Resultado = primer_numero * segundo_numero
#Ejemplo de concatenacion con la forma "','{:decimales}' .format(Variable a calcular)"
print('El re... |
import pycovis.matlab as pymatlab
from pycovis.postprocess import runtime
def test_imaging_sweep():
with runtime.Runtime() as pp:
metadata = pp.postproc_metadata()
for key in ["matlab_version", "verstr", "postprocessing_gitrev", "postprocessing_gittags"]:
assert key in metadata
|
import scipy.integrate as scint
import numpy as np
import matplotlib.pyplot as plt
#Sol1
def f1(x, y):
return np.vstack((y[1], -np.exp(-2*y[0])))
def bc1(ya, yb):
return np.array([ya[0], yb[0]-np.log(2)])
x = np.linspace(1,2)
y1 = np.zeros((2, x.size))
Sol = scint.solve_bvp(f1, bc1, x, y1)
y = np.log(x)#exac... |
#16. Implement a program to get three values from CLA and print the sum of them.
import sys
a=int(sys.argv[1])
b=int(sys.argv[2])
c=int(sys.argv[3])
sum=a+b+c
print(sum)
|
import sqlite3
DB_NAME = 'blog.db'
conn = sqlite3.connect(DB_NAME)
conn.cursor().execute('''
CREATE TABLE IF NOT EXISTS posts
(
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT,
description TEXT,
article_id INTEGER,
file_path TEXT,
user_id INTEGER,
FOREIGN K... |
# r/dailyprogrammer
# challenge 3, difficult
# https://www.reddit.com/r/dailyprogrammer/comments/pkwgf/2112012_challenge_3_difficult/
# solution by Luke Demas
scrambled_words = ['mkeart', 'sleewa', 'edcudls', 'iragoge', 'usrlsle', 'nalraoci', 'nsdeuto', 'amrhat', 'inknsy', 'iferkna']
file = open('wordlist.txt', 'r')... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# the above line is to avoid 'SyntaxError: Non-UTF-8 code starting with' error
'''
Created on
Course work:
@author: raja
Source:
https://pypi.org/project/python-barcode/
'''
# Import necessary modules
import barcode
def startpy():
#print(barcode.PROVIDED_B... |
from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
path('', views.login, name='login'),
path('home/', views.home, name='home'),
path('check/', views.check, name='check'),
path('register/', views.register, name='register'),
path('inventory/', views.inve... |
# 575. Distribute Candies
# Difficulty: Easy
# https://leetcode.com/problems/distribute-candies/
class Solution:
def distributeCandies(self, candy_types: List[int]) -> int:
num_can_eat_candies = int(len(candy_types) / 2)
possible_candies = len(set(candy_types))
return min(num_can_eat_candie... |
def computepay(h,r):
if h<=40:
pay = h*r
else:
pay = 40*r + (h-40)*1.5*r
return pay
hrs = raw_input("Enter Hours:")
hours = float(hrs)
rt = raw_input("Enter Rate:")
rate = float(rt)
p = computepay(hours,rate)
print p
|
from sqlalchemy import Column, Integer, String, DateTime
from base import Base
import datetime
class DeliveryDetails(Base):
""" Delivery Details """
__tablename__ = "delivery_details"
id = Column(Integer, primary_key=True)
customer_id = Column(String(250), nullable=False)
delivery_id = Column(St... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
from django.utils.timezone import utc
import datetime
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL... |
# changed from .unet
from .unet_model_3d import unet_model_3d
#from .isensee2017 import isensee2017_model
|
import urllib.request
import shutil
from Utilities.Functions import is_image, get_file_name
from Exceptions.Exceptions import NoImage
class FileDownloader:
@staticmethod
def download(url):
if is_image(url):
file_name = "./Downloaded/" + get_file_name(url)
# Download the file f... |
a = 0
while a<100:
a = a+1
if (a % 3 == 0) and (a % 5 == 0):
print ("FizzBuzz")
elif (a % 5 == 0):
print ("Buzz")
elif (a % 3 == 0):
print("Fizz")
else:
print(a) |
__author__ = 'cmlee'
class Device:
def __init__(self):
self.ip = None
self.port = None
self.type = None
|
#Exercício Python 094:
# Crie um programa que leia nome, sexo e idade de várias pessoas,
# guardando os dados de cada pessoa em um dicionário e
# todos os dicionários em uma lista. No final, mostre:
#A) Quantas pessoas foram cadastradas
#B) A média de idade
#C) Uma lista com as mulheres
#D) Uma lista de pessoas com ... |
from flaskblog import app
from flask import Blueprint, render_template, url_for, flash, redirect, abort, request
from flaskblog.post.forms import Createpost
from flaskblog.models import Post
from flask_login import current_user, login_required
from flaskblog import db
from flaskblog.main.utils import save_pic
posts = ... |
from __future__ import annotations
from typing import Any, Callable, List, Union
from util import valid_comp, valid_min
from variables import AllVariable, IndexVariable, RandomVariable, RangeVariable, SampleVariable, SizeVariable, \
Variable, VariableDict, VariableSet, merge
# Default syntax specifiers
_default_... |
import sys
from math import log
def convert(s):
try:
x=int(s)
print(x)
# except ValueError:
except (ValueError, TypeError):
print("conversion error")
x=-1
return x
def convert1(s):
x=-1
try:
x=float(s)
return(x)
# except (ValueError, TypeErro... |
from time import timezone
from pyowm import OWM
from pyowm.utils import config
from pyowm.utils.config import get_config_from
from pyowm.utils import timestamps
config_dict = config.get_default_config_for_subscription_type('professional')
owm = OWM('ввести код полученный на сайте https://openweathermap.org/... |
import math
def countPrimes(n):
isPrime = [True]*(n)
isPrime[0] = isPrime[1] = False
for i in range(2, int(math.ceil(math.sqrt(n)))):
if isPrime[i]:
for j in range(i, n, i):
if i != j:
isPrime[j] = False
return sum(isPrime)
print(countPrimes(32)... |
import datetime
from code_source.dataset import Dataset
import calendar
from dateutil.relativedelta import relativedelta
import pandas as pd
class DateContainer:
df = Dataset.clean_df
min_date = df.DisbursementDate.min()
max_date = df.DisbursementDate.max()
min_month = calendar.month_name[min_date.m... |
import math
import random
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from algorithm.ML.RandomForest.xiechengRF.MyLog import MyLog
random.seed(0)
#定义BPNeuralNetwork类, 使用三个列表维护输入层,隐含层和输出层神经元, 列表中的元素代表对应神经元当前的输出值.
# 使用两个二维列表以邻接矩阵的形式维护输入层与隐含层, 隐含层与输出层之间的连接权值, 通过同样的形式保存矫正矩阵... |
#!/usr/bin/python
from pwn import *
p = remote("pwnable.kr", 9008)
print p.recvuntil("... -")
print p.recvline()
print p.recvline()
for i in range(0, 100):
data = p.recvline()
print data
d1, d2 = data.split(" ")
N = int(d1.split("=")[1])
C = int(d2.split("=")[1])
#
nums=[]
for i in ra... |
# file containing commands for the DC box so that commands can be imported without calling main
import serial
import numpy as np
import time
#Generates a sin wave of provided amplitude and frequency. The wave can be made more
#continous by decreasing step sizes but below 13 ms it will not be able keep time correctly
... |
from paramak import RotateStraightShape
class CenterColumnShieldCylinder(RotateStraightShape):
"""A cylindrical center column shield volume with constant thickness.
Arguments:
height (float): height of the center column shield.
inner_radius (float): the inner radius of the center column shiel... |
import string, re
def idIsAcceptable(ver_id):
for character in ver_id:
if character in string.ascii_letters:continue
if character in string.digits: continue
if character == "_": continue
return False
return True
def processSingle(ver_assignment):
pattern = ".(?P<portName>... |
from collections import namedtuple
class InvalidSizeError(Exception):
pass
class Size(namedtuple('Size', ['height', 'width'])):
def __init__(self, height, width):
if not (
1 <= height and
1 <= width and
width % 2 == 1 and
width < height * 2
):
... |
import sys
sys.path.append('../doubly_linked_list')
from doubly_linked_list import DoublyLinkedList
# FIFO
class Stack:
def __init__(self):
self.size = 0
self.storage = []
def push(self, value):
return self.storage.insert(0, value)
def pop(self):
if len(self.storage) == 0:... |
# Copyright 2021 The NetKet Authors - 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 ... |
from django.db import models
from django.utils.translation import gettext_lazy as _
class TemplateWashList(models.Model):
title = models.CharField(max_length=250, default="")
def __str__(self):
return self.title
class Meta:
verbose_name = _("Mal for vaskeliste")
class TemplateListItem(... |
import timeit
# TODO: break this into atomic parameters
parameters_database = [[0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], ['tukey', 3, 'prod', 1, 2, 'frequencia_relativa', 0.075, [0, 0], [1, 1], 0.95, 'MQR', 'MQR', 5, 4, 0.9, 10]]
data = 'automobile-10-fold_csv.zip'
report_folder = '... |
class cell():
def __init__(self, cols = 1, style = "unwork", content = ""):
self.cols = cols
self.style = style
self.content = content
class day():
def __init__(self, hour_cell, hhour_cell):
self.hour = hour_cell
self.hhour = []
for cel in hhour_cell:
... |
import logging
from telegram.ext import *
import pdiskuploader
API_KEY = '1967670843:AAFxcZxYw643MS0KFPPHSKkP-n6WMFzjJ08'
# setting up logs
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
logging.info("Starting bot...")
header = {
'api_key': pdiskuploader.... |
x = int(input('podaj liczbe'))
y = int(input('podaj 2 liczbe'))
if x % 2 == 0:
print('twoja liczba jest parzysta')
elif x % 3 == 0 and x % 2 == 0:
print('twoja liczba jest parzysta i jest wielokrotnoscia liczby 4')
else:
print('twoja liczba jest nieprzaysta')
if x % y == 0:
print('twoja liczba jest tez ... |
#!/usr/bin/env python3
from flask import Flask, jsonify, abort, request, make_response, session, send_from_directory
from flask_restful import Resource, Api, reqparse
from flask_session import Session
import json
import werkzeug, os, shutil
from ldap3 import Server, Connection, ALL
from ldap3.core.exceptions import *
i... |
#purpose of this is to create a shapefile of 1x1 deegree polygons
from shapely.geometry import Polygon
import pandas as pd
import geopandas as gpd
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import cartopy
def grid_creator(start_lat, end_lat, start_long, end_long):
"""
Creates 1 degree gridcells... |
# Append the images with the extension .sad into image_paths
image_paths = [os.path.join(path, f) for f in os.listdir(path) if f.endswith('.sad')]
for image_path in image_paths:
predict_image_pil = Image.open(image_path).convert('L')
predict_image = np.array(predict_image_pil, 'uint8')
faces = faceCascade.detectMu... |
import time
import math
import os
import stat
import boto
import boto.ec2
import boto.utils
import sh
def retry(tries, delay=1, backoff=2):
if backoff <= 1:
raise ValueError("backoff must be greater than 1")
tries = math.floor(tries)
if tries < 0:
raise ValueError("tries must be 0 or gre... |
from datetime import date
from django.contrib.postgres.fields import CICharField
from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import models
from django.utils.translation import gettext_lazy as _
from apps.core.models import BaseModel
class Coupon(BaseModel):
"""Represen... |
face_0 = ['yellow', 'blue', 'white', 'orange', 'orange', 'yellow', 'red', 'red', 'red']
face_1 = ['blue', 'red', 'green', 'green', 'white', 'red', 'green', 'orange', 'red']
face_2 = ['orange', 'green', 'orange', 'red', 'red', 'orange', 'orange', 'blue', 'blue']
face_3 = ['orange', 'blue', 'blue', 'orange', 'yellow', 'y... |
class SchemaError(Exception):
"""Raised when an unknown schema is requested."""
pass
class FilterError(Exception):
"""Raised when an unknown or invalid set filter is used."""
pass
class NoDataError(Exception):
"""Raised when no data is found in the local cache."""
pass
class NoCodelistsErr... |
'''Libraries for Prototype selection'''
import numpy as np
import cvxpy as cp
from sklearn.datasets import load_breast_cancer
from sklearn.datasets import load_iris
from sklearn.datasets import load_digits
import math as mt
from sklearn.model_selection import KFold
import sklearn.metrics
import matplotlib.pyplot as plt... |
from django import forms
from django.contrib.auth.models import User
from .models import Profile
# form for log-in
class LoginForm(forms.Form):
username = forms.CharField()
password = forms.CharField(widget=forms.PasswordInput)
# form for email
class EmailPostForm(forms.Form):
name=forms.CharField(... |
import cv2
src = cv2.imread("lion_black_img.png")
dst = src.copy()
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3,3))
gray = cv2.cvtColor(src, cv2.COLOR_RGB2GRAY)
ret, binary = cv2.threshold(gray, 230, 255, cv2.THRESH_BINARY)
morp = cv2.morphologyEx(binary, cv2.MORPH_CLOSE, kernel, iterations=2)
ima... |
from datetime import timedelta
from django.http import HttpResponse
from django.shortcuts import render, redirect, get_object_or_404
# Create your views here.
from post.models import Posting, Comment
def new(request):
if request.method == 'POST':
title = request.POST.get('title', '')
content = re... |
#!/usr/bin/env python2.7
#coding:utf-8
import ast
import time
import datetime
import os
import json
import re
import requests
from celery import task,platforms
from django.contrib.auth.models import User
from django.conf import settings
from mtree.models import *
from mtree.views import get_node_path_by_treeid
from mys... |
from django.test import TestCase
from companies.api.serializers import CompanyReportSerializer
from companies.tests.factories import CompanyFactory
field_mappings = {
"nome": "name",
"cnpj": "cnpj",
"dono": "owner",
"telefone": "full_phone",
}
class TestCompanySerializers(TestCase):
def test_com... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.