text
stringlengths
8
6.05M
from django.contrib import admin from api.models import Item,Cart,Order # Register your models here. admin.site.register(Item) admin.site.register(Cart) admin.site.register(Order)
#!/usr/bin/env python3 import sys import time from Nav_funs import Distance, Direction import rospy from geometry_msgs.msg import Point #from mcu_control.msg import RoverPosition, AntennaGoal def subscriber_callback(message): rospy.loginfo(message) if message.x < -900 or message.y < -900: return ...
# Written by Muhammad Sarmad # Date : 31st July # This file is only to ascertain the value of ZMAX and ZMIN import torch import torch.utils.data import torch.nn.parallel import Datasets import models import numpy as np import argparse import torchvision.transforms as transforms import pc_transforms np.random.seed(...
from django.http import HttpResponse,Http404 from django.shortcuts import render import datetime def hello(request): return HttpResponse('Hello world') def root_page(request): return HttpResponse('The root page!') def current_date(request): now = datetime.datetime.now() context = {'current_date':now}...
#!/usr/bin/env python3 from io import StringIO from textwrap import dedent import matplotlib.pyplot as plt from pandas import read_csv # %% data = StringIO(dedent("""\ category,photon,eta_fd theory,14.5,4.572 theory,15.0,4.448 theory,15.5,4.367 theory,16.0,4.307 theory,16.5,4.258 theory,1...
from .WebHelper import WebHelper from .models import Query, Counter def create_counters(): queries = Query.objects.all() for q in queries: counter = Counter() req = WebHelper(q.phrase, q.region) counter.count = req.get_count() counter.query = q counter.save() print(...
import pandas as pd import numpy as np import matplotlib.pyplot as plt import json import os.path as op # ---------------------------------------------------------------------- # Script qui permet de tracer les figures des résultats d'un entraînement # d'un modèle. # ---------------------------------------------------...
from os import listdir, getcwd from os.path import isfile, join import json def merge_file(): c_dir = getcwd() + f'/service_workers/data/' onlyfiles = listdir(c_dir) data = [] for filename in onlyfiles: with open(getcwd() + f'/service_workers/data/{filename}', 'r') as fp: data_colle...
from fastapi import FastAPI, HTTPException from fastapi.middleware.cors import CORSMiddleware from model import Todo app = FastAPI() from database import( fetchOneTodo, fetchAllTodos, createTodo, updateTodo, removeTodo, ) origins = ['http://localhost:3000', 'http://localhost:4000'] app.add_middl...
import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BOARD) GPIO.setup(12, GPIO.OUT) p = GPIO.PWM(12, 50) p.start(7.5) class DistanceSensor: class servoMotion: """docstring for servoMotion.""" def __init__(self,angle,distance): self.angle=0 self.distance=0 theta=0 def wallFinde...
import numpy as np import scipy.stats as st import matplotlib.pyplot as plt import pandas as pd import sklearn as sk from sklearn import decomposition from ICA_noise import FastICA mydata = pd.read_csv("/Users/tangyehui/UG_Project/dataset/personality/UKDA-7656-tab/tab/bbc_individual_level_data_file.tab", sep ="\t") ...
from django.apps import AppConfig class ArwebConfig(AppConfig): name = 'Arweb'
from tortoise import Model, fields class TimestampMixin: created_at = fields.DatetimeField(auto_now_add=True) updated_at = fields.DatetimeField(auto_now=True) class AbstractBaseModel(Model): id = fields.IntField(pk=True) class Meta: abstract = True class User(AbstractBaseModel, TimestampM...
# -*- coding: utf-8 -*- # Generated by Django 1.9.4 on 2016-03-08 10:00 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('annonces', '0002_auto_20160308_1056'), ] operations = [ migrations.AlterFiel...
from googletrans import Translator import eel def translate(text,dest,src): tr = Translator() translated = tr.translate(text,dest=dest,src=src) eel.view_log_js(translated.text)
import copy import os from operator import itemgetter #pos1 = copy.deepcopy(pos) # copier une liste d'objets def creer_sudoku() : sudoku = [[1,2,3,4,5,6,7,8,9],[1,2,3,4,5,6,7,8,9],[1,2,3,4,5,6,7,8,9],[1,2,3,4,5,6,7,8,9],[1,2,3,4,5,6,7,8,9],[1,2,3,4,5,6,7,8,9],[1,2,3,4,5,6,7,8,9],[1,2,3,4,5,6,7,8,9],[1,2,3,4,5,6,7,...
from Utils.parse import tfrecord_reader_dataset import os import tensorflow as tf import matplotlib.pyplot as plt if __name__ == "__main__": epoch = 1 # 1.获取所有TFRecord文件的列表 dir = "D:\\data\\COVID19\\TFRecord" files_name = os.listdir(dir) train_files_name = [os.path.join(dir, name) for name in files...
"""盤面の列挙 盤面を列挙し、gmlファイルに出力する。 """ import gobbletgobblers as game import player_ai as ai # ゲームAI.ミニマックスによる行動.ランダムな行動. import networkx as nx def main(): print() print("盤面の列挙を行います。") print("出力するファイル名を打ち込んで下さい(.gml含む):", end="") filename = input() if not filename: print("filenameが正常に入力...
import behaviors import unittest class TestTargetFollowingBehavior(unittest.TestCase): # * {-45}-------{ 0 }-------{45} # * | +-----[ +y]-----+ | # * | | | | # * | | | | # * {-90} [-x] [0,0] [+x] {90} # * | | | | # * | | |...
from django.urls import path from . import views app_name = 'chains' urlpatterns = [ path('', views.index, name='index'), path('view_chain/<int:story_id>/', views.view_chain, name='view_chain'), path('get_details/<int:story_id>/', views.get_details, name='get_details') # path('<int:question_id>/', view...
__author__ = "Panagiotis Garefalakis" __copyright__ = "Imperial College London" # The MIT License (MIT) # # Copyright (c) 2016 Panagiotis Garefalakis # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the...
# Generated by Django 2.2 on 2021-06-07 01:37 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('store_app', '0001_initial'), ] operations = [ migrations.RemoveField( model_name='cart', name='amount', ), ...
# Work with Python 3.6 import os import asyncio import discord from itertools import cycle from discord.ext.commands import Bot BOT_PREFIX = "." client = Bot(command_prefix=BOT_PREFIX) extensions = ['Events', 'Fun', 'Roller'] status = [ 'against the Fallen.', 'against the Vex.', ...
#ファイルを利用する file = open('Company.txt', 'r', encoding='utf-8') print(file.read()) file.close() #自動で閉じるためにwithを利用します。 with open('Company.txt', 'r', encoding='utf-8') as file: print(file.read()) #文字列を1行ずつ取得する file = open('Company.txt', 'r') for line in file: print(line) file.close() #文字列を1行ずつ取得する(while) file...
#!/usr/bin/python import math n = 100000000 count = 3 isPrime = [True] * (n + 1) k = int(math.sqrt(n)) for i in range(2, k + 1): if isPrime[i]: j = i * i while j <= n: isPrime[j] = False j += i def valid(num): sq = int(math.sqrt(num)) for d in range(1, sq + 1): ...
from django.db import models from django.urls import reverse from django.core.files.storage import FileSystemStorage from django.contrib.auth.models import User fs = FileSystemStorage(location='/media/img') class Product(models.Model): name = models.CharField(max_length=200, verbose_name = 'Название продукта' ) ...
''' Utility functions for the monitoring and log generation. ''' import time import logging def init_logger(): ''' Initialise the logger. Returns: logger (Logger): Logger to use for the monitoring. ''' log_format = '%(asctime)s %(levelname)s %(message)s' logger = logging.getLogger(...
import os import pickle import subprocess import warnings from datetime import datetime import fsspec from rubicon_ml import client, domain from rubicon_ml.client.utils.exception_handling import failsafe from rubicon_ml.client.utils.tags import filter_children from rubicon_ml.exceptions import RubiconException clas...
# -*- coding: utf-8 -*- class Coche(object): #Abstracción de los objetos coche. def __init__(self, gasolina): self.gasolina = gasolina print ("Tenemos " + str(gasolina) + " litros") def arrancar(self): if self.gasolina > 0: print ("Arranca") else: pri...
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2013-2015 Marcos Organizador de Negocios SRL http://marcos.do # Write by Eneldo Serrata (eneldo@marcos.do) # ############################################################################## impor...
# -*- coding: utf8 -*- from aliyunsdkcore.client import AcsClient from aliyunsdkcore.acs_exception.exceptions import ClientException from aliyunsdkcore.acs_exception.exceptions import ServerException from aliyunsdkecs.request.v20140526 import DescribeInstancesRequest from aliyunsdkecs.request.v20140526 import StopInsta...
from zutils.task.task_redis import TaskRedis from zutils.tensorflow.tf_session import TFSession from zutils.convert import convert_dict,convert_dict_log from zutils.logger import Logger from zutils.utils import relative_project_path import traceback import time import json import os class Task: def __init__(self, ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('query', '0004_auto_20150507_1024'), ] operations = [ migrations.CreateModel( name='Newspaper', field...
from flask import Blueprint, jsonify, request from mybib.bibtext.reader import load_from_string from mybib.graphql.access_layer import EntityAlreadyExistsError from mybib.graphql.access_layer import get_paper as get_paper_da from mybib.graphql.access_layer import insert_paper from mybib.web.authentication import requi...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('rentacar', '0001_initial'), ] operations = [ migrations.AlterModelOptions( name='rentacar', options=...
from blog.models import Entry, Comment, Category from django.template import RequestContext from django.http import HttpResponseRedirect, HttpResponse from django.shortcuts import render_to_response from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from datetime import date # Create your views h...
# Generated by Django 3.0.3 on 2020-02-13 22:30 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Article', fields=[ ...
from pylearn2.utils import serial from glob import glob import pickle import os import numpy as np from copy import deepcopy from sklearn.metrics import confusion_matrix import itertools import logging from collections import Counter, OrderedDict from braindecode.util import dict_equal, dict_is_subset import shutil log...
# -*- coding: utf-8 -*- # Generated by Django 1.9 on 2017-03-06 05:38 from __future__ import unicode_literals from django.db import migrations, models import tinymce.models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( ...
import numpy as np import sys def sub_partition(S): types = np.unique(S) tuple_number = choose(len(types),2) sub_partitions = [] for i in types: for j in types: if i != j: # remove the first ith and jth elements S = [e for e in S] # add (i+j)th element sub_partitions = np.append(sub_partitions,...
""" La idea es crear un script que tenga una funcion que me de Rc'\D' y R0'/D' dandole como entrada beta, para toda i posible. Luego, dar un intervalo para Rc/Ro y para R0/D y de la salida que me dio ver cuales valores de i dan un R0 y Rc que caigan en el intervalo, y guardar esos valores de i en un archivo, y graf...
# -*- coding: utf-8 -*- import numpy as np import pylab as pl from sklearn.cluster import KMeans from sklearn.decomposition import PCA from sklearn.preprocessing import scale from sklearn import metrics # Для воспроизводимости случайного выбора центроидов из множества # объектов в случае вызова kmeans с параметром in...
import numpy as np import math # from sklearn.linear_model import LinearRegression from curvature import calcurvature from scipy.optimize import curve_fit # prev_leftdy = 0 # prev_rightdy = 0 # prev_leftc = 0 # prev_rightc = 0 def curve(left_lane, right_lane): xleft_plot = np.arange(5,40,0.01).reshape(-1,1) ...
#!/usr/bin/env python3 """ Analysis class to read a ROOT TTree of MC track information and do jet-finding, and save response histograms. Author: James Mulligan (james.mulligan@berkeley.edu) """ from __future__ import print_function # General import os import sys import argparse # Data analysis and plotting...
def search(budget,prices): return ','.join([str(x) for x in sorted(prices) if x<=budget]) ''' You love coffee and want to know what beans you can afford to buy it. The first argument to your search function will be a number which represents your budget. The second argument will be an array of coffee bean prices....
from typing import Iterable, List from parseridge.corpus.sentence import Sentence from parseridge.corpus.signature import Signature from parseridge.utils.helpers import Relation, T from parseridge.utils.logger import LoggerMixin class Relations(LoggerMixin): def __init__(self, sentences: List[Sentence]): ...
import pathlib print(pathlib.Path(__file__).resolve().parents[3])
from django.contrib import admin from products.models import * admin.site.register(Vendor) admin.site.register(Category) admin.site.register(Product) admin.site.register(Page)
import sys # we need this hack to pass a static library # from command line last_opt = sys.argv[-1] static_libs = [last_opt] if last_opt != "GUARD" else [] sys.argv = sys.argv[:-1] from distutils.core import setup from distutils.extension import Extension from Cython.Build import cythonize include_dirs = ['/Users/n...
print("Muhammad Saad Hasan\n18B-117-CS\nPractice Problem 4.4") def even(num): for x in range(2,num): if x%2==0 or x%3==0: print(x,end=", ") user = int(input("Please enter a number :")) even(user)
import numpy as np from isolation_forest.node import Node from isolation_forest.tree import Tree class TreeGrowerBasic: def __init__(self, X, sample_size): self.X = X self.dim_cnt = self.X.shape[1] self.sample_size = sample_size self.indeces = np.arange(0, self.X.shape[0]...
from unittest.case import TestCase from pythonbrasil.lista_2_estrutura_de_decisao.ex_06_mostrar_maior_de_tres_numeros import obter_maior_numero class ObterMaiorNumeroTests(TestCase): def test_todos_numeros_iguais(self): self.assertEqual(1, obter_maior_numero(1, 1, 1)) self.assertEqual(5, obter_m...
import datetime x = datetime.datetime.now() print(x) # date present tanggal dan jam second dari system computer print(x.year) # cetak tahun saat ini print(x.month) # cetak bulan saat ini a = datetime.datetime(2020, 6, 4) print(a) print(a.month) print(x.strftime("%B")) # string dari nama month print(x.strftime("%A...
t1 = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] t2 = [ ' Janvier ' , ' Février ' , ' Mars ' , ' Avril ' , ' Mai ' , ' Juin ' , ' Juillet ' , ' Août ' , ' Septembre ' , 'Octobre ' , ' Novembre ' , ' Décembre ' ] a = 0 t3 = [] while a < len(t1): t3.append(t2[a]) t3.append(t1[a]) a = a+1 print(t3)
import flask from flask import Flask import sklearn.externals import joblib from flask import render_template, request import numpy as np app = Flask(__name__) model = joblib.load('model.pkl') @app.route("/") def home(): return render_template('Iris.html') @app.route('/predict', methods=['POST']) def mak...
from inspect import stack # To write log import matter_lib as matt import structure as sct # Structure objects hierarchy log_file_heading = 'File: '+__file__.split('/')[-1]+' ' class MRI_inspect(object): files_MRI_path = '' files_MRI_names = [] matter_obj_list = [] relat...
n,m = map(int,input().split()) arr = [] first = [] second = [] for k in range(n): a = list(map(int,input().split()))[:m] arr.append(a) for i in range(n): for j in range(m): if arr[i][j] == 1: x = i+1 y = j+1 for j in range(2): print(x,y) ...
import unittest from header import Header from message import Message from set import Set class TestList(unittest.TestCase): def test_init(self): for t in 'bBhHiIqQfds': Set(t) Set('m', Message) Set('m', Header) self.assertRaises(TypeError, lambda: Set('x')) ...
# Generated by Django 2.1.1 on 2018-09-20 07:59 import django.contrib.postgres.fields.jsonb import django.core.serializers.json from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('manager', '0001_initial'), ] operations = [ migrations.AlterField( ...
from datetime import date from selenium.webdriver.support.ui import Select from .base import FunctionalTest DAYNUMS = {'mandag': 1, 'tirsdag': 2, 'onsdag': 3, 'torsdag': 4, 'fredag': 5, 'lørdag': 6, 'søndag': 7} class NewVisitorTest(FunctionalTest): def assert_elements_in_table(self, elements): table ...
# -*- coding: utf-8 -*- from mod_base import * def get_mimetype(url): import httplib from urlparse import urlparse urlobj = urplarse(url) domain = urlobj.netloc get = urlobj.path + urlobj.query conn = httplib.HTTPConnection(domain, timeout=5) conn.request("HEAD", get) res = conn.getres...
from .Fraction import Fraction class _Real: def __init__(self, value): if type(value) != int: if type(value) != float: if type(value) != Fraction: try: value = int(value) except ValueError: ...
from __future__ import division import sys import csv import pandas as pd import numpy as np import re import math """ this script analyze cabin and print some result in % """ """ iter on dataframe : for index,row in new_csv.iterrows(): write in csv : new_csv.to_csv('data/train_extract.csv',mode = 'w', index=False)...
from __future__ import print_function import matplotlib.pyplot as plt import numpy as np import os import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torchvision import datasets, transforms import vggish_params as params from network import ClassifyNet, Vggish, generato...
import torch.nn as nn from pathlib import Path import torch import torch.nn.functional as F import torch.optim as optim import torch.utils.data as data_utils def calculate_f1(log_proba: torch.tensor, target: torch.tensor, pos: int = 0, thresh: float = 2./3): """...
def ground_shipping_cost(weight): if weight <= 2: return 20.00 + (1.50 * weight) elif 2 < weight <= 6: return 20.00 + (3.00 * weight) elif 6 < weight <= 10: return 20.00 + (4.00 * weight) else: return 20.00 + (4.75 * weight) print("$%.2f" % ground_shipping_cost(8.4)) p...
#!/usr/bin/env python3 import argparse import subprocess def parse_args(): parser = argparse.ArgumentParser(description='Execute Terraform') parser.add_argument('-d', '--dry-run', action='store_true') parser.add_argument('--destroy', action='store_true') parser.add_argument('--plan', action='store_t...
import device from time import sleep from peak_detect2 import peakdetect def peak_found(maxtab,mintab): print maxtab print mintab pass def test_live_peaks(): '''run peak detection on device stream or archive data''' from device import sensor_stream gen=sensor_stream() data=[] t=[] x=[] y=[] z=[] lookahea...
import random class Board(object): ''' Board for the tic tac toe game ''' def __init__(self): '''initialize game state''' self.gameState = ['_', '_', '_', '_', '_', '_', '_', '_', '_'] self.symbols = ['x', 'o'] self.userSymbol ...
from ns_event_codes import event_codes from constants import headers, ns_login_dict, ns_login_url, ns_tracing_url from datetime import datetime class NorfolkSouthern: def __init__(self, session): self.session = session def login(self): self.session.headers.update(headers) self.session...
# Generated by Django 2.2.4 on 2019-08-31 14:45 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('encuestas', '0001_initial'), ] operations = [ migrations.AlterField( model_name='respuesta', name='codigo', ...
import cv2 img = cv2.imread("lena.jpg") im_scaled = cv2.resize(img, None, fx=0.75, fy=0.75) im_scaled2 = cv2.resize(img, (640, 480), fx=0.75, fy=0.75,interpolation=cv2.INTER_AREA) # dsize is used to desirable size # Skewed size im_scaled_interplotation=cv2.resize(img, None, fx=2, fy=2,interpolation=cv2.INTER_CUBIC) ...
import dash_bootstrap_components as dbc from dash import html tab1_content = dbc.Card( dbc.CardBody( [ html.P("This is tab 1!", className="card-text"), dbc.Button("Click here", color="success"), ] ), className="mt-3", ) tab2_content = dbc.Card( dbc.CardBody( ...
import turtle # Turtleモジュールのインポート t = turtle.Pen() for x in range(50): t.left(90) t.forward(30 + x * 5) #
#python imports import sys import os import json import time import extract_msg import email from email import policy from email.header import decode_header, make_header from email.parser import BytesParser from termcolor import colored #third-party imports #No third-party imports #programmer generated imports from l...
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys from os.path import abspath, dirname, join sys.path.append(abspath(join(dirname(__file__), '..'))) from uuid import uuid4 from mcfly import Connection def test_connection(): connection = Connection(username='test', password='test') assert connection.co...
# Generated by Django 2.2.4 on 2019-12-04 01:46 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('announcements', '0006_auto_20191122_1418'), ] operations = [ migrations.AddField( model_name='announcement', name='s...
import pandas as pd # from sklearn import linear_model # import csv # from sklearn.preprocessing import Binarizer # import ast df = pd.read_csv('txt_to_understand.txt', delimiter="\t") # a is the file name print(df) # לחלק את הדאטה למילים לאותיות למספרים, לתת לכל מילה מספר, לעשות חלוקה לפי מ...
from sys import argv import sqlite3 def roster(): if len(argv) != 2: print("Usage: python roster.py House") exit(1) else: connection = sqlite3.connect("students.db") cursor = connection.cursor() cursor.execute("SELECT first, middle, last, birth FROM 'students' ...
from rest_framework.response import Response from rest_framework import response, status # Библиотеки для сариализации from rest_framework import serializers, viewsets # Модели данных from .models import OverProfCompetencesInGroupOfGeneralCharacteristic, GroupOfOverProfCompetencesInGeneralCharacteristic, IndicatorInO...
#!/usr/bin/env python #-*- coding:utf-8 -*- from django import template register = template.Library() @register.simple_tag def get_nota_multipla(questaoAvaliacao, opcao): """"Retorna a nota que uma opcao multipla escolha tem em uma determinada questao de avaliacao """ return opcao.get_nota(questaoAvaliacao...
import csv with open ('DB1.csv') as csv_file: csv_reader = csv.reader(csv_file,delimiter=",") line = 0 list1 = list() idlst = set() for row in csv_reader: if line == 0: line+=1; continue idlst.add(row[1]) list1.append(row) with open ('DB2.csv') as csv_file: csv_reader = csv.reader(csv_file,delimiter=...
import sys from PySide import QtGui from aside.facade import AsideFacade from standalone import main as sa_main, components from . import controller class PluginFacade(AsideFacade): STARTUP = 'startup' PLUGIN_DIR = "plugins/user" def __init__(self, multitonKey): super(PluginFacade, self).__init...
from yabadaba import databasemanager from .IprPyDatabase import IprPyDatabase # Extend the yabadaba LocalDatabase to include IprPyDatabase operations class LocalDatabase(databasemanager.get_class('local'), IprPyDatabase): pass
#Cal n! n=eval(input('请输入一个不小于0的整数:')) def jc(n): if n==0: return 1 else: return n*jc(n-1) #用一个新的内存来存储n-1的函数 print(jc(n))
from .copy import copy from .file import file from .synchronize import synchronize from .command import command from .template import template cmd_map = {"copy": copy, "file": file, "synchronize": synchronize, "command": command, "template": template}
n1 = int(input('Digite um valor: ')) n2 = int(input('Digite outro valor: ')) action = 0 while action != (5): print('[1]Somar ' '\n[2]Multiplicar' '\n[3]Maior' '\n[4]Novos números' '\n[5]Sair do programa') action = int(input('O que você deseja fazer? ')) if action == 1: s = n...
import ipaddress as ip def get_peer_info(pd, hostvars): peer = { 'name': pd['peer'] } our_net = ip.IPv4Interface(pd['ip']).network pvars = hostvars[peer['name']] for k,v in pvars['ports'].iteritems(): if not v['ip']: continue peer_nobj = ip.IPv4Interface(v['ip']) if...
from client import Bot from load import configs, extensions import asyncio bots = [] loop = asyncio.get_event_loop() for c in configs: if('extensions' in c): bot = Bot(loop=loop) ext = c['extensions'] newext = [] for e in ext: newext.append(extensions[e](bot, ext[e])) ...
import argparse from da_manager import DaData from data_manager import dataman_factory from plotter import Plotter class Runner(object): def __init__(self, args): self._daman = DaData() self._dataman = dataman_factory("june", link_route_shapes=False, link_stops=True) def run(self): ...
from django.shortcuts import render, render_to_response from django.http import HttpResponse from django.template import RequestContext from blog.models import Post from blog.models import Tag def load(request,id): t = Tag.objects.get(id=id) p = t.post_set.all().order_by('-updateDatetime') return render( r...
import os, shutil file_paths = [os.path.join(root,f) for root, _, files in os.walk('wiki/fr/') for f in files] for path in file_paths: print path try: if not os.path.exists('/run/media/user/LBOX21/LibraryBox/Shared/'+os.path.dirname(path)): os.makedirs('/run/media/user/LBOX21/LibraryBox/Shared/'+os.path.dirname...
#!/usr/bin/python3 # This is the Python 3.x client-sided message viewer script for a Chat Server. from socket import socket, AF_INET, SOCK_STREAM, error HOST = 'localhost' PORT = 1337 serverAddress = (HOST, PORT) Message_Socket = socket(family=AF_INET, type=SOCK_STREAM) try: Message_Socket.conne...
#post data 长度,用于Content-Length def get_content_length(data): length = len(data.keys()) * 2 - 1 total = ''.join(list(data.keys()) + list(data.values())) length += len(total) int(time_now2())>2 and int(common.time_now2())<12)
#!/usr/bin/env python # # Copyright 2017 Google 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
#!/usr/bin/python3 ''' import statistics as s ''' ''' import statistics from statistics import * ''' from statistics import mean as m,median as me,stdev as dev examplelist = [3,4,5,6,7,8,9,10] x=m(examplelist) y=me(examplelist) z=dev(examplelist) print(x) print(y) print(z)
from django.urls import path from .views import Authorize, gen_auth_code urlpatterns = [ path('', Authorize.as_view(), name='blog'), path('auth_code/', gen_auth_code, name='auth_code'), ]
# Copyright (c) 2017-2023 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved. # SPDX-License-Identifier: Apache-2.0 from __future__ import annotations from typing import Optional def n_things(count: int, plural_noun: str, singular_noun: Optional[str] = None): if count == 1: if s...
from flask_restplus import Namespace, fields
from sklearn.metrics import confusion_matrix, mean_squared_error import numpy as np def calc_pdf_hist(x, x_bins): return np.histogram(x, x_bins, density=True)[0] def hellinger(x, pdf_p, pdf_q): pdf_distances = (np.sqrt(pdf_p) - np.sqrt(pdf_q)) ** 2 return np.trapz(pdf_distances, x) / 2 def root_mean_s...