text stringlengths 38 1.54M |
|---|
#!/usr/bin/env python3
import sys
import yaml
import re
import pdb
import mistune
class CustomRenderer(mistune.Renderer):
templatecnt = 0 # Used for each template value for ordering in the YAML file
yamldata = {}
def addelement(self, text):
name = f"element{self.templatecnt:03}"
self.yamld... |
import json
import logging
import settings
import urllib
from google.appengine.api import urlfetch
from constants import START_ADDRESS, END_ADDRESS, DAYS, TRANSPORT_METHOD, \
OUTBOUND, HOMEBOUND, EARLIEST_START, LATEST_START, CURRENT_START, \
EARLIEST_HOME, LATEST_HOME, CURRENT_HOME, OUTBOUND_HOMEBOUND, \
... |
from display import *
def display_card(card,cycle,pack_name):
if card['type_code'] == 'identity':
display_identity(cycle,pack_name,**card)
elif card['type_code'] == 'event':
display_event(cycle,pack_name,**card)
elif card['type_code'] == 'operation':
display_operation(cycle,pack_nam... |
# 拆分成整数和小数来处理,不要用round!不要用round!不要用round!
# In : round(0.5)
# Out: 0
while True:
try:
a, b = tuple(map(int, input().split('.')))
if b >= 5:
a += 1
print(a)
except:
break
|
# -*- coding: utf-8 -*-
import uuid
import datetime
import os.path
from django.db import models
from users.models import User
class Feedback(models.Model):
user = models.ForeignKey(User, null=True, blank=True)
email = models.EmailField(u'E-mail', null=True, blank=True,
help_text=u'Мы отправим вам о... |
#!/usr/bin/env python
"""
A simple python script template.
"""
import os
import sys
import time
import shutil
import argparse
import logging
import json
import textwrap
import pprint as pp
from prettytable import PrettyTable
from prettytable import MSWORD_FRIENDLY
import ROOT as rt
import functools, logging
class ... |
from gibbsduhem import Read
import matplotlib.pyplot as plt
output = Read("output.dat")
temp = output.find("T")
press = output.find("p")
plt.plot(temp, press)
plt.xlabel("Temperature [K]")
plt.ylabel("Pressure [kPa]")
plt.grid()
plt.show()
|
#!/usr/bin/env python
# encoding: utf-8
"""
Convert WIRCam photometry.
"""
# Constants added to vega mags to obtain AB mags
# From Blanton et al 2005 AJ 129 2565 eq 5.
WIRCAM_VEGA_TO_AB = {
"J": 0.91,
"H": 1.39,
"Ks": 1.85}
def wircam_vega_to_ab(vegamag, band):
"""Returns the AB mag of a WIRCam AB ma... |
import pytest
import offsetbasedgraph as obg
from graph_peak_caller.control.linearmap import LinearMap
from graph_peak_caller.control.linearintervals import\
LinearIntervalCollection
@pytest.fixture
def hierarchical_graph():
nodes = {i: obg.Block(i-90) for i in range(100, 106)}
edges = {100: [101, 102],
... |
import os, time, operator, logging, copy , sys
from datetime import timedelta
from collections import defaultdict
#from scipy import stats
#import numpy as np
infile_dir = sys.argv[1]
file_list = os.listdir(infile_dir)
global_bp_cov_sum = 0.0
global_bp_cov_div = 0.
global_masked_cnt = 0.0
global_masked_div = 0.0
for i... |
from fzutils.common_utils import json_2_dict
from fzutils.ocr_utils import yundama_ocr_captcha
with open('/Users/afa/myFiles/pwd/yundama_pwd.json', 'r') as f:
yundama_info = json_2_dict(f.read())
username = yundama_info['username']
pwd = yundama_info['pwd']
app_key = yundama_info['app_key']
res = yundama... |
import os, sys
from os.path import join, isdir, isfile, dirname
from time import sleep
import pyperclip
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from pprint import pprint as pp
e=sys.exit
chrome_options = Options()
data_dir=r'chrome-data'
options = Options()
options.ad... |
from flask import Flask, jsonify
import mysql.connector
from json_encoder import json
app = Flask(__name__)
def getMysqlConnection():
return mysql.connector.connect(user='root', host='db', port='3306', password='root', database='city')
def query_result(query, method):
db = getMysqlConnection()
cur = db... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class veiculo:
def init (self):
self.ligado = False
self.rodas = 4
self.flex = False
self.marchaatual = 0
|
# -*- coding: utf-8 -*-
"""
Created on Sun Sep 30 13:11:25 2018
@author: Robi
A Mersenne number is any number that can be written as 2p−1 for some p.
For example, 3 is a Mersenne number (2^2−1) as is 31 (2^5−1).
Write a function that accepts an exponent p and returns the corresponding Mersenne number.
"""
def merse... |
import os
import cv2
import numpy as np
from IPython.display import clear_output
import matplotlib.pyplot as plt
import torch
import random
def training_setup_seed(seed):
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
np.random.seed(seed)
random.seed(seed)
torch.backends.cudnn.determinis... |
# -*- coding: utf-8 -*-
from ast import Module
from typing import Generator, Tuple
from wemake_python_styleguide.version import __version__
from wemake_python_styleguide.visitors.high_complexity import ComplexityVisitor
from wemake_python_styleguide.visitors.wrong_function_call import (
WrongFunctionCallVisitor,
... |
# Generated by Django 3.0.7 on 2020-10-06 19:10
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('cases', '0009_auto_20201006_2209'),
]
operations = [
migrations.AddField(
model_name='defendant',
name='description_... |
from django.shortcuts import render
from django.http import HttpResponse
from django.contrib.auth.decorators import login_required
from exams.models import Question
@login_required
def update_answer(request):
"""This function updates/adds answer"""
if request.method == 'POST':
question = Question.obj... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import MySQLdb
import datetime
from datetime import timedelta
from decimal import Decimal
from flask import Flask
from flask import current_app
from flask import jsonify
from flask import make_response
from flask import request
from flask.ext.restful import Api
from funct... |
"""
TERMS
i.b. "Freelancer"
For the protections contained in this document, henceforth FREELANCER
refers to Mike Rightmire and any and all agents affiliated with him including
but not limited to officers in any corporate entity in which he is a corporate
officer, employees, contractors, advisors, affiliates, or part... |
from enum import Enum
class EnumEnumCityEnum_parks(Enum):
park_a = "park_a"
park_b = "park_b"
|
from PIL import ImageGrab
from pynput.mouse import Button, Controller
import time
from ctypes import windll
import sys
limit = 20
if (len(sys.argv) == 1):
print("No limit specified, using default of %i" % (limit))
print("Usage example: python %s 30" % (sys.argv[0]))
elif (sys.argv[1].isdigit()):
... |
#! /bin/python2
import numpy
import cv2
import os
import struct
BLACK = (0,)
WHITE = (255,)
DIR_OUT = "./img/"
SIZE_CANVAS = 50
SIZE_FEATURE = 28
SIZE_BLOCK = 32
DIGITS = tuple([chr(ord("0") + i) for i in range(10)] + [""])
FONTS = (cv2.FONT_HERSHEY_SIMPLEX, cv2.FONT_HERSHEY_PLAIN,
cv2.FONT_HERSHEY_DUPLEX, c... |
# -*- coding: utf-8 -*-
"""
* TencentBlueKing is pleased to support the open source community by making 蓝鲸智云-蓝鲸 PaaS 平台(BlueKing-PaaS) available.
* Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except in co... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'uimodify.ui'
#
# Created by: PyQt5 UI code generator 5.5
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
from dbase import *
class Ui_Modify(object):
def setupUi(self, Modify):
... |
#!/usr/bin/env python2.7
import sys
import os
import argparse
from scapy.all import *
from subprocess import call
import subprocess
import binascii
import time
import telnetlib
import json
import re
pcie_id=None
lif_id=0
CMD_FMT='tbl {tbl} idx {idx} post'
CTRL_FMT=None
DATA_FMT=None
HOST_OS= ''
REMOTE_CMD_FMT='{cmd} ... |
# -*- coding: utf8 -*-
# Copyright (c) 2017-2018 THL A29 Limited, a Tencent company. 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... |
from rest_framework import serializers
class SocialSerializer(serializers.Serializer):
"""
Serializer which accepts an OAuth2 access token.
"""
accessToken = serializers.CharField(allow_blank=False, trim_whitespace=True, )
class PageDetailsSerializer(serializers.Serializer):
about = serializers.... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('pnxyvqx', '0011_ecatm'),
]
operations = [
migrations.RemoveField(
model_name='nrnexasxp',
name='irgw... |
from VAE1D import *
from scipy.stats import multivariate_normal
from time import sleep
import matplotlib.pyplot as plt
plt.style.use('ggplot')
size = 512
n_channels = 14
n_latent = 50
kl_weight = 1
date = '190130'
desc = 'accumulator'
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
def loa... |
### importing essetial libraries
# dash (needed to be installed via pip or the like)
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State
# datetime
import datetime
# pandas (needed to be installed via pip or the like)
import ... |
from django.db import models
class Place(models.Model):
title = models.TextField()
description = models.TextField()
thumbnail = models.URLField(null=True, blank=True)
image = models.URLField(null=True, blank=True)
lat = models.FloatField(null=True, blank=True)
long = models.FloatField(null=Tr... |
import codecs
str = "ПГПГ ПЮОГ УГПЦ"
for i in range(32):
for j in str:
print (chr(ord(j) + i), end = "")
print()
|
doc+='''
<link rel="stylesheet" type="text/css" href="'''
try: doc+=str(config.base_url)
except Exception as e: doc+=str(e)
doc+='''static/js/jquery-ui-1.12.1.custom/jquery-ui.css">
<style type="text/css">
#accordion{
width:300px;
font-size:14px;
}
.ui-accordion .ui-accordion-content{
padding: 0px;
height: 3... |
import gspread
from oauth2client.service_account import ServiceAccountCredentials
from utils import getNumLevels
from game import BloxorzGame, h1, h2
import time
# use creds to create a client to interact with the Google Drive API
scope = ['https://www.googleapis.com/auth/drive']
creds = ServiceAccountCredentials.fro... |
'''
# pip help
shows all the commands
# pip help <command>
shows help for spacific command
# pip search <package name>
shows package name and discription
# pip list
shows all the installed package
# pip uninstall <package name>
for uninstall package
# pip list -o
or
# pip list --outdated
shows list of package who ... |
distancia = float(input('Digite a distancia da viagem [em KM]:'))
if distancia >= 200:
print(f'O valor da viagem sera de R${distancia*0.45:.2f}')
else:
print(f'O valor da viagem sera de R${distancia*0.5:.2f}')
|
from random import randint
def findMax(arr): # for finding the biggest element in the list
m = 0
for i in range (0,len(arr)):
if m < arr[i]:
m = arr[i]
return m
def binsort(array):
n = len(array) # the length of the lsit
tmp = []
m = findMax(array)
for j in range(0,m+1... |
from django.conf.urls import url
from . import views
# def index(request):
# print("I'm running")
urlpatterns = [
url(r'^$', views.index, name="index")
] |
# Copyright 2016 Leon Sixt
#
# 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 agreed to in writing, so... |
# Generated by Django 3.0.5 on 2020-05-02 01:25
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('bookstore', '0002_auto_20200502_0016'),
]
operations = [
migrations.AlterField(
model_name='book',
name='edition',
... |
#!/usr/bin/python
import credentials
import MySQLdb
from phases import *
# Open database connection
db = MySQLdb.connect("localhost",credentials.username,credentials.password,"lab_resourcer" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
researcher_id, n_slices, primaries, stainings = input_... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from modules.net.usersesion import LoggedUserSesion
from modules.wrappers.wraper import Functions
x=LoggedUserSesion(0,'login','password')
e=Functions(x)
print 'Api For PRIMERA Server Immported'
print e.train()
print e.work()
x.logout()
print 'Logout'
print '==============... |
from unittest import TestCase
from test.common import *
from main.decoder_attention import DecoderAttention
class TestDecoderAttention(TestCase):
def test(self):
dec_hidden = t.randn(2, 2 * conf('hidden-size'))
pre_dec_hidden = t.randn(2, 3, 2 * conf('hidden-size'))
decoder_att = Decode... |
conversion = {'0':0,'1':1, '2':2, '3':3, '4':4,'5':5,'6':6,'7':7,'8':8, '9':9,'A':10,'B':11,'C':12, 'D':13,'E':14,'F':15}
def binary(num):
global result
for i in range(4):
mok = num // 2
nam = num % 2
result = str(nam) + result
num = mok
return
T=int(input())
for test_case ... |
from manimlib.imports import *
import numpy as np
class Function_General(Scene):
def construct(self):
#TITLE
title = TextMobject("What is a function?")
title.scale(1.3)
title.to_edge(UP)
#FUNCTION NOTATION
function_notation = TexMobject("f(x) = y", tex_to_color_map={... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
###########################################
# (c) 2016-2017 Polyvios Pratikakis
# polyvios@ics.forth.gr
###########################################
import re
import json
import sys
from collections import Counter
from progress.bar import Bar
from twkit.utils import *
db, api... |
import numpy as np
import matplotlib.pyplot as plt
import subprocess
import sys
# For nice plots
plt.style.use('seaborn')
plt.rc('text', usetex=True)
plt.rc('text.latex', preamble=r'\usepackage{amsmath}')
# Defining arguments for c++ script
try:
timestep, dt, numberOfBodies, file = sys.argv[1:]
timestep = i... |
import torch
import torch.nn as nn
class CondSequential(nn.Sequential):
def __init__(self, *args):
super(CondSequential, self).__init__(*args)
def forward(self, input, cond):
for module in self._modules.values():
input = module(input, cond)
return input
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.contrib import messages
from django.contrib.auth.models import User
from django.views.generic import FormView
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import ListView
from app.mixins.CustomContextMixin import CustomCont... |
def solution(A):
# write your code in Python 3.6
total = sum(range(len(A)+2))
return total - sum(A)
A = [2, 3, 1, 5]
print(solution(A))
|
"""
Distributed under the MIT License. See LICENSE.txt for more info.
"""
from django import forms
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext_lazy as _
from .public import ConeSearchForm
class ConeSearchCollaboratorForm(ConeSearchForm):
"""
Form to perfo... |
song = []
artiste = []
insong= ""
byartist= ""
end = "end"
back = "prev"
#functoin to take input values from of lat from user appending to list named song
def insong():
insong = input("({}). enter lat.: ".format(len(song) + 1)).lower()
song.append(insong)
if insong == back:
previousS()
elif in... |
#!/usr/bin/env python3
# Example mouser csv to partkeepr REST api
# -------------------------------------------
#
import sys
import time
import csv
import json
# for json pretty printing
from pprint import pprint as pp
# http://docs.python-requests.org/en/master/
import requests
# set this to part... |
"""
A restful api generator for the lazy
"""
from snooze_exceptions import SnoozeError
from transport import RESTfulRequest
import re
class Snooze(object):
def __init__(self, domain, uri='', secure=False):
if domain[-1] == '/':
domain = domain[:-1]
self.domain = domain
... |
""" NOTE: This version works with 1 channels """
import os
import datetime
# os.environ['TF_CPP_MIN_LOG_LEVEL'] = '0'
now=datetime.datetime.now()
CURRENT_DAY = now.strftime('%m%d')
CURRENT_TIME = now.strftime('%H%M')
BASE_DIR = os.path.dirname(os.path.realpath(__file__))
DATA_ROOT = BASE_DIR+'/../DATA'
WIDTH = 12... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import pygame
import easygui as eg
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
SEMIWHITE = (245, 245, 245)
GRAY = (128, 128, 128)
LIGHTGRAY = (192, 192, 192)
GANSBORO = (220, 220, 220)
SLATEGRAY = (112, 128, 144)
class Container:
"""Clase que permite dibujar ... |
# $Id$
##
## This file is part of pyFormex 0.8.5 Sun Nov 6 17:27:05 CET 2011
## pyFormex is a tool for generating, manipulating and transforming 3D
## geometrical models by sequences of mathematical operations.
## Home page: http://pyformex.org
## Project page: https://savannah.nongnu.org/projects/pyformex/
... |
#Ejecutar: Crtl+Alt+B
#Paquetes a utilizar
import math
from math import floor #Redondear al valor inferior
from math import ceil #Redondear al valor superior
from tabulate import tabulate
import os
desktop = os.path.join(os.path.join(os.environ['USERPROFILE']), 'Desktop')
#Codigo para truncar numeros
def... |
# -*- coding: utf-8 -*-
"""
app
~~~
Entrance
:copyright: (c) 2019 by staugur.
:license: MIT, see LICENSE for more details.
"""
from uuid import uuid4
from flask import Flask, g, jsonify
from version import __version__
from views import front_bp, api_bp
from utils.tool import Attribute, err_logger... |
from typing import List
'''
问题:
给你一个整数数组 nums ,找到其中最长严格递增子序列的长度。
子序列是由数组派生而来的序列,删除(或不删除)数组中的元素而不改变其余元素的顺序。例如,[3,6,2,7]是数组[0,3,1,6,2,2,7]的子序列。
定义函数:
f(i)=>以第i个数字结束的最长递增子序列
边界:
f(0) = nums[0]
推导过程:
nums=[10,9,2,5,3,7,101,18]
i=0 => [10]
i=1 => [9]
i=2 => [2]
i=3 => [2,5]
i=4 => [2,3]
i=5 => [2,3,7]
i=6 => [2,3,7,101]
i=... |
'''
역수열(그리디)
"T" : 빈 공간
'''
import sys
#sys.stdin = open("in1.txt","r")
'''
n = 8
arr = [5,3,4,0,2,1,1,0]
'''
n = int(input())
arr = list(map(int,input().split()))
ans = ["T"] * n
def F(ans,v):
idx = -1
n = 0
while 1:
idx +=1
if ans[idx] == "T":
n... |
#
# test03 (b)
#
# image resize bug test
#
# http://stackoverflow.com/questions/37032251/tensorflow-image-resize-mess-up-image-on-unknown-image-size
#
import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
plt.ion()
file_contents = tf.read_file('fot1.jpg')
im = tf.image.decode_jpeg(file_contents... |
from Tkinter import *
from PIL import ImageTk, Image
master = Tk()
canvas = Canvas(master,width=200,height=200)
canvas.pack()
test = [[75,75],[125,75],[125,125],[75,125]]
canvas.create_polygon(test, fill='white', outline='black')
L = ImageTk.PhotoImage(Image.open("L.png"))
canvas.create_image((100,100),... |
import pytest
from calculator.ast import BinOp, Constant, UnaryOp
from calculator.core import operations
from .evaluator import Evaluator
@pytest.fixture
def vis():
return Evaluator()
def test_evaluate_constant(vis):
c = Constant(42)
assert vis.visit_and_get_value(c) == 42
def test_evaluate_unaryop_i... |
import random
import numpy as np
import similarity
class KMeans(object):
def __init__(self, k, vectors, metric):
assert len(vectors) >= k
self.centers = random.sample(vectors, k)
self.clusters = [[] for c in self.centers]
self.vectors = vectors
self.metric = metric
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Dec 10 09:54:00 2017
@author: andrea
"""
import scipy.integrate as integrate
from scipy.stats import norm
import numpy as np
import matplotlib.pyplot as plt
import time
# define parameters
a = 0.1670; b = 0.0280; sigma = 0.0160; p = 0.5745; lambda_p = 5... |
# -*- coding: utf-8 -*-
import MySQLdb
from MySQLdb import Error
from warnings import filterwarnings
filterwarnings("ignore")
class MysqlManager(object):
def __init__(self, db_info):
self.db_info = db_info
self.db_connection = None
self._connect_to_mysql()
def _connect_to_mysql(self... |
import turtle
def draw_square():
#window = turtle.Screen()
#window.bgcolor("white")
draw=0
turtle.register_shape("C:\prank\poke.gif")
brad=turtle.Turtle()
brad.shape("C:\prank\poke.gif")
brad.color("yellow")
brad.speed(1)
while draw < 4:
brad.forward(100)
brad.right(90)
draw+=1
def create_background():... |
from lpsolve55 import lpsolve, IMPORTANT
class max_independent_set_with_ILP:
def __init__(self, g):
self.g = g
self.n = g.number_of_nodes()
self.zeros = [0] * self.n
self.__lp()
self.__independent_set()
def __lp(self):
self.lp = lpsolve('make_lp', 0, self.n)
... |
#!/usr/bin/env python
import openpyxl
book = openpyxl.load_workbook('sheets.xlsx')
print(book.sheetnames)
active_sheet = book.active
print(type(active_sheet))
sheet = book["March"]
print(sheet.title) |
import Minmax
import Board
import copy
VALUE = 10
class Tminmax(Minmax.Minmax):
def __init__(self, maximizer, minimizer):
super().__init__()
self.maximizer = maximizer
self.minimizer = minimizer
def updateStructre(self, structre, move, isMaximizer):
if isMaximizer:
structre.board.set(move[0], move[1], ... |
"""
todolist index (main) view.
URLs include:
/
"""
import os
import pathlib
import flask
import todolist
from todolist.views.util import hash_salt, check_password, save_picture
@todolist.app.route('/accounts/login/', methods=['GET', 'POST'])
def show_login():
"""Show the login page."""
# Redirect to index i... |
'''
Conversions between date and time representations
Brett Hosking 2018
'''
import datetime
from calendar import monthrange
import numpy as np
import pandas as pd
import sys
def ticks(startdate,enddate,starttime=[0,0,0],endtime=[0,0,0],timeticks=False,dayticks=False,monticks=True,yearticks=True):
'''
... |
# Calculate the future value of the investment and print it out
future_value = 100 * (1 + 0.06)**30
print("Future Value of Investment: " + str(round(future_value, 2))) |
from __future__ import absolute_import, unicode_literals
import pytest
import spacy
from textacy import cache
def test_load_spacy():
for lang in ("en", "en_core_web_sm"):
for disable in (None, ("parser", "ner")):
assert isinstance(
cache.load_spacy(lang, disable=disable), spa... |
from spotipy.oauth2 import SpotifyClientCredentials
from spotipy import Spotify
from genres import config
SPOTIFY_TAGS = ['acousticness', 'danceability', 'duration_ms', 'energy', 'instrumentalness', 'key', 'liveness',
'loudness', 'mode', 'speechiness', 'tempo', 'time_signature', 'valence']
MULTIPLIER... |
"""Reverse Polish Notation
**Reverse Polish notation**, also referred to as **Polish postfix notation** is a way of laying out operators and operands.
When making mathematical expressions, we typically put arithmetic operators (like `+`, `-`, `*`, and `/`) *between* operands. For example: `5 + 7 - 3 * 8`
However, i... |
import math
def generateFiboArray(elements):
a =[0,1]
for i in range(2,elements):
a+= [a[i-1]+a[i-2]]
return a
diameter = sum(generateFiboArray(1000))
print (diameter)
omtrek = math.pi*diameter
print (omtrek)
# pas op, goed afronden! |
"""empty message
Revision ID: c60d7b68a8ca
Revises: 8adc6efc9b58
Create Date: 2018-08-11 17:42:55.586854
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'c60d7b68a8ca'
down_revision = '8adc6efc9b58'
branch_labels = None
depends_on = None
def upgrade():
# ... |
#Bank Data
#import dependencies
import os
import csv
# Path to the file
d2 = os.path.join('budget_data.csv')
d2_out = os.path.join('d2output.txt')
# Set variable starting values
totalMonths = 0
totalRevenue = 0
prevRevenue = 0
averageChange = 0
revChange = 0
# store both date & the change
greatestInc = ["", 0]
great... |
from setuptools import setup, find_packages
VERSION = '0.4.0'
with open('requirements.txt') as requirements:
INSTALL_REQUIRES = []
for line in requirements.readlines():
if not line.startswith('#'):
INSTALL_REQUIRES.append(line)
with open('README.md') as f:
LONG_DESCRIPTION = f.read()
... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from .dac import DACDataset as dac
from .voc import MPIIDataset as mpii
from .coco import COCODataset as coco |
# coding: utf-8
# In[ ]:
# This Python 3 environment comes with many helpful analytics libraries installed
# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python
# For example, here's several helpful packages to load in
import numpy as np # linear algebra
import pandas as pd # ... |
import re
import numpy
import math
import random
import copy
class StaticCell:
def __init__(self):
self.id = -1
self.nbs = []
self.tris = []
self.position = [0,0,0]
self.vol = 0
self.color = [random.uniform(0,1), random.uniform(0,1), random.uniform(0,1), 1]
def pos(self):
return self.position
de... |
"""
buzzword explorer: collection of reusable CSS styles
"""
FRONT = {"position": "relative", "zIndex": "999"}
VERY_NEAR_FRONT = {"zIndex": "950"}
NEAR_FRONT = {"position": "relative", "zIndex": "900"}
VERTICAL_MARGINS = {"marginBottom": 15, "marginTop": 15}
HORIZONTAL_PAD_5 = {"paddingLeft": 5, "paddingRight": 5}
CEL... |
#!/usr/bin/env python
import wx,commands,os,subprocess
import wx.grid
import wx.lib.dialogs
filepath=""
pid=0
rownum=0
dirfile=0
watchpro=""
colLabels=("Filename","Event","Relates","Processname","Time")
def refresh(event):
global filepath
global pid
global dirfile
global colLabels
global rownum
global watchpro
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
num_a_mult = range(1, 11)
for multiplos_uno in num_a_mult:
print "\n" + "Tabla del " + str(multiplos_uno)
+ "\n" + "------------"
for multiplos_dos in num_a_mult:
print str(multiplos_uno) + " x " + str(multiplos_dos)
+ " = " + str(multiplos_uno*multiplos_dos)
|
##########################################################################################
#
# Copyright (c) 2009 The MadGraph5_aMC@NLO Development team and Contributors
#
# This file is a part of the MadGraph5_aMC@NLO project, an application which
# automatically generates Feynman diagrams and matrix elements for arb... |
from .CCPRestSDK import REST
# from django.conf import settings
from async_task.tasklist.sms import constent
#说明:主账号登录云通讯网站后, 可在“控制台-应用”中看到开发者主账号ACCOUNT SID
# _accountSid=settings.SMS_ACCOUNTSID
# _accountSid=settings.SMS_ACCOUNTSID
_accountSid=constent.SMS_ACCOUNTSID
#说明:主账号Token登录云通讯网站后, 可在“控制台-应用”中看到开发者主账号AUTH TOKE... |
# rsEditAttributes
# @author Roberto Rubio
# @date 2013-07-30
# @file rsEditAttributes.py
import maya.OpenMayaMPx as OpenMayaMPx
import maya.cmds as cmds
from pymel import versions
kPluginCmdRsEditAtt = "rsEditAttributesUI"
##
# rs Edit Attributes command class.
# Launch UI for reset Attributes.
class rsEditAttribu... |
#Exercise 2 ~~~~~~~~~~~~~~~~~~FAULTY CALCULATOR~~~~~~~~~~~~~~~~~~~~~
# 45*3 = 555, 56+9 = 77, 56/6 = 4
print("what do u want to do?\n[a]addition\n[b]multiplication\n[c]division")
userinput=input()
if userinput=="a":
print("enter your first number")
a=int(input())
print("enter second number")
b... |
class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
if not matrix:
return False
def helper(up, down, left, right):
if left>right or up>down:
return False
if matrix[up][left]>target or matrix[d... |
from .base.Config import Config
from .factory.createSpider import CreateSpider
from .factory.createPipeline import CreatePipeline
from pprint import pprint
class Dispatcher(object):
def __init__(self, project):
self.project = project
self.config = Config(self.project)
async def start(self):
... |
# deck.py
#
# Copyright(c) Exequiel Ceasar Navarrete <esnavarrete1@up.edu.ph>
# Licensed under MIT
# Version 2.0.0
from app.blackjack.cards.card import Card
from app.cards.card import FACE_VALUES, SHAPES
from app.cards.deck import Deck as BaseDeck
from app.cards.transformer import CardToTextTransformer
import Pyro4
c... |
'''
Problem Statement: Create a function that builds a word from the scrambled letters contained in the first list. Use the second list to establish each position of the letters in the first list. Return a string from the unscrambled letters (that made-up the word).
Problem Link: https://edabit.com/challenge/R5F99Deu... |
import pygame
import numpy as np
pygame.init()
display = pygame.display.set_mode((1150, 700))
clock = pygame.time.Clock()
FPS = 30
x = 0
y = 350
heading = 0
while True:
# check exit event
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
... |
#!/usr/bin/env python
# -*- coding: utf8 -*-
from datetime import datetime
import cx_Oracle
from twisted.web import server,xmlrpc
from twisted.internet import reactor,threads
from utilities.memcache.sessions import SessionManager
from config import root
class MenuService(xmlrpc.XMLRPC):
def __init__(self):
... |
import argparse
from time import sleep
from socket import socket
smb_negotiation_request = b'\x00\x00\x00\xd4\xff\x53\x4d\x42\x72\x00\x00\x00' \
b'\x00\x18\x43\xc8\x00\x00\x00\x00\x00\x00\x00\x00' \
b'\x00\x00\x00\x00\x00\x00\xfe\xff\x00\x00\x00\x00' \
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.