text stringlengths 38 1.54M |
|---|
from typing import Collection, Dict, Any
import website_analyser.analysing.paths
import website_analyser.shared.webpage
import website_analyser.shared.website
from website_analyser.mixins.logger_mixin import LoggerMixin
Webpage = website_analyser.shared.webpage.Webpage
Website = website_analyser.shared.website.Websit... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
from django.dispatch import receiver
#Create your models here.
from django.db import models
from django.db.models.signals import pre_save
from .utils import setcost
class businesses(models.Model):
gst_id = models.AutoFi... |
#-*- encoding=utf-8 -*-
def calc(x):
return x**2
res = map(calc,[1,4,2,13,5])
res2 = map(lambda x:x**2,[1,3,4,2])
print(res2)
print(res)
map1 =[]
for i in res:
map1.append(i)
for i in res2:
map1.append(i)
print(map1) |
import os
import numpy as np
import dynalysis.classes as clss
from gen_pro import exec_pro
from dynalysis.gen_conf import exec_conf
mother = os.getcwd()
for ID in [1131,3426,2347,3401,274,1290,3435,1791,4086]: #1131,3426,2347,3401,274,1290,3435,1791,4086
Freyja = os.path.join(mother,'scan_'+str(ID))
e1b=0.5; e2b=0.5... |
from .exceptions import (ReturnValueError, DFEmptyError, MissingColumnError, ColumnNullError,
WrongDtypeError, ColumnNotUniqueError, ColumnNotSingleValueError)
from .decorators import (NotEmpty, HasColumn, ColumnHasDtype, ColumnNotNull, ColumnUnique, ColumnSingleValue)
|
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Python Data Structures - Queue\n"
]
},
{
"attachments": {
"queue.jpeg": {
"image/jpeg": "/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBw0NDQ0NDQ0NDQ0NDQ0NDQ0NDw8NDQ0NFREWFhURFRUYHiggGBolHRUVLTEhJSouLi4uFx8zODMvNygtLisBCgoKD... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
from django.db import models
from django.utils.timezone import now
from django.contrib.auth.models import User
# Create your models here.
class Category(models.Model):
name= models.CharField(max_length=100, verbose_name="Nombre")
created = models.DateTimeField(auto_now_add=True, verbose_name="Fecha de Creacio... |
import sys
sys.path.append('..')
from gamemanager import button
def test_init():
button0 = button.Button('image', 'words', (0, 0.5, 0.3, 0.7), 3)
assert button0.image == 'image'
assert button0.words == 'words'
assert button0.x1 == 0
assert button0.x2 == 0.5
assert button0.y1 == 0.3
assert... |
import numpy as np
import torch
class Compose(object):
"""Composes several transforms together.
Args:
transforms (list of ``Transform`` objects): list of transforms
to compose.
Example:
>>> transforms.Compose([
>>> transforms.MriNoise(),
... |
import csv
import json
import random
import numpy as np
import torch
def load_kakao_csv(fname:str):
'''
input : kakao message filename csv
ex) '2020-03-20 00:01:19', 'kakao Eric', '왜 프로필 사진이 안바뀌지'
output : str list
ex) 'kakao Eric 왜 프로필 사진이 안바뀌지'
'''
chats = []
with open(fname, newlin... |
# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
import pymysql as MySQLdb
from Tournaments.items import TournamentsItem
from Tournaments.spiders import database_con as dbc
c... |
##################################
'''
# Written by Shaoli Huang
# Date: 26 April 2018
# Modified by Jing Zhang
# Date: 16 Dec. 2018
# [1]. add quota monitor @Dec. 12
# [2]. add waiting time stats & hpc exec_vnode info @Dec.13
# [3]. update the user_gpu_quota @Dec.13
# [5]. update the hpc node information and ... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Sat May 6 13:46:07 2017
@author: Work
"""
import pandas as pd
df = pd.read_csv("https://raw.githubusercontent.com/ajschumacher/gadsdata/master/user_brand.csv", header=None)
df.columns = ['user','brand']
df.head()
import numpy as np
brands, unique_brand_m... |
from celery import task, shared_task
# from django.core.mail import send_mail
from .models import Order, OrderItem, OrderStatistics
# from mall.models import Product
from login.models import Profile
# from datetime import date
from .wechartAPI.api.src import sendmsg
# 计划任务
# @shared_task
# def stat_orders_today():
# ... |
from odoo import models, fields, api, _
import datetime
class DocumentControl(models.Model):
_name="document.control"
_inherit = ['mail.thread', 'mail.activity.mixin', 'portal.mixin']
_description = 'Document Control'
_rec_name="name"
name = fields.Char(string="Doc control Number", readonly=Tr... |
from python_command import PythonCommand #part of a slack bot command framework I wrote
import boto3
import traceback
class Code(PythonCommand): #command is "code <color>"
def run_command(self,context,command,util):
color=command.split(" ")[1].strip()
try:
keys=util.config.annunciator_... |
# Copyright 2015 Google Inc. 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 law or a... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'AdminandUser.ui'
#
# Created by: PyQt5 UI code generator 5.15.4
#
# 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 impo... |
"""
A test of bert in evaluation
"""
import argparse
import logging
from tqdm import tqdm
import numpy as np
import os
os.environ['CUDA_VISIBLE_DEVICES'] = '1'
import torch
from transformers import glue_output_modes as output_modes
from transformers import glue_processors as processors
from transformers import (
... |
from django.db import models
# Create your models here.
class pretty(models.Model):
objects = models.Manager() #vs code 오류 제거용
id = models.AutoField(primary_key=True)
na = models.CharField(max_length=200)
ag = models.CharField(max_length=200)
pw = models.CharField(max_length=... |
from oslo_log import log
from oslo_utils import timeutils
from oslo_config import cfg
from ceilometer.agent import plugin_base
from ceilometer import sample
from cinderclient.v2.client import Client as cinderclient
cfg.CONF.import_group('service_credentials', 'ceilometer.service')
cfg.CONF.import_opt('http_timeout', ... |
class Square:
def __init__(self, aa):
self.a = aa
def area(self):
return self.a * self.a
def perimeter(self):
return self.a * 4
class Circle:
def __init__(self, rr):
self.r = rr
def area(self):
return self.r * self.r * 3.14159265
def circumference(self):
return self.r * 2 * 3.14159265
|
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def distanceK(self, root: TreeNode, target: TreeNode, K: int) -> List[int]:
ret = []
self.ancestor_dist(root, K, target, ret)
return ret
def... |
'''
based on Aymeric Damien's MNIST tensorflow implementation from the
Project: https://github.com/aymericdamien/TensorFlow-Examples/
'''
import tensorflow as tf
######################
# Network Parameters #
######################
img_size = 64 # data input (img shape: 64*64)
n_input = img_size ** 2 * 3
n_classes... |
import keras.models
from keras.layers import Dense, Dropout, Input, Conv1D, Concatenate, Flatten
from keras.utils.vis_utils import plot_model
import logging
from sklearn.dummy import DummyRegressor, DummyClassifier
from sklearn.linear_model import LogisticRegression, LinearRegression
from sklearn.svm import SVC... |
from math import floor as fl
def func(n,cache):
global b
if(n==0):
return 0
if(cache[n]!=-1):
return cache[n]
else:
cache[n]=n+func(fl(n/2),cache)
return cache[n]
t=int(input())
for I in range(t):
n=int(input())
a=[int(i) for i in input().split()]
cache=[-1]... |
#Implementation of sieve of Eratosthenes borrowed from Problem 010
from math import ceil
from math import sqrt
def primes(n):
#Taking care of trivial cases
if n <= 2:
return []
elif n == 3:
return [2]
numbers = [False, False]
for i in range(2, n + 1):
numbers.append(True)
... |
import cv2, time
class MyVideo():
def capturefaceinVideo(self, video):
face_cascade = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")
a = 1
while True:
a = a + 1
check, frame = video.read()
print(check)
face = face_cascade.dete... |
class Solution:
def findNumbers(self, nums: List[int]) -> int:
#==========11111111111111111===============
# times=0
# for i in range (len(nums)):
# if len(str(nums[i]))%2 == 0:
# times+=1
# return times
#==========22222222222222222=============== ... |
from django.views.generic import ListView, DetailView
from .models import Profile
class ProfileHomeView(ListView):
model = Profile
class ProfileView(DetailView):
model = Profile
slug_field = 'user__username'
|
def try_char(cipher, char):
letter_freqs = {
"a" : 8.167,
"b" : 1.492,
"c" : 2.782,
"d" : 4.253,
"e" : 12.702,
"f" : 2.228,
"g" : 2.015,
... |
def cb():
print('Hello!')
print('Hi cb+, How are you today?')
def add_sub(x, y):
r1 = x + y
r2 = x * y
return r1, r2
cb()
result1, result2 = add_sub(5, 3) # imp note : if function returns two values then variable must receive two values
print(result1, result2)
|
import moderngl
import numpy as np
class Surface:
def __init__(self, vts, ids, ns, cs=(0, 0, 1)):
self.vts, self.ids, self.ns, self.cs = vts, ids, ns, cs
self.box = np.vstack((vts.min(axis=0), vts.max(axis=0)))
self.mode, self.blend, self.visible = 'mesh', 1.0, True
self.color = cs... |
from sys import argv
script, one, two = argv
print raw_input("The script is called: "), script
print raw_input("The first one is called: "), one
print raw_input("The second one is called: "), two |
from django.contrib import admin
# Register your models here.
from upazillas.models import Upazilla
admin.site.register(Upazilla)
|
import numpy as np
import math
import os
from PIL import Image
import random
def Rest_Img(im):
return np.uint8(127.5 * (im + 1))
class Real_DB():
def __init__(self,db_type,batch_size,db_pt='',img_size=64,db_size=64,seed=0,crop_length=108):
self.DB_Type=db_type
self.Batch_size=batch... |
#!/usr/bin/python
## For OS X, sets up link to this library, and also HDF5 XOP.
## Verbose
## UNTESTED
import os
import subprocess
IGORLIB = os.path.join(os.environ['HOME'],'git/projects/igorlib')
USERFILES = os.path.join(os.environ['HOME'],'Documents/WaveMetrics/Igor Pro 6 User Files')
IGORFOLDER = '/Applications/I... |
in=int(input())
if in>1:
for i in range(2,in):
if in%i==0:
print("no")
break
else:
print("yes")
else:
print("no")
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Thanks to JD Porter / Literary Lab in 2019 for help with writing this script!
import os, io, csv, string, scipy.stats
#variables for this usage
my_main_directory = f"{os.getcwd()}/corpus/"
my_metadata_table = f"{os.getcwd()}/Austen_Metadata.csv"
ofn = my_main_directory +... |
#!/usr/bin/python
# -*- coding:utf-8 -*-
import json
import requests
import time
class LinkHUB:
def __init__(self, _ip):
self.ip = _ip
self.URL = 'http://{}/jrd/webapi'.format(_ip)
self.session = requests.Session()
self.token = None
def Headers(self):
headers = {}
... |
import math
from typing import List
class Solution:
# # 动态规划?
# def maxDotProduct(self, nums1: List[int], nums2: List[int]) -> int:
dp = [[-0xfffffff for i in range(501)] for j in range(501)]
def maxDotProduct(self, nums1: List[int], nums2: List[int]) -> int:
len1 = len(nums1)
len2 =... |
import os
import logging
from flask import Flask, request, jsonify
from flask_pymongo import PyMongo, pymongo, MongoClient
from bson.objectid import ObjectId
from pprint import pprint
app = Flask(__name__)
app.config["MONGO_DBNAME"] = 'milestone_3'
app.config["MONGO_URI"] = 'mongodb+srv://Neil:BrooklynWooD@myfirstclu... |
import os, datetime, timeit, shutil, time, sys
clear = lambda: os.system('cls')
#times = '8:50'
#before_time = time.mktime(datetime.datetime.strptime(date+'/'+times, "%d/%m/%Y/%H:%M").timetuple())
def printWelcome():
welcomeMessage = '''
/$$ /$$ /$$$$$$$... |
class PortfolioManager:
def __init__(self):
self.syms = set(['ETH','BTC','USD','BNB'])
self.positions = {}
self.locked = {}
def getPosition(self, sym):
return self.positions.get(sym, 0.0)
def processPositionUpdate(self, msg):
for pu in msg['B']:
self.po... |
# this program is created to extract from "pdf_2.pdf"
import re
#import csv
#import BeautifulSoup
from lxml import html
from lxml import etree
#import requests
import pdfquery
#------------------------------------------------------------------------------#
#---------------------------------------------------... |
import json
import numpy as np
def hello(event, context):
body = {
"message": "Go Serverless v1.0! Your function executed successfully!",
"input": event
}
response = {
"statusCode": 200,
"body": json.dumps(body)
}
return response
def goodbye(event, context):
... |
#
# *
# **
# ***
# ****
# *****
# def right_triangle(Rows):
# for i in range(Rows):
# j=0
# for j in range(i+1):
# print("*",end="")
# print("")
# right_triangle(10)
# Amstrong num
# count=3
# 153 = 1^3+5^3+3^3=153
# def is_Amstrong(Number):
# temp = Number
# count =... |
#
# this program is designed to be run from console after ZooKeeper &
# Kafka are already launched
#
from kafka import KafkaProducer
import time
import json
import requests
bootstrap_servers = ['localhost:9092']
topicName = 'kafkaRapidAPISpark' #'First_Topic' ... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('api', '0002_auto_20141016_1743'),
]
operations = [
migrations.AddField(
model_name='server',
name='a... |
#!/usr/bin/env python
#
# Copyright 2012 Dominic Rout
#
# 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 ... |
from operator import add
path1 = input().split(",")
path2 = input().split(",")
def addlists(l1, l2):
return list(map(add, l1, l2))
def build_structure(path):
ret = []
ret.append([[0,0], None, 0])
i = 1
for inst in path:
dxn = inst[0]
hop = int(inst[1:])
dst = None
... |
def get(e, key, default):
"""
return e.get(key, default)
if bibtex version of key not found, use biblatex version
"""
BIBLATEX = {'year': 'date',
'journal': 'journaltitle',
'address': 'location'}
if key not in BIBLATEX:
return e.get(key, default)
else:... |
from plasTeX.PackageResource import (PackageResource, PackageCss, PackageJs, PackageTemplateDir)
from plasTeX import Command, Environment, sourceArguments
from plasTeX.Base.LaTeX import Math, Lists, Floats
def ProcessOptions(options, document):
tpl = PackageTemplateDir(renderers='html5',package='caption')
docu... |
#pragma out
#pragma repy
def foo():
print 'OK!'
if callfunc=='initialize':
settimer(0.1, foo, ())
|
from refextract import extract_references_from_file
import os
def extract_title(misc):
return misc.split('.')[0]
def read_files_from_path(directory_path):
refrence_dic = {}
for file_name in os.listdir(directory_path):
if file_name.endswith('.pdf'):
references = extract_references_from_... |
# Import Needed Packages
import numpy as np
import cv2
# Load Image
image = cv2.imread("../images/basketball.jpg")
# Split Channels
# b = image[:,:,0]
# g = image[:,:,1]
# r = image[:,:,2]
b, g, r = cv2.split(image)
# Merge Channels
merged = cv2.merge((b,g,r))
# Can Fill Channel Without Splitting
# merged[:,:,2] =... |
# -*- coding: utf-8 -*-
"""
sheetsync
~~~~~~~~~
A library to synchronize data with a google spreadsheet, with support for:
- Creating new spreadsheets. Including by copying template sheets.
- Call-back functions when rows are added/updated/deleted.
- Protected columns.
... |
import pyodbc
__author__ = 'ifayner'
def connect_to_database(str_sql, hostname, wfg_database):
# *** function to connect to SQL Server database, return rows and close connection ***
conn = pyodbc.connect("DRIVER={SQL Server};SERVER=" + hostname + ";DATABASE=" + wfg_database + ";Trusted_Connection=True")
... |
name = "aaa"
if name is "Bucky":
print("Hi Nukey !!")
elif name is "Lucy":
print("what up lucy boo!!")
elif name is "ahmed":
print("hi ahmed :: ")
else:
print("you fuck with me mother fucker !!") |
# 402. Remove K Digits
# https://leetcode.com/problems/remove-k-digits/description/
class Solution:
# 以下根據討論 https://leetcode.com/problems/remove-k-digits/discuss/88678/Two-algorithms-with-detailed-explaination
# 解決這個問題的時候(或是 Greedy 的問題)
# 可以先想想如果 k=1 要怎麼做, 最簡單的方法就是掃過整個數列
# 找出 "峰值"- 也就是比右邊元素還高的值
# ... |
#Bounty05-Tkinter Button Maker
from tkinter import *
import webbrowser
root = Tk()
frame = Frame(root, width=400, height=200)
theLabel = Label(root, text='main frame window')
theLabel.pack()
frame.pack()
topFrame = Frame(root)
topFrame.pack()
bottomFrame = Frame(root)
bottomFrame.pack(side=BOTTOM)
#def printit():
# ... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2016 Binux <roy@binux.me>
import config
from db.task import TaskDB as _TaskDB
from sqlite3_db.basedb import BaseDB
import db.task
class TaskDB(_TaskDB, BaseDB):
def __init__(self, path=config.sqlite3.path):
self.path = path
... |
import boto3
import io
ec2_client = boto3.client("ec2")
key_pair = ec2_client.create_key_pair(KeyName="string_")
key_data = key_pair["KeyMaterial"]
with io.open("tutu.pem", 'w' , encoding='utf-8') as f1:
f1.write(str(key_data))
f1.close
|
"""
RPSFpy - PSF reconstruction for GLAO
This is a set of tools to reconstruct PSFs of GLAO systems, taking
into account the anisoplanetism effect.
Method
------
The PSF estimation method is the one described in [1]. The basic idea is to approximate the
residual phase in WFM considering the most dominant source of v... |
#!/usr/bin/python -u
"""Time-warps a speech parameter sequence based on a reference."""
# Copyright 2014, 2015, 2016, 2017 Matt Shannon
# This file is part of mcd.
# See `License` for details of license and warranty.
import os
import sys
import argparse
import math
import numpy as np
from htk_io.base import DirRea... |
#!/usr/bin/python
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(24, GPIO.IN, pull_up_down=GPIO.PUD_UP)
pressed = False
def btn_callback(channel):
global pressed
if pressed is False:
# hier kommt der SQL INSERT hin
print('Button pressed ... |
import os,sys
import DataStorage.Database as db
from datetime import datetime
'''
This module is to mimic very roughly some database functionality for the project.
'''
def insert_heartbeat(path, heartbeat):
db.writeToFile(path, "w+", heartbeat)
def insert_steps(path, steps):
db.writeToFile(path, "w+", step... |
t=int(input("t"))
for i in range(t):
n=int(input("n"))#no of element
k=int(input("k"))#rotation steps
a=[]
for j in range(n):
get=int(input("get"))
a.append(get)
x=(a[:-k])#123
y=(a[-k:])#45
print(*(y+x))
|
import unit_demand_experiments_config as config
import itertools as it
from unit_demand import elicitation_with_pruning, epsilon_to_num_samples
import math
import time
import pandas as pd
def save_results(results_data):
print('\n Saving results...')
results_dataframe = pd.DataFrame(results_data, columns=['num... |
from sklearn import datasets
import numpy as np
from sklearn.datasets import fetch_mldata
class DataLoader:
def __init__(self, list_of_data_tuples):
self.list_of_data_tuples = list_of_data_tuples
self.idx = -10
def generator(self):
while True:
self.increase_idx()
... |
from tkinter import *
root = Tk()
def print_something(event):
print(event)
print("something")
button = Button(root, text="Call Func")
button.bind("<Button-1>", print_something)
button.pack()
root.mainloop()
|
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import torch
import itertools
import random
import json
import pandas as pd
def repeat_explode(input, input_length, n_t... |
from django import forms
from django.forms.models import inlineformset_factory
from .models import Request
from inquiry.models import *
class RequestForm(forms.ModelForm):
class Meta:
model = Request
exclude = ("listing","owner",)
#event = forms.ModelChoiceField(queryset=Inquiry.objects.filter(owner=kwargs.po... |
import os
from selenium import webdriver
import urllib2
import csv
from bs4 import BeautifulSoup
import time
directories = ['https://yomanga.co/reader/directory/',
'https://yomanga.co/reader/directory/2/'
'https://yomanga.co/reader/directory/3/']
opener = urllib2.build_opener()
opener.addheaders = [('User-Agent', '... |
def snake11_to_camel(word):
import re
return ''.join(x.capitalize() or '_' for x in word.split('_'))
print(snake11_to_camel('aab _xxy'))
|
import random
import numpy
class Sorter:
def __init__(self, lst):
self.lst = lst
self.counter = 0
def getPivot(self, start, end):
retval = numpy.median([self.lst[start], self.lst[(start+end)/2], self.lst[end]])
return retval
def swap(self, in_a, in_b):
tmp = self.... |
import os
from sequence_sample_set_class import sequence_sample_set
from subprocess import Popen, PIPE
import subprocess
import random
from sequence_sample_class import sequence_sample
import re
import tempfile
import numpy
import itertools
class sequence_time_series(sequence_sample_set):
"""
This class inheri... |
"""
classe CSV(csv):
- Cargar los datos
- Output(csv=False, pickle=False, parquet=False)
- Media de una columna
- __sum__ () --> df = datos1 + datos2
CSV1 = CSV("datos1.csv")
CSV2 = CSV("datos2.csv")
suma = CSV1 + CSV2
print(suma) --> datos csv1 y los datos csv2
"""
impor... |
import cv2
import mediapipe as mp
import time
mpDraw = mp.solutions.drawing_utils
mpPose = mp.solutions.pose
pose = mpPose.Pose()
cap = cv2.VideoCapture('PoseVideos/1.webm')
curTime = 0
prevTime = 0
while True:
success, img = cap.read()
#image is read in BGR format but mediapipe require RGB format
imgRG... |
from numpy import genfromtxt
import re
VOW = list('aȃáiîíuúoóôeéêę')
CONS = list('bcdðfghjklmnprstvwxz')
# кодировка - что-то не так, диакритические знаки не парсятся
my_data = open('/Users/a123/PycharmProjects/Kolbaster/prefix.csv', 'r', encoding='utf-8')
my_data = my_data.read()
prefix = re.sub("^\s+|\n|\r|\s+", ... |
# generates coordinates for molecules
# If number of molecules = 2, center of mass of first molecule aligned at 0,0,0
# Requires prototype MoleculesDescriptor.
from project1 import spherical
import random
from project1 import IOfunctions
from project1 import structure
import copy
import os
import shutil
imp... |
#第12章 函数式编程: 匿名函数、高阶函数、装饰器
#python map函数
# for x in list_x:
# square(x)
list_x = [1,2,3,4,5,6,7,8]
def square(x):
return x * x
f = map(square, list_x)
#函数式编程map,reduce,filter,lambda. 其本质还是 命令式编程;只是一个语法糖提供给你用
#匿名函数写法
f = map(lambda x: x*x, list_x)
print(list(f))
list_y = [1,2,3,4,5,6,7,8]
f2 = map(lambda x, y:... |
# coding=utf8
from django.views.generic import ListView, DetailView
from django.db.models import Q
from django.http import JsonResponse, HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.shortcuts import render
from pure_pagination.mixins import PaginationMixin
from django.contrib... |
# Generated by Django 3.0.5 on 2020-08-11 13:50
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('shop', '0013_auto_20200811_1647'),
]
operations = [
migrations.AlterField(
model_name='product',
... |
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('info/<int:id>/', views.getAccountInfo, name='getAccountInfo'),
path('add/', views.addAccount, name='addAccount'),
path('save/', views.saveAccount, name='saveAccount'),
path('remove/<int:id>/'... |
'''
Authors : Chinmay, Salil, Swarali
Live Capture
Algorithm 1
'''
import pyshark as py
import csv
interfacen ="any"
op = "live.pcap"
packet = {}
'''
Packet contains the counter for src->dst IP
packet = {
src1 : {
dst1 : counter
dst2 : counter
},
src2 : {
dst1 : counter
dst2 : counter
}
}
packet[s][d] gi... |
import sys
import redis
def parse_file(file_name, rds):
total_processado = 0
pipe = rds.pipeline()
print("Contador será atualizado de 200 em 200 registros processados.")
print("\rProcessado:", total_processado, end = "")
#iniciando o parse do arquivo
with open(file_name, 'rb') as f:
... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import datetime
import re
import string
import time
import os
try:
from urlparse import parse_qs
except ImportError:
from urllib.parse import parse_qs
import pytest
import pytz
from betamax import Betamax, BaseMatcher
from reques... |
# Testing the fixed voltage method.
# steps:
# 1. load linear model
# 2. split into upstream/downstream of regulator(s)
# 3. find LTC matrices
# 4. reorder & remove elements as appropriate
# 5. run continuation analysis.
# A bunch of notes on the main method in WB 7-01-19 and 15-01-19
import time, win32com.client, ... |
# coding: utf-8
import seaborn as sb
import pandas as pd
import numpy as np
import math
df=pd.read_csv('Restaurant.csv')
df.replace({ 'sex': {'Male':0 , 'Female':1} ,
'smoker' : {'No': 0 , 'Yes': 1},
'time' : {'Lunch': 0 , 'Dinner': 1},
'day': {'Sun':7 , 'Sat':6, 'Fri':5, 'Thur':... |
'''
Car detection and tracking program. It uses HAAR Cascades and KCF tracking alg.
'''
import cv2
import numpy as np
from time import time
import kcftracker
import thread
def isNewRoi(rx,ry,rw,rh,rectangles):
for r in rectangles:
if abs(r[0] - rx) < 2.5*rw and abs(r[1] - ry) < 2.5*rh:
retur... |
# -*- coding: utf-8 -*-
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
from apps import commonmodules
from app import app
meta_tags = [
{'name':'description',
'content':'Дивидендный калькулятор с учетом сложного процента'},
{'name':'titl... |
##############################################################################
#
# Module: setup.py
#
# Description:
# setup to install the rwclib package
#
# Copyright notice:
# This file copyright (c) 2021 by
#
# MCCI Corporation
# 3520 Krums Corners Road
# Ithaca, NY 14850
#
# S... |
import pandas as pd
import os
from collections import OrderedDict
from sklearn import preprocessing
from graphs import attach_graph_attributes, attach_real_attributes
def set_prefix_attributes(prefix, node):
attributes_dict = {
prefix + key: value
for key, value in node.items()
}
return ... |
import random
def diceRoll(num,dice):
res = 0
for i in range(num):
res+=random.randint(1,dice)
return res
class Race:
def __init__(self):
pass
def getGender():
pass
def getAge():
pass
def getName(gender):
pass
def getHeight():
pass
... |
from selenium import webdriver
from selenium.common.exceptions import *
from selenium.webdriver.support.wait import WebDriverWait
from PageObjects import home_page
from Selenium_helper import selenium_helper
"""This class gets and executes tests from the different pages in the page-object-model"""
class selenium_test(... |
import csv
# 開啟 csv 檔案
with open('test1.csv', newline='') as csvfile:
# 讀取 csv 檔案內容
rows = csv.reader(csvfile)
# 以迴圈顯示每一列
for row in rows:
print(row) |
import datetime
import time
import sys
import os
from url_checker.validator import check_if_url
class Generate_table(object):
def __init__(self, table_dict):
self.table_title = table_dict["table_title"]
self.generate_sn = table_dict["generate_sn"]
self.generate_summary = table_dict["genera... |
"""
Verifies that kext bundles are built correctly.
"""
import TestGyp
test = TestGyp.TestGyp(formats=['xcode'], platforms=['darwin'])
test.run_gyp('kext.gyp', chdir='kext')
test.build('kext.gyp', test.ALL, chdir='kext')
test.built_file_must_exist('GypKext.kext/Contents/MacOS/GypKext', chdir='kext')
test.built_file_m... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.