text
stringlengths
8
6.05M
import random from Card import * # criando baralho BARALHO = [] for cor in range(4): for content in range(13): BARALHO.append(Carta(CardColor(cor), CardContent(content)).__str__()) for black_content in range(13, 15): BARALHO.append(Carta(CardColor(4), CardContent(black_content)).__str__()) BARALH...
from activity.models import TodoList from activity.serializers import TodoListSerializer from rest_framework.generics import ListCreateAPIView from rest_framework.generics import RetrieveUpdateDestroyAPIView class TodoListAPIListCreateView(ListCreateAPIView): queryset = TodoList.objects.all() serializer_class...
# 转成一句话脚本 # echo aW1wb3J0IHJlcXVlc3RzCmhvc3QgPSAnIGh0dHA6Ly8xMjcuMC4wLjEnCmZvciBpIGluIHJhbmdlKDIwMDAsMjUwMCk6CiAgICBhZGQgPSBob3N0Kyc6JytzdHIoaSkKICAgIHRyeToKICAgICAgICBzID0gcmVxdWVzdHMuZ2V0KGFkZCkKICAgICAgICBwcmludChpKQogICAgICAgIHByaW50KHMudGV4dCkKICAgICAgICBleGl0KDEpCiAgICBleGNlcHQ6CiAgICAgICAgcHJpbnQoaSkKICAgICAgICB...
# -*- coding: utf-8 -*- import string import collections import porter import pickle replace_dictionary = str.maketrans(string.punctuation+'\n', ' '*len(string.punctuation+'\n')) def replace_punctuation(text): """replace_punctuation(text, replace_dictionary): """ global replace_dictionary return text.tran...
# -*- coding: utf-8 -*- """ Created on Fri Dec 28 10:18:34 2018 @author: AnsonHsu """ '''Given a dictionary such as:''' dict = {'Python' : '.py', 'C++' : '.cpp', 'Java' : '.java'} '''save dictionary as csv file''' import csv w = csv.writer(open("output.csv", "w")) for key, val in dict.items(): w.wr...
import pandas as pd import numpy as np import matplotlib.pyplot as plt from behaviordisc import cp_detection_KSWIN, tp_detection, cp_detection_PELT, subseqeuence_clustering import re from statsmodels.tsa.stattools import adfuller, acf from scipy.fftpack import fft, fftfreq from math import ceil EXPECTED_PERIODS = {'1H...
#!/usr/bin/env python from distutils.core import setup version = '0.7.3' setup(name='Hillup', version=version, description='Retrieves and prepares digital elevation data for rendering as map tiles.', author='Michal Migurski', author_email='mike@stamen.com', url='https://github.com/migur...
N = int( input()) A = [ int( input()) for _ in range(N)] A = [ a-1 for a in A] L = [ 0 for _ in range(N)] L[0] = 1 cnt = 0 now = 0 while True: if now == 1: break now = A[now] if L[now] == 0: L[now] = 1 cnt += 1 else: cnt = -1 break print(cnt)
#!/usr/bin/python3 # -*- coding:utf8 -*- # Author : Arthur Yan # Date : 2019-02-16 17:00:03 # Description : 斐波那契数列 # F(n) = F(n-1) + F(n-2) # 1, 1, 2, 3, 5, 8 ...... def fib(num): if num == 1: return 1 elif num == 2: return 1 else: result = fib(num-1) + fib(num-2) ...
def f(): print(a) a = 0 a = 1 f()
#viral Advertising n = int(input()) m = 5 ppl = 0 temp = 0 for i in range(n): if i == 0: ppl = (m // 2) temp = ppl m = temp * 3 else: temp = (m // 2) ppl += temp m = temp * 3 ...
/home/ajitkumar/anaconda3/lib/python3.7/__future__.py
# -*- coding: utf-8 -*- from django.contrib import admin from .models import BatchNumberGroup,BatchNumberOid class ExamAdmin(admin.ModelAdmin): list_display = ('batch_number','group','created',) admin.site.register(BatchNumberGroup, ExamAdmin) class ExamPaperAdmin(admin.ModelAdmin): list_display =...
""" 4. Реализовать возможность переустановки значения цены товара. Необходимо, чтобы и родительский, и дочерний классы получили новое значение цены. Следует проверить это, вызвав соответствующий метод родительского класса и функцию дочернего (функция, отвечающая за отображение информации о товаре в одной строке). """ ...
#from setuptools import setup, find_packages from setuptools import * from pymanager import version description='A process manager in Python.' long_description = open('README.rst').read() setup( name='pymanager', version=version, description=description, long_description=long_description, url='htt...
#!/usr/bin/python3 """module of from_json_string""" import json def from_json_string(my_str): """function to convert from js str to py obj""" return json.loads(my_str)
from flask_admin.contrib.sqla import ModelView from flask_login import current_user, login_required from flask import url_for, redirect, flash, render_template, current_app class EmployeeView(ModelView): form_columns = ['hired_date', 'active', 'email', 'first_name', 'last_name', 'password', '...
# -*- coding: utf-8 -*- # @Author : 赵永健 # @Time : 2020/2/24 15:22 # 4、切回管理员,测试帐号赋值测试企业,(编辑测试帐号)--用户扩展信息 from time import sleep import pykeyboard from pymouse import PyMouse from selenium.webdriver import ActionChains from process.commonProc import commonProc from public import excel from util.webdr import webdr ...
#! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright © 2019 shady <shady@MrRobot.local> # import logging import time import asyncio from sanic import Blueprint from sanic.response import json from config.server import tracing from models import * seckill_bp = Blueprint("order", url_prefix="o...
from django.contrib.auth.admin import UserAdmin from django.contrib.admin import register from .forms import AccountCreationForm, AccountChangeForm from .models import Account @register(Account) class AccountAdmin(UserAdmin): """Admin model for administration Account model. Configure admin inteface.""" add_f...
class Clasetotal: def firstn(self, n): num = 0 while num < n: yield num num += 1 class Clase2: class Clase3: def firstn(self, n): num = n**2 while num > n: yield num num -= 1 def primera(): def segund...
import numpy as np import pandas as pd import tensorflow as tf import tensorflow_addons as tfa import matplotlib.pyplot as plt import warnings warnings.filterwarnings('ignore') from sklearn.model_selection import train_test_split, StratifiedKFold from sklearn.utils import shuffle from tensorflow.keras.utils import to_...
# coding: cp949 while True: num=int(input("홀수를 입력하세요(0<-종료): ")) point = 1 #별표 첫번d째 empty=int(num/2) if num == 0 : break elif num % 2 == 0 : continue else: while point <= num: print(" "*empty+"*"*point) point=int(point+2) empty=int(empty-1)
from rest_framework import serializers from .models import * from django.contrib import auth from rest_framework.exceptions import AuthenticationFailed # from .Scheduler import Schedules_operation from rest_framework_simplejwt.serializers import TokenObtainPairSerializer from rest_framework.response import Respon...
#coding=utf-8 #元组不可变的好处。保证数据的安全,比如我们传给一个不熟悉的方法或者数据接口,确保方法或者接口不会改变我们的数据从而导致程序问题。 #tuple def info(a): '''一个我们不熟悉的方法''' a[0] = 'haha' a = [1, 2, 3] info(a) print(a) #following will cause error, but as we expected. #b = (1,2,3) #info(b) # python的set和其他语言类似, 是一个无序不重复元素集, 基本功能包括关系测试和消除重复元素. # 集合对象还支持union(联合), in...
import matplotlib.pyplot as plt import euler_richardson plt.title("") plt.xlabel("x") plt.ylabel("v") w2 = 5 k = 0 S = 30 for i in range(S): X, V = euler_richardson.simulate(x=0, v=i, f=lambda _v, _x: -k * _v - w2 * _x) plt.plot(X, V,...
#!/usr/bin/env python import json import incapsula import argparse parser = argparse.ArgumentParser(description="Given a site_id, list status") parser.add_argument("-s", "--site",dest='site_id', help='The site id to retrieve information for') args = parser.parse_args() r = json.loads(incapsula.getSiteStatus(args.site...
from django.apps import apps from django.forms.models import modelform_factory def normalize_model_name(model_name): return model_name.capitalize() if model_name.lower() == model_name else model_name def get_model_form(model_name): for model in apps.get_models(): if model.__name__ == model_name: ...
#install keras from https://github.com/kundajelab/keras/tree/keras_1 from __future__ import print_function import keras import numpy as np from keras.optimizers import SGD import math import matplotlib.pyplot as plt import sys ''' Usage: python 3_train_revcomp_CNN.py featureMat_directory TFID saveDir ''' #Load traini...
import json import requests from bs4 import BeautifulSoup import sys import string from twilio.rest import Client from time import sleep global_client = Client("secret", "secret") def send_text_message(text): to_phone = "+11DigitPhoneToText" from_phone = "+11DigitPhoneTextFrom" global_client.messages.crea...
import cv2 from PIL import Image, ImageFont, ImageDraw import os import numpy as np from matplotlib import pyplot as plt from keras import layers from keras import models from keras import optimizers from keras.utils import plot_model from keras import backend path = os.path.dirname(os.path.realpath(__file__)) + "/...
#!/usr/bin/env python3 # ROS stuff import rospy from nav_msgs.msg import Odometry from geometry_msgs.msg import Point, Twist from sensor_msgs.msg import LaserScan # other useful math tools from tf.transformations import euler_from_quaternion from math import atan2, sqrt import math # angle and distant difference co...
# -*- coding:utf-8 -*- # @Time : 2019/5/5 19:57 # @Author: xiaoxiao # @File : regulax.py import re from common.config import config import configparser from common.my_logger import Logger log=Logger(__name__) class Regulax: mobilephone=None def regulax(data,p="#(.*?)#"): while re.search(p,data): res...
import csv import datetime def convert_str_to_datetime(datetime_str): """ Конвертирует строку с датой в формате 11/10/2019 14:05 в объект datetime. """ return datetime.datetime.strptime(datetime_str, "%d/%m/%Y %H:%M") def convert_datetime_to_str(datetime_obj): """ Конвертирует строку с датой...
#!/usr/bin/env python # ---------------------------------------------------------------------------- # Copyright 2014 Nervana Systems Inc. # 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 # # ...
import re import os import pystache from . import utils class Renderer: def __init__(self): self.mustacher = pystache.Renderer() def _process_file(self, tree, file, properties): new_content = self.mustacher.render_path(file, properties) with open(file, 'w') as file_hd: f...
if __name__ == '__main__': n = int(input()) integer_map = map(int, input().split()) tp = tuple(list([int(x) for x in integer_map])) #print(tp) print(hash(tp))
import numpy n,m = map(int,input().split()) arr = numpy.zeros((n,m),int) for i in range(n): arr[i] = numpy.array(input().split(),int) print(numpy.prod(numpy.sum(arr, axis = 0)))
import os from orun.core.management.base import BaseCommand, CommandError from orun.apps import apps from orun.core.management import commands from orun.db import transaction, DEFAULT_DB_ALIAS class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument( 'schema', nargs='1...
import math x = -49 if ( x < 16 ): result = x ** 5 - 68 * x ** 7 + 46 elif ( 16 <= x < 109 ): result = math.log(math.e, math.cos(x) - 93 * x - 71) + x ** 5 elif ( 109 <= x <= 151 ): result = 88 * x ** 8 + x - 60 elif ( x >= 151 ): result = 19 * (math.fabs(x) + math.cos(x)) ** 4 - math.fabs(x) print(f...
#!/usr/bin/env python # -*- coding: utf-8 -*- # ResoucesPrj.py # Author: gfcocos # python_tool install # 安装方法 # 1. install Gow-0.8.0.exe # 2. install python3.msi # 3. double click ./install/install_python_tool.py import os,sys bash_cmd = { 'find_python_path' : 'which python.exe', 'copy_to_site_packa...
class AutoAttributes: attrs = () def __init__(self, **kwargs): """Método construtor genérico""" for attr in self.attrs: if attr in kwargs: setattr(attr, kwargs[attr]) def __repr__(self): body = [f"{attr}={getattr(self, attr, None)}" for attr in self.__table__.columns] return f"{self.__class__._...
#! /usr/bin/env python3 ''' sensu 2.0 api calls requires python3 - validate json for asset definitions and check defintions - sync asset and check definitions to API - sync actual asset files to server ''' import json import requests from urllib import parse from hinoki.logger import log from hinoki.config import ...
''' Created on 30-May-2012 @author: NANDU ''' from initialise import screen from pygame import image from math import ceil from random import random, randrange class BALL: def __init__(self,x=0,y=0): self.pic = image.load('images/ball.png') self.width = self.pic.get_width() self.heig...
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def deleteDuplicates(self, head): """ :type head: ListNode :rtype: ListNode """ if head == None: return None dum...
# Generated by Django 3.0.8 on 2020-07-17 14:00 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('profiles', '0007_guides_...
import datetime import enum import flask_sqlalchemy db = flask_sqlalchemy.SQLAlchemy() class ModelMixin(object): id = db.Column(db.Integer, primary_key=True) created_at = db.Column(db.DateTime, default=datetime.datetime.utcnow) updated_at = db.Column(db.DateTime, onupdate=datetime.datetime.utcnow) cla...
# [ EXPRESSION for Sign in List if CONDITION] list1 = [ x * 2 for x in range(0,5)] print(list1) list2 = [ x for x in range(0,10) if x % 2 == 0] print(list2) c=[(1,2),(3,4),(5,6)] list3 = [ i for i,j in c] print(list3) list4 = [[i*2, j*3, i+j] for i,j in c] print(list4)
################################################################## # FILE : hangman.py # WRITER : Lior Paz, lioraryepaz, 206240996 # EXERCISE : intro2cs ex4 2017-2018 # DESCRIPTION : hangman game - with a large scale of optional words, # max errors of 6, and... a special option of hints!!!. ######################...
import psycopg2 #define postgre db config hostname = 'localhost' username = 'postgres' password = 'nicetry' database = 'GenomeData' port = 5432 msg = ("Connecting to database: host: {}, port: {}, dbname: {}").format(hostname, port, database) print (msg) #Provides a connection to postgre server. Used throughout the pro...
from app_service.service_helper.error_deal import ErrorDeal from app_service.service_helper.code_deal.equipment_list import EquipmentList code_map = { 'error': ErrorDeal.deal_with, '1': EquipmentList.deal_with, }
import numpy as np import os from tqdm import tqdm if not os.path.exists('./Train'): os.makedirs('./Train') if not os.path.exists('./Train_annot'): os.makedirs('./Train_annot') cell_len = 80 cell_wid = 45 cell_ht = 45 max_ldc_x = 1 max_ldc_y =1 def getStabilityScore(i, j , ldc, dimn, currldc_x, currldc_y):...
import os import json from multiprocessing import Pool import billboard import datetime from PyLyrics import PyLyrics from yt import get_stats def get_data(params): artist, title, rank, year = params print("Fetching data for {}:{}".format(rank,title)) data = { 'artist': artist, 'title': t...
class Solution: def totalNQueens(self, n): """ :type n: int :rtype: int """ def dfs(queens, t45, t135): if len(queens) == n: result.append(queens) return for i in range(n): j = len(queens) ...
class Solution: def nextPermutation(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ if len(nums) <= 1: pass else: do_it = False for i in range(len(nums) - 2, -1, -1): ...
# Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def maxDepth(self, root): """ :type root: TreeNode :rtype: int """ def find(root, path): ...
from twisted.internet import reactor, defer def multiplyByThree(x): d = defer.Deferred() reactor.callLater(2, d.callback, x * 3) return d def printData(d): print(d) d = multiplyByThree(3) d.addCallback(printData) # manually set up the end of the process by asking the reactor to # stop itself in...
import turtle import sys #sys.setExecutionLimit(1500000) def seq3np1(n): """ Print the 3n+1 sequence from n, terminating when it reaches 1.""" count = 0 while n != 1: # print(n) count += 1 if n % 2 == 0: # n is even n = n // 2 else: # n is odd ...
#!/usr/bin/python3 """Provides a function to create an object from a JSON string""" import json def from_json_string(my_str): """Create an object from a JSON string""" return json.loads(my_str)
# -*- coding: utf-8 -*- # Generated by Django 1.9.8 on 2016-07-19 01:54 from __future__ import unicode_literals import datetime import django.core.validators from django.db import migrations, models from django.utils.timezone import utc class Migration(migrations.Migration): dependencies = [ ('webapp', ...
from nested_inline.admin import NestedModelAdmin class CustomNestedModelAdmin(NestedModelAdmin): def add_nested_inline_formsets(self, request, inline, formset, depth=0): if depth > 5: raise Exception("Maximum nesting depth reached (5)") for form in formset.forms: nested_form...
# from os import getcwd # print(getcwd()) from collections import Counter import re with open('zbior_zadan/69_geny/dane_geny.txt') as file: genes = [gen for gen in file.read().split()] # 69.1 species = [] for element in genes: species.append(len(element)) print("69.1\nliczba wszystkich gatunkow: {}\nnajwiecej oso...
from dataclasses import dataclass from math import pi from rlbot.utils.game_state_util import GameState, BallState, CarState, Physics, Vector3, Rotator, GameInfoState from rlbottraining.common_exercises.common_base_exercises import GoalieExercise from rlbottraining.rng import SeededRandomNumberGenerator from rlbottra...
produtos = ('Caderno', 11.5, 'Borracha', 0.56, 'Régua', 5.99, 'Lápis', 1.5, 'Adesivo', 99.5) print('-' * 30) print(f'{"LISTAGEM DE PREÇOS":^30}') print('-' * 30) for i, produto in enumerate(produtos): if i % 2 == 0: print(f'{produto:.<20}:', end=' ') else: print(f'R$ {produto:>5.2f}') print('...
from clean import data,pd,np,names print("Running pre.py\n") print("The Data Has 8 Features along with an Index Column(1st Column) : ") print(names) row,columns=np.shape(data) print("\nThe size of each Feature in the Data is : ",row) d_allc=data.iloc[:,8:9] d_allc=np.ravel(d_allc) y=[];c=0;z=[];t=0;tar=0 whi...
# Generated by Django 2.1 on 2018-08-20 08:05 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('users', '0002_auto_20171227_2246'), ] operations = [ migrations.CreateModel( name='Attendance', fields=[ ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # ============================================================================= # Created By : Krikor Herlopian # Created Date: Wed May 12 2021 # Email Address: kherl1@unh.newhaven.edu # ============================================================================= d=dic...
from gui.Gui import MyWindow from PyQt5 import QtWidgets import sys import preprocesamiento import libreria as lib from excepciones import BadQuery, WrongInput, MovieError class T03Window(MyWindow): def __init__(self): super().__init__() def process_query(self, queries): # Agrega en pantalla ...
import json import pandas as pd def loadLabels(): test = pd.read_csv('./data/Alsafari_2020/AH-Test.csv',sep=",", encoding="utf-8", dtype={'iD': object}) train = pd.read_csv('./data/Alsafari_2020/AH-Train.csv',sep=",", encoding="utf-8", dtype={'iD': object}) return pd.concat([train, test]) def loadTexts():...
""" This is the people module and supports all the REST actions for the people data """ from flask import abort from config import db from models import InvoiceModel, InvoiceInvoiceItemModel from schemas import Invoice_Schema def get_all(): invoices = InvoiceModel.query.all() invoices_schema = Invoice_Schem...
""" Main application file DO NOT TOUCH/EDIT """ from flask import Flask from config import Config from routes import handler from models import db def create_app(config): # Initializes flask object with config app = Flask( Config.APP_NAME, template_folder=Config.TEMPLATE_FOLDER, sta...
acumulador = 0 numero = -1 while numero != 0: numero = int(input("Digite um número: ")) acumulador = acumulador + numero print("A soma de todos os números recebidos é: ", acumulador)
from django.contrib.auth.models import User from .models import Article, Like, Comment from rest_framework import serializers class ArticleSerializer(serializers.ModelSerializer): class Meta: model = Article fields = ('author', 'publication_date', 'headline', 'content', 'published') class LikeSer...
import os, sys stext = '<joint name="double_stereo_frame_joint" type="fixed">' rtext = '<joint name="openni_rgb_frame_joint" type="fixed">\n\ <origin rpy="0.0074253744 0.0418016634 -0.0065419807" xyz="0.0440562178 -0.0135760086 0.1129906398"/>\n\ <parent link="head_plate_frame"/>\n\ <child link="openni_rg...
# Generated by Django 3.0.3 on 2020-02-11 11:37 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Caption', fields=[ ('id', models.AutoField(...
N, M = input().split(' ') N, M = [int(N), int(M)] six = 987654321 one = 987654321 ans = 987654321 for i in range(M): a, b = input().split(' ') a, b = [int(a), int(b)] six = min(six, a) one = min(one, b) ans = min(ans, N*one) ans = min(ans, (N//6 + 1)*six) ans = min(ans, (N//6)*six + (N%6)*one) print ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import decoratucasa.models class Migration(migrations.Migration): dependencies = [ ('decoratucasa', '0002_auto_20141120_0233'), ] operations = [ migrations.CreateModel( n...
import falcon from sdnms_api.resources.base_resource import BaseResource class HealthResource(BaseResource): def on_get(self, req, resp): resp.status = falcon.HTTP_200 resp.body = ('{"result":"OK"}')
import json import os.path from typing import cast SUSPICIOUS_KEYWORDS: dict[str, int] = { "login": 25, "log-in": 25, "sign-in": 25, "signin": 25, "account": 25, "verification": 25, "verify": 25, "webscr": 25, "password": 25, "credential": 25, "support": 25, "activity": ...
import tensorflow as tf import numpy as np # 创建一个常量 m1 = tf.constant([[3,3]]) m2 = tf.constant([[2],[2]]) # 创建一个矩阵常量 product = tf.matmul(m1,m2) print(product) # 定义一个会话,启动默认图 ss = tf.Session() # 调用session的run方法执行矩阵乘法 result = ss.run(product) print(result) ss.close() # 需要手动关闭 with tf.Session() as sess: result = ses...
import csv from furl import furl BASE_URL = 'https://imdb.com/title' def getMovieLinkMap(linkFilename, movieFilename): movieLinkMap = {} with open(linkFilename) as csvf: reader = csv.DictReader(csvf) for row in reader: imdbId = row['imdbId'] f = furl(BASE_URL) ...
import requests from bs4 import BeautifulSoup def extract_news(soup): """ Extract news from a given web page """ news_list = [] try: table = soup.table.findAll('table')[1] except AttributeError: return for i in range(0, 89, 3): try: tr0 = table.findAll('tr')[i...
############################# #파이썬 기본 - 반복문 ############################# print('='*100) a = [1,2,3,4,5] for num in a: print ( num ) a = [(1,2), (3,4), (5,6)] for i,j in a: print( i, j ) a = range( 1, 10 ) print ( a ) # range(x,y) => x <= n <y for num in range( 1, 10 ): print (num) # 3~7단까지 구구단 ( 3 X...
from ED6ScenarioHelper import * def main(): # 格兰赛尔 CreateScenaFile( FileName = 'C4111 ._SN', MapName = 'Grancel', Location = 'C4111.x', MapIndex = 1, MapDefaultBGM = "ed60089", Flags = 0, ...
# range(10) # print(range(10)) # print(range(2, 20, 3)) for i in range(0, 10, 1): print(i, end=' ') print() for i in range(10): print(i, end=' ') print() for i in range(3, 10): print(i, end=' ') print() for i in range(2, 20, 2): print(i, end=' ') print() for i in range(10, 1, -1): print(i, end=...
import numpy as np import cv2 import datetime face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_alt.xml') # face_cascade = cv2.CascadeClassifier('haarcascade_profileface.xml') # eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml') #cap = cv2.VideoCapture(0) cap = cv2.VideoCapture("/root/Desktop/xxx....
# Generated by Django 2.2.1 on 2019-06-09 12:10 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('accounts', '0002_phoneotp'), ] operations = [ migrations.AddField( model_name='phoneotp', name='validated', ...
from rest_framework import views from rest_framework.response import Response from django import http from django.conf import settings from django.shortcuts import get_object_or_404 from django.views.decorators.http import require_GET from django.views.generic.base import RedirectView from share.models import Source ...
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the...
from sklearn.externals import joblib from cfepm.util.io_utils import read_dataset from cfepm.pipeline import Row2BeanConverter model = joblib.load('testpipe.pkl') df = read_dataset('ebay_52K_raw_balanced.csv') bean_tuples = Row2BeanConverter().transform(df) print(model) print(model.transform(bean_tuples))
#!/usr/bin/python # -*- coding: utf-8 -*- ## # this script serves to do the dirty cleaning work for # users' tweets. # # @author Yuan JIN # @contact chengdujin@gmail.com # @since 2012.03.06 # @latest 2012.03.08 # # reload the script encoding import sys reload(sys) sys.setdefaultencoding('UTF-8') # CONSTANTS # Datab...
import os import urllib import re from WMCore.Database.CMSCouch import CouchServer from WMCore.Configuration import loadConfigurationFile class CouchDBConnectionBase(object): def __init__(self, couchConfig): self.couchURL = couchConfig.couchURL self.acdcDB = couchConfig.acdcDBName self.jo...
#! usr/bin/python3 def climbStairs(n: int) -> int: ans = 0 for x in range(n+1): for y in range(n//2 + 1): if x+2*y == n: ans += cmbt(x, y) return ans def climbStairs1(n: int) -> int: dp = [1, 1, 2] if n < len(dp): return dp[n] else:...
#!usr/bin/env import rospy import time import math import tf import roslib def brodcaster(x,y,z,w): rospy.init_node('frame_a_to_frame_b_brodcaster_node',anonymous=False) time.sleep(0.5) bc=tf.TransformBroadcaster() while not rospy.is_shutdown(): # we need to brodcast translation,rotation and ti...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.test import TestCase from django.contrib.auth.models import User from .models import Brand, Person, Location, Data class DataTestCase(TestCase): def create_brand(self): return Brand(name='Sprite', company='Coca Cola', description...
# To change this license header, choose License Headers in Project Properties. # To change this template file, choose Tools | Templates # and open the template in the editor. __author__="Brandon" __date__ ="$Sep 30, 2014 1:11:17 PM$" import replaceQueries if __name__ == "__main__": replaceQueries.main()
import pexpect import pytest @pytest.mark.parametrize("src", [ "aliyun", "douban", "edu", ]) def test_pipsrc(src): child = pexpect.spawn("bash") child.sendline(f"pipsrc {src}") child.expect(f".*{src}*.*") child.sendline("pip install pip") child.expect(f".*indexes.*{src}*.*")
from django.forms import ModelForm from .models import Developer, User, Project class ProjectForm(ModelForm): class Meta: model = Project fields = ['project_name', 'project_overview', 'languages'] class DeveloperForm(ModelForm): class Meta: model = Developer fields = ('name', '...
from django.shortcuts import render, redirect, get_object_or_404 from django.urls import reverse from order.forms import OrderForm import json from afriventapp.models import Event, EventTicket, UserProfile from order.models import Order, OrderItem from django.http import JsonResponse from python_paystack.objects.transa...
import requests import time import json from hatebase_credentials import api_key auth_path = "https://api.hatebase.org/4-4/authenticate" query_path = "https://api.hatebase.org/4-4/get_vocabulary" #establish api connection and get token r_auth = requests.post(auth_path, data = {'api_key': api_key}) assert ...