text stringlengths 38 1.54M |
|---|
import unittest
from steps_to_zero import steps_to_zero
class TestStepsToZero(unittest.TestCase):
def test_steps_to_zero(self):
self.assertEqual(steps_to_zero(14), 6)
self.assertEqual(steps_to_zero(8), 4)
self.assertEqual(steps_to_zero(123), 12)
if __name__ == '__main__':
unittest.ma... |
from django.contrib import admin
from .models import Metric, Record
@admin.register(Metric)
class MetricAdmin(admin.ModelAdmin):
list_display = ('name',)
@admin.register(Record)
class RecordAdmin(admin.ModelAdmin):
list_display = ('metric', 'timestamp', 'value')
list_filter = ('metric',)
date_hiera... |
#โปรแกรมเปรียบเทียบตัวเลข
a = float(input("ป้อนตัวเลขที่ 1 :"))
b = float(input("ป้อนตัวเลขที่ 2 :"))
if a>b:
print("1 > 2")
else :
print("2 > 1") |
from lab import decorators
from lab.nodes.virtual_server import VipServer, LibVirtServer
class Vtc(VipServer):
"""
set cisco-vts devices device TORSWITCHB ports port Ethernet1/39 connection-type server
set cisco-vts devices device TORSWITCHB ports port Ethernet1/39 servers server nfvbench_tg type baremeta... |
'''
Created on 04/11/2015
@author: Bruna
'''
class Node():
def __init__(self, chave, dado):
self._value = dado
self._left = None
self._right = None
self._father = None
self._key = chave
self._color= "red"
def getValue(self):
retu... |
#!/Users/fritjof/anaconda3/bin/python3
# problem: taisformula, rating: 1.5
# could convert floats to int before calculating to use less memory
n = int(input())
a = 0
t_i = v_i = -1
for _ in range(n):
d = input().split()
t_0 = t_i
v_0 = v_i
t_i = int(d[0])
v_i = float(d[-1])
if t_0 != -1:
... |
# You've just started to study impartial games, and came across an interesting theory. The theory is quite complicated, but it can be narrowed down to the following statements: solutions to all such games can be found with the mex function. Mex is an abbreviation of minimum excludant: for the given set s it finds the m... |
# Generated by Django 2.2.3 on 2019-07-23 06:42
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('fkrdjan', '0003_auto_20190722_1223'),
]
operations = [
migrations.AddField(
model_name='document',
name='status',
... |
#This is a python program to add numbers
# Check even or Odd
def is_even(number):
is_even = False
if number % 2 == 0:
is_even = True
return is_even
def is_odd(number):
is_odd = False
if number % 2 != 0:
is_odd = True
return is_odd
def sum_of_even_numbers(n):
sum = 0
for... |
from CovidTracker.app import app
from CovidTracker.crud.covid_data import get_current_covid_data
from flask import (render_template)
import datetime
@app.route('/')
def index():
"""Display Landing Page"""
now = datetime.datetime.now().strftime('%B %d, %Y')
year = datetime.datetime.now().strftime('%Y')
... |
#!/usr/bin/env python3
import sys
import os
from urllib.request import urlopen
from bs4 import BeautifulSoup
scrapingDirectory = "WEB"
html = urlopen("https://morningstar.in/library/archives.aspx").read()
soup = BeautifulSoup(html)
tableContainer = soup.find('div', {"summary": "An archive of articles"})
tabl... |
import boto3
path = "/var/www/html/assets/audio/"
voices = ["Brian", "Amy"]
session = boto3.session.Session(aws_access_key_id="AKIAJ37H4XBNDTXP6GJQ",
aws_secret_access_key="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",
region_name="us-east-2")
polly = ses... |
# -*- coding: utf-8 -*-
"""
/***************************************************************************
DEMto3D
A QGIS plugin
Description
-------------------
copyright : (C) 2022 by Javier
email : demto3d@... |
def sol(score):
result=None
if score>=90 and score<=100:
result="A"
elif score>=80:
result="B"
elif score>=70:
result="C"
elif score>=60:
result="D"
else:
result="F"
print(result)
score=int(input())
sol(score) |
from django.db import models
#from django.contrib.auth.models import AbstractUser
# Create your models here.
# userの情報を構成する
#class User(AbstractUser):
# 名前(policy-> 5文字以上20文字以下)
#username = models.CharField(max_length=20)
# パスワード(policy-> 5文字以上20文字以下)
#password = models.CharField(max_length=20)
#... |
import json
import discord
from discord.ext import commands, tasks
from constants import AOC_JOIN, AOC_ID, AOC_SESSION
class AdventOfCode(commands.Cog, name="Advent of Code"):
def __init__(self, bot):
self.bot = bot
self.lb = {}
self.lb_url = "https://adventofcode.com/2020/le... |
# -*- coding: utf-8 -*-
#爬虫-大众点评
import urllib.request
from bs4 import BeautifulSoup
from urllib.request import urlopen
import pandas as pd
import DataFrame
import re
html = 'https://www.dianping.com/shop/20832376/review_more?pageno=1'
# html = urlopen('https://www.dianping.com/shop/20832376/review_more?pageno=1')
... |
# coding: utf-8
# In[1]:
import nltk
nltk.download()
# 1. brown corpus
# 2. Inaugural speech
# 3. book corpus - frequency distribution can be done(most common words in textbook)
# In[2]:
from nltk.corpus import brown
# In[4]:
brown.categories()
# In[5]:
print(type(brown))
# In[10]:
brown.words(categorie... |
# Copyright 2020-2023 OpenDR European Project
#
# 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 agree... |
from flask import Flask, render_template, request
app = Flask(__name__)
if __name__ == '__main__':
app.run(debug=True)
@app.route('/')
def index():
return render_template("index.html")
@app.route('/submit', methods=["POST"])
def submit():
name = request.form.get("name")
establishment = request.fo... |
from flask import Flask
from .extensions import neo4j_driver
from neo4j_app.modules.api import register_api
# GET DATABASE SESSION
def get_db():
""" Return a session for neo4j database driver
"""
return neo4j_driver.session()
# CREATE FLASK APP
def create_app(config_object='neo4j_app.settings'):
"... |
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtGui import QPixmap
from front import FrontMainClass
class ProfileMainClass(object):
def setupUi(self, profDialog):
profDialog.setObjectName("profDialog")
profDialog.resize(549, 589)
self.presentProfileFrame = QtWidgets.QFrame(profDialo... |
import sys
val1 = sys.argv[1]
val2 = sys.argv[2]
def percentage(newValue=val1, original=val2):
price1=float(original)
price2=float(newValue)
change =((price1-price2)/price2)*100
print "Change: %.2f %% \nOrigianl: %.6f \nNew: %.6f" % (change, price1, price2)
if __name__ == "__main__":
percentage()... |
"""
Test pygmt.blockmedian.
"""
from pathlib import Path
import numpy.testing as npt
import pandas as pd
import pytest
from pygmt import blockmedian
from pygmt.datasets import load_sample_data
from pygmt.exceptions import GMTInvalidInput
from pygmt.helpers import GMTTempFile, data_kind
@pytest.fixture(scope="module"... |
# Authors: Jessica Su, Wanzi Zhou, Pratyaksh Sharma, Dylan Liu, Ansh Shukla
import numpy as np
import random
import time
import pdb
import unittest
from PIL import Image
import matplotlib.pyplot as plt
# Finds the L1 distance between two vectors
# u and v are 1-dimensional np.array objects
# TODO: Implement this
def ... |
import re
from datetime import datetime
with open('b827eb6a07fb.txt') as fd:
data = fd.read().split()
list1 = []
new_list=[]
for words in data:
if words[0:7] == 'AHeader':
list1.append(words)
for string in list1:
list1 = re.split('[=&]',string) # Seperated with & which is a seperator to identify
... |
import numpy as np
import objectives
# Take delta input from user
delta = 0.6
def hybridize_(archive_in, min_, max_):
"""
Augment our archive to explore locally and improve search capabilities.
For each dimension we perform x_i = x_i +/- delta_x_i
For large input dimensions, we can choose dimensions ... |
# predio = [
# ["Ap 100", "Ap 101", "Ap 102", "Ap 103"],
# ["Ap 200", "Ap 201", "Ap 202", "Ap 203"],
# ["Ap 300", "Ap 301", "Ap 302", "Ap 303"],
# ["Ap 400", "Ap 401", "Ap 402", "Ap 403"]
# ]
# for andar in predio:
# print(andar)
predio = []
andares = int(input("Qual a quantidade de andares? "))
aptos... |
#encoding=utf-8
import sys, codecs, jieba
reload(sys)
sys.setdefaultencoding('utf-8')
jeiba_output_file = codecs.open('jeiba_title_output1.txt', 'w','utf-8')
with codecs.open('embBaiduIndexName.txt', 'r','utf-8') as content:
for line in content:
#print line
words = jieba.cut(line, cut_all=False)
... |
import sklearn
import scipy
import meta_utils
from scipy.stats import multivariate_normal
import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn.gaussian_process import GaussianProcessClassifier
from sklearn.gaussian_process.kernels import RBF
from matplotlib.patches import Elli... |
from django.contrib.auth import get_user_model
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django.contrib.contenttypes.fields import GenericForeignKey
from django.urls import reverse
User = get_user_model()
def get_product_url(obj, viewname, model_name):
ct_model ... |
# -*- coding: utf-8 -*-
{
'name': "cinema",
'summary': "Cinema Erp System Management",
'description': """
An Erp System to Manage Cinema
Manage Films and info
Manage Reservation and tickets
""",
'author': "Huzaifa",
'website': "huz.dark1@gmail.com",
'category': 'Ma... |
import numpy as np
import datetime
import os
from network import NN
class NEAT:
def __init__(self, population_size, n_parents_new_gen, n_mutated_parents_new_gen, n_mates_new_gen, prob_weight_change, gamma):
self.population_size = population_size
self.n_parents_new_gen = n_parents_new_gen
s... |
# _*_ coding:utf-8 _*_
from django.views.generic import View
from django.shortcuts import render
from django.conf import settings
from django.shortcuts import get_object_or_404
from django.http import HttpResponse
from questionnaire.models import *
from users.models import UserProfile
import random
import json
from has... |
import psycopg2
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas
import os
# Function to fetch student data with classroom, term, and marks from the PostgreSQL database
def get_student_data():
connection = psycopg2.connect(
host='localhost',
database='postgres',
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import logging.handlers
import logging
class Log:
logger = None
@staticmethod
def init (filePath, logLevel , logName): # constructor
if Log.logger == None:
Log.logger = logging.getLogger(logName)
handler = logging.handler... |
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 14 16:20:31 2021
@author: seoun
"""
import os
import sys
import time
import torch
import torch.nn as nn
import torch.optim as optim
import pytorch_lightning as pl
from tqdm import tqdm
from torch.utils.data import TensorDataset, DataLoader
from pytorch_lightning.callba... |
# -*- coding: utf-8 -*-
# Copyright (c) 2020 DDN. All rights reserved.
# Use of this source code is governed by a MIT-style
# license that can be found in the LICENSE file.
import logging
from django.db import models
from django.db.models import CASCADE
from chroma_core.models import AlertStateBase
from chroma_core.m... |
# CSE572
# Assignment 5
# Aditi Baraskar, James Smith, Moumita Laraskar, Tejas Ruikar
# Spring 2019
import pandas as pd
import enum
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score
from sklearn.naive_bayes import GaussianNB
import warnings
warnings.filterwarnings("ignore")
KERNEL = ... |
from flask import Flask, request, render_template, redirect, flash, session
from flask_debugtoolbar import DebugToolbarExtension
from models import db, connect_db, Photo, User
from secrets import API_SECRET_KEY
from forms import AddPhotoForm, UserForm
from sqlalchemy.exc import IntegrityError
import requests
app = Fl... |
import os
import sys
sys.path.append(os.path.abspath(os.path.join(__file__, "../../../..")))
import argparse
import json
import logging
import traceback
import v2.lib.resource_op as s3lib
import yaml
from v2.lib.exceptions import RGWBaseException
from v2.lib.resource_op import Config
from v2.lib.s3.write_io_info impo... |
#tutorial 61
#generate payslip from csv file reportlab
import io
from reportlab.pdfgen import canvas
from reportlab.platypus import SimpleDocTemplate,Table,TableStyle,Frame,Spacer,Paragraph
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.lib.units import cm
from reportlab.lib import colors
from nltk... |
# Example: Get Number information
data = api.get_number_info('+1234567890')
print(data)
## { 'created': '2017-02-10T09:11:50Z',
## 'name' : 'RALEIGH, NC',
## 'number' : '+1234567890',
## 'updated' : '2017-02-10T09:11:50Z'}
|
import my_module
my_module.greeting()
my_module.greeting('dre')
from my_module import greeting
greeting('soul')
from my_module import pi as p
print(p)
print(my_module.pi)
|
# -*- coding: utf-8 -*-
"""
Created on Sat Jun 22 00:36:26 2019
@author: hweem
"""
import numpy as np
class Sparse_Regression:
def __init__(self, l, h, p, mx):
self.l = l
self.h = h
self.p = p #shuffle
self.X = None #.shape = (nx, mx)
self.Y = None #.shape = (1, mx)
... |
# https://leetcode.com/problems/path-sum/discuss/36486/Python-solutions-(DFS-recursively-DFS%2Bstack-BFS%2Bqueue)
# https://leetcode.com/problems/path-sum/submissions/
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = le... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# coding=utf-8
"""
@author: Li Tian
@contact: 694317828@qq.com
@software: pycharm
@file: sample_data_deal.py
@time: 2019/2/8 20:30
@desc: 输入数据处理框架
"""
from figuredata_deal.figure_deal_test2 import preprocess_for_train
import tensorflow as tf
# 创建文件列表,并通过... |
import logging
import os
import chainer
import numpy as np
class GraphDataset(chainer.dataset.DatasetMixin):
def __init__(self, loc_npy, vel_npy, edges_npy):
self.features, self.edges = self.prepare_datasets(loc_npy, vel_npy, edges_npy)
self.num_episodes = self.features.shape[0]
self.nu... |
import numpy as np
name = ['Alice', 'Bob', 'Cathy', 'Doug']
age = [25, 45, 37, 19]
weight = [55.0, 85.5, 68.0, 61.5]
data = np.zeros(4, dtype={'names': ('name', 'age', 'weight'), 'formats': ('U10', 'i4', 'f8')})
# print(data.dtype)
data['name'] = name
data['age'] = age
data['weight'] = weight
print(data)
|
from django.contrib import admin
from photos.models import Photo
class PhotoAdmin(admin.ModelAdmin):
list_display = ('__unicode__', 'side_of_street', 'x_offset', 'width', 'height')
admin.site.register(Photo, PhotoAdmin)
|
from options.test_options import TestOptions
from data import DataLoader
from models import create_model
from util.writer import Writer
from models.layers import mesh_prepare
import os
import numpy as np
def add_adverserial_examples(dataset):
#dataset.dataset.paths = []
return
def run_test(epoch=-1, vertices ... |
# Determines if a year is a leap year or not
#
# Creates a function which calculate if year is leap or not
def lpyear(year):
if year>=1582:
if (year%4)!=0:
return False
elif (year%100)!=0:
return True
elif (year%400)!=0:
return False
else:
return True
else:
return False
yearData=[1900,200... |
a = input()
alist = list(a)
m = []
ind = 0
while a:
alist = alist[::-1]
for el in alist:
if ind % 3 == 2:
alist[ind] = ''
ind += 1
ares = ''.join(alist)
m.append(ares)
a = input()
alist = list(a)
ind = 0
for word in m:
print(word)
|
#morphologicsl transformation are some simple operations based on the image shape ,normally performed on binary images
#kernal is generally a shape which we are going to apply on image
import cv2
from matplotlib import pyplot as pyp
import numpy as np
#img=cv2.imread('smarties.png',cv2.IMREAD_GRAYSCALE)
img2=cv2.imre... |
# -*- coding: utf-8 -*-
# @Time : 2019-06-28 11:28
# @Email : aaronlzxian@163.com
# @File : module_parser_test.py
import os
import unittest
from abyss.module_parser import ModuleParser
directory = os.path.join(os.path.dirname(os.path.abspath(__file__)) + os.path.sep + "..", 'build/build')
if not os.path.exists(direct... |
# Generated by Django 3.2.7 on 2021-10-09 22:40
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('servicios', '0002_auto_20210311_1855'),
]
operations = [
migrations.AddField(
model_name='servicio',
name='direccion... |
# user_input=input('Write a word')
# # print(user_input[-2:])
# if user_input[-2:]in(('th','sh','ch')):
# print(user_input +'es')
# if user_input[-1] in ('s','x'):
# print(user_input+'es')
# # else print(user_input+'s'):
# #bin-max
# highest_num=0
# places=20
# for n in range(256):
# highest_num=0
# #comput... |
import nose
from nose.tools import ok_
from nose.plugins.attrib import attr
from birdfeeder.utils import humanize_filesize
def test_humanize_filesize():
print humanize_filesize(20000000)
assert humanize_filesize(256) == '256.0B'
assert humanize_filesize(1024) == '1.0K'
assert humanize_filesize(1048576... |
# -*- coding: utf-8 -*-
from time import clock
import zlib
from math import acos, radians, pi
from numpy import ones, cos, array, sin
from typing import Tuple, NamedTuple
'General tools'
'This is arbitrary, and will change in the tests'
SEED = 0x23587643
def dhash(*data):
"""Generates a random-looking determin... |
# -*- encoding: utf-8
from os.path import dirname
import enum
from database.utils import submodule_initialization, set_logger
from database.const import DataFormatCategory, NaS, FilledStatus, ENCODING, REL_PATH_SEP
SUBMODULE_NAME = 'jsondb'
# 设置日志选项
DB_CONFIG = submodule_initialization(SUBMODULE_NAME, dirname(__file... |
# -*- coding: utf-8 -*-
"""
Created on Sun Oct 18 00:58:22 2020
@author: jalil garcia jeronimo
"""
print ("introdusca un numero")#se solicita un dato desde el teclado
num=int(input())#se almacena el dato introducido desde el teclado
def factorial(num):#Funcion recursiva
if num == 0 or num == 1:#condicion... |
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
# useful for handling different item types with a single interface
from itemadapter import ItemAdapter
import os
class ScrappagePipeline:
def p... |
# Não se esqueça de incluir o módulo numpy
# Use o navegador Chrome, para copiar/colar a entrada de exemplo
from numpy import*
v = array(eval(input("Insira um vetor: ")))
#Quant elemento
print(size(v))
#Primeiro elmento
print(v[0])
#Ultimo elemento
print(v[-1])
#Maior elemento
print(max(v))
#Menor elemento
print(min... |
N = int(input())
arr = list(map(int, input().split()))
if N == 2:
for i in range(1, min(arr) + 1):
if arr[0] % i == 0 and arr[1] % i == 0:
print(i)
else:
for i in range(1, min(arr) + 1):
if arr[0] % i == 0 and arr[1] % i == 0 and arr[2] % i == 0:
print(i) |
import configparser
import os
import instaloader
from instaloader.lateststamps import LatestStamps
from configparser import ConfigParser
from datetime import datetime
import pytz
import telebot
from telethon.sync import TelegramClient
from telethon.tl.types import InputPeerUser, InputPeerChannel
from telethon import T... |
from django.contrib import admin
from django.utils.html import format_html
from .models import Deliver_Executive,ongoing_delivery
# Register your models here.
@admin.register(Deliver_Executive)
class DeliveryAdmin(admin.ModelAdmin):
list_display = (
'id',
'name',
'contract_name',
... |
def concha(arr):
sub = len(arr)//2
while sub:
for st in range(sub):
conchaEntra(arr,st,sub)
print("After increments of size ", sub, " the list is ", arr)
sub=sub//2
return arr
def conchaEntra(arr,st,gap):
for i in range(st+gap, len(arr),gap):
cur = arr[i]
... |
import sys
def load_mappings(fname):
fp=open(fname)
CLAWS_TO_POS={}
for line in fp:
words=line.split()
CLAWS_TO_POS[words[1].lower()]=words[0].lower()
return CLAWS_TO_POS
def strip_trailing_integers(s):
leading_string=""
lastplusone=len(s)
for i in range(len(s)):
if(s[i:i+1].isdigit()):
lastplusone=i
... |
#!/usr/bin/python
"""
ZetCode wxPython tutorial
In this example, we create a wx.html.HtmlWindow widget.
author: Jan Bodnar
website: www.zetcode.com
last modified: May 2018
"""
import wx
import wx.html
class Example(wx.Frame):
def __init__(self, *args, **kw):
super(Example, self).__init__(*args, **kw)
... |
import cv2
coffeePic = cv2.imread('coffee.jpg')
#changing picture to grayscale
gray = cv2.cvtColor(coffeePic, cv2.COLOR_BGR2GRAY)
cv2.imshow("Grayed Image",gray)
#writing the gray Image as newfile.jpg
cv2.imwrite("newfile.jpg",gray)
cv2.waitKey(0) |
from bs4 import BeautifulSoup
import urllib.request
import re # dk what this is && scared of removing it
import time
import tkinter as tk
from PIL import ImageTk, Image
import os
import requests
from io import BytesIO
# test
url_list = [] # contains the urls in string form of all the short screener webpages
links_with... |
from tkinter import *
import solve as solved
#how to use a class to with Tkinter
def main():
class Application(Frame):
""" Gui application with 3 methods"""
def __init__(self,master):
#inilitilazes the frame
Frame.__init__(self,master)
self.grid()
... |
class Solution:
def lexicalOrder(self, n):
stack, res = [], []
start = 1
while len(res) < n:
if start <= n:
res.append(start)
stack.append(start)
start *= 10
else:
start = stack.pop()
... |
#!/usr/bin/env python
import os
from Gallimaufry.USB import USB
here = os.path.dirname(os.path.realpath(__file__))
def test_device_string_descriptor():
pcap = USB(os.path.join(here,"examples","webcam","logitech_C310_enum.pcapng"))
device = pcap.devices[0]
assert device.string_descriptors == {2: '7D... |
import base64
import binascii
#Initial value and expected output
h = '49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d'
solution = 'SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t'
#Convert from HEX to BINARY and then BINARY to BASE64
def hexToBase64(... |
from django.urls import path
from . import views
app_name = "authenticate"
urlpatterns = [
path("", views.home, name="home"),
path("login/", views.login_user, name="login"),
path("logout/", views.logout_user, name="logout"),
path("register/", views.register_user, name="register"),
path("edit_profil... |
from django import forms
from.models import Venta
class VentaForm(forms.ModelForm):
class Meta: #para indicar de que modelo se va a crear el formulario
model = Venta
fields = [
'codigo_venta',
'id_producto',
'fecha_venta',
'cantidad',
'valor_venta',
... |
#!/usr/bin/python
import urllib.request
import os, sys
from gmap_utils import *
import time
import random
import json
def download_tiles(zoom, lat_start, lat_stop, lon_start, lon_stop, satellite=True):
start_x, start_y = latlon2xy(zoom, lat_start, lon_start)
stop_x, stop_y = latlon2xy(zoom, lat_stop, lon_sto... |
import asyncio
import aiohttp
import logging
import os
import sys
import getopt
async def check_cert(q_main, q_good, q_bad):
while True:
hostname = await q_main.get()
conn = aiohttp.TCPConnector()
session = aiohttp.ClientSession(connector=conn)
success = False
try:
... |
import os
from bokeh.models import CustomJS, CustomAction, PolyEditTool
from holoviews.streams import Stream, PolyEdit, PolyDraw
from holoviews.plotting.bokeh.callbacks import CDSCallback
from geoviews.plotting.bokeh.callbacks import GeoPolyEditCallback, GeoPolyDrawCallback
from .models.custom_tools import PolyVert... |
import matplotlib.pyplot as plt
import numpy as np
import smoothcurve
import statistics
import csv
file = open("csv/activity.csv", "r")
csvReader = csv.reader(file)
def getStepsPerDay(file, reader):
next(reader)
steps = []
stepsToday = 0
acc = 0
while True:
try:
acc += 1
... |
num, m = map(int, input().split())
# str로 만들기 -> 한 글자 씩 빼서 숫자로 만들기
num = list(map(int, str(num)))
stack = []
for x in num :
# stack : 비어 있지 않으면 True
while stack and m > 0 and stack[-1] < x :
# stack의 제일 뒤(=최상단) 요소 빼기
stack.pop()
m -= 1
stack.append(x)
# for문 다 돌아도 m개 만큼 지우지 못한 경우
i... |
# -*- coding: utf-8 -*-
import scrapy
import time
import unicodedata
from bs4 import BeautifulSoup
from shfine.items import ShfineItem
head_url = 'http://183.194.249.79/web/'
url_dict = {'jingan': 'http://183.194.249.79/web/search.aspx?keyword=&type=1&organ=3df201d9-c63e-4c54-b9a5-e252737cf31f',
'pudong':... |
from airflow.hooks.postgres_hook import PostgresHook
from airflow.models import BaseOperator
from airflow.utils.decorators import apply_defaults
import os
import pandas as pd
import numpy as np
from datetime import datetime
import gzip
from elasticsearch import Elasticsearch
import elasticsearch.helpers
import json
fro... |
num= 4
k=0
for i in range(2,int(num/2)):
if (num%i==0):
k = k+1
if (k==0):
print("IS a prime number")
else:
print("IS not a prime number")
|
#!/usr/bin/env python
import sys
import logging
import argparse
from time import sleep
from securecscc import ApplicationFactory
def _logger():
logger = logging.getLogger('securecscc')
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler = logging.StreamHandler()... |
from typing import TYPE_CHECKING, List
from .helpers import is_pow2, roundup_pow2, roundup_to
from .. import walker
from .. import rdltypes
from ..node import Node, AddressableNode, SignalNode
from ..node import AddrmapNode, RegfileNode, MemNode, RegNode, FieldNode
if TYPE_CHECKING:
from ..compiler import RDLEnvi... |
#!/usr/bin/env python
import os
from decimal import Decimal, getcontext
import numpy as np
from matplotlib import pyplot as plt
from astropy.io import ascii
from scipy.integrate import quad
import plot_mc
NEED_PARAMS = ['Omega_m', 'Omega_lambda', 'H0']
NEED_NUISANCE = ['M_nuisance']
class LK:
def __init__(self,... |
def binary_search(arr,l,r,item):
if l<r:
mid=int(l+(r-l)/2)
print("The mid is:",mid)
if arr[mid]==item:
return mid
elif arr[mid] < item:
return binary_search(arr,arr[mid+1],r,item)
else:
return binary_search(arr,l,arr[mid-1],item)
else:... |
#! /usr/bin/env python
"""
Module with 2d/3d plotting functions.
"""
from __future__ import division, print_function
__author__ = 'Carlos Alberto Gomez Gonzalez, O. Wertz'
__all__ = ['pp_subplots']
import numpy as np
from matplotlib.pyplot import (figure, subplot, show, colorbar, Circle, savefig,
... |
"""
Django settings for lexoom project.
Generated by 'django-admin startproject' using Django 1.8.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Build paths i... |
from django import forms
from .models import Tracks
class TrackForm(forms.ModelForm):
class Meta:
model = Tracks
fields = ['track_name','audio_file',]
labels = {
'audio_file': ('Audio File')
}
help_texts = { 'track_name': "Add a name to your file", }
|
#!/usr/bin/env python3
import sys
import re
import string
ign_regs = False
num_re = re.compile(r'[0-9]+')
comments = re.compile(r'<.*?>')
regs = re.compile(r'\b(a[0-3]|t[0-9]|s[0-7]|at|v[01])\b')
sprel = re.compile(r',([1-9][0-9]*|0x[1-9a-f][0-9a-f]*)\((sp|s8)\)')
forbidden = set(string.ascii_letters + '_')
skip_lines... |
# Scatter
plt.scatter(x_values, y_values, c=y_values, cmap=plt.cm.Blues, edgecolors='none', s=40)
# Organizando plot
plt.title('Quadrados', fontsize=26)
plt.xlabel('Valores', fontsize=14)
plt.ylabel('Quadrado dos Valores', fontsize=14)
# Especificando limites do gráfico
plt.axis([0, 1100, 0, 1100000])
# Organizando ... |
from element import Element
class Create(Element):
def __init__(self, delay):
self.nextElements = []
super().__init__(delay)
def setNextElements(self, elems):
self.nextElements = elems
def outAct(self):
super().outAct(1)
self.setTnext(self.getTcurr() + self.getDela... |
def horners(input, coefficents):
if len(coefficents) >1:
return coefficents[0] + input*horners(input, coefficents[1:])
else:
return coefficents[0]
for i in range(5):
print(horners(i,[1,3,2])) |
from random import seed
seed(1)
import numpy
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
import simpy
class Sender(object):
def __init__(self, env, nextcable, sendrate):
self.env = env
self.sendrate = sendrate
self.nextcable = nextcable
env.process(self.s... |
import numpy as np
import pandas as pd
from web_scrapper import scroll
# Now that the page is fully scrolled, grab the source code.
# browser = scroll(max_interations=5,url="https://twitter.com/search?l=&q=esquerda%20OR%20direita%20since%3A2013-01-01%20until%3A2013-12-31&src=typd&lang=pt", delay=1)
browser = scroll(ma... |
played_before = ""
while played_before.lower() != "xxx":
#Ask user if they have played this game before
played_before = input("Have you played this game before?").lower()
#If user says yes, output 'program continues'
if played_before == "yes" or played_before == "y":
played_before = "yes"
... |
'''
github的API可以让我们通过调用API来请求各种信息, 这个API将返回GitHub当前托管了多少个python项目, 滑油有关最受欢迎的python仓库的信息
'''
API = "https://api.github.com/search/repositories?q=language:python&sort=stars"
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.