text
stringlengths
38
1.54M
#! /usr/bin/python3 import time import iota.harness.api as api import iota.protos.pygen.topo_svc_pb2 as topo_svc_pb2 import iota.test.iris.testcases.penctl.penctldefs as penctldefs import iota.test.iris.testcases.penctl.common as common def Setup(tc): tc.Nodes = api.GetNaplesHostnames() tc.venice_ips = [["1.1....
#!/usr/bin/env python3 import util import time class DeviceInfo: ''' Class representing the contents of the IDXH section ''' def __init__(self, data, sectionName): self.data = data self.dataSize = len(data) self.sectionName = sectionName # 1st 32-bit (LE) int self.device = None # 2nd 32-bit (LE) int...
#import pandas as pd import matplotlib.pyplot as plt from datetime import datetime, timedelta X= ["KERELA","MAHARASHTRA","TAMIL NADU","J&K", "UP","KARNATAKA","BIHAR","RAJASTHAN","PUNJAB","GUJURAT","AP","ASSAM","TELENGANA","WEST BENGAL","GOA","MP","ODISHA","JHARKHAND","HARYANA","MANIPUR","CHATTISHGARH","UTTARAKHAND","H...
# -*- coding: utf-8 -*- from dp_tornado.engine.helper import Helper as dpHelper from dp_tornado.engine.handler import Handler as dpHandler class SessionHelper(dpHelper): def key(self, identifier): return 'session_%s' % (identifier.replace('-', '_')) def is_authorized(self, controller, identifier): ...
import requests import json def getIPCity(ip): url="http://ip-api.com/json/"+ip res=requests.get(url) resStr = res.text jsonStr = json.loads(resStr) IPCity = jsonStr["country"]+"/"+jsonStr["regionName"]+"/"+jsonStr["city"] # for ["MACAO","TAIWAN","HONG KONG"] country should be "CHINA" if...
import sqlite3 from flask_restful import Resource , reqparse class User: def __init__(self , _id , username , password): self.id = _id self.username = username self.password = password @classmethod def find_by_username(cls , username): connection = sqlite3.connect(...
#!/usr/bin/env python #Allow for commandline arguments import sys #define the commandline arguments to a variable FilesToRead = sys.argv #remove program name,starting at value 1 listoffiles = FilesToRead[1:] print(listoffiles) number = 13 #for files in command line open each file and read the firstline for files in l...
import utils import requests import json import pymysql import traceback from datetime import datetime from pandas.io.json import json_normalize from sqlalchemy import create_engine import pandas as pd f=open(r"weatherload.json", "r") out = f.read() f.close() tmp = json.dumps(out) tmp = json.loads(out) num = len(tmp) ...
import scrapy from scrapy.selector import Selector import re from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor as selink from scrapy.contrib.spiders import CrawlSpider,Rule from huxiuspider.items import BookItem class BookSpider(CrawlSpider): name = "books" allow_domains = ["huxiu.com"] start_urls ...
# -*- coding: utf-8 -*- """ Created on Sun Apr 8 02:20:41 2018 @author: Hager - Lab """ from prepareLearning import prepare from GenderModule.genderExtract import GenderDetect from AgeModule.AgeExtract import AgeDetect from EmotionModule.EmotionExtract import EmotionDetect from TextRecognation.TextRecognati...
# -*- coding: utf-8 -*- """ Importance nested sampler. """ import datetime import logging import os from typing import Any, List, Literal, Optional, Union import matplotlib import matplotlib.pyplot as plt import numpy as np from scipy.special import logsumexp from .base import BaseNestedSampler from .. import config ...
def search(item,loof) : t1 = item i = loof result = 0 for k in range(i,0,-1) : temp = t1//10**k for p in range(1,temp) : result += p*10**k result += temp*(t1%10**k+1) #print(result) result += k*(t1//10**k) * (10**(k-1))*45 #print(k,k*t1//10**k ...
import unittest import unittest.mock as mock import json import math import sys sys.path.append('.') from sunlight.sunlight_calculator import SunlightCalculator class SunlightCalculatorTest(unittest.TestCase): def setUp(self): self.calculator = SunlightCalculator() self.s = """[ {"neighborhood":"N1", "apa...
from orm import ORM from computer import Computer class User(ORM): tablename = "users" fields = ["name", "phone", "email", "credit_card"] def __init__(self, **kwargs): self.pk = kwargs.get('pk') self.name = kwargs.get('name') self.phone = kwargs.get('phone') self.email = ...
from django.db import models class Kouka2(models.Model): product = models.CharField(max_length=1000) area = models.CharField(max_length=1000) delivery = models.CharField(max_length=1000) price = models.IntegerField(default=0) attachment = models.CharField(max_length=1000) def __str__(self): ...
from threading import Thread from time import sleep import pygame import pygame.gfxdraw class Game(object): def __init__(self): self.__canvas = None self.__model = None self.__running = False self.__surface = pygame.Surface((400, 400), pygame.SRCALPHA, 32) def get_surface(...
# -*- coding: utf-8 -*- """The compressed stream file entry implementation.""" from dfvfs.lib import definitions from dfvfs.lib import errors from dfvfs.vfs import root_only_file_entry from dfvfs.vfs import vfs_stat class CompressedStreamFileEntry(root_only_file_entry.RootOnlyFileEntry): """Class that implements a...
import sqlite3 connection = sqlite3.connect("tresor_sql.db") # create database cursor = connection.cursor() # set cursor # create database with uniqueID, user or email, password, storage, creation date sql_command = """ CREATE TABLE entries ( unique_id INTEGER PRIMARY KEY, user_email VARCHAR(50), password VARCHA...
def get_alipay_user(): url = "https://openauth.alipaydev.com/oauth2/publicAppAuthorize.htm?app_id=2016091700530193&scope=auth_user&redirect_uri=http://neverqaz.cn/ali_login/" return url
#Under MIT License, see LICENSE.txt import unittest from ai.STP.Play.pQueueLeuLeu import * class TestPQueueLeuLeu(unittest.TestCase): def setUp(self): self.pTestQueueLeuLeu = pQueueLeuLeu() def test_getTactics_with_no_args(self): self.assertEqual(SEQUENCE_QUEUELEULEU, self.pTestQueueLeuLeu.getTactics()) ...
""" Contains the non-database models for our app. Purpose: contains the models for unsaved data and read-only data in json format Author: Tom W. Hartung Date: Winter, 2017. Copyright: (c) 2017 Tom W. Hartung, Groja.com, and JooMoo Websites LLC. Reference: (none, yet) """ import json import os from django.contrib im...
# coding: utf-8 import os, json, random, nltk import pandas as pd import numpy as np import matplotlib.pyplot as plt np.random.seed(0) random.seed(0) misinfo = { # Snopes verdicts. "unproven", "unconfirmed", "undetermined", "probably", "maybe", "mixture", "incomplete", "partly", "outdate", "legend",...
import numpy as np import matplotlib.pyplot as plt import sys """ Top-5 accuracy Trained the database with original dataset, query with rotated from all 3 axes. """ # With all rotated # Class : new_partial_exp/rot-z-y-x-Brackets_slices4_fanout10_minsig5.txt # Total queries : 52 # Accuracy (naive) ...
"""Implementation of InvertedPendulum System.""" from .ode_system import ODESystem import numpy as np from scipy import signal from .linear_system import LinearSystem import os from gym.envs.classic_control import rendering class InvertedPendulum(ODESystem): """Inverted Pendulum system. Parameters ----...
import pytest from app import create_app, db from app.models import Host """ These tests are for testing the db model classes outside of the api. """ @pytest.fixture def app(): """ Temporarily rename the host table while the tests run. This is done to make dropping the table at the end of the tests a b...
from youtube_searcher import extract_videos import pafy class EuroNewsLiveStream: lang2url = { "en": "https://www.youtube.com/user/Euronews", "ru": "https://www.youtube.com/user/euronewsru", "pt": "https://www.youtube.com/user/euronewspt", "it": "https://www.youtube.com/user/eurone...
import urllib.request import csv from bs4 import BeautifulSoup BASE_URL = "http://www.nfl.com/teams/roster?team=" teams = ["NE", "BUF", "NYJ", "MIA", "BAL", "CLE", "PIT", "CIN", "IND", "HOU", "JAX", "TEN", "KC", "OAK", "DEN", "LAC", "DAL", "PHI", "NYG", "WAS", "GB", "MIN", "CHI", "DET", "NO", "CAR", "TB", "ATL", "SF...
"""Custom exceptions used by Annif""" from click import ClickException class AnnifException(ClickException): """Base Annif exception. We define this as a subclass of ClickException so that the CLI can automatically handle exceptions. This exception cannot be instantiated directly - subclasses should be ...
from utils import * from sklearn.ensemble import RandomForestClassifier, ExtraTreesClassifier, AdaBoostClassifier, GradientBoostingClassifier from sklearn.metrics import log_loss from sklearn.cross_validation import cross_val_score, StratifiedKFold train_features, train_labels, test_features, ids, outfile = read_data...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright European Organization for Nuclear Research (CERN) since 2012 # # 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.apach...
#!/usr/bin/env python3 """PWM Led using RPi.GPIO.""" import RPi.GPIO as GPIO import time import sys def do_led_things(pin_led): # setup pin mode GPIO.setup(pin_led, GPIO.OUT) # setup pwm signal pwm = GPIO.PWM(pin_led, 50) pwm.start(0) try: while True: for dc in range(0, ...
from flask import Flask, render_template, request, url_for, jsonify from numpy import matrix from math import * # globals() returns a dictionary of globals variables. You can create a new variable by simply writing globals()['a'] = 1, and that would lead to creation of a variable a = 1 globals()['ans'] = 0 # Default ...
import twitter import time from xml.sax.saxutils import unescape ''' Basic twitter corpuss script that gather tweets based on smileys and tags them correspondely to negative and positive and put them in our corpus so they can later be used by our machine learning algorithm ''' CORPUS="corpusnew3" api=twitter.Api(...
from playwright.sync_api import sync_playwright with sync_playwright() as p: browser = p.chromium.launch(headless=False, proxy={ 'server': 'http://127.0.0.1:7890' }) page = browser.new_page() page.goto('https://httpbin.org/get') print(page.content()) browser.close()
#!/usr/bin/env python import rospy from std_msgs.msg import Header from sensor_msgs.msg import PointCloud,ChannelFloat32 from geometry_msgs.msg import Point32 import random def generate_simulated_points(stage): x_mod, y_mod, z_mod = 0,0,0 if stage == 'A': x_mod, y_mod, z_mod = 85,0,-10 elif stage ...
# Flow control ############################################################################################## # if / else mood = input("How are you felling today? >> ") """ if mood == "happy": print("It is great to see you happy!") else: print("Cheer up, mate!") """ if mood == "happy": print("It is great ...
x = input().split() x = sorted(x) y = "yes" for i in range(1,len(x)): if(x[i] == x[i - 1]): y = "no" break print(y)
#To reverse any inputted number using python number=int(input("Enter the number:\n")) reverse=0 while(number>0): digit=number%10 reverse=reverse*10+digit number=number//10 print("The number when reversed is:",reverse)
import numpy as np import scipy.io as sio from sklearn.feature_selection import VarianceThreshold as VarThresh # for feature selection i have a few ideas. 1) run feature selection over the whole matrix of features. #2) remove some of the recordings and do it a few times (so manually k-folding), because that way if the...
# Generated by Django 2.1 on 2018-08-07 09:56 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('mpcontroller', '0007_auto_20180807_0902'), ] operations = [ migrations.RenameField( model_name='muse_device', old_name='MAC_ad...
import contextlib import random import socket import warnings import eventlet from eventlet import greenio from eventlet.green import socket try: from eventlet.green import ssl except ImportError: __test__ = False import six import tests def listen_ssl_socket(address=('localhost', 0), **kwargs): sock = s...
import sys import winreg from argparse import ArgumentParser def search(needle): found = False with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Installer\\UserData", access=winreg.KEY_READ | winreg.KEY_WOW64_64KEY) as userDataParentHandle: for userDataIndex...
input = """ a(2). b(1,3). e(2). s(1). c(X) :- not a(X), not e(Y), b(X,Y), not #count{V:s(V)} = 1. """ output = """ {a(2), b(1,3), e(2), s(1)} """
#!/usr/bin/env python from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer import json from io import open from training import preprocessing from keras.models import Model, load_model from keras.layers import merge, concatenate, multiply from keras import backend as K from training import constants from train...
# 3_7 # number of islands def deleteIsland(grid, i, j): grid[i][j] = "0" if i - 1 >= 0 and grid[i-1][j] == "1": deleteIsland(grid, i-1, j) if i + 1 < len(grid) and grid[i+1][j] == "1": deleteIsland(grid, i+1, j) if j - 1 >= 0 and grid[i][j-1] == "1": deleteIsland(grid, i, j-1) if j + 1 < len(grid[0]) and...
""" Classes.py that contains different classes and methods for model.py for the labyrinth's game Class : Labyrinth, Item, Character Ludovic GROS """ import pygame import random from pygame.locals import * from constant import * class Labyrinth: def __init__(self, file): self.file = file self.str...
class RhinoObjectSelectionEventArgs(EventArgs): # no doc Document=property(lambda self: object(),lambda self,v: None,lambda self: None) """Get: Document(self: RhinoObjectSelectionEventArgs) -> RhinoDoc """ RhinoObjects=property(lambda self: object(),lambda self,v: None,lambda self: None) """Get: Rhin...
def letter_found(letter, secret_word, gamer_word): for idx, symbol in enumerate(secret_word): # print(idx, symbol) if symbol == letter: gamer_word[idx] = symbol.upper() return gamer_word
import os import sys path = os.getcwd()+"/dont_remove/" primaryContents = os.listdir(path) for i in primaryContents: if(os.path.isdir(path+i)): imageList = os.listdir(path+i+"/.image/") for image in imageList: os.popen('cp ' + path+i+"/.image/"+image+" " + os.get...
import matplotlib.pyplot as plt import numpy as np import scipy.special as sp #Create a plot of \theta vs L(\theta) step = 0.01 theta_0 = 0 theta_end = 1 def likelyhood(theta,success,total): binomial = sp.binom(total,success) failure = total - success return (theta)**success * (1-theta)**failure def p...
import logging from abc import ABC from autoconf import conf from autofit.mapper.prior_model.collection import CollectionPriorModel from autofit.non_linear.analysis.multiprocessing import AnalysisPool from autofit.non_linear.paths.abstract import AbstractPaths from autofit.non_linear.result import Result from autofit....
from rest_framework import serializers from .models import FoodItem class FoodItemSerializer(serializers.ModelSerializer): class Meta: model = FoodItem fields = ('name', 'sd', 'group', 'cf', 'ff', 'pf', 'ru')
print("This is just a small survey before login") print(input("Did you donate the blood before?")) print(input("Are you ready to donate the blood in future?")) print("Donate blood save lives") a= int(input(print(" Enter your profile:\n 1. Admin \n 2. User\n "))) if a==1: print('Admin\n') b=int(input('Please check t...
########################################################################## # # Copyright (c) 2010, Image Engine Design Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistribu...
import os import tushare as ts import requests.exceptions import pandas as pd from conf.conf import get_conf from conf.log import server_logger def get_stocks(): try: ts.set_token(get_conf("tushare_token")) pro = ts.pro_api() data = pro.query('stock_basic', exchange='', list_status='L', fi...
# Variables # https://www.youtube.com/watch?v=BJ-VvGyQxho class Employee: raise_amount = 1.04 num_of_emps = 0 # Counting employees. This is constant for all instances def __init__(self, first, last, pay): # Instance is passed always self.first = first self.last = last self.pay =...
#!/usr/bin/env python from peyotl.api import APIWrapper ps = APIWrapper().phylesystem_api studies = ps.get_study_list() print(studies[0]) blob = ps.get(studies[0]) nexson = blob['data']['nexml'] print(nexson['^ot:studyId'], ':', nexson['^ot:studyPublicationReference'])
import os data_path = '/run/media/ashbylepoc/b79b0a3e-a5b9-41ed-987f-8fa4bdb6b2e6/tmp/data/nlp_dev_2/' train_y = os.path.join(data_path, 'train.y') train_en = os.path.join(data_path, 'train.en') train_fr = os.path.join(data_path, 'train.fr') lexicon = os.path.join(data_path, 'lexique.en-fr') lines_train_y = open(trai...
from PyPDF2 import PdfFileMerger filelist = ["Yakisoba.pdf","Teriyaki.pdf"] merger = PdfFileMerger() for fh in filelist: #just put files in order print(fh) merger.append(fh) output = open("./joined.pdf","wb") merger.write(output) """ merger = PdfFileMerger() merger.append("Yakisoba.pdf") merger.a...
# Applying Linear Regression to an imaginary example # The example is the relation between page speed and amount purchased of an online shop # The idea is to show that the faster the page loads, the more are people spending # Or, in other words, displaying the correlation between page speed and amount purchased # Inte...
import numpy as np import RPi.GPIO as GPIO GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) BlueLED = 21 Hexa = 20 GPIO.setup(BlueLED, GPIO.OUT) GPIO.setup(Hexa, GPIO.OUT) toggling = True while toggling == True: user_input = input() if user_input == 'Hexagon': GPIO.output(Hexa, 1) elif user_input ...
def magicSquare(matrix): N=len(matrix) M=len(matrix[0]) maxD=1 for i in range(N-1): for j in range(M-1): print() print("start point is: ",matrix[i][j]) isMagic=True d=2 while i+(d-1)<=N-1 and j+(d-1)<=M-1: print("dimensi...
import socket host = "localhost" server_port = 2333 port = 6666 server = (host, server_port) s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.bind((host, port)) transport = raw_input("Input your data to server->\t") while 1: s.sendto(transport, server) if transport == "exit": break data,addr = s.recvfrom...
import sys, os, io, time, base64 from datetime import datetime platform = sys.platform if platform == 'win32': import win32gui, win32console, win32clipboard from PIL import ImageGrab cbData= ' ' #global clipboard data flePath= 'help.jpg' #output file slpDur = 3 #how often to check clipboard imgQly = ...
""" Import sample data for E-Commerce Recommendation Engine Template """ import predictionio import argparse import random SEED = 3 def import_events(client): random.seed(SEED) count = 0 print(client.get_status()) print("Importing data...") # generate 10 users, with user ids u1,u2,....,u10 user_ids = ["...
from django.apps import AppConfig class CongressopaisAppConfig(AppConfig): name = 'congressoPais_app'
#Base code from: https://heartbeat.fritz.ai/real-time-object-detection-on-raspberry-pi-using-opencv-dnn-98827255fa60 import cv2 import time import numpy as np from intersectionOld import * from imutils import object_detection import pdb import os import serial # Pretrained classes in the model classNames = {0: 'bac...
#coding=utf-8 from collective.constants import AbstractConstant class TicketsStates(AbstractConstant): def __init__(self): super(TicketsStates, self).__init__() self.set_ids({ 'open': 0, 'closed': 1, }) def open(self): return self.ids['open'] def closed(self): return self.ids['closed'] TICKET...
from flask import Flask app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://tara:mypassword@localhost/todoapp' from views import * if __name__ == '__main__': app.run()
############# Final Project ############## ###### Authors: ###### # import os import pandas as pd import numpy as np from datetime import date import random import statsmodels.api as sm import cvxopt as opt from cvxopt import matrix from cvxopt impo...
# Advent of Code 2019: https://adventofcode.com/2019/day/11 # # from AoC13_classes import ArcadeCabinet infile = open('data/input_13.txt','r') inputData1 = infile.readline().strip().split(',') # Part 1 e = ArcadeCabinet(inputData1) e.RunGame() # e.PlotPanels() print("Part 1: ", e.NumberOfBlocks()) # Part 2 # res...
from sys import argv script, filename = argv txt = open(filename) print "Here's your file %r:" % filename print txt.read() print "Press y to close the file or N to keep open" x = raw_input("") if x == "y": txt.close() elif x == "n": txt.read() print "Lets open a second file:" file_again = raw_input ("> ") txt...
""" This is the ADT for Queue data structure that can be used Assumption : Rear end of the queue is at index 0 and front is at the end of the list """ class QueueADT: def __init__(self): self.items = [] def isEmpty(self): return len(self.items) == 0 def enqueue(self,item): self.i...
# Generated by Django 2.2.2 on 2019-07-22 08:28 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('post', '0005_auto_20190719_0917'), ] operations = [ migrations.CreateModel( name='Post', fields=[ ('...
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-02-22 10:55 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.Crea...
from django.contrib import admin from django_mongoengine import mongo_admin as mongo # Register your models here. from mongoapp import models mongo.site.register(models.Profile)
from controllers.relations.group_course_relation import group_course_controller from controllers.course.group_project import GroupProjectController from methods.errors import * from flask_restful import Resource, reqparse from flask import jsonify controller = group_course_controller() # /courses/<course_code>/groups...
from collections import defaultdict class Solution: def checkIfPrerequisite(self, n: int, prerequisites: List[List[int]], queries: List[List[int]]) -> List[bool]: graph = defaultdict(set) for pair in prerequisites: graph[pair[1]].add(pair[0]) def bfs(start): visited...
import os from argparse import ArgumentParser from pytorch_lightning import Trainer, seed_everything from models.ComposerVAE import InfoVAE from datasets.collection import * _MODELS = dict(InfoVAE=InfoVAE) _DATASETS = dict(BigMIDI=BigMIDISet, VideoGameMIDI=VideoGameMIDI) distributed = False def mai...
from django import forms from django.forms import ModelForm from ckeditor.widgets import CKEditorWidget from pages.models import Page class PageForm(ModelForm): content = forms.CharField(widget=CKEditorWidget()) class Meta: model = Page
import pandas as pd import numpy as np import tensorflow as tf import tflearn from tflearn.data_utils import to_categorical from collections import Counter reviews = pd.read_csv('reviews.txt', header=None) labels = pd.read_csv('labels.txt', header=None) total_counts = Counter() for idx, row in reviews.iterrows(): ...
#Set is unordered and unindexed . #so we cannot change set values or access values using index. But we can add values """ s={1,21,2,2,"ram","ram"} print("len :",len(s)) print("type :",type(s)) for x in s: print("set :",x) """ #Set constructor """ l=[1,2,3,4,2,"ram",True,30.6] print("list :",l) s=set(l) print("set ...
#! /usr/bin/env python2.6 # $Author: ee364d02 $ # $Date: 2013-10-30 13:18:33 -0400 (Wed, 30 Oct 2013) $ # $HeadURL: svn+ssh://ece364sv@ecegrid-lnx/home/ecegrid/a/ece364sv/svn/F13/students/ee364d02/Prelab11/bitWorker.py $ # $Revision: 62157 $ import os import re import math import sys if len(sys.argv) != 2: sys.stder...
# -*- coding:utf-8 -*- import unittest import mock from ...haystack.utils import HaystackActionTask class HaystackActionTaskTestCase(unittest.TestCase): @mock.patch('libs.haystack.utils.get_indexes') @mock.patch('libs.haystack.utils.get_instance_from_identifier') def test_run_should_call_remove_object_fo...
import sys from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * import paramiko class Window(QWidget): def __init__(self, parent = None): QWidget.__init__(self, parent) self.setGeometry(100,100,256,128) self.loginFrame = QFrame() self.usern...
#to remove duplicate from a list lst=[] n=int(input("enter the number of elements:\n")) for i in range(n): x=input("enter elements:\n") lst.append(x) lst=(dict.fromkeys(lst)) print(lst) lst=list(dict.fromkeys(lst))#this prints in list form print(lst) #print(set(lst)) this prints in the form of set
from django.contrib.auth import authenticate, login, logout from django.core.exceptions import ObjectDoesNotExist from django.http import HttpResponse from django.shortcuts import render, redirect, get_object_or_404 from django.views.generic import ListView from django.views.generic.base import View from django.views.g...
#!/usr/bin/python # encoding: utf-8 """ @author: dong.lu @contact: ludong@cetccity.com @software: PyCharm @file: infer.py @time: 2019/04/9 10:30 @desc: 模型推理部分,分为本地载入模型推理或者tensorflow serving grpc 推理 """ import os import grpc import codecs import pickle import warnings import tensorflow as tf from tensorflow_serving.a...
# -*- coding: utf-8 -*- """ lantz.drivers.example.foreign_example ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Foreign library example. :copyright: 2015 by Lantz Authors, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ import ctypes as ct from lantz import Feat, Action, D...
from typing import Optional, Generic, List, TypeVar from project_name.exceptions import NotFoundInRepository from project_name.storage.database import db from project_name.storage.database.base import CommonQueryBuilderMixin, CommonSerializerMixin from project_name.storage.database.sessions import Session T_ID = Typ...
# python中的元组 和列表类似,不同之处是元组的 元素不能修改 info_tuple = ("zhangsan", 18, 1.75) print(info_tuple[0]) print(info_tuple[1]) print(info_tuple[2]) # 创建空元组 ,一般不建议这么操作,因为一旦元组被定义就不能修改了 empty_tuple = () # 定义一个只包含一个元素的元组 # single_tuple = (5) 这样是不行,解析器会识别为一个整数 single_tuple = (5,) # count 指定元素在元组中出现的次数 print(info_tuple.count(18)) # i...
from django.shortcuts import render, redirect from django.views.generic import CreateView,UpdateView,FormView,DeleteView,DetailView,ListView from django.contrib.auth.decorators import login_required from consultant.models import ( User, PersonalDetails, ...
from .lenet import lenet from .vgg16 import vgg16 from .vgg19 import vgg19 from .alexnet import alexnet from .mobilenet import mobilenet from .full_mobilenet import full_mobilenet from .xception import xception from .resnet50v2 import resnet50v2 from .resnet152v2 import resnet152v2
####################################################################### ## ## CS 101 ## Program #7 ## Name: Harrison Lara ## Email: hrlwwd@mail.umkc.edu ## ## PROBLEM : ## You’ll have 2 files to work with; all_words.csv and total_counts.csv. All words will contain all the words that ## the user can compare wi...
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # --------------------------------------------------------------------...
# -*- coding: utf-8 -*- # Generated by Django 1.9.1 on 2016-08-12 18:29 from __future__ import unicode_literals import django.contrib.postgres.fields.jsonb import django.core.validators from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('annotation', '0023_...
from django.db import models from django.core.validators import MaxValueValidator, MinValueValidator from django.conf import settings from django.contrib.postgres.fields import ArrayField from django.dispatch import receiver class Problem(models.Model): class Category: NONE = "None" RECURSION = "R...
from BaseAI import BaseAI #from random import randint depthLimit = 5 log = False applyStateHeuristic = True applyMoveHeuristic = True infinity = float('inf') class PlayerAI(BaseAI): def __init__(self): self.util = TreeFunctions() def getMove(self, grid): if log: prin...
from typing import List from django.core.management.base import BaseCommand, CommandParser from sok.models import Publication class Command(BaseCommand): def add_arguments(self, parser: CommandParser): parser.add_argument('pk', nargs='+', type=int) def handle(self, *args, **options): pks: List[int] = option...
import datetime def printTimeStamp(name): print('Автор програми: ' + name) print('Час компіляції: ' + str(datetime.datetime.now())) n = input("Введите 4-значное число: ") l = list(n) d1 = int(l[0]) d2 = int(l[1]) d3 = int(l[2]) d4 = int(l[3]) print("Сумма цифр числа:", d1 + d2 + d3+ d4 ) printTimeSta...