text stringlengths 8 6.05M |
|---|
from typing import List
class ColumnIterator:
"""
Iterates over a list of strings and warps around if end of list is reached, thus returning the first element again.
"""
def __init__(self, columns: List[str]):
self.columns = columns
self.index = 0
def __iter__(self):
sel... |
# Write a procedure download_time which takes as inputs a file size, the
# units that file size is given in, bandwidth and the units for
# bandwidth (excluding per second) and returns the time taken to download
# the file.
# Your answer should be a string in the form
# "<number> hours, <number> minutes, <number> secon... |
# overriding default arguments
def foo(a, b=3):
print(a, b)
# override with positional
foo(1, 333)
# override with keyword
foo(1, b=333)
# override with keyword
foo(a=2, b=333)
|
# Generated by Django 2.2.5 on 2019-11-06 11:44
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Appointment',
fields=[
('id', models.AutoFi... |
import json
import requests
body = json.dumps({
"notification": "Hello World!",
"accessCode": "ACCESS_CODE"
})
requests.post(url = "https://api.notifymyecho.com/v1/NotifyMe", data = body)
|
#!/usr/bin/python
"""
This file is used for all weather related functions.
"""
# Copyright (c) 2010-2014 LiTtl3.1 Industries (LiTtl3.1).
# All rights reserved.
# This source code and any compilation or derivative thereof is the
# proprietary information of LiTtl3.1 Industries and is
# confidential in nature.
# Use of ... |
"""Author Arianna Delgado
Created on July 1, 2020
"""
|
from WhatABlock_GameLib import *
import pygame
from pygame.locals import *
class IsoBlock(object):
isoPos = 0
screenPos = 0
width = 0
height = 0
tall = 0
worldRect = 0
visible = True
def __init__(self, isoPos, width, height):
self.isoPos = isoPos
self.width = width
self.height = height
self.visibl... |
import numpy as np
import os
from ..collector.generator import Generator
from .. import arguments
import fenics as fa
import matplotlib.pyplot as plt
import time
def run_and_save(disp, pore_flag, name):
print("\ndisp={}, pore_flag={}, name={}".format(disp, pore_flag, name))
start = time.time()
generator =... |
"""Advent of Code Day 16 - Permutation Promenade"""
def dance(moves, dances):
""" Return final position of programs after the dance moves are done."""
programs = 'abcdefghijklmnop'
program_list = list(programs)
move_list = moves.strip().split(',')
completed_dances = 0
seen = []
cycle_leng... |
import requests
from opentelemetry.context import attach, detach, set_value
from opentelemetry.sdk.resources import Resource, ResourceDetector
_GCP_METADATA_URL = (
"http://metadata.google.internal/computeMetadata/v1/?recursive=true"
)
_GCP_METADATA_URL_HEADER = {"Metadata-Flavor": "Google"}
def get_gce_resourc... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.10 on 2016-11-08 13:45
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('gomez', '0020_auto_20161023_0232'),
]
operations = [
migrations.AddField(
... |
import boost.python
ext = boost.python.import_ext("rovinj_numopt_tut_constraints_ext")
from rovinj_numopt_tut_constraints_ext import *
|
"""
Author: JiaHui (Jeffrey) Lu
Student ID: 25944800
"""
import numpy as np
import matplotlib.pyplot as plt
S = [0, 1]
for i in range(2, 101):
S.append(S[i - 2] + 0.5 * S[i - 1])
plt.plot(S)
plt.show()
"""
Solving the recurrence relation using eigenvalue decomposition, we get
Sk+1 = ((2^(-3 - 2 n) (1 - Sqrt[1... |
# -*- coding: UTF-8 -*-
import smtplib,traceback,os,sys,time,os.path,base64
import urllib,urllib2
SN = 'SDK-MOV-010-00421'
PWD = '134706'
MD5PWD='9E92A17D16DC171C7D3288CBFCFF0FEF'
SENDURL='http://sdk2.zucp.net:8060/z_mdsmssend.aspx'
BALANCEURL='http://sdk2.zucp.net:8060/z_balance.aspx'
def send_sms(target,conten... |
N = int(input())
K = int(input())
x = int(input())
y = int(input())
p = (2 * x + y) % K
if p == 0:
p = K
|
from math import ceil, floor
class Point():
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return f"({self.x}, {self.y})"
def point_x(point):
return point.x
def point_y(point):
return point.y
points = [Point(0,1),
Point(1,0),
... |
from django.db import models
class SGUser(models.Model):
username = models.CharField(max_length=191)
class Meta:
db_table = 'auth_user'
managed = False
class SGProfile(models.Model):
user = models.OneToOneField(SGUser, related_name="profile")
name = models.CharField(max_length=20)
... |
# from challenges.stacks_and_queues.stacks_and_queues import Queue, Node, InvalidOperationError
class InvalidOperationError(BaseException):
pass
class Node():
def __init__(self, value, next = None):
self.value = value
self.next = next
class Stack():
def __init__(self, node = None):
... |
import argparse
import csv
import glob
import json
import os
import traceback
from datetime import datetime
from os.path import join
import pandas as pd
from pydub import AudioSegment
import global_constants as constant
import function_library
# Reads files with the specified Noise types in allowed values'
def read... |
#euler sayısını ilk 10 terimi kullanarak hesaplayan algoritma
import math
euler = 1
for n in range(1,10): #1/10! ekleniyor
euler += 1/math.factorial(n)
print(euler) #fonk ile bu şekilde yazılır
|
"""
File Name: CNN
Author: Ryan Cho
Implementation of Keras and Tensorflow
LeNet-5 Architecture
"""
from __future__ import print_function
import keras
import #the dataset
from keras.layers import Dense, Flatten
from keras.layers import Conv2D, MaxPooling2D
from keras.models import Sequential
import matplotlib.pylab as... |
import os, time, random
from isasusy_status import isaout_investigate
def isasusy_make_in(par={}, mode=[], fnID='', fnIDtmp='', save=1):
if fnIDtmp == '': fnIDtmp = fnID
outs = []
outs.append('%s.out' %(fnIDtmp)) # 2014-03-10: hack to allow long output names: use tmp here, rename to the original ones... |
import pytest
from .. import *
def test_add():
expr = Add(Int(2), Int(3))
assert expr.type_of() == TealType.uint64
expected = TealSimpleBlock([
TealOp(Op.int, 2),
TealOp(Op.int, 3),
TealOp(Op.add)
])
actual, _ = expr.__teal__()
actual.addIncoming()
actual = Te... |
from django import template
from django.template.defaultfilters import stringfilter
# we want all the model objects avaiable
from eggs.models import Reference
register = template.Library()
# you must define an upload function on each model class you want to use.
# The object and the upload name are the input, and then ... |
# 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 sqlite3
class QuotesPipeline:
def... |
import numpy as np
class NPArith(SuperNP):
def __init__(self, OP):
SuperNP.__init__(self, OP)
self.OPS = {'add' : '+',
'subtract': '-',
'multiply': '*',
'divide': '/'}
self.OPER = self.OPS[OP]
def GetOper(se... |
#!/usr/bin/env python
# encoding: utf-8
# pip install pyexcel
# pip install pyexcel_xlsx
import re
import os
import sys
from pyexcel_xlsx import get_data
import warnings
warnings.simplefilter("ignore")
COMPAT = False
if '2.7' in sys.version:
COMPAT = True
def get_module(modules):
""":modules: list, install ... |
import pygame
import random
class Alien(pygame.sprite.Sprite):
# class level variables
speed = 13
animation_cycle = 12
# this is the animation of the alien on the screen
images = []
def __init__(self, screen_rectangle):
"""
this is the constructor! Gets called when class is in... |
#Calculate the sum of the proper divisors of a number.
def d(num):
""" (int) -> int
Return the sum of the proper divisor of num.
>>> d(220)
284
>>> d(284)
220
>>> d(10)
8
"""
divisor = []
for i in range(1, num):
if num % i == 0:
divisor.ap... |
# Split string method
names_string = input("Give me everybody's names, separated by a comma. ")
names = names_string.split(", ")
# 🚨 Don't change the code above 👆
#Write your code below this line 👇
import random
number_of_names = len(names)
payer = random.randint(1, number_of_names - 1)
print(f"{names[payer]} is g... |
#_*_coding:utf-8_*_
# Author:Topaz
a = eval('True or False')
print(a )
|
#!/usr/bin/python3
"""
List all states starting with 'N' from a MySQL db on localhost at port 3306
"""
from mysqlman import MySQLMan
from MySQLdb import Error
from sys import argv, exit, stderr
HELP = '{} username password database'.format(argv[0])
HOST = 'localhost'
PORT = 3306
if __name__ == '__main__':
try:... |
#"Prelab4Ejercicio1.py" Programa realizado por Alejandro Martinez (13-10839@usb.ve) y Jesus Kauze (12-10273@usb.ve)
#Programa Que almacena 10 enteros y los suma
#Variables
lista=[] #Lista vacia donde se guardaran los valores
Sumatoria=0 #variable donde se guardara la sumatoria de lista
#Bucle for para introducir lo... |
"""Linear Regression with TnesorFlow."""
import os
import sys
import numpy as np
import tensorflow as tf
from sklearn.datasets import fetch_california_housing
sys.path.insert(1, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from confs import logconf
logger = logconf.Logger(__file__).logger
def main(... |
class Point:
'''Defines simple 2D Points'''
def __init__(self):
self.x = 10
self.y = 20
def __str__(self):
return "Point(x=%d, y=%d)" % (self.x, self.y)
def __repr__(self):
return "P(x=%d, y=%d)" % (self.x, self.y)
def show(self, flag, capital):
'''prints the... |
print("project")
|
# Generated by Django 2.2.8 on 2020-08-12 01:42
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('projects', '0002_project_user'),
]
operations = [
migrations.AlterField(
model_name='project',
name='navers',
... |
"""Cluster Number Count statistic support.
This module reads the necessary data from a SACC file to compute the
theoretical prediction of cluster number counts inside bins of redshift
and a mass proxy. For further information, check README.md.
"""
from __future__ import annotations
from typing import List, Dict, Tuple... |
#!/usr/bin/python3
""" Provides an (empty) base class for geometric objects
"""
class BaseGeometry:
""" Implement a base class for geometric objects
"""
|
import time
import random
def timeit(func):
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
print("'{}' was running for: {} seconds".format(func.__name__, time.time() - start))
return result
return wrapper
@timeit
def time_waster(wait_seconds):... |
from rest_framework.views import APIView
from django.http import HttpResponse
import numpy as np
np.set_printoptions(threshold=np.nan)
import sklearn.linear_model as lm
from sklearn import cross_validation, grid_search, metrics
import json
import pickle
from django.shortcuts import render
from django.http import HttpRe... |
"""
back.app.routes.general_traffic
This module contains the different services for the sections traffic information table.
"""
from flask import jsonify, request, Blueprint
from sqlalchemy import func
from .. import app, db
from ..models.section_traffic import SectionTraffic
from ..utils import required_fields
sec... |
class Matrix:
def __init__(self, matrix_string):
self.rows = list(map(lambda x : list(map(lambda y: int(y), x.split(" "))) , matrix_string.split("\n")))
self.columns = list(map(list, zip(*self.rows)))
def row(self, index):
return self.rows[index - 1]
def column(self, index):
... |
from pycocotools.coco import COCO
import cv2
import os, sys
import glob
import string
def show_anns(annFile, imageFile, resultFile):
"""
函数功能:读取图片数量,并对每一张图片进行标注并讲结果保存到resultFile文件夹中。
:param annFile:使用的标注文件
:param imageFile:要读取的image所在文件夹
:param resultFile:画了标注之后的image存储文件夹
:return:
"""
... |
from flask import Flask, request, render_template, jsonify
import pickle
import numpy as np
import re
classifier = pickle.load(open('classifier.pickle','rb'))
count_vectorizer = pickle.load(open('count_vectorizer.pickle','rb'))
app = Flask(__name__)
@app.route('/')
def home():
return render_template('index.htm... |
def register(request):
pass
def login(request):
pass
|
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
def area2(self, owner):
return owner.get_width() * owner.get_height()
class Window:
def __init__(self, width, height):
s... |
marks = int(input("Enter the marks: "))
|
import streamlit as st
from PIL import Image
import io
import os
import numpy as np
import requests
TESSERACT_API_IP = os.getenv("TESSERACT_API_IP", "localhost")
TESSERACT_API_PORT = os.getenv("TESSERACT_API_PORT", 5000)
API_URL = f"http://{TESSERACT_API_IP}:{TESSERACT_API_PORT}/process"
DEMO_IMAGE = "text1.jpg"
de... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django.contrib.auth.decorators import login_required
from django.shortcuts import redirect, render
@login_required
def summary_trips(request, template_name='dashboard/summary.html'):
data = {
'green_trips': [],
'y... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 20 12:12:06 2019
@author: ben
"""
import numpy as np
steps = 1
t = np.zeros(steps)
i = 0
r = 1
g = 0.99
def q0(t, r):
gg = 1
l = len(t)
for j in range(len(t)):
t[l - j - 1] += (gg * r)
gg *= g
def q(t, r, s):
gg = ... |
#####################################################################################
# Creator : Gaurav Roy
# Date : 18 May 2019
# Description : The code performs APRIORI Association Rule Learning algorithm on
# the Market_Basket_Optimisation.csv.
########################################... |
# =========================================================================================================
# Main calling routine for printing tables with statistics
# =========================================================================================================
import logging
import pdb
import IncludeFil... |
import math
d=list(map(int,input().split(',')))
q=[]
c=50
h=30
for i in d:
b=math.sqrt((2*c*i)/h)
q.append(round(b))
print(*q,sep=',')
|
from .db import db
from .subscription import subscriptions
class Module(db.Model):
__tablename__ = 'modules'
id = db.Column(db.Integer, primary_key = True)
name = db.Column(db.String(40), nullable = False, unique = True)
users = db.relationship(
"User",
secondary=subscriptions,
back_populates="... |
'''
Design an algorithm and write code to remove the duplicate characters
in a string without using any additional buffer. NOTE: One or two additional
variables are fine. An extra copy of the array is not.
FOLLOW UP
Write the test cases for this method.
Created on Mar 16, 2016
@author: chunq
'''
def re... |
#encoding:utf-8
def describe_pet(pet_name, animal_type='dog'):
"""显示宠物的信息"""
print("\nI have a " + animal_type + ".")
print("My " + animal_type + "'s name is " + pet_name.title() + ".")
describe_pet('harry', 'hamster')
describe_pet(animal_type='harry', pet_name='hamster')
describe_pet(pet_name='harry', animal_type=... |
import numpy as np
import tensorflow as tf
from cvae import CVAE
from sklearn.datasets import make_classification, make_moons
import matplotlib.pyplot as plt
EPOCH = 50000
BATCH = 20
#X_tr, Y_tr = make_classification(n_samples=60000, n_features=100)
#Y_tr = Y_tr.reshape(-1,1)
#y = y.reshape(-1,1)
(X_tr, Y_tr), (X_t... |
n = input("Enter n: ")
n = int(n)
count = 1
divisors = []
while count <= n - 1:
if n % count == 0:
divisors += [count]
count += 1
print("Divisors of {} are {}".format(n, divisors)) |
# a=10
# b=23
# if a>=b:
# print(a)
# else:
# print(b)
age = int(input("please enter your age: "))
if age < 21:
print("you can not somke.")
elif age == 21:
print("you are 21, you can smoke")
else:
print("you can smoke")
|
# coding: utf-8
import sys
import os
from argparse import ArgumentParser
sys.path.append( os.path.abspath( os.path.join(os.path.dirname(__file__), '..') ) ) # импорт внешнего пространства имен
from expr_eval.core.eval_machine import build_external_func
from expr_eval.core.common_functions import CliUtils, SystemUtil... |
import xml.etree.ElementTree as Et
import csv
# Papers owned by Reviewers
paper_reviewer = {}
# Papers owned by ACs
paper_metareviewer = {}
# reviewer to paper
reviewer_paper = {}
# This function parses the paper to reviewer and AC extracted from CMT
def parse_files():
# Assignment Paper to Reviewer
# Links ... |
# -*- coding: utf-8 -*-
class SST():
pass
class Conll():
pass |
m=1
n = int(input("请输入数值n求n的阶乘:"))
for x in range(1,n+1):
m=m*x
print("n!=",m)
|
#from '/Users/vsubr2/spark-1.6.1-bin-hadoop2.6/bin/pyspark'
import collections
from pyspark import SparkConf, SparkContext
conf = SparkConf().setMaster("local").setAppName("PopularMoviesv")
sc = SparkContext(conf=conf)
lines = sc.textFile("file:///Users/vsubr2/Projects/KaneSpark/ml-100k/u.data")
movies = lines.map(lam... |
import sys, time
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch import distributions as dist
import numpy as np
sys.path.append('.')
sys.path.append('..')
from .tpointnet2 import TPointNet2
from .latent_ode_model import LatentODE
from .flow import get_point_cnf, count_nfe, PointCNFArg... |
import cv2
import numpy as np
class detection:
#detect first frame and his feautures
def __init__(self,im1):
self.im1=im1
self.detector=cv2.FastFeatureDetector_create(
threshold=10,nonmaxSuppression=True,type=2
)
self.computer = cv2.xfeatures2... |
N = int (input ())
n = str (N)
if len (n) == 2:
if int (n [0]) < int (n [1]): print (0)
elif min (int (n [0]), int (n [1])) == 0:
print (1, end = '')
print (max (int (n [0]), int (n [1])) - 1, end = '')
print ('00')
else:
print (1, end = '')
print (min (int (n [0]), i... |
import csv,datetime
from twilio.rest import Client
# Twilio Account SID and Auth Token
client = Client("TwilioAccountSID", "TwilioAuthToken")
from_num = "+12345678888"
csv_file = "//pathToCSVFile/smsdata.csv"
current_datetime = datetime.datetime.now()
session = ''
if (current_datetime.strftime('%p'))=='AM':
sessi... |
from django.shortcuts import render
# Create your views here.
from rest_framework.views import APIView
from carts.serializers import CartSerializer,CartSKUSerializer
from django_redis import get_redis_connection
from rest_framework.response import Response
import base64
import pickle
from goods.models import SKU
f... |
DIM = 8
# Helper boards
"""
-0 -1 -2 -3 -4 -5 -6 -7
0 br bn bb bq bk bb bn br 0
1 bp bp bp bp bp bp bp bp 1
2 -- -- -- -- -- -- -- -- 2
3 -- -- -- -- -- -- -- -- 3
4 -- -- -- -- -- -- -- -- 4
5 -- -- -- -- -- -- -- -- 5
6 wp wp wp wp wp wp wp wp 6
7 wr wn wb wq wk wb wn wr 7
-0 -1 -2 -3 -4 -5 -6 -7
-0 -1 ... |
from typing import *
import requests
from bs4 import BeautifulSoup
from parser.schedulecourse import ScheduleCourse
from parser.coursecode import CourseCode
class ScheduleParser:
def __init__(self):
self.SCHEDULE_SOURCE_CUR = "http://schedules.calpoly.edu/depts_52-CENG_curr.htm"
self.SCHEDULE_SOUR... |
#!/usr/bin/python
# (c) lovemonkey257, 2005-2015
from __future__ import print_function
import GeoIP
import re
import sys
import argparse
import urllib
import json
import os.path
parser = argparse.ArgumentParser(description='Geolocate IP addresses. Uses Maxmind datasets')
parser.add_argument('--geoipdb', help='Base di... |
#---------------------------------------------------------------------
# Author: https://github.com/MartijnBraam/gpsd-py3/blob/master/DOCS.md
# Date: 23/09/19
# Modified: Tanner L
# Desc: Print GPS available gps values
#---------------------------------------------------------------------
import gpsd
# Connect to the... |
#!/usr/bin/env python3
import numpy as np
import cv2 as cv
import glob
import simplejson as json
from control import *
from arm import *
import os
width = 9
height = 17
def calib_do():
image_path = '/storage/emulated/0/DCIM/Camera/'
image_file = 'board_%d_%d.jpg'%(width, height)
os.system('./gen_pattern.... |
# Import modules to read/write csv's
import os
import csv
# Get file path to read
pybank = os.path.join('Resources', 'budget_data1.csv')
#Initialize csv reader
with open(pybank, newline='') as csvfile:
csvreader = csv.reader(csvfile, delimiter=',')
# get past header
csvHeader = next(csvreader)
#Var... |
# -*- coding: utf-8 -*-
import logging
import mysqlbinlog2blinker
import mysqlbinlog2blinker.signals
__author__ = 'tarzan'
_logger = logging.getLogger(__name__)
def start_publishing():
from mysqlbinlog2gpubsub import config
from mysqlbinlog2gpubsub import publishers
publishers.init_publishers()
my... |
SOURCE_URL = 'http://therecord.co/feed.json'
|
# Generated by Django 3.0.8 on 2020-10-12 11:12
import LandingPage.models
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
... |
from pyspark import SparkContext, SparkConf
from pyspark.sql import SQLContext
conf = SparkConf()
sc = SparkContext(conf=conf)
sqlContext = SQLContext(sc)
products_df = sqlContext.read.format('com.databricks.spark.csv').options(header='true', inferschema='true').load('/user/cloudera/instacart/products/products.csv')
... |
#!/usr/bin/env python
"""
This is pytmx module for loading tmx files and making them maps.
"""
import pygame
|
from Speed import test
from time import sleep
sp = test()
sp.setActive(0)
sp.writeActive()
sleep(1)
try:
while True:
user_in = input("Enter Axis: ")
sp.setActive(user_in)
sp.writeActive()
print("Written!")
except:
print("End of Test")
|
from django.shortcuts import render
from django.http import HttpResponse, Http404
from django.core.management import call_command
from django.core import serializers
from .models import Post, PostSerializer
from rest_framework.renderers import JSONRenderer
from django.core.urlresolvers import reverse
# Create your vie... |
import pytest
import logging
import numpy as np
import pandas as pd
from pandas.testing import assert_frame_equal
import pexels_scraper
# def pytest_configure():
# logger = logging.getLogger()
@pytest.fixture
def driver():
driver = pexels_scraper.create_driver()
yield driver
driver.quit()
@pytest.fi... |
class Vertex:
def __init__(self, node):
self.id = node
self.adjacent = {}
self.visited = False
self.contorno = []
def __call__(self,node):
self.__init__(self,node)
def add_neighbor(self, neighbor, weight=0):
self.adjacent[neighbor] = weight
def get_co... |
try:
from PySide.QtWidgets import *
except:
from PyQt5.QtWidgets import *
## CRAP TO BE DELETED
from moc.ui_dummy import Ui_Dummy
class Dummy(QWidget, Ui_Dummy):
def __init__(self, parent=None):
super(Dummy, self).__init__(parent)
self.setupUi(self)
######################
import sy... |
from django.contrib import admin
from .models import *
from django.contrib.auth.admin import UserAdmin
# Register your models here.
class CustomUserAdmin(UserAdmin):
fieldsets = (
*UserAdmin.fieldsets, # original form fieldsets, expanded
( # new fieldset added on to the bottom
# group... |
#! /home/jody/software/anaconda2/bin/python
from __future__ import division
import sys
from tqdm import tqdm
from collections import defaultdict
import re
import numpy as np
indel_re = re.compile("[ACGTNacgtn]([\+-])([0-9]+)([ACGTNacgtn]+)")
if len(sys.argv)!=3:
print "script.py <mat> <prefix>"
quit()
def file_len... |
num = int(input('Digite um número inteiro: '))
# dob = (num * 2)
# tri = (num * 3)
# raiz = (num ** (1 / 2))
# print('O dobro de {0} vale {1}.'.format(num, dob))
# print('O triplo de {0} vale {1}.'.format(num, tri))
# print('A raiz quadrada de {0} vale {1:.2f}.'.format(num, raiz))
print('O dobro de {0} vale {1}.'.forma... |
import cv2
import numpy as np
from matplotlib import pylab as plt
img = cv2.imread('road.jpg')
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
#Step 1: masking the image by defining the region of interest (ROI)
print(img.shape)
height, width = img.shape[:2]
roi_vertices = [
(0, height),
(0, 1100),
... |
import logging
import time
_LOG = logging.getLogger("metoffice_ec2")
class Timer:
def __init__(self):
self.t = time.time()
def tick(self, label=""):
now = time.time()
time_since_last_tick = now - self.t
self.t = now
_LOG.info("{} took {:.2f} secs.".format(label, time_... |
with open("/data/test.txt", "w") as f:
for i in range(100):
f.write("Hello, world!!!!\n")
|
from instagram_private_api import Client, ClientCompatPatch
import pandas as pd
df = pd.DataFrame(columns = ['post_code', 'post_time', 'post_likes', 'post_comments', 'post_link'])
user_name = 'resolution_movement_follower'
password = 'resmvt'
api = Client(user_name, password)
results = api.feed_timeline()
items = [... |
'''
author: juzicode
address: www.juzicode.com
公众号: juzicode/桔子code
date: 2020.5.27
'''
print('\n')
print('-----欢迎来到www.juzicode.com')
print('-----公众号: juzicode/桔子code\n')
print('a=',a)
print('end---') |
from setuptools import setup, find_packages
import sys
requirements = ['future', 'six']
if not (sys.version_info.major == 3 and sys.version_info.minor >= 4):
requirements.append('enum34')
setup(
name='ScalaFunctional',
description="Scala functional programming style in Python",
url="https://github.co... |
import unittest
import contracts
from VM_Message import VM_Message
class MessageTestCase(unittest.TestCase):
def test_set_payload(self):
msg = VM_Message()
msg.set_payload({"test": "first"})
target = dict(test="first")
self.assertEqual(msg.payload, target)
def test_set_payloa... |
def my_abs(x):
if x>=0:
return x
else:
return -x
print(my_abs(-9))
def nop():
pass
age=19
if age>=18:
pass
def my_abs(x):
if not isinstance(x,(int,float)):
raise TypeError("bad operand type")
if x>=0:
return x
else:
return -x
print(my_abs(-8))
impo... |
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 30 13:11:49 2018
@author: david
"""
# -*- coding: utf-8 -*-
"""
Created on Sat May 5 15:48:21 2018
@author: david
"""
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import networkx as nx
from pgmpy.models import MarkovModel
import ran... |
#! /usr/bin/env python3
# coding=utf-8
try:
from .resume_base import BaseExtract
except:
from resume_base import BaseExtract
import time
import re
from core.base import Base
from config import SITE_SOURCE_MAP
import json
from copy import deepcopy
class HtmlToDict(BaseExtract, Base):
def set_unix_time(se... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.