text stringlengths 8 6.05M |
|---|
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import socket
from path import path
from datetime import timedelta
from handy.cipher import MessageCipher
import django.conf.global_settings as DEFAULT_SETTINGS
LANGUAGE_CODE = 'en-us'
USE_TZ = False
TIME_ZONE = 'America/Chicago'
USE_I18N = True... |
from abc import ABC
from abc import abstractmethod
class State(ABC):
def __init__(self):
pass
@abstractmethod
def enter(self, data):
pass
@abstractmethod
def exit(self):
pass
@abstractmethod
def handle_event(self, event):
pass
@abstractmethod
def... |
from control import Control
def test_control_degree():
assert Control(1000, 2000).degree(-5000) == 0, "Should be 0"
assert Control(1000, 2000).degree(910) == 0, "Should be 0"
assert Control(1000, 2000).degree(5010) == 180, "Should be 180"
assert Control().degree(1) == 0, "Should be 0"
assert C... |
from django.urls import path, include
from . import views
from rest_framework import routers
from django.conf.urls import url
router = routers.DefaultRouter()
urlpatterns = [
path('',include(router.urls)),
url(r'prueba/',views.prueba.as_view(),name="prueba")
] |
import matplotlib; matplotlib.use('Agg') # NOQA
import os
import json
import skimage.io
import skimage.transform
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Arrow
from .config import cfg
from util import boxes
def vis_one_vqa(img_path, words, vqa_scores, label, module_names, a... |
import numpy as np
from sklearn.datasets import load_boston
from sklearn.preprocessing import MinMaxScaler, StandardScaler
from sklearn.model_selection import train_test_split, KFold, cross_val_score
from sklearn.metrics import accuracy_score, r2_score
# from sklearn.svm import LinearSVC, SVC
from sklearn.neighbors im... |
# -*- coding:UTF-8 -*-
from rest_framework import serializers
from . import models
from index.models import Application
class CheckApplicationSerializer(serializers.ModelSerializer):
application = serializers.PrimaryKeyRelatedField(queryset=Application.objects.filter(application_status=1))
class Meta:
... |
from socket import *
import time
import threading as th
from multiprocessing import Process, Lock,RLock, Semaphore
def fromGateway():
print "The server for Gateway is ready to receive"
while 1:
messageFromGateway, gatewayClientAddress = fromGatewayserverSocket.recvfrom(2048)
fromGatewayLock.acquire()
messag... |
# -*- coding: utf-8 -*-
import scrapy
class MalaysiaSongSpider(scrapy.Spider):
name = 'malaysia_song'
allowed_domains = ['www.youtube.com/playlist?list=PLgNjz5kKawRiPXT7l3XT60v3iWogBvGP0']
start_urls = ['http://www.youtube.com/playlist?list=PLgNjz5kKawRiPXT7l3XT60v3iWogBvGP0/']
def parse(self, respon... |
import matplotlib.pyplot as plt
from matplotlib.ticker import NullFormatter
import numpy as np
%matplotlib inline
y = [1,2,3,4,10]
x = [1,2,3,4,10]
line, = plt.plot(x, y, "-", linewidth=5.0) # linewidth means the width of the line
line.set_antialiased(False) # this removes the blur
plt.plot(x, y, "ro") # r means red... |
# Generated by Django 3.0.3 on 2020-03-17 15:37
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('shop', '0006_auto_20200317_1832'),
]
operations = [
migrations.RenameField(
model_name='wishitem',
old_name='Item',
... |
# from django.test import TestCase
# I would create tests here if this was intended for production. Upon request I can add some.
|
import logging
import re
import time
import typing
logger = logging.getLogger()
# Just for performance timing tests
def timed_request(method):
def timed(*args, **kw):
ts = time.time()
try:
uri = args[0].__dict__.get('base_url', '') + kw.get('resource_path', '')
except IndexEr... |
def authenticate(uname,pword):
login={"abc":"123",
"helen":"li",
"soft":"dev"
}
if uname in login:
if login[uname]==pword:
return True
else:
return False
|
import numpy as np
import pandas as pd
import random
train = pd.read_csv('../data/train.csv')
sample_places = random.sample(set(train['place_id']), 100)
sample_train = train[train['place_id'].isin(sample_places)]
sample_train.to_csv('../processing/random.100.places.csv')
|
# nc2pdf - main program
# vim:fileencoding=utf-8
"""Plot cuts from a Gerber cloth cutter NC file to a PDF."""
__version__ = '1.12-beta'
_lic = """nc2pdf {}
Copyright © 2013, 2015 R.F. Smith <rsmith@xs4all.nl>. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are ... |
from flask import Flask, request, jsonify, session,\
make_response, url_for, redirect, abort, Response, \
session
# from flask_script import Manager
import json, os
app = Flask(__name__)
# manager = Manager(app)
# 127.0.0.1:5000?city=Beijing&country=china&city=nanchang ... |
#!/usr/bin/env python
from optparse import OptionParser
parser = OptionParser()
parser.add_option("--noMultiThreading", dest="noMultiThreading", default = False, action="store_true", help="noMultiThreading?")
parser.add_option("--selectWeight", dest="selectWeight", default=None, ... |
r"""
###############################################################################
:mod:`OpenPNM.Utilities` -- IO, geometry tools and other functions
###############################################################################
.. automodule:: OpenPNM.Utilities.IO
:members:
:undoc-members:
:show-inheritan... |
import math, operator
def choose(n, k):
if 0 <= k <= n:
ntok = 1
ktok = 1
for t in range(1, min(k, n - k) + 1):
ntok *= n
ktok *= t
n -= 1
return ntok // ktok
else:
return 0
def is_prime(x):
return all(x%d for d in range(2, 1+math... |
import os
import random
from collections import defaultdict, OrderedDict
import chainer
import cv2
import numpy as np
import config
from dataset_toolkit.compress_utils import get_zip_ROI_AU, get_AU_couple_child
from img_toolkit.face_mask_cropper import FaceMaskCropper
# obtain the cropped face image and bounding box ... |
n = int(input("Digite o numero: "))
numero = list(range(1,n, 2))
print (numero) |
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 15 14:49:49 2018
@author: shams
reading in raw data json files for each user, reorganizng and pickling the data
"""
import numpy as np
import pandas as pd
import networkx as nx
def usr_top_chans(usr, netWindow , nchans = 5):
chanList = list(netWindow.... |
import numpy as np
import pandas as pd
from matplotlib.colors import ListedColormap
import matplotlib.pyplot as plt
from sklearn.preprocessing import StandardScaler
import os
from sklearn.utils import resample
df = pd.read_csv(os.path.abspath('dataset.csv'),header=None)
y = df.iloc[:, 11].values
X = df.iloc[:, [2, 4]]... |
import graphene
from models import PhaseEnumGraphene
from utils.ordering import OrderedList
from .case import CaseTypeGrapheneEnum, DeleteCase, ImportCase, Case, resolve_case, resolve_case_types, resolve_cases
from .field import Case as CaseType, AddField
from .role import AssignRole, resolve_role_by_user, resolve_rol... |
from logs import logDecorator as lD
import jsonref
import vtk
import numpy as np
config = jsonref.load(open('../config/config.json'))
logBase = config['logging']['logBase'] + '.lib.simpleFunctions.simpleObjects'
class MeshXZ():
def __init__(self, startX, startZ, endX, endZ, yValue=0, nPoints=20):
self.x... |
# Generated by Django 2.2.5 on 2019-12-05 22:22
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('trips', '0008_auto_20191129_1613'),
]
operations = [
migrations.CreateModel(
name='SelectedTrip',
fields=[
... |
#! /user/bin/python/
# -*-coding:utf-8 -*-
import os
import sys
BASE_DIR=os.path.dirname(os.path.dirname(__file__))
BASE_ADMIN_DB=os.path.join(BASE_DIR,"db","admin")
Base_TEACHER_DB=os.path.join(BASE_DIR,"db","teachers")
BASE_COURSE_DB=os.path.join(BASE_DIR,"db","courses") |
#!/usr/bin/python
# -*- coding: utf-8 -*-
data = \
'''3COM ,CoreBuilder ,7000/6000/3500/2500 ,Telnet ,debug ,synnet , ,
3COM ,CoreBuilder ,7000/6000/3500/2500 ,Telnet ,tech ,tech , ,
3COM ,HiPerARC ,v4.1.x ,Telnet ,adm ,(none) , ,
3COM ,LANplex ,2500 ,Telnet ,debug ,synnet , ,
3COM ,LANplex ,2500 ... |
from socket import *
import threading
#设计思想:
#1.让服务器连接多台客户端
#2.服务器可以客户端进行收发操作,互不干扰
class tcpserver_test(threading.Thread):
def __init__(self,port):
"""初始化变量"""
threading.Thread.__init__(self)
self.port = port #自定义开启端口
addr = ('10.48.41.61',self.port)
#创建套接字
self.tc... |
# Generated by Django 3.1.6 on 2021-04-07 01:04
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('log', '0015_auto_20210406_2035'),
]
operations = [
migrations.RenameField(
model_name='entry',
old_name='img',
... |
'''++
Copyright (C) 2019 PrimeDevelopers
All rights reserved.
This file has been generated by the Automatic Component Toolkit (ACT) version 1.4.0.
Abstract: This is an autogenerated Python application that demonstrates the
usage of the Python bindings of Ray Marching Library
Interface version: 1.1.0
'''
import... |
import tensorflow as tf
import numpy as np
model = tf.keras.Sequential()
model.add(tf.keras.layers.Embedding(1001, 64, input_length=3, mask_zero=True))
# The model will take as input an integer matrix of size (batch,
# input_length), and the largest integer (i.e. word index) in the input
# should be no larger than 999... |
in_file = open('input_8.txt', 'r')
# in_file = open('test_8.txt', 'r')
def op(line):
global acc
global pointer
ops, num = line.split(' ')
if ops == 'acc':
if num[0] == '+':
acc += int(num[1:])
else: acc -= int(num[1:])
return 1
elif ops == 'jmp':
if num[0] == '+':
pointer += int(num[1:])
else: poi... |
import logging
import pickle
import time
import h5py
import numpy as np
import tensorflow as tf
import tensorflow.contrib.layers as layers
from . import tf_util as U
logger = logging.getLogger(__name__)
class Policy:
def __init__(self, *args, **kwargs):
self.args, self.kwargs = args, kwargs
sel... |
#!/usr/bin/python3
import random
number = random.randint(-10000, 10000)
if (number < 0):
last = (abs(number) % 10) * -1
else:
last = number % 10
if last > 5:
str = "and is greater than 5"
elif last == 0:
str = "and is 0"
elif last < 6 and last != 0:
str = "and is less than 6 and not 0"
print("Last d... |
import random
num = random.randint(1, 10)
answer = input('Guess number:')
if answer.isdigit():
answer = int(answer)
if num > answer:
print(f'Bigger..{answer}')
elif num < answer:
print(f'less...')
else:
print('BINGO!')
else:
print('oops... need number')
if answer != num:
... |
from rest_framework import generics, permissions
from rest_framework.response import Response
#from knox.models import AuthToken
from .serializers import *
from django.contrib.auth import login
from rest_framework.authtoken.serializers import AuthTokenSerializer
from rest_framework.renderers import TemplateHTMLRenderer... |
{
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"name": "NPK predictionAI .ipynb",
"version": "0.3.2",
"provenance": [],
"include_colab_link": true
},
"kernelspec": {
"name": "python3",
"display_name": "Python 3"
}
},
"cells": [
{
"c... |
# coding: utf-8
"""
NiFi Rest API
The Rest API provides programmatic access to command and control a NiFi instance in real time. Start and stop processors, monitor queues, query provenance data, and more. Each endpoint below includes a description, ... |
from linear_algebra import *
# Some samples
A = [[1, 4], [-2, 3]]
B = [[-2, 5], [6, 7]]
print('Matrix A:')
print_matrix(A)
print('Matrix B:')
print_matrix(B)
print('Addition of matrices A and B:')
# Addition
print_matrix(add_matrix(A, B))
print('Subtraction of matrices A and B:')
# Subtracti... |
from django import forms
from .models import Blog, Comment
# from pagedown.widgets import PagedownWidget
class BlogCreateForm(forms.ModelForm):
# for pagedown
# content = forms.CharField(widget=PagedownWidget(show_preview=False))
class Meta:
model = Blog
fields = ('title', 'content')
cl... |
#Data correlation source: http://tylervigen.com/view_correlation?id=28590
import matplotlib.pyplot as plt
from numpy.random import rand
Year = ['2008', '2009', '2010']
Color = ['green', 'blue', 'red']
MilitarySpending = [38579, 40246, 39461]
LawnmowerDeaths = [43, 84, 73]
plt.subplot(211)
plt.plot(MilitarySpending, ... |
'''Jinjer操作サービス'''
import os
import time
from urllib import parse
from collections import defaultdict
from django.utils import timezone
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdrive... |
#!/usr/bin/env python
# Author: Jin Lee (leepc12@gmail.com)
import sys
import os
import argparse
from encode_lib_common import (
assert_file_not_empty,
log,
ls_l,
mkdir_p,
)
from encode_lib_genomic import (
peak_to_bigbed,
peak_to_hammock,
get_region_size_metrics,
get_num_peaks,
pe... |
import json
with open('data.json') as data_file:
data = json.load(data_file)
contour_points = data["contour_points"]
x_max = data["x_max"]
y_max = data["y_max"]
init_flow_len = data["init_flow_len"]
alfa = data["alfa"]
circulation = data["circulation"] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Sends JSON-formatted tweets related to meteors to stdout in real time
Author: Geert Barentsen (geert.io)
Inspired by: http://peter-hoffmann.com/2012/simple-twitter-streaming-api-access-with-python-and-oauth.html
"""
import sys
import tweepy
import secrets
class Custom... |
# -*- coding: UTF-8 -*-
import MySQLdb
def saveToMysql():
file_in = open('activation_code', 'r')
db = MySQLdb.connect(host = "localhost",
user = "",
passwd = "",
db = "")
table_name = "test"
cur = db.cursor()
count = 0
... |
from django.shortcuts import render, get_object_or_404, redirect
from .models import ClubTeam
from .forms import ClubTeamForm
# Create your views here.
def club_teams(request):
clubs = ClubTeam.objects.all().order_by('created_date')
return render(request, 'club_team/club_team_list.html', {'clubs':clubs})
def club_... |
"""
File for ingredient parser implemented using a linked list.
Used to make ingredients parsing faster relative to using a list to parse.
Each removal operation is O(1) instead of O(n) where n is the number of words
in the ingredient description.
Author: John Li
"""
import re
# special cases: wanted to get rid o... |
import logic
def input_params():
print('Выберите уравнение:\n'
'1. y\' + 2y - x^2 = 0\n'
'2. y\' + 5ln(x) = 0\n'
'3. y\' + 2xy = 0')
t = float(input())
print('Введите начальные условия через пробел (х0 у0)')
x0, y0 = input().split()
print('Введите конец отр... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# The above lines tell the shell to use python as interpreter when the
# script is called directly, and that this file uses utf-8 encoding,
# because of the country specific letter in my surname.
"""
Name: Christmas Tree
Author: Martin Bo Kristensen Grønholdt.
Version: 1.0... |
import torch
import torch.nn as nn
import torch.nn.functional as F
class AHDRNet(nn.Module):
def __init__(self, in_c=6, out_c=3, fc=64, growth_rate=32):
super(AHDRNet, self).__init__()
self.z1 = BasicBlock(in_c, fc)
self.z2 = BasicBlock(in_c, fc)
self.z3 = BasicBlock(in_c, fc)
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('imagematch', '0002_auto_20150421_0508'),
]
operations = [
migrations.AlterField(
model_name='image',
... |
import numpy as np
import math
class RobotKol:
def __init__(self, DH_Parametresi, UzuvUzunluklari):
self.dh = DH_Parametresi
self.Uzunluk = np.array(UzuvUzunluklari)
self.EklemSayisi = len(self.dh)
self.TransferFonksiyonlari = []
def FK(self):
for i in ra... |
from django.shortcuts import render
from app.models import TrendRepo
from django.views import generic
# Create your views here.
def index(request):
trend_list = TrendRepo.objects.all()
return render(request,'app/index.html',{'trend_list':trend_list})
def detail(request,pk):
trend = TrendRepo.objects.get(i... |
#!/usr/bin/env python
"""
_New_
MySQL implementation of Masks.New
"""
__all__ = []
import logging
from WMCore.Database.DBFormatter import DBFormatter
class New(DBFormatter):
plainsql = """INSERT INTO wmbs_job_mask (job, inclusivemask) VALUES (:jobid, :inclusivemask)"""
sql = """INSERT INTO wmbs_job_mas... |
'''
This module defines the behaviour of a client in your Chat Application
'''
import sys
import getopt
import socket
import random
from threading import Thread
import os
import util
import time
import select
import re
'''
Write your code inside this class.
In the start() function, you will read user-input and act ac... |
from rest_framework.routers import DefaultRouter
from .views import UserRegistrationView
router = DefaultRouter()
router.register(r'register', UserRegistrationView, basename='user_register')
urlpatterns = router.urls |
#! /usr/bin/python
import time
import re
import datetime
# non stdlib external
import wikitools
class WikiHandler():
def __init__(self, apiURL, username, password):
self.apiURL = apiURL
self.username = username
self.password = password
self.lastTimestamp = time.strftime("%Y-%m-%dT... |
from os import environ
from flask import Flask, jsonify, request, make_response
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.sql import func
from flask_migrate import Migrate
from flask_cors import CORS
import boto3
from datetime import datetime
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] ... |
from numpy import *
from glue.ligolw import utils, ligolw, lsctables
from glue.lal import LIGOTimeGPS
from glue import lal
from glue import segments as seg
import os
from optparse import OptionParser
from gwpy.timeseries import TimeSeries
from glue import datafind
parser = OptionParser(
version = "Name: Overflow Trig... |
import requests
from bs4 import BeautifulSoup
import simplejson
def getLensList():
headers = {
'Connection': 'keep-alive',
}
data = [
('Type', ''),
('Diameter_min', ''),
('Diameter_max', ''),
('Length_min', ''),
('Length_max', ''),
('Sort', 'Diameter'),
('... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from typing import Any, Union
from smorest_sfs.extensions import db
from smorest_sfs.modules.menus import models
from smorest_sfs.plugins.hierachy_xlsx.parsers import HierachyParser
from smorest_sfs.plugins.hierachy_xlsx.transformers import (
HierachyModelProtocol,
... |
import re
class BibParser:
def __init__(self, fname):
self.filename = fname
def read_raw_content(self):
item = ""
items = []
with open(self.filename) as f:
while True:
line = f.readline()
if not line:
items.appe... |
class Product:
def __init__(self, name, description, quantity, buying_cost, selling_price, manufacturer_id, id= None):
self.name = name
self.description = description
self.quantity = quantity
self.buying_cost = buying_cost
self.selling_price = selling_price
self.manu... |
import numpy as np
# numpy.frombuffer
s = 'Hello World'
a = np.frombuffer(s, dtype='S1')
print(a)
x = [(1, 2, 3), (4, 5)]
a = np.asarray(x)
print(a)
# numpy.asarray
x = [1, 2, 3]
a = np.asarray(x)
print(a)
x = [1, 2, 3]
a = np.asarray(x, dtype=float)
print(a)
x = (1, 2, 3)
a = np.asarray(x)
print(a)
# numpy.fromi... |
from django.db import models
from django.utils import timezone
class Bug(models.Model):
id = models.AutoField(primary_key=True)
title = models.CharField(max_length=200)
description = models.TextField()
created_date = models.DateTimeField(auto_now_add=True)
completed_date = models.DateTimeField(auto... |
def lowestCommonAncestor(self, root, p, q):
while (root.val - p.val) * (root.val - q.val) > 0:
root = root.left if p.val < root.val else root.right
return root |
with open('attendees.html') as in_file:
attendees = []
attendees_by_name = {}
current = {}
info_count = 0
for line in in_file:
if '<h3>' in line:
current['name'] = line[4:-6]
if '<img' in line:
out = line.split('src=')
current['image'] = out[1]... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
import singlylinkedlist
class Solution:
def isPalindrome(self, head):
if head == None:
return True
temp = []
pointer = head
mid = head
... |
# Generated by Django 2.2 on 2019-06-10 17:48
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('django_nginx_access', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='UrlsDiction... |
"""
GAME CLASS FILE
this file can be used to import the game class into the
main server loop
"""
import random
import re
import asyncio
# stores a reference to the file containing the game's phrases
phrases_file = "src/phrases"
# used to check if a guess is in the alphabet
alphabet = "abcdefghijklmnopqrstuvwxyz"
cl... |
# -----------------------------------------------------------------------------
# Copyright (c) 2014--, The Qiita Development Team.
#
# Distributed under the terms of the BSD 3-clause License.
#
# The full license is in the file LICENSE, distributed with this software.
# ------------------------------------------------... |
#Programa: raices.py
#Propósito: Calcular la raíz cuadrada y la raíz cúbica de un número
#Autor: Jose Manuel Serrano Palomo.
#Fecha: 13/10/2019
#
#Variables a usar:
# n1 es el numero que vamos a usar
# sq1 es la raíz cuadrada
# sq2 es la raíz cúbica
#
#Algoritmo:
# LEER n1
# sq1 <-- math.sqrt(n1)
# sq2 <-- n1 ** (1/3)... |
import bs4
import re
import io
import logging
import zipfile
import webFunctions
import mimetypes
import urllib.parse
import urllib.error
class GDocExtractor(object):
log = logging.getLogger("Main.GDoc")
wg = webFunctions.WebGetRobust(logPath="Main.GDoc.Web")
def __init__(self, targetUrl):
isGdoc, url = s... |
S_ = "SI" |
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2018-04-15 07:46
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations... |
{
"name" : "Redondeo en pedidos",
"version" : "1.0",
"author" : "Econube Pablo Cabezas",
"website" : "http://openerp.com",
"category" : "Econube",
"description": """
Se redonde segun la configuracion de contabilidad metodo de redondeo
""",
... |
# %%
import os
import shutil
from glob import glob
from pathlib import Path
# %%
def combinetxt(dir_path, pattern, out_name):
folder = dir_path + '/values'
Path(folder).mkdir(parents=True, exist_ok=True)
with open(folder + '/' + out_name, 'wb') as out_file:
for file_name in glob(os.path.join(dir... |
"""Base class for LegendreTransformer and PrimitiveTransformer
"""
from sklearn.base import TransformerMixin, BaseEstimator
import dask.array as da
class BasisTransformer(BaseEstimator, TransformerMixin):
"""Basis transformer for Sklearn pipelines
Attributes:
discretize: function to discretize the dat... |
n = int(input())
l = list(map(int,input().split(', ')))
for i in range(len(l)):
num = l[i]
a = 0
while num>0:
a += num%6
num = num//6
l[i] = a
count = 0
for i in range(n):
for j in range(i,n):
if l[i]>l[j]:
count += 1
print(count) |
from pwn import *
def main(input):
t = process(['python2','service.py'])
t.recvline()
t.sendline(input)
a = t.recvall()
encoded = a.decode()
return encoded[64:96]
if __name__ == '__main__':
flag = ''
while True:
print("==========================================================... |
import cv2
import numpy as np
import os
from PIL import Image
recognizer = cv2.face.LBPHFaceRecognizer_create()
path = 'dataSet'
def getImagesWidthID(path):
#lay duong dan cua du lieu anh trong thu muc
imagePaths=[os.path.join(path,f) for f in os.listdir(path)]
print(imagePaths)
faces=... |
global_config = None
if global_config is None:
from .config import Config
global_config = Config() |
"""
#------------------------------------------------------------------------------
# Input generation for Boom Crane - inputgen.py
#
# Create a specific vibration and a shaped command that is designed to offset that vibration.
# Formatted for input to a small-scale boom crane
#
# Created: 4/26/17 - Daniel Newman -- da... |
#!/usr/bin/env python3
import argparse
import sys
from time import time
import yaml
n_comparisons = 0
n_swaps = 0
def insertion_sort(array):
global n_comparisons
global n_swaps
for i in range(1, len(array)):
elem = array[i]
for k in range(i):
n_comparisons += 1
if array[k] > elem:
break
for j in ... |
class Solution(object):
def spiralOrder(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
if not matrix:
return matrix
res = []
c,r = len(matrix[0]),len(matrix)
x1,y1,x2,y2 = 0,0,r-1,c-1
while x1<=x2 and y1<=y2:... |
import turtle
bob = turtle.Turtle()
print(bob)
def draw_leaf(t, n, l, a):
# t = turtle_name
# n = accuracy = about30
# l = length_of_leaf
# a = thinness_of_leaf
#go
for i in range(n):
t.fd(l)
t.lt(a)
#turn
turn = 180 - (a*n)
t.lt(turn)
#back
for... |
# A simple MDP where agent has to traverse a specific path
# in gridworld - wrong action will throw player back to start or do nothing.
# Player is rewarded for reaching new maximum length in the episode.
#
# State is represented by a positive ndim vector that tells
# where the player is. This is designed to mimic coor... |
import warnings
warnings.filterwarnings("ignore")
from fingerprinter.reader import read
from fingerprinter.fingerprint import fingerprint
from database.fingerprint_db import FingerprintDatabase
from etc.util import get_args_for_input_file
DESCRIPTION = """
This script will load a single wav file (-f), fingerprint it, ... |
# It reads two values and show a menu screen:
# [1] Addition
# [2] Multiplication
# [3] Greater Number
# [4] New Numbers
# [5] Finish the program
# It accomplish the requested operaton of each option:
from time import sleep
n1 = int(input('First Value: '))
n2 = int(input('Second Value: '))
option = 0
while option != 5... |
print("Hello, World from python")
print("Hi there, webdev!")
total = 2 + 2
print("the new total is", total)
|
import math, time, functools
M = 1000000007
# We see that s(n) looks like 19, 29, 39, etc.
# The sum is given easily via summation.
# For S(20), we get the following sum:
# 0 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8
# + 9 + 19 + 29 + 39 + 49 + 59 + 69 + 79 + 89
# + 99 + 199 + 299 => 100 + 200 + 300 - 3 = 597 = su... |
def getIntersectionNode(self, headA, headB):
"""
:type head1, head1: ListNode
:rtype: ListNode
"""
if headA is None or headB is None:
return None
l1 = headA
l2 = headB
while l1 is not l2:
l1 = headB if l1 is None else l1.next
l2 = headA if l2 is None else l2.nex... |
file = 'Textfile.py'
def write_to_file(student):
new_file = open(file,'a') #Append
new_file.write(student + "\n") #New Line
new_file.close()
def get_student_info(studentName):
test_scores = []
print("Enter scores for: " +studentName)
while True:
student_score = int(in... |
# Generated by Django 3.1.1 on 2020-10-02 11:02
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('joseph_blog', '0005_auto_20201002_1859'),
]
operations = [
migrations.AlterField(
model_name='comment',
... |
from random import randint
from time import sleep
print('='*10+' JOGO DE ADIVINHA '+'='*10)
print('\n>> Vou pensar em um numero de 0 a 10. Tente adivinhar.')
numeroComputador = randint(0,5)
for palplites in range(1, 6):
numeroUtilizador = int(input('>> Resposta: '))
print('PROCESSANDO...')
sleep(1)
if... |
class LinearRegression:
def __init__(self):
self.intercept = 0
self.slope = 0
def predict(self, data):
try:
iterator = iter(data)
res = []
for x in iterator:
res.append(self.predict(x))
return res
except TypeError:
... |
from collections import defaultdict
class TopoSort(object):
def __init__(self, n,e):
super(TopoSort, self).__init__()
self.vertices=n
self.g=defaultdict(list)
for edge in e:
x,y=edge[0],edge[1]
self.g[x].append(y)
def Sort(self):
used={}
res=[]
for i in range(self.vertices):
if i not in used:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.