text stringlengths 8 6.05M |
|---|
from django.shortcuts import render, get_object_or_404
from rest_framework import generics
from rest_framework.permissions import IsAuthenticatedOrReadOnly
from .models import Note, Episode
from .serializers import NoteSerializer, EpisodeSerializer
# Create your views here.
class NoteListCreateApiView(generics.ListCr... |
import pandas as pd
Data={}
Data_IndexCol={"employees":['emp_no']}
Data_Names={"employees":['emp_no','birth_date','first_name','last_name','gender','hire_date','ids']}
employees=pd.read_csv("./files/employees.csv",
names=Data_Names['employees'],
index_col=Data_IndexCol['employees'], header=None,d... |
__author__ = "Narwhale"
import socket
server = socket.socket()
server.bind(('localhost',6565))
server.listen() #监听
conn,addr = server.accept() #等待
data = conn.recv(1024)
print('recv:',data)
conn.send(data.upper())
server.close()
|
"""Tools specific to template rendering."""
def domain_renderer(domain):
"""Template helper to add IDNA values beside Unicode domains."""
idna_domain = domain.encode('idna')
if idna_domain == domain:
return domain
return domain + ' ({})'.format(idna_domain)
|
ano_nasc = int(input('ano de nascimento: '))
geracao = str('Qual a sua geraçao?: ' )
# BBoomer = nascido até 1964
# Geracao X = 1964 até 1981
#Geracao y = 1981 até 1996
# Geraçao z = depois de 1996
# Calculo
if (ano_nasc <= 1964):
print('Vocé é da geracao BBoomer')
elif (ano_nasc > 1964 and ano_nasc < 1981):
... |
"""Plot uniform time-series of one variable."""
# author: Christian Brodbeck
from __future__ import division
from itertools import izip
import operator
from warnings import warn
import matplotlib as mpl
import numpy as np
from .._data_obj import ascategorial, asndvar, assub, cellname, Celltable
from .._stats import ... |
import json, sys, codecs, copy
# 2017-07-24
# A script that takes a json file and outputs a modified json file
# (changes the structure and replaces null values with proper strings)
# sys.argv[0] -- name of the python script
# sys.argv[1] -- arg1
# sys.argv[2] -- arg2
inputFile = sys.argv[1]
outputFile = ... |
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import NullFormatter
import warnings
warnings.simplefilter('ignore', np.RankWarning)
def vis_accuracy(X, Y, title1='', title2='', xlab='', ylab=''):
'''
Arg
X = a list of tuple where a tuple = (X_values, accuracy)
Y = a list ... |
"""
Vault as in fuzzy vault
:var self.vault_original_minutiae: list of representation of minutiae without chaff points
:var self.vault_chaff_points: list of representation of chaff points
"""
import random
from Polynomial_Generator import PolynomialGenerator
from Geometric_Hashing_Transformer import GHTra... |
import textdistance
res1 = textdistance.hamming('test', 'text')
print(res1)
|
import pytest
from django.contrib.auth.models import User
@pytest.fixture()
def create_user(db):
user = User.objects.create_user(
username='test',
email='test@email.com'
)
print('Creating User')
return user
@pytest.fixture()
def new_user_factory(db):
# inner function
def crea... |
import asyncio
class AsyncFile:
def __init__(self, filename):
self.filename = filename
async def __aenter__(self):
self.file = await asyncio.to_thread(open, self.filename, encoding="utf8")
return self
async def __aexit__(self, ext, exc, tb):
await asyncio.to_thread(self.fi... |
# Generated by Django 2.0.7 on 2020-08-13 12:09
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('aid', '0004_auto_20200813_1146'),
]
operations = [
migrations.AlterModelOptions(
name='drugdetail',
options={'verbose_name':... |
import datetime, time
import os,sys,shlex
import re
import socket, select, fcntl
import json, testlink
from robot.api import logger
TSP_SGL_COMMAND_INDEX = 0
TSP_SGL_STATUS_INDEX = 1
TSP_STL_COMMAND_INDEX = 2
TSP_STL_STATUS_INDEX = 3
TSP_RCS_COMMAND_INDEX = 4
TSP_RCS_STATUS_INDEX = 5
TSP_VMS_COMMAND_INDEX = 6
TSP_... |
import sys
import numpy as np
def data_split(Data):
all_sentences = []
for i in Data:
all_sentences.append(i.strip().split('\n'))
sentence_words = [j[0].split(' ') for j in all_sentences]
# print(sentence_words)
return sentence_words
def train_data(words_dict, tags_dict, Data):
list_... |
from pydantic import BaseModel
class Album(BaseModel):
title: str
artist_id: int
|
# Hi, with this Code, you can send a WhatsApp Message to your Loved Ones very Easily on Time.
# Points to Remember:
# • You should be connected to the WhatsApp Web from the Number you want to send the Message.
# • You should have an Internet Connection during the Process.
# • It takes 130 Seconds to Open Whatsapp... |
#this program is used load the file and do sorting using buble sort
from data import main
try:
file = open('number', 'r') # opening the file
str_ = file.read() # reading the text and storing it into the object
split_array = str_.split() # splitting the wor... |
"""
Fishing - TO BE TESTED
Fish in a suitable room.
"""
import time
from django.conf import settings
from evennia.utils import utils, evmenu
from evennia import CmdSet
from evennia.utils.create import create_object
from typeclasses.objects import Object
COMMAND_DEFAULT_CLASS = utils.class_from_module(settings.COMM... |
from .models import *
from aristo.models import *
from payment.models import *
import time
from datetime import datetime, timezone,timedelta
now = datetime.now(timezone.utc)
def get_linked_accounts(user):
instagram_accounts=Instagram_Accounts.objects.filter(main_user=user)
instagram_accounts_list=[]
for i... |
# _*_ coding:UTF-8 _*_
#! /usr/bin/env python
import time
from pymouse import PyMouse,PyMouseEvent
from pykeyboard import PyKeyboard
m = PyMouse()
k = PyKeyboard()
poslist = []
def exliststr(plist,x,y):
plist.extend([str(x),str(y)])
class mmouse(PyMouseEvent):
def __init__(self):
PyMouseEvent.__init_... |
#!/usr/bin/env python
import flickrquery
import argparse
import os.path, os
import subprocess
def download_image(data, filename):
if data['originalsecret'] and data['originalsecret'] != 'null':
url_original = 'http://farm%s.staticflickr.com/%s/%s_%s_o.%s' % (data['farm'], data['server'], data['id'], data['origi... |
import pandas as pd
from data_operation import *
# DS-GA 1007 Assignment 10
# Author: Junchao Zheng
def main():
try:
data_raw = pd.read_csv('DOHMH_New_York_City_Restaurant_Inspection_Results.csv', low_memory = False)
data = data_raw.dropna() # Drop the rows where data has NaN values.
d... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pygmsh as pg
import numpy as np
def generate():
geom = pg.Geometry()
X0 = np.array([
[0.0, 0.0, 0.0],
[0.5, 0.3, 0.1],
[-0.5, 0.3, 0.1],
[0.5, -0.3, 0.1]
])
R = np.array([0.1, 0.2, 0.1, 0.14])
holes... |
import pygame
import sys
import random
pygame.init()
# Display
screen_height = 800
screen_width = 600
background_color = (169, 169, 169)
black = (0, 0, 0)
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
white = (255, 255, 255)
# Player
player_color = (81, 156, 213)
player_size = 50
player_pos = [(screen_... |
"""Status Services Classes."""
import logging
from .taskstatuses import TaskStatuses
logging.debug("In the status_services __init__.py file.")
__all__ = ["TaskStatuses"]
|
import urllib
import urllib.request as url
import re
class plugin:
handle = "ddg"
method = "args"
do_init = False;
cron_time = False
join_hook = False
help_str = "Usage: " + handle + " [search]. Search duckduckgo for whatever."
def run( self, pman, server, nick, host, channel, args ):
if channel[0] == "#": ... |
"""
Prints out all the melons in our inventory
"""
from melons import melon_info
# def print_melon():
# for melon, value in melon_info.items():
# print melon
# for attribute, value in attributes.items():
# print "{}: {}".format(attribute, value)
# print
# print_melon()
def p... |
from .base import Badge
class BadgeCache(object):
"""
This is responsible for storing all badges that have been registered, as
well as providing the pulic API for awarding badges.
This class should not be instantiated multiple times, if you do it's your
fault when things break, and you get to pic... |
# I pledge my honor I have abided by the Stevens Honor System
# I understand that I may access the course textbook and course lecture notes
# but I am not to access any other resource.
# I also pledge that I worked alone on this exam.
# Jacob Aylmer
# Quiz 2 Part 2
def main():
math_or_string = float(input("Enter ... |
'''
Created on 15 nov. 2012
@author: David
inspired by Telmo Menezes's work : telmomenezes.com
'''
"""
this class inherits from pyevovle.DBAdapters.DBBaseAdaoter. It computes and stores statistics during genetic algorithm processing.
"""
import pydot
import pyevolve as py
import pyevolve.DBAdapters as db
i... |
__author__ = "Narwhale"
import urllib
#urllib.request 请求
#urllib.error 错误信息
#urllib.response 响应
#urllib.parse 解析
data = bytes(urllib.parse.urencode({'hello':'world'}))
|
import sys
from data import Data
from flights import *
from statistics import *
def main():
# path = argv[1]
# features = argv[2]
default_path = 'Airports.csv' # REMEMBER T0 CHANGE BEFORE HANDING
default_features = ['Origin_airport', 'Destination_airport', 'Flights', 'Distance', 'Seats', 'Passengers'... |
a=[1,3,5,7]
b=[2,4,6,8]
c=[11,12,13]
d=[11,21,31]
# e={[2,3]:2,[4,5]:3} #no,type list no permit
e={2:3,3:4}
f={4:5,5:6}
# g={e:10,f:20} #no ,tpye dict no permit
a=int(input('please input a year '))
if (a%4)==0:
if (a%100)!=0:
print (a ,"is 闰年")
else:
print (a ,"is not 闰年")
else:
print (a ,"is not 闰年")
|
import random
class Dice:
def __init__(self, dice_type):
self.dice_type = self.__validate_dice_type(dice_type)
def __validate_dice_type(self, new_dice_type):
if new_dice_type not in [3, 4, 6, 8, 10, 12, 20, 100]:
raise ValueError("Wrong dice type")
return new_dice_type
... |
class Constants:
cache_base_path = "/Users/joergsimon/Documents/phd/HELENA/ssl-ecg/cache/"
data_base_path = "/Volumes/knownew/600 Datasets/human-telemetry/other_datasets_joerg/"
# data_base_path = "/Users/joergsimon/Documents/work/datasets_cache/
# data_base_path = "/home/jsimon/Desktop/knownew/600 Da... |
import numpy as np
import tensorflow as tf
from constants import overlap_thresh, max_boxes, anchor_size as s, feature_size, real_image_height, real_image_width
def non_max_suppression_fast(boxes, probs):
x1 = boxes[:, 0]
y1 = boxes[:, 1]
x2 = boxes[:, 2]
y2 = boxes[:, 3]
area = (x2 - x1) * (y2 - y1)
np.testing... |
import unittest
import json
from elasticsearch import helpers, Elasticsearch, TransportError
from flask import current_app as app
from app.main import db
from app.test.base import BaseTestCase
class TestGlossaryBlueprint(BaseTestCase):
maxDiff = None
def setUp(self):
super().setUp()
es = Elastics... |
#!/usr/bin/python3
import sys, os
from PyQt4 import QtCore, QtGui
from PyQt4.QtGui import QDialog, QApplication
from sessiondialog import SessionDialog
def main():
os.system("./generate_weight_plot")
app = QApplication( sys.argv )
sdialog = SessionDialog()
sdialog.show()
sys.exit( app.exec_() )
if __name__ == "... |
# -*- coding: utf-8 -*-
from typing import Tuple, Any
import aiomysql
import asyncio
import json
class Database:
"""
Class used to represent the database connection used by the bot.
"""
__slots__ = []
pool = None
@classmethod
async def _make(cls, **credentials):
"""
Initia... |
import cv2
import uuid
from model import face_model as fm
from controller.face_detector import FaceDetector
from controller.worker import Worker
from queue import Queue, Empty
class FrameController:
def __init__(self, sim_threshold=0.54, num_workers=2, max_queue_size=10, frame_proc_freq=3):
self.frame_cou... |
from django.shortcuts import render, redirect
from django.urls import reverse
from django.contrib import messages
from django.contrib.auth.models import User
from .models import Messages, MessageFeatures
from django.db.models import Q, Max, Count
from django.http import Http404, JsonResponse, HttpResponse
from d... |
import datetime
import fileinput
import logging
import os
import socket
import ssl
import time
from ssl_expiry import *
from sendOutlookMail import *
# initialize log file
#logging.basicConfig(filename='CertificateChecker.log', format='%(asctime)s %(message)s: %(levelname)s', filemode='w', level=logging.DEB... |
# session management
import random
import pickle
import settings
r = settings.r
_sidChars='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
_defaultTimeout=30*60
_defaultCookieName='gsid'
class Session(dict):
def __init__(self,request,response,name=_defaultCookieName,timeout=_defaultTimeout):
"""
... |
#!/usr/bin/env python
from ironicclient import client
import os
import subprocess
import sys
if os.environ.get('OS_AUTH_TOKEN'):
OS_AUTH_TOKEN = os.environ['OS_AUTH_TOKEN']
else:
OS_AUTH_TOKEN = 'fake-token'
if os.environ.get('IRONIC_URL'):
IRONIC_URL = os.environ['IRONIC_URL']
else:
IRONIC_URL = 'ht... |
import random
HANGMANPIC='''
---------
I I
I
I
I
I
I
I
--------------''','''
---------
I I
O I
I
I
I
I
I
--------------''','''
---------
I I
O I
/ I
I
I
I
I
----... |
t = int(input())
while t > 0:
n,s = map(int,input().split())
arr = list(map(int,input().strip().split()))[:n]
mx_len = 0
for i in range(n):
cur_sum = 0
for j in range(i,n):
cur_sum += arr[j]
if cur_sum == s:
mx_len = max(mx_len,j - i + 1)... |
from pynput import mouse, keyboard
import logging
from time import sleep
logger = logging.getLogger('MouseMoveApp')
logger.setLevel(logging.DEBUG)
fh = logging.FileHandler('mousemove.log')
fh.setLevel(logging.DEBUG)
formatter = logging.Formatter(
'%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setForma... |
# *_*coding:utf-8 *_*
import sys
reload(sys)
sys.setdefaultencoding('utf8')
from public.publicExcel import PublicExcel
class InsuranceOpera(object):
"""
读取excel所有字段值
"""
def __init__(self,path):
self.excel = PublicExcel(path)
# 产品名称
def get_productName(self,row):
read_productNa... |
from django import forms
from django.forms import (
ModelForm, Textarea
)
from .models import Review
class CustomerLoginForm(forms.Form):
email = forms.EmailField(label='Email', required=True, error_messages={'required': 'Please enter your Email'})
password = forms.CharField(label='Password',
... |
from django.template.loader import render_to_string
from django.conf import settings
from sendgrid.helpers.mail import Mail
from sendgrid import SendGridAPIClient
def send_init_pwd(user, password):
email_template = render_to_string('send_init_pwd.html',
context={'user': user,... |
import os
import sys
import stat
import urllib
import zipfile
import time
import re
from selenium.webdriver import Chrome
# User's Reddit credentials
USERNAME = 'username'
PASSWORD = 'password'
def get_reddit_api_keys():
pass_chrome_binary()
os.environ['webdriver.chrome.driver'] = './chromedriver'
drive... |
import prometheus_client
from prometheus_client import Counter
from prometheus_client import Gauge
from prometheus_client.core import CollectorRegistry
import psutil
import time
import datetime
import requests
import socket
import threading
from flask import Response, Flask
app = Flask(__name__)
class GetNetRate:
... |
numero = int(input("Escribe un numero decimal: "))
binario = ''
while True:
print(numero)
if numero % 2 == 0:
binario = '0' + binario
else:
binario = '1' + binario
numero = numero // 2
if numero == 0:
break;
print(binario)
|
''' PyTorch backend '''
import json
import os
class ModelFactory: # pylint: disable=too-few-public-methods
''' PyTorch backend model factory '''
def open(self, model): # pylint: disable=missing-function-docstring
return _Model(model)
class _Model: # pylint: disable=too-few-public-methods
def __in... |
from django.db import models
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.fields import GenericForeignKey
from django.db.models import Sum
from django.contrib.contenttypes.fields import GenericRelation
class LikeDislikeManager(... |
import itertools
import pytest
import tigger.cluda as cluda
from tigger.helpers import min_blocks, product
import tigger.cluda.dtypes as dtypes
from helpers import *
from pytest_contextgen import parametrize_context_tuple, create_context_in_tuple
pytest_funcarg__ctx_with_gs_limits = create_context_in_tuple
def s... |
from .dataset import Dataset
from .in_memory_dataset import InMemoryDataset
from .planetoid import Planetoid
from .npz_dataset import NPZDataset
from .ppi import PPI
from .reddit import Reddit
from .tu_dataset import TUDataset
from .karateclub import KarateClub
from .musae import MUSAE
|
#!/usr/bin/env python
# test has been developed by Robert Harakaly and changed for SAM by Victor Galaktionov
# get the replica entries associated with a list of GUIDs (lfc_getreplicas)
# meta: proxy=true
# meta: preconfig=../../LFC-config
import os, lfc, sys, errno
from testClass import _test, _ntest, _testRunner, ... |
"""
Defines the Maze data type, which can store and draw a maze of arbitrary size.
"""
class Maze:
def __init__(self, size=(8, 8)):
"""
Creates a blank maze
:param size:
"""
pass |
import setuptools
from os.path import join, dirname
setuptools.setup(
name="django_bulb_switcher",
version='0.1',
packages=["django_bulb_switcher"],
install_requires=open(join(dirname(__file__), 'requirements.txt')).readlines(),
author="Bernardo Fontes",
author_email="bernardoxhc@gmail.com",
... |
from django.contrib.auth.decorators import login_required
from django.shortcuts import render
import json
from django.http import HttpResponse
from django.utils.safestring import mark_safe
from django.shortcuts import get_object_or_404
from .models import Chat,Message
from accounts.models import User
from courses.model... |
# http://www.practicepython.org/exercise/2014/07/05/18-cows-and-bulls.html
from random import randint
if __name__=="__main__":
cifra0 = str(randint(0,9))
cifra1 = str(randint(0,9))
cifra2 = str(randint(0,9))
cifra3 = str(randint(0,9))
numero = cifra0 + cifra1 + cifra2 + cifra3
num = 0
wh... |
# Generated by Django 3.1 on 2020-08-29 07:06
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('manager', '0003_order_detail_start_time'),
]
operations = [
migrations.CreateModel(
name='order_choice_log',
fields=[
... |
from attractor import *
from parity_game import ParityGame
from game_solver import GameSolver
class QPZSolver(GameSolver):
def __init__(self, game: ParityGame):
super().__init__()
self.game = game
def solve(self):
i = self.game.d % 2
wi = self.qpz(self.game, self.game.d, self.... |
print("욥욥욥욥욥욥")
print("얍얍얍얍얍얍얍") |
"""todolist URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-base... |
from direct.distributed.DistributedObjectAI import DistributedObjectAI
from direct.directnotify import DirectNotifyGlobal
class HolderTentacleAI(DistributedObjectAI):
notify = DirectNotifyGlobal.directNotify.newCategory('HolderTentacleAI')
def __init__(self, air):
DistributedObjectAI.__init__(self, ai... |
#coding:gb2312
#传递实参
print("位置实参:")
def favorite_numbers(name,number):
print("被调查者的名字是:"+name.title())
print(name.title()+"'s favorite number is "+number+"."+"\n")
favorite_numbers('lyl','1')
favorite_numbers('hl','9') #函数是可以调用多次的
#关键字实参
print("\n\n\n关键字实参:")
def favorite_numbers(name,number):
print("被调查者的名字是:"... |
"""
Biblioteca criada com todas as funções criadas em Programação 2
"""
"""
Um n-grama é uma sequência de caracteres de tamanho n, por exemplo:
"goiaba" --> 1-grama: g, o, i, a, b, a
2-grama: go, oi, ia, ab, ba
3-grama: goi, oia, iab, aba
...
Construa a função ngrama(<texto>, <tam>) que retorna uma lista ... |
d=input("Write diameter: ")
L=(3.14 * float(d))
print(L) |
#!/usr/bin/env python3
"""
__author__ = "Axelle Apvrille"
__license__ = "MIT License"
"""
import argparse
import os
import subprocess
import droidutil # that's my own utilities
import droidsample
import droidreport
import sys
property_dump_file = 'details.md'
report_file = 'report.md'
json_file = 'report.json'
__vers... |
import pandas as pd
import plotly.express as px
url = 'http://api.open-notify.org/iss-now.json'
# Get position of ISS
df = pd.read_json(url)
#print(df)
df['latitude'] = df.loc['latitude','iss_position']
df['longitude'] = df.loc['longitude','iss_position']
df.reset_index(inplace=True)
df = df.drop(['index','mess... |
from sklearn.svm import SVC
from DataSet.iris import learn_iris
from DataSet.xor import learn_xor
# SVMに関するテスト
# カーネルトリック
# カーネル = 簡単に言うと, 2つのサンプル(x_i, x_j)間の類似度を表す関数( 0 ~ 1 )
# ガウスカーネル
# k(x_i, x_j) = exp(- |x_i - x_j|^2 / 2σ^2)
# = exp(-γ|x_i - x_j|^2) (γ = 1/2σ^2)
svm = SVC(kernel='rbf', random_s... |
from pico2d import *
import random
import time
import game_world
import config
from ball import Ball
# Boy State
# IDLE, RUN, SLEEP = range(3)
# Boy Event
RIGHT_DOWN, LEFT_DOWN, RIGHT_UP, LEFT_UP, TIME_OUT, SPACE_DOWN, ENTER_DOWN = range(7)
key_event_table = {
(SDL_KEYDOWN, SDLK_RIGHT): RIGHT_DOWN,
(SDL_KEYD... |
import matplotlib.pyplot as plt
plt.plot([1, 2.5, 3, 4.5])
plt.ylabel('some numbers')
plt.show()
|
import sys
import os
import fam
sys.path.insert(0, 'tools/trees')
import cut_long_branches
import ete3
ali = "../BenoitDatasets/families/pdb_plants23/families/Phy003MBZY_CUCME/alignment.msa"
tree= "../BenoitDatasets/families/pdb_plants23/families/Phy003MBZY_CUCME/gene_trees/raxml-ng.bestAA.geneTree.newick"
out = "p... |
from rest_framework import viewsets
from .models import Message
from rest_framework.permissions import AllowAny
from .serializers import MessageSerializer
class MessageViewSet(viewsets.ModelViewSet):
serializer_class = MessageSerializer
queryset = Message.objects.all()
http_method_names = 'get', 'post'
... |
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.forms.models import model_to_dict
from django.dispatch import receiver
from datetime import datetime
import urllib.request
from django import template
from tagging.fields import TagField... |
import datetime
from django.contrib.syndication.views import Feed
from django.utils.feedgenerator import Atom1Feed
from django.db.models import Q
from tssite.models import TalmudStudy, Class
class RSSAllFeed(Feed):
title = "Tanach Study Daily Updates"
link = "/feeds/rss/all"
description = "Description of ... |
import os
import cv2
from scipy.fftpack import dct
from tools import detect_face
import image_preprocessing_functions as ipf
import investigation_functions as inv_func
def make_db(path_to_dataset, is_detection=False):
people = {}
for images_dir in os.listdir(path_to_dataset):
if images_dir.startswi... |
# Set your API key here
api_key = "" |
import tkinter as tk
import sys
import os.path
from os import path
import time
from tkinter import *
import datetime
import os
from tkinter import messagebox
import smtplib
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import random
from email.message import EmailMessage
import funct... |
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 17 18:13:19 2015
@author: eejvt
Code developed by Jesus Vergara Temprado
Contact email eejvt@leeds.ac.uk
University of Leeds 2015
"""
import numpy as np
import sys
#sys.path.append('C:\opencv\build\x64\vc12\bin')
import cv2
from glob import glob
im... |
import cv2
body_cascade = cv2.CascadeClassifier('/Users/jeremy.meyer/opencv/data/haarcascades/haarcascade_fullbody.xml')
face_cascade = cv2.CascadeClassifier('/Users/jeremy.meyer/opencv/data/haarcascades/haarcascade_frontalface_default.xml')
#ped_cascade = cv2.CascadeClassifier('/Users/jeremy.meyer/opencv/data/hogcasc... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2020-04-08 18:45:15
# @Author : Fallen (xdd043@qq.com)
# @Link : https://github.com/fallencrasher/python-learning
# @Version : $Id$
#闭包
#在函数中提出的概念
#当函数定义内部函数,且返回值时内部函数名,就叫闭包
#1.闭包必须是外部函数中定义了内部函数
#2.外部函数是有返回值的,且该返回值就是内部函数名,不能加括号
#3.内部函数引用外部函数的变量值
'''
闭包格式:... |
'''Author: Akash Shah (ass502)
This module contains the Grades class, along with its member functions.
An instance of the grades class consists of the restaurant grades that has been pre-processed
and a dataframe containing the scores for each of the restaurants, indexed by borough and camis id'''
import pandas as pd
... |
import subprocess
experiments = [
'experiment_folders\paper\\cv1\\' + s for s in [
## Experiments to evaluate modalities on PET/CT/MRI dataset (36 patients):
#'ADC_adc_basic_f1_adam',
#'CT_ct_windowing_c32_w220_basic_f1_adam',
#'Perf_perf_basic_f1_adam',
#'PETCT_petct_wind... |
# 生产者,消费者模型
# 爬虫的时候
# 分布式操作 :celery
# 本质:就是让生产数据和处理数据的效率达到平衡并且最大化效率
from multiprocessing import Queue,Process
import random
import time
def consumer(q,name): # 消费者:通常收到数据后还要进行某些操作
while True: # 这样,保证我们消费者可以及时消费,而且当生产者不提供的时候,可以停下程序
food = q.get()
if food:
print('%s吃了%s'%(n... |
def fibonacci(n):
if (n <= 1):
return 0
elif (n == 2):
return 1
else:
return (fibonacci(n-1) + fibonacci (n-2))
n = int(input("Digite a quantidade de numeros da sequencia: "))
for i in range(n):
print(str(fibonacci(i)) + " ")
|
from PyInstaller.utils.hooks import logger
def pre_safe_import_module(psim_api):
import PyMca5.PyMcaGui as PyMcaGui
for p in PyMcaGui.__path__:
psim_api.append_package_path(p)
|
#!/usr/bin/env python
# vim: autoindent tabstop=4 shiftwidth=4 expandtab softtabstop=4 filetype=python fileencoding=utf-8
'''
Copyright © 2013
Eric van der Vlist <vdv@dyomedea.com>
Jens Neuhalfen <http://www.neuhalfen.name/>
See license information at the bottom of this file
'''
import re
import os
import Con... |
from src.util.Logging import warn
from src.util.Exceptions import PathValidationException, NotSupportedException
from src.plan.GraphAssembler import MergeAssembler
from src.plan.Region import RegionLoop, RegionPair
from src.layout.PlannedGraph import Vertex, Edge
from src.layout.EdgeStyles import EdgeStyle, AUTO_BEND, ... |
#!/usr/bin/env python
# coding: utf-8
import numpy as np
import pandas as pd
import csv
import matplotlib.pyplot as plt
import datetime
# In the following, change 'Country/Region' to your desired choice. I wrote the Python file for the Country/Region Lebanon.
# Change the following to the location of the CSSE file "... |
import torch
import torch.nn as nn
import torch.tensor as tensor
from torch.nn import functional as F
import pdb
from torchvision.models.resnet import resnet18
class SpatialTransformBlock(nn.Module):
def __init__(self, num_classes, pooling_size, channels):
super(SpatialTransformBlock, self).__init__()
... |
import test_class0
import test_class1
#bb= B()
#cc= B()
#A.aaa= '789'
if(1):
cls = getattr(test_class1, 'B', None)
#print obj
obj = cls()
func = getattr(obj, 'bbb', None)
#print func
func()
cls = getattr(test_class1, 'B', None)
obj2 ... |
import numpy as np
# Utility functions
def updateIndividual (I, O, M, prob):
for dim in range(0, M):
if O[dim] != 0:
if (np.random.choice(2, p = [prob, 1-prob]) == 0):
I[dim] = O[dim]
def VecSimm(Vec1, Vec2):
return len(list(x for x,y in zip(Vec1, Vec2) if x == y))
def Vec... |
import pandas as pd
import numpy as np
import math
import re
import matplotlib.pyplot as plt
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.linear_model import LogisticRegression, SGDClassifier
from sklearn.metrics import roc_curve, auc
from sklearn.model_selection import StratifiedKFold
from ... |
from tools import ReadJson,ReadRedis,ReadDB,ReadConfig
from common import FormatConversion,RunMain
import json
class DisposeEnv:
def __init__(self):
self.readenvjsonhandle = ReadJson.ReadJson('Env','ENV')
self.readrelyjsonhandle = ReadJson.ReadJson('RelyOn','RELYON')
self.readredishandle =... |
# -*- coding: utf-8 -*-
# @Time : 2020-04-28 10:57
# @Author : speeding_motor |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.