text
stringlengths
8
6.05M
import os import random import numpy as np import time import neat6 as neat class CuatroEnRaya(): def __init__(self,alto=6,ancho=7,cantidad=100,f1=None,f2=None,imp=True,profundidad=2): self.alto = alto self.ancho = ancho '''self.tablero=[ [ 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, ...
# -*- coding: utf-8 -*- # # Copyright 2015 Forest Crossman # Copyright 2014 funoverip.net. # # This is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # ...
def func1(): print("Module 1") def func2(): print("Module 1 function 2") number1 = 21
# Copyright (c) 2011, James Hanlon, All rights reserved # This software is freely distributable under a derivative of the # University of Illinois/NCSA Open Source License posted in # LICENSE.txt and at <http://github.xcore.com/> from math import floor import error import ast from walker import NodeWalker class EvalE...
from decimal import Decimal from django.shortcuts import get_object_or_404 from apps.bitcoin_crypto.utils import create_connection from .models import TransactionFee def set_mining_fees(mining_fees): access = create_connection() try: access.settxfee(mining_fees) return True except: ...
# @Title: 替换空格 (替换空格 LCOF) # @Author: 2464512446@qq.com # @Date: 2020-07-21 14:50:20 # @Runtime: 40 ms # @Memory: 13.3 MB class Solution: def replaceSpace(self, s: str) -> str: # return s.replace(" ",'%20') # 这道题也可以用双指针法来解(感觉这才是题目用意) # p1 等于末尾,p2等于用多少个空格就加多少个占位符的末尾 # 然后向前遍历 ...
# import urllib import hashlib from django.conf import settings from django.contrib.auth import get_user_model from rest_framework import serializers from rest_auth.serializers import UserDetailsSerializer User = get_user_model() class UserSerializer(UserDetailsSerializer): """ The user serializer is child ...
import argparse import matplotlib.pyplot as plt import numpy as np import pickle as p import os from Games import utils_draws as ud from Games import UnimodalGame as ug from Environments import Rank1Env as r1e from Policies import OSUB from Policies import UTS if __name__ == "__main__": ## Parameters draw...
import re a = input() x = [m.start() for m in re.finditer('AB', a)] y = [m.start() for m in re.finditer('BA', a)] res = 0 i = 0 j = len(y) - 1 k = len(x) - 1 l = 0 while i < len(x) and j > -1 and k > -1 and l < len(y): if abs(x[i] - y[j]) > 1 or abs(x[k] - y[l]) > 1: res = 1 i += 1 j -= 1 k -= 1 l += 1 if re...
import pywapi import string result = pywapi.get_weather_from_yahoo('JAXX0030') print '---' print result['title'] print 'city: ' + result['location']['city'] print 'date_time: ' + result['condition']['date'] print 'condition: ' + result['condition']['text'] print 'temp: ' + result['condition']['temp'] + '('+ result['...
from datetime import datetime now = datetime.now() print("=============================") print("Now :", now) print("hello world!") print("Welcome to python cron job") print("=============================")
""" #------------------------------------------------------------------------------ # generate_pulse_fit.py # # This script iterates through a normalized acceleration period and # performs a curve fit to the calculated response versus the response # of a pure impulse. The specific application is to a boom crane. # # #...
# Generated by Django 2.2.11 on 2020-06-02 10:19 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('detskoePostelnoe', '0001_initial'), ] operations = [ migrations.CreateModel( name='Size', ...
#!/usr/bin/python3 # -*- coding=utf-8 -*- import email import imaplib import os import re import subprocess import sys from datetime import datetime from script.process_html_table import ProcessHtmlTable # 测试模式 debug = False # 定义目录 local_path = sys.path[0] config_path = local_path + '/config.json'...
from test_plus import TestCase from zhihu.articles.models import Article class ArticleModelsTest(TestCase): def setUp(self) -> None: self.user = self.make_user() self.draft = Article.objects.create( user=self.user, title='第一篇文章', content='测试', image...
""" LeetCode - Medium """ """ Given a 2D board and a word, find if the word exists in the grid. The word can be constructed from letters of sequentially adjacent cells, where "adjacent" cells are horizontally or vertically neighboring. The same letter cell may not be used more than once. Example 1: Input: board ...
print("Menghitung Volume Balok Dengan Python") p = 5 l = 7 t = 4 volume = p * l * t print ("Hasilnya adalah = ", volume)
#Cadeias de caracteres strings frase = str(' Curso em Video Python ') print(len(frase)) #tamanho da frase print(frase.count('o')) # quantas vezes aparece a letra print(frase.count('o',0, 13)) #Quantas vezes aparece a letra dentro do range (sempre o ultimo não é considerado print(frase.find('deo')) #quantas vezes ele...
# Generated by Django 2.1.1 on 2018-10-05 08:58 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('posts', '0006_auto_20180926_0034'), ] operations = [ migrations.AlterModelOptions( name='category', options={'orderi...
#%% import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.linear_model import LinearRegression from sklearn.svm import SVR import lightgbm from workalendar.asia import SouthKorea # 한국의 공휴일, version : 1.1.1 from utils import WindowGenerator, save_results #%% class Config(): d...
#!/usr/bin/env python """Example factory function for DES Y1 3x2pt likelihood.""" import os from typing import Dict, Union, Tuple import sacc import pyccl as ccl import pyccl.nl_pt import firecrown.likelihood.gauss_family.statistic.source.weak_lensing as wl import firecrown.likelihood.gauss_family.statistic.source...
import cpu mappers = {0:'NROM',1:'MMC1',2:'UNROM',3:'CNROM',4:'MMC3',5:'MMC5'} def romCheck(path): with open(path,encoding='ascii',errors='replace') as ROM: ROM = ROM.read() if ROM[:4] != 'NES\x1a': print('The cartridge is not of the iNES format.') else: print('The ...
import numpy as np import os, sys, time from chainer import cuda from chainer import functions as F sys.path.append(os.path.split(os.getcwd())[0]) from progress import Progress from mnist_tools import load_train_images, load_test_images from model import params_energy_model, params_generative_model, ddgm from args impo...
import sys import socket from Crypto import Random from Crypto.Cipher import AES import base64 import serial import threading import time import queue import pandas as pd import numpy as np from sklearn.externals import joblib import pickle from scipy import stats mlp_model = joblib.load('ML_Models/mlp_10move_update...
# Módulo destinado a correr el programa from chaucraft import ChauCraft from galaxia import Galaxia from planeta import Planeta from clases import Aprendiz, Asesino, Maestro, Edificio from datetime import datetime game = ChauCraft() try: with open("galaxias.csv", "r", encoding="utf-8") as galaxias_file: ...
from __future__ import print_function import pyautogui import speech_recognition as sr import os from time import gmtime import time import random from flask import Flask ,render_template ,request from chatterbot import ChatBot from chatterbot.trainers import ChatterBotCorpusTrainer english_bot=ChatBot("C...
aminhastring = 'ola a todos bem vindos ao meu canal' omeuarraydenumeros = [1, 2, 3, 4] familia = [ ['1', 'olha a vaca ah ima gossto em vela'], ['2', 'tiago, leva a roupa a lavandaria'], ['3', 'estas sempre a implicar comigo'], ['4', 'silencio sepulcral seguido de um lindo gesto -> .|.'] ] familiav2 = { '1'...
import matplotlib.pyplot as plt import math import random N= 20 data = open("finalDataCoords.txt") incomes, callRatios= [], [] line = data.readline() while line: fields = line.split("|") incomes.append(float(fields[0])) callRatios.append(float(fields[1][:-1])) line = data.readline() print(incomes) pr...
import email.parser import re from datetime import datetime import dateutil.parser import sb.util from xml.sax.saxutils import escape, quoteattr from jk.islojban import is_lojban from_re = re.compile("^From ") # Dates are of lots of forms: # Fri, 2 Apr 1993 16:40:37 BST # Wed, 06 Jun 90 11:44:24 -0700 # 6 Nov 90...
# Generated by Django 2.1.4 on 2019-01-11 17:05 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('speciality', '0036_auto_20190111_1651'), ('clientele', '0005_clientele_services'), ] operations = [ migrations.CreateModel( ...
from django.contrib import admin from .models import List, Item admin.site.register(List) admin.site.register(Item)
""" run the script press c to capture the detected face press q to quit or continue adding faces """ import numpy as np import cv2 faceCascade = cv2.CascadeClassifier('cascades/haarcascade_frontalface_default.xml') cap = cv2.VideoCapture(0) cap.set(3,640) # set Width cap.set(4,480) # set Height face_num=1 while True:...
#if-else x = 5 if x > 0: print("The number is positive") elif x < 0: print("The number is negative") else: print("The nuber is Zero")
#-*- coding:utf8 -*- from django.conf import settings from django.core import exceptions from shopback import paramconfig as pcfg from .handler import (BaseHandler, InitHandler, ConfirmHandler, FinalHandler, StockOutHandler, ...
import abc import boto3 from botocore.exceptions import ClientError from backend.settings import DEBUG class _AbstractS3(metaclass=abc.ABCMeta): @abc.abstractmethod def get_upload_dict(self, bucket, key): pass @abc.abstractmethod def get_download_url(self, bucket, key): pass @...
from torch import tensor from sentanalyzer_api.utils.vocabulary import Vocabulary from sentanalyzer_api.utils.preprocess import tweet_cleaner # vocab_file = r'sentanalyzer_api/utils/vocab_V4_.json' import os from dotenv import load_dotenv load_dotenv() vocab_file = r'sentanalyzer_api/utils/vocab_V4_.json' if os.envir...
""" The controller file... Following operations can be performed: 1. `cap`, `pcap` or `pcapng` (or similar formats) can be converted to csv format -- frame csv file Headers extracted: 'frame.number' 'frame.time_epoch' 'frame.len' 'wlan.duration' '-e wlan.bssid' '-e wlan.ra' '-e wlan.ta...
# send_crest_request import http.client import csv import json import os.path import threading import datetime #import redis def send_crest_requset(url, flag, option): global standaloneWriter conn = http.client.HTTPConnection(url) conn.request("GET", "/crest/v1/api") res = conn.getresponse() dat...
import json from rest_framework.views import status from api.tests.base import AuthBaseTest from django.urls import reverse class AuthRegisterUserTest(AuthBaseTest): """ Tests for /auth/register/ endpoint """ def test_create_a_user_profile_with_valid_data(self): # test creating a user with va...
import numpy as np # numpy.frombuffer s = 'Hello World' a = np.frombuffer(s, dtype='S1') print(a)
# plot the energies # Created by Martin Gren 2014-10-25. # imports import matplotlib.pylab as plt import numpy as np # input file filename = 'energy_data_eq.dat' # import data data = np.loadtxt(filename) cols = np.size(data,1) # initial size of plot window plt.figure(figsize=(8,6)) # plot plt.plot(data[:,0], data[...
VALID_NUCLEIC_ACIDS = 'ACGTNUKSYMWRBDHV' VALID_AMINO_ACIDS = 'APBQCRDSETFUGVHWIYKZLXMN' NUCLEIC_DELCHARS = str.maketrans({ord(c): None for c in VALID_NUCLEIC_ACIDS}) AA_DELCHARS = str.maketrans({ord(c): None for c in VALID_AMINO_ACIDS}) def validate_sequence(sequence, valid_chars): """Check whether sequence is va...
def voto(ano): """ Indica se a pessoa tem voto obrigatório ou não de acordo com a idade :param int ano: ano de nascimento da pessoa :return str: """ from datetime import date idade = date.today().year - ano if idade <= 0: return 'Essa pessoa nem nasceu!' elif idade < 16: ...
import pandas as pd import numpy as np ########## Specify the name of excel with the data ########## fileData=pd.read_excel('Sample DataSet.xlsx') ########## Removes last 2 characters ########## for loop in range(0,fileData['Section'].count()): temp_String=str(fileData['Section'].iloc[loop]) temp_Str...
from splinter import Browser from bs4 import BeautifulSoup as bs from webdriver_manager.chrome import ChromeDriverManager import time import pandas as pd def init_browser(): executable_path = {'executable_path': ChromeDriverManager().install()} return Browser('chrome', **executable_path, headless=False) def...
from flask import Flask, render_template, request, redirect, url_for import csv, random, json app = Flask(__name__) profiles = [] data = open("./static/MOCK_DATA.csv") data = data.read()[:-1] data = data.split("\n") for x in data: person={} x = x.split(",") person["ID"] = x[0] person["first"] = x[1] ...
def gd5consect_numbers(number): """ (int) -> int Return the greatest product of five consecutive digits in number. >>> gd5consect_numbers(12345678935) 15120 >>> gd5consect_numbers(9998543521) 29160 """ s_number = str(number) result_list = [] for i in range(len(s_number)-4): ...
import re import os import sys def banner(): print(' ****************************************** ') print(' ******************************************************************* ') print('******************************* ********************************...
import logging import torch from typing import Dict from torch.utils.tensorboard import SummaryWriter from ..abstract_callback import AbstractCallback, ModelTrainer from sonosco.serialization import serializable LOGGER = logging.getLogger(__name__) @serializable class LasTextComparisonCallback(AbstractCallback): ...
from flask import Flask, request from flask_restful import Resource, Api from deta import Deta from dotenv import load_dotenv import os app = Flask(__name__) api = Api(app) deta = Deta(os.environ["DETA_KEY"])
from .stubs import * output = "" history = "" win = {"R": "P", "P": "S", "S": "R"} def rchoice(s): if not s: return "P" return s[ int(get_turn() * 24.542243858834 - 4832.584377 * 7325285848277677.3485 % 3285787478 % (get_turn() + 1)) % len(s)] opp_side = {RobotTeam.FIRST: RobotTeam.S...
# -*- coding: utf-8 -*- import scrapy from scrapy.linkextractors import LinkExtractor from scrapy.spiders import Rule import time class CrawlpageSpider(scrapy.Spider): name = 'crawlpage' allowed_domains = ['nytimes.com'] def parse(self, response): page = response.text filename = 'output....
"""updated columns in power gen table Revision ID: af833ec69790 Revises: b3d6c710aa26 Create Date: 2021-09-15 16:56:44.335825 """ from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import mysql # revision identifiers, used by Alembic. revision = 'af833ec69790' down_revision = 'b3d6c710aa26' bran...
def findstr(instr): str = 'This is such a long string that I would like to find a substring of' print str if str.find(instr) >= 0: print "Found %s" % instr else: print "Did not find %s" % instr
../../../py_ros/arm7dp_key.py
#https://leetcode-cn.com/contest/weekly-contest-215/problems/minimum-operations-to-reduce-x-to-zero/ #https://leetcode-cn.com/problems/minimum-operations-to-reduce-x-to-zero/ #思路1 最直观的思路,不断迭代 从 最左 和 最右 计算子迭代是否能成功,但时间复杂度随着LIST变大,呈现指数扩张 #思路2 求最大的1个内部子串,使得 SUM内部 = SUM ALL - X,因为如果不存在这样的内层子串,那根本不存在这样的计算方法使得X=0;且要计算得到这个...
import unittest import numpy as np from ized import qr class QRchecker(unittest.TestCase): def setUp(self): self.test_matrix = np.r_[ np.eye(4) - np.eye(4, k=1) - np.eye(4, k=-1), np.ones((1, 4))] def assertUpperTriangular(self, mat): nrows = mat.shape[0] se...
""" A module that preprocesses adverse events data to be ready for xgboost training. """ import json import os import time import numpy as np import pandas as pd #import modin.pandas as pd import torch from collections import OrderedDict def get_frequent_features(vocab, num_features, codes_only=True, exclusion_list=...
import time import pandas as pd import numpy as np CITY_DATA = { 'chicago': 'chicago.csv', 'new york city': 'new_york_city.csv', 'washington': 'washington.csv' } months = ['january', 'february', 'march', 'april', 'may', 'june','all'] week = ['sunday', 'monday', 'tuesday', 'wednesday', 'thur...
#!/usr/bin/python # -*- coding: utf-8 -*- import openravepy import numpy env= openravepy.Environment() env.SetViewer('qtcoin') env.Load('data2/hiro_test.env.xml') raw_input("Press Enter to start...") #robot= env.GetRobots()[0] robot= env.GetRobot('HiroNX') robot.SetActiveManipulator('rightarm') # rightarm, rightarm...
from flask import app, render_template import flask app = flask(__name__) @app.route('/log') def log(): return render_template('log/log.html') def ini_app(config): app.config.from_object(config) return app
# -*- coding: utf-8 -*- from common import * def visualize(board): board = list(reversed(board)) h, w = len(board), len(board[0]) box(0, 0, h, w, edgecolor='k', color='white') for y in range(h): for x in range(w): if board[y][x] == '#': box(y, x, y+1, x+1, color="0...
# Copyright The OpenTelemetry Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in ...
new_list = [ i ]
import MySQLdb def connection(): conn = MySQLdb.connect(host="localhost", user="root", passwd='cross1994', db="uniplan") c = conn.cursor() return c, conn
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None from made_list import ListNode class Solution: # @param head, a ListNode # @return a ListNode def deleteDuplicates(self, head): if head == None: return head cur = head while cur.next != N...
def check_if_alnum(s): for char in s: if char.isalnum(): return True return False def check_if_alpha(s): for char in s: if char.isalpha(): return True return False def check_if_digit(s): for char in s: if char.isdigit(): return True r...
from django.db import models class Alumno(models.Model): nombre = models.CharField(max_length=200) def __str__(self): return self.nombre class Clase(models.Model): numero = models.IntegerField(default=0,unique=True) def __str__(self): return str(self.numero) class Asistencia(models....
#!/usr/bin/python # -*- coding: utf-8 -*- # @author: yuanzi def main(): lst = ['大白菜','花菜','空心菜','生姜','小龙虾'] for lst_item in lst: print '老妈看到了 %s ' % (lst_item) print '~~~~~~~~~~~~~~~' def main2(): my_food_list = ['牛奶','饼干','薯片','海苔','虾条','可乐'] print '我要买', len(my_food_list), '种零食,它们是' for item in my_food_...
#!/usr/bin/env python3 from zlib import adler32 def deterministic_choice(sequence, choice_seed): return sequence[adler32(bytes(choice_seed, 'utf8')) % len(sequence)] def deterministic_triple(sequence, choice_seed): result = [] nonces = ['a', 'b','c','d','e','f','g','h'] nonceIndex = 0 while len(re...
# coding=utf-8 ''' @author: 黄鑫晨 ''' import json import tornado from sqlalchemy import desc from tornado import gen from tornado.concurrent import Future from tornado.web import asynchronous from Appointment.APgroupHandler import APgroupHandler from BaseHandlerh import BaseHandler from Database.tables import Appointme...
w, h = map(int, input().split()) x, y = map(int, input().split()) t = int(input()) dis_x = t - (t // (w*2))*(w*2) dis_y = t - (t // (h*2))*(h*2) if w - x-dis_x >=0: x += dis_x else: x = 2*w -x-dis_x if h - y-dis_y >=0: y += dis_y else: y = 2*h -y - dis_y print("%d %d" % (abs(x), abs(y)))
#!/usr/bin/env python # -*-coding:utf-8 -*- # author:罗徐 time:2019/5/17 import cv2 as cv import numpy as np #实现控制图像的对比度与亮度 def contrast_brightness_demo(image,c,b): #c代表亮度,b代表对比度 h,w,ch=image.shape blank=np.zeros([h,w,ch],image.dtype) dst=cv.addWeighted(image,c,blank,1-c,b) cv.imshow("c...
# -*- coding: utf-8 -*- # Generated by Django 1.10.4 on 2017-03-24 12:21 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('chemhunt', '0001_initial'), ] operations = [ migrations.AlterField( ...
from myhdl import * def toTwosComplement(binarySequence): convertedSequence = [0] * len(binarySequence) carryBit = 1 # INVERT THE BITS for i in range(0, len(binarySequence)): if binarySequence[i] == '0': convertedSequence[i] = 1 else: convertedSequence[i] = 0 ...
from django.apps import AppConfig class DterpAppConfig(AppConfig): name = 'dterp_app'
__author__ = "Pruthvi Kumar, pruthvikumar.123@gmail.com" __copyright__ = "Copyright (C) 2018 Pruthvi Kumar | http://www.apricity.co.in" __license__ = "Public Domain" __version__ = "1.0" import redis from configuration import ProtonConfig from nucleus.generics.logUtilities import LogUtilities class CacheManager(Proton...
# 2.2 更新 # 1. 更改了策略的函数名,更加直观 # 2. 将注释从英文改为中文 # 3. # 加载所需模块 import pandas as pd # 数据处理 import datetime as dt # 日期 from WindPy import * # 万德数据API from WindAlgo import * # 回测 from WindCharts import * # 绘图 w.start(show_welcome = False) # 启动万德 # 反转&小市值交易策略。 today = dt.datetime.now(...
import os import discord import dotenv dotenv.load_dotenv() class Client(discord.Client): def __init__(self): super().__init__() async def on_ready(self): print(self.user.name) print(self.user.id, "\n") async def on_voice_state_update(self, member, before, after): chan...
"""Classes for creating basic modal dialogs Such as YES-NO, Question, Information dialogs etc. """ from julesTk import view, controller from julesTk.view.window import Window __author__ = "Joeri Jongbloets <joeri@jongbloets.net>" class ModalWindow(Window): """A window taking all focus and blocking interaction...
satu = 1; dua = 2; tiga = 3; empat = 4; lima = 5; enam = 6; tujuh = 7; delapan = 8; sembilan = 9; loop = 1 nama = "Nama : M Firman Kahfi" npm = "NPM : 1144015" kelas = "Kelas : D4TI3B" import time start_time = time.time() while loop == 1: print "PROGRAM OPERASI ARITMATIKA LEBIH DARI 1 OPERATOR " print (nama) ...
from io import BytesIO import base64 from PIL import Image from python_helper import Constant as c from python_framework import Service, ServiceMethod from dto import QRCodeDto @Service() class ImageService : @ServiceMethod(requestClass=[str, str]) def save(self, imageAsBase64, pathWithNameAndExtension) : ...
from flask import Blueprint, render_template, url_for, redirect from flask_login import login_user, logout_user, login_required, current_user from app.form import SearchForm, LoginForm, RegisterForm, WatchForm, UnWatchForm, DelPackageForm from app.model import Express, Package, User from config import INTERNAL_CODE ...
import random hand_list = {1:"グー",2:"チョキ",3:"パー"} def janken(): g,t,p = 0,0,0 rand_num = random.randint(0,90) while(1): hand = int(input("1:グー 2:チョキ 3:パー : ")) if hand == 1 or hand == 2 or hand == 3: break print() print("1,2,3のどれかを入力してください") print("ポン!") print() print("あなた:" + h...
import random a = [random.randrange(1, 6) for i in range(10)] print("Массив:") print(' '.join([str(i) for i in a])) print(f"Элементов, которые равны 3: {len([i for i in a if i == 3])}")
# -*- coding: utf-8 -*- """ Created on Fri Jun 16 10:26:16 2017 @author: Peter Wilson """ import numpy as np import sympy as sp print("Sympy version: ",sp.__version__) x = sp.Symbol('x') y = sp.Symbol('y') xi = sp.Symbol('xi') eta = sp.Symbol('eta') loc1 = sp.Symbol('loc1') loc2 = sp.Symbol('loc2') alpha = sp.Sym...
import numpy as np import copy from td import TD from alg_plugin import AlgPlugin import common class TDLearning(AlgPlugin): def __init__(self, alpha, gamma, eligibility, epsilon, next_action_considered): super().__init__() # store the hyper parameters self.alpha = alpha self.gamma = gamma self.eligibilit...
from enum import Enum class EthereumChain(Enum): MAIN_NET = 1 ROPSTEN = 3 RINKEBY = 4 UBIQ = 8 KOVAN = 42 SOKOL = 77 DOLOMITE_TEST = 1001 ZEROEX_TEST = 1337
from onegov.agency.models import ExtendedAgency from onegov.agency.utils import filter_modified_or_created from onegov.core.collection import GenericCollection, Pagination from onegov.people import AgencyCollection from sqlalchemy import or_, func from sqlalchemy.orm import joinedload class ExtendedAgencyCollection(A...
#figure out how to link login to usersession and pass the info onto usersession from flask import Flask, render_template, request, session, redirect,url_for import utils app = Flask(__name__) @app.route("/usersession") def user(): uname=session['username'] return render_template("user.html",uname=uname) @app...
from MyException import MyException from Date import Date date = Date(20, 12, 2002) print(date) try: date.findDate() except MyException as e: print(e.value)
from rest_framework import serializers from app.users.serializers.user import UserSerializer from app.pools.models.pool_user import PoolUser class PoolUserListSerializer(serializers.ModelSerializer): user = UserSerializer() class Meta: model = PoolUser fields = '__all__'
from django.shortcuts import render from rest_framework import serializers, viewsets from . import models class AlarmSerializer(serializers.ModelSerializer): class Meta: model = models.Alarm fields = '__all__' class Alarms(viewsets.ModelViewSet): serializer_class = AlarmSerializer quer...
""" Author: Sidhin S Thomas (sidhin@trymake.com) Copyright (c) 2017 Sibibia Technologies Pvt Ltd All Rights Reserved Unauthorized copying of this file, via any medium is strictly prohibited Proprietary and confidential """ from django import forms from django.core.exceptions import ValidationError from trymake imp...
#!env python3 # -*- coding: utf-8 -*- import pandas as pd import numpy as np import matplotlib as mpl mpl.use('Agg') import matplotlib.pyplot as plt import json import seaborn as sb plt.rcParams['figure.figsize'] = 8, 4 df = pd.read_json('../data/nobel_winners_biopic_cleaned.json') by_gender = df.groupby('gender') b...
# !encoding=utf8 # name = raw_input() # print name # t = {"name":"wang", "agent":2} for (key,value) in t.items(): print key, value d = {} d["key1"] = "value1" l = "key1" in d l2 = d.get("key12") print l print l2 print [x*x for x in range(1, 11)] #list print [x*x for x in range(1, 11) if x%2==0] #只取偶数 print [...
import numpy as np from sklearn import svm from Classification.ClassifierBaseClass import ClassifierBaseClass from config import * class SVM (ClassifierBaseClass): def __init__(self, **kwargs): ClassifierBaseClass.__init__(self, **kwargs) self.C = kwargs.get("C", 1.0) self.kernel = kwar...
from django.contrib.auth.models import User from project.api import models from rest_framework import viewsets, response, permissions from project.api import serializers import logging logger = logging.getLogger(__name__) class PartCategoryViewSet(viewsets.ModelViewSet): queryset = models.PartCategory.objects.al...
def find(val, curr, n): if val==n: return curr if val>n: temp = val mark = curr while(temp>=n): if temp==n: return mark mark+=1 temp=int(temp/3) val*=2 curr+=1 return find(val, curr, n) print(find(1, 0, 10))
#!/usr/bin/python3 # -*- coding: utf-8 -*- # @Time : 2018/9/27 21:47 # @Author : dapengchiji!! # @FileName: code8.py ''' 函数传入的参数为不可变的,对外部的变量就没有影响 如 数字、字典 按值传--传入的不是变量对应的内存地址 函数传入的参数为可变的,对外部的变量就有影响 按引用传--传入的变量对应的内存地址 ''' a=111 def f(): global a a = 11 b = a+1 print(b) print (f()) # args可变参数 def...