text
stringlengths
8
6.05M
import sys import time import rtmidi import random from funcgen import * notes = ["C","Db","D","Eb","E","F","Gb","G","Ab","A","Bb","B"] # Midi output setup midiout = rtmidi.MidiOut() available_ports = midiout.get_ports() if available_ports: midiout.open_port(0) else: midiout.open_virtual_port("My virtual ou...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2017 Universitaet Bremen - Institute for Artificial Intelligence (Prof. Beetz) # # Author: Minerva Gabriela Vargas Gleason <minervavargasg@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Gen...
import pyotp from flask_security.utils import hash_password, verify_password from .misc import gen_random_code, clean_random_code BACKUP_CODE_COUNT = 16 ISSUER = 'Zcash Grants' def gen_backup_code(): return f'{gen_random_code(5)}-{gen_random_code(5)}'.lower() def gen_backup_codes(): return [gen_backup_code...
import numpy as np from sklearn.ensemble import GradientBoostingRegressor class GradientBoosting: def __init__(self, validate=True,adaptive=False): self.x_train=None self.y_train = None np.set_printoptions(precision=5) self.model = GradientBoostingRegressor(loss='ls',n_estimators=1...
from datetime import datetime import math import requests import time from alembic.util import CommandError from bitcoin_acks.constants import PullRequestState from bitcoin_acks.database import create_or_update_database from bitcoin_acks.github_data.polling_data import PollingData from bitcoin_acks.github_data.pull_...
from django.db import models # from cloudinary.models import CloudinaryField class Site(models.Model): title = models.CharField('Titulo', max_length=120) url = models.URLField('URL Site') description = models.TextField('Descrição') modified = models.DateField('Modificado em', auto_now=True) created = models.Date...
class Board: def __init__(self): self.__rows = 16 self.__cols = 16 self.__matrix = [[0 for _ in range(self.__cols)] for _ in range(self.__rows)] def load(self, file_name): f = open(file_name, "r") for line in f.readlines(): x, y = line.split(" ") ...
mass_table = { 'G': 57.021464, 'A': 71.037114, 'S': 87.032028, 'P': 97.052764, 'V': 99.068414, 'T': 101.047678, 'C': 103.009184, 'I': 113.084064, 'L': 113.084064, 'N': 114.042927, 'D': 115.026943, 'Q': 128.058578, 'K': 128.094963, 'E': 129.042593, 'M': 131.040485, 'H': 137.058912, 'F': 147.068414, 'R': 156.101...
from itertools import product ADJACENT = {'1': '124', '2': '1235', '3': '236', '4': '1475', '5': '24568', '6': '3569', '7': '478', '8': '05789', '9': '689', '0': '08'} def get_pins(observed): return [''.join(a) for a in product(*(ADJACENT[b] for b in observed))]
# -*- coding: utf-8 -*- class Solution: def maxLengthBetweenEqualCharacters(self, s: str) -> int: occurrences, result = {}, -1 for i, c in enumerate(s): if c in occurrences: result = max(result, i - occurrences[c] - 1) else: occurrences[c] = ...
def inverse_lookup(xs): result = dict() for i in range(0, len(xs)): x = xs[i] if x not in result: result[x] = i return result def get_with_default(map, key, default): raise NotImplementedError() def count_frequencies(xs): raise NotImplementedError() def css_looku...
import requests from .builder import AmazonRequestBuilder from .response import ( AmazonItemSearchResponse, AmazonItemLookupResponse, AmazonSimilarityLookupResponse, ) class AmazonProductAPI(object): def __init__(self, access_key, secret_key, associate_tag): self.access_key = access_key ...
import os import sys from jinja2 import Template basename = "/home/zcyang/fortinet/ddos/autotest/config" dirname = "acl" def get_settings(**args): template_file = args.get('template') variable_dict = args.get('variable_dict', {}) fname = os.path.join(basename, dirname, template_file) print(fname) ...
""" Created by Alejandro Daniel Noel """ from core import ale_optimizer from core.plant_graph.ExternalSupplier import ExternalSupplier from core.plant_graph.machine import Machine from core.plant_graph.product import Product from core.plant_graph.json_parser import write_json ExternalSupplier.reset_instance_tracker() ...
import wx import os import prefs import datetime, time import EnhancedStatusBar as ESB from utility import platform # get the images once at compile time icons = {} iconpath = os.path.join(wx.GetApp().path, "icons", "features") if os.path.exists(iconpath): for icon_file in os.listdir(iconpath): feature, _ ...
#!/bin/python import sys if "recent_outputs" in sys.argv[1]: import mine.generate_gallery mine.generate_gallery(sys.argv[1]) else: print ("special_execute does not know how to handle ", sys.argv[1])
import collections import copy def is_number(s): try: float(s) return True except ValueError: return False class Component(collections.MutableMapping): def __init__(self, **kwargs): for k, v in list(kwargs.items()): if k not in self._prop_names: ...
import sqlite3 import json import os import requests #Database setup def setUpDatabase(db_name): ''' This function sets up a database. It will return a cursor and connector. ''' path = os.path.dirname(os.path.abspath(__file__)) conn = sqlite3.connect(path+'/'+ db_name) cur = conn.cursor() ...
import os GEOSPATIAL_BOUND = (59.9112, 59.9438, 10.7027, 10.7772) GEOSPATIAL_BOUND_NEW = (59.9040, 59.9547, 10.6478, 10.8095) MAX_DISTANCE = 12 CLUSTER_CENTER_DELTA = 0.01 # Colors for visualizer BLUE, GREEN, RED, BLACK, WHITE = "blue", "green", "red", "black", "white" # Speed of service vehicles VEHICLE_SPEED = 30 ...
from .authorization_handler import AuthorizationHandler from .db_session_manager import DBSessionManager from .json_decoder import JSONDecoder
#!/usr/bin/env python3 from ev3dev2.motor import MoveSteering, MoveTank, MediumMotor, LargeMotor, OUTPUT_A, OUTPUT_B, OUTPUT_C, OUTPUT_D from ev3dev2.sensor.lego import TouchSensor, ColorSensor, GyroSensor from ev3dev2.sensor import INPUT_1, INPUT_2, INPUT_3, INPUT_4 from ev3dev2.button import Button import xml.etree.E...
__author__ = 'avasilyev2' from selenium.webdriver.common.by import By import selenium from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.keys import Keys import time from selenium.common.exceptions import NoSuchElement...
# Enter your code here. Read input from STDIN. Print output to STDOUT class queueUsingTwoStack: def __init__(self): #stack1 for enqueue and stack2 is for dequeue self.stack1=[] self.stack2=[] def enqueue(self,item): self.stack1.append(item) #print(self.stack1) ...
from django import forms from .models import GENDER_CHOICES GENDER_CHOICES = GENDER_CHOICES + [('', '---------')] class ProfileSearchForm(forms.Form): gender = forms.ChoiceField(label='Sex', choices=GENDER_CHOICES, required=False) yearly_income = forms.IntegerField(label='saraly (above)', required=False) ...
import time import pygame import config import pprint from src import backlight from src import metoffer from src import weather from src import clock from src import display from threading import Timer,Thread,Event weather = weather.Data( metoffer.MetOffer(config.metoffice_key) ) clock = clock.DateTime() display = di...
"""proposal_contribution: add private, remove no_refund Revision ID: 4505f00c4ebd Revises: 0f08974b4118 Create Date: 2019-06-07 10:31:47.120185 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '4505f00c4ebd' down_revision = '0f08974b4118' branch_labels = None de...
import cv2 as cv import matplotlib.pyplot as plt def read_image(img): """ Function responsible for read an image :param img: Path to image :return: Image read from the path """ return cv.imread(img) def show_images(images: list, columns: int, rows: int): """ Function responsible for ...
import pickle from flask import Flask, render_template, request app = Flask(__name__) # load the model from disk filename = 'marriage_age_predict_model.pkl' model = pickle.load(open(filename, 'rb')) @app.route('/', methods=['GET']) def Home(): return render_template('index.html') @app.route("/predict", metho...
import pandas import densityx import Tkinter import tkFileDialog import sys import os def open_file_handler(): Tkinter.Tk().withdraw() # Close the root window filePath = tkFileDialog.askopenfilename() print filePath return filePath if __name__ == "__open_file_handler__": open_file_handler() def h...
#!/usr/bin/env /data/mta/Script/Python3.8/envs/ska3-shiny/bin/python ######################################################################### # # # acis_gain_plot_trend.py: plotting gain and offset trends # # ...
#!/usr/bin/env python2 import requests import re import json class FailedRequest(Exception): pass def get_results(user): r = requests.get('https://www.root-me.org/%s' % user, params={'inc': 'score', 'lang': 'fr'}) if r.status_code != 200: raise FailedRequest(r) return r.content def get_status(user): content...
import polars as pl def test_date_datetime() -> None: df = pl.DataFrame( { "year": [2001, 2002, 2003], "month": [1, 2, 3], "day": [1, 2, 3], "hour": [23, 12, 8], } ) out = df.select( [ pl.all(), # type: ignore ...
""" refer to src/1282.cpp """ class Solution: # Runtime: 72 ms, faster than 95.14% # Memory Usage: 12.8 MB, less than 100.00% def groupThePeople(self, groupSizes: List[int]) -> List[List[int]]: d = {} for idx, v in enumerate(groupSizes): if v not in d: d[v] = [id...
import os from flask import Flask, jsonify, request from flask_sqlalchemy import SQLAlchemy from models import db, User, Planets, Characters, Vehicles, Favorite from flask_migrate import Migrate #from flask_script import Manager BASEDIR = os.path.abspath(os.path.dirname(__file__)) app = Flask(__name__) app.config['SQ...
# import json library for json file loading and dumping import json # Import custom errors, IO logger, and client models from .ClientDAO import ClientDAO from .Client import Client, requires_client from error.Error import ClientSetupError from logger.Logger import Logger log = Logger(__name__) class Cli...
# Python Imports import traceback from threading import Thread from datetime import datetime import socket from collections import * # Local Imports import globals import yamaha def setup_ip(self): """ If auto detect ip is enabled, this function will attempt to configure the ip address, otherwise if stati...
import numpy as np import numba # gradients for one element of the loss function's sum, don't call this directly @numba.jit(nopython=True) def ABCD_grad(xa, ya, xb, yb, xc, yc, xd, yd, dab, dac, dad, dbc, dbd, dcd, pab): sum_dist = dab + dac + dad + dbc + dbd + dcd dr_ab = (dab/sum_dist) ...
t = int(input()) while t > 0: n = int(input()) if n == 1: print(9) elif n ==2: print(98) else: print("989",end="") for i in range(1,n-2,+1): print((i-1)%10,end="") print("\t") t = t-1
def solve(bo): find=find_empty(bo) if not find: return True else: row, col= find for i in range(1, 10): if valid(bo, i, (row, col)): bo[row][col]=i if solve(bo): return True bo[row][col]=0 return False def valid(bo, num,...
import time from sklearn.ensemble import BaggingClassifier from sklearn.tree import DecisionTreeClassifier from sklearn.metrics import precision_score from sklearn.metrics import recall_score from sklearn.metrics import f1_score def bootstrap(data_train, data_test, target_train, target_test): time1 = time.time() ...
import pytest from ai.backend.client.session import Session # module-level marker pytestmark = pytest.mark.integration @pytest.mark.asyncio async def test_list_agent(): with Session() as sess: result = sess.Agent.list_with_limit(1, 0) assert len(result['items']) == 1
import os import torch import numpy as np import argparse import random import yaml from easydict import EasyDict import gensim import torch.utils.data as data import torch.backends.cudnn as cudnn import torch.optim as optim import torch.nn as nn from tensorboardX import SummaryWriter import data_helpers from models.st...
import re from django import forms from django.http import QueryDict from django.utils.translation import ugettext_lazy as _ from ..models import artist import datetime from django.conf import settings from application.library.viewer import * class Form(forms.Form): name = forms.CharField(required=True,widget=for...
#!/usr/bin/env python3 # -*- encoding: utf-8 -*- from pwn import * #context.log_level = 'debug' elf = ELF('./dubblesort') libc = ELF('./libc_32.so.6') # Memory locations bin_sh = elf.bss() + 0x100 # Byte sequence alias A4 = 4 * b'A' def main(): proc = remote('chall.pwnable.tw', 10101) #proc = process(['....
from urllib2 import urlopen #from bs4 import BeautifulSoup import requests import time import os from urlparse import unquote from unidecode import unidecode f = open("/home/ubuntu/pageedits/SPARK_AGG_VIEWS/Month/part-00000",'r') lines = f.readlines() article_list = [] not_found_list = [] for line in lines: line ...
#! /usr/bin/env python3 # -*- coding: utf-8 -*- import sys, time from PyQt4 import QtCore, QtGui from pymouse import PyMouse from pykeyboard import PyKeyboard class ScreenSaverPreventer(QtGui.QWidget): def __init__(self): QtGui.QWidget.__init__(self) self.key = PyKeyboard() def doSomet...
__author__ = "Narwhale" s = "ajldjlajfdljddd" s = set(s) s = list(s) s.sort(reverse=False) res = ''.join(s) print(res)
#!/usr/bin/env python import Tkinter root = Tkinter.Tk() canvas = Tkinter.Canvas(root, width=300, height=200) canvas.pack() canvas.create_rectangle(50, 50, 150, 100, fill="yellow") #canvas.create_oval(5, 5, 300, 200, fill="green") #canvas.create_text(150, 100, text="Amazing!", fill="purple", font="Helvetica 26 bold und...
import pytest from openapi_spec_validator import validate_spec from apiflask import Schema as BaseSchema from apiflask.fields import Integer from apiflask import input from apiflask import output from apiflask import doc from .schemas import FooSchema from .schemas import BarSchema from .schemas import BazSchema de...
x = range (1,100) divisors = [] number = int(input("Give me a number to return it's divisors:")) for i in x: if ((number % i == 0)): divisors.append(i) print (divisors)
print('hello') thank you
from flask_api import status from tests.base_login_test_case import BaseLoginTestCase from tests.base_photo_test_case import BasePhotoTestCase class ResizedTestCase(BasePhotoTestCase, BaseLoginTestCase): """ Tests the route for resizing images. """ def test_route(self): """ Tests the...
import logging import configparser import os import time from selenium import webdriver from gui import * from math import ceil from threading import Thread # from selenium.webdriver.common.keys import Keys # from selenium.webdriver.chrome.options import Options log = logging.getLogger(__name__) log.setLevel(logging...
import os import csv from itertools import chain with open('buckets.csv', 'r') as f: reader = csv.reader(f) s3_buckets = list(reader) for buckets in s3_buckets: for bucket in buckets: os.system(f"aws s3 rb {bucket} --force")
"""This program plays a game of Rock, Paper, Scissors between two Players, and reports both Player's scores each round.""" import random moves = ['rock', 'paper', 'scissors'] """The Player class is the parent class for all of the Players in this game""" class Player: def move(self): return 'rock' de...
import json import csv import requests import DiscoveryDetails as dt output_file = open("./training_file.tsv", "w") writer = csv.writer(output_file, delimiter="\t") try: with open ("./Questions.txt", encoding="Windows 1252") as questions: noOfQuestions = 0 for line in questions: print("...
import pygame from view.game_view import GameView from model.game_model import GameModel from controller.player_input import player_input from controller.enemy_input import enemy_input from model.vehicle_handling.spawn_enemies import spawn_chance import time def p1_start(window): game_view = GameView(window) ...
''' 66. Plus One Given a non-empty array of decimal digits representing a non-negative integer, increment one to the integer. The digits are stored such that the most significant digit is at the head of the list, and each element in the array contains a single digit. You may assume the integer does not contain any l...
from cryptography.fernet import Fernet from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import hashes import codecs import os import sys def my_xor(x, y): """ Xor x et y qui sont deux integer """ return (x | y) & (~x | ~y) def generate_ferne...
from DeepLearning.Layers.Affine import * from DeepLearning.Layers.Add import * from DeepLearning.Layers.MulLayer import * from DeepLearning.Layers.ReluLayer import * from DeepLearning.Layers.SigmoidLayer import * from DeepLearning.Layers.SoftmaxWithLossLayer import *
# -*- coding:utf-8 -*- ''' Created on 2016年3月24日 @author: huke ''' def Cycle(): L = ['Bart', 'Lisa', 'Adam'] for x in L: print(x) def Cycle2(): s = 0 for x in range(101): s += x print(s) if __name__ == '__main__': Cycle() Cycle2() input()
# __author__ = 'azhukov' # import cProfile # import random # # from py_skiplist.skiplist import Skiplist # from py_skiplist.iterators import geometric from bintrees import RBTree # # DATA_SET = [random.randint(1, 10**3) for i in range(100000)] # READ_INPUT = [random.randint(1, 10**3) for j in range(1)] # # def run_skip...
class Record(bytearray): """ Unit of physical stored information in the database """ def __init__(self, data: bytes, index: int = 0): """ Creates new record object from initial bytes of data. :param data: initial bytes. :param index: physical index of record in the ...
import os import requests import collections import re import sys import numpy as np class ReadForexData: """read the up-to-date forex data via oanda API""" def __init__(self, parameter_dict): self.mode = parameter_dict['mode'] self.instruments_list = ['EUR_USD', 'USD_JPY', 'USD_CAD', 'GBP_U...
# This is a program which generates password list import itertools f = open("wordlist.txt","w") capletters = ["A","B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"] smallletters = ["a","b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from ctrl_citylist import CitylistCtrl from common.cache import pop_portal_id if __name__ == '__main__': while True: portal_id = pop_portal_id() print(portal_id) clc = CitylistCtrl(portal_id = portal_id) clc.entry()
from modules import cell as c, explosion as ex, explosive as exive class Empty(c.Cell, exive.Explosive): def __init__(self, position): self._position = position @property def position(self): return self._position @position.setter def set_position(self, position): ...
from rest_framework import serializers from .models import Transaction, PolicyRule, PolicyRuleDestination class TransactionSerializer(serializers.ModelSerializer): class Meta: model = Transaction fields = ['id', 'amount', 'destination', 'outgoing'] class PolicyRuleDestinationSerializer(serializ...
import numpy as np import tensorflow as tf import matplotlib.pyplot as plt import matplotlib.patches as mpatches from matplotlib import cm from matplotlib.colors import Normalize from tensorflow import keras from som_keras.classification import classify_SOM, cluster_SOM from sklearn.decomposition import PCA from sklear...
# Generated by Django 2.2.1 on 2019-05-07 04:25 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('portalapp', '0002_auto_20190507_0424'), ] operations = [ migrations.RenameField( model_name='points', old_name='efoort', ...
#!/usr/bin/env python # Copyright (c) 2009 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Verifies simplest-possible build of a "Hello, world!" program using an explicit build target of 'hello'. """ import TestGyp test = Tes...
import nltk import re nltk.download('punkt') nltk.download('stopwords') from nltk.corpus import stopwords from nltk.tokenize import word_tokenize def stripTags(pageContents): # Removes the headers of the html startLoc = pageContents.find('<p>') endLoc = pageContents.find('<br/>') pageContents = pageConten...
import requests import urllib.parse as urlparse from bs4 import BeautifulSoup import pandas as pd import time import os base_url = 'https://www.uta-net.com/' url_by_artist = 'https://www.uta-net.com/artist/2750/4/' response = requests.get(url_by_artist) soup = BeautifulSoup(response.text, 'lxml') links = soup.find_all...
import os import logging logger = logging.getLogger(__name__) from django.conf.global_settings import MEDIA_ROOT from django.db import models from audited_models.models import AuditedModel from .version import Version class ApprovedProjectManager(models.Manager): """Custom project manager that shows only approved...
#-*-coding:utf8-*- from lxml import etree htmlsrc = ''' <!DOCTYPE html> <html> <head> </head> <body> <div id="content"> <ul id="useful"> <li>abc1</li> <li>abc2</li> </ul> <ul id="useless"> <li>没用1</li> <li>没用2</li> </ul> <div id="url"> <a href="http://www.douban.com">douban</...
# -*- coding: utf-8 -*- """ @author: Zhen-Wang 此代码的作用为对训练好的原始模型进行样本的PGD攻击,生成对抗样本。 """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf import numpy as np import os from tensorflow.examples.tutorials.mnist import input_dat...
#!/usr/bin/python3.4 # -*-coding:Utf-8 prenoms = ["Anthony", "Mathilde", "Simon", "Mateu", "Ugo"] prenoms.sort() print(prenoms) list_prenoms = ["Anthony", "Mathilde", "Simon", "Mateu", "Ugo"] s_prenom = sorted(list_prenoms) print(s_prenom) print(list_prenoms) etudiants = [ ("Clément", 14, 16), ("Charles", 12...
class hotelkingston: def __init__(self, rt='', n=0, s=0,r=0,c = 0, d = 0, a = 1800, Name='',Address='', cindate = '', coutdate='', rowno = 100): print("WELCOME TO KINGSTON HOTEL") print("Izhevsk, Russia, Pecochnaya 38A 426069:\n") self.rt = rt self.r = r self.t = '' ...
#All Configurations FILE_DUPLICATE_NUM = 2 # how many replications stored FILE_CHUNK_SIZE = 1024*1024 # 1KB, the chunk size, will be larger when finishing debugging HEADER_LENGTH = 16 # header size SAVE_FAKE_LOG = False # for single point failure, will greatly reduce the performance IGNORE_LOCK = True # for test...
import os import sys sys.path.insert(0, 'scripts') import experiments as exp sys.path.insert(0, os.path.join("tools", "families")) sys.path.insert(0, os.path.join("tools", "mappings")) import fam import ete3 import get_dico def build_short_names_seq(): alphabet = " ABCDEFGHIJKLMNOPQRSTUVWXYZ" seq = [] for a in a...
def count_correct_characters(correct, guess): if len(correct)!=len(guess): raise "different length" return sum(1 for x in range(len(correct)) if correct[x]==guess[x]) ''' Consider a game, wherein the player has to guess a target word. All the player knows is the length of the target word. To help them in the...
from binance_f import RequestClient from binance_f.constant.test import * from binance_f.base.printobject import * from binance_f.model.constant import * import define def getallorder (): request_client = RequestClient(api_key=define.api_key, secret_key=define.secret_key) result = request_client.get_op...
# coding: utf-8 # --- # # _You are currently looking at **version 1.5** of this notebook. To download notebooks and datafiles, as well as get help on Jupyter notebooks in the Coursera platform, visit the [Jupyter Notebook FAQ](https://www.coursera.org/learn/python-data-analysis/resources/0dhYG) course resource._ # ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models from ahead.utils.db import DateTimeModel SECTION_MODULE_CHOICES = (('article', '文章列表'), ('simple', '单页面')) # class Foundation(DateTimeModel): # pass # class module(DateTimeModel): # name = models.CharField('模块名称', ...
# Copyright (c) 2012-2021, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. # # *** Do not modify - this file is autogenerated *** # Resource specification version: 43.1.0 from troposphere import Tags from . import AWSObject, AWSProperty from .validators import integer class ...
class Solution: def allPossibleFBT(self, n: int) -> List[TreeNode]: if n % 2 == 0: return [] if n == 1: return [TreeNode()] res = [] for i in range(1, n, 2): left = self.allPossibleFBT(i) right = self.allPossibleFBT(n - i - 1) ...
import nmap from prettytable import PrettyTable # scan network - dispaly all opened ports in given range nm = nmap.PortScanner() nm.scan('156.17.40.1-255', '25') tab = PrettyTable(["IP address", "Protocol", "Port", "Product name", "Version", "Extra info"]) for host in nm.all_hosts(): for pro...
from numpy import genfromtxt import numpy as np vector_file = "/Users/mengqizhou/Desktop/datamining/programing3/data/initialdata/feature_vectors.csv" weight_file = '/Users/mengqizhou/Desktop/datamining/programing3/data/initialdata/weight.csv' weighted_vector = '/Users/mengqizhou/Desktop/datamining/programing3/data/ini...
import os from random import randrange import time import uuid from novaclient.client import Client import paramiko import sys if len(sys.argv) < 2: print "WRONG INPUT!" print "Usage: python create_instance.py <number_of_workers>" sys.exit(0) else: NR_OF_WORKERS = int(sys.argv[1]) print "Creating " + str(N...
HTML_SPACE = '&nbsp;' def prefill_with_character(value, column_length=4, fill_char=HTML_SPACE): """Prepend value with fill_char for given column_length""" str_val = str(value) fill_length = column_length - len(str_val) return fill_char*fill_length + str_val
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models from pycdek import AbstractOrder, AbstractOrderLine, Client class Product(models.Model): title = models.CharField('Название', max_length=255) weight = models.PositiveIntegerField('Вес, гр.') price = models.Decimal...
from common.run_method import RunMethod import allure @allure.step("极客数学帮(家长APP)/订单/计算订单总价(旧)") def app_order_countOrderPrice_post(params=None, body=None, header=None, return_json=True, **kwargs): ''' :param: url地址后面的参数 :body: 请求体 :return_json: 是否返回json格式的响应(默认是) :header: 请求的header :host: 请求的...
import pickle from code import compute_model dataset = [] with open('dataset.pickle', 'rb') as f: dataset = pickle.load(f) i = 0 while i < len(dataset): j = i + 1 while j < len(dataset): if ((dataset[i]["input"] == dataset[j]["input"]) and (dataset[i]["output"] != dataset[j]["output"])): ...
import base64 import os import re from flask import request, Flask, jsonify from PIL import Image from train import train as train from predict import predict from utils import decode_image app = Flask(__name__) @app.route("/", methods=["GET"]) def home(): return "Fashion AI" @app.route("/train", methods=["GE...
# -*- coding: utf-8 -*- import os import re import yaml import glob import six from string import Template import docutils from collections import OrderedDict from django.conf import settings from reclass import get_storage from reclass.core import Core from reclass.settings import Settings from architect import utils...
''' Look at crops from an experiment, given some property filters. ''' import config import numpy as np import os from os.path import isdir, isfile, join from lib.Database import Database import matplotlib.pyplot as plt import shutil async def main(args): await view_crops() async def view_crops(): ...
# -*- coding: utf-8 -*- # __author__ = "zok" 362416272@qq.com # Date: 2019-10-15 Python: 3.7 """ 腾讯防水墙 【不提供完整代码】 仅提供部分参数以供参考 """ # 滑块参数解密
Descriptive Statistics For pandas Dataframe Import modules import pandas as pd data = {'name': ['Jason', 'Molly', 'Tina', 'Jake', 'Amy'], 'age': [42, 52, 36, 24, 73], 'preTestScore': [4, 24, 31, 2, 3], 'postTestScore': [25, 94, 57, 62, 70]} df = pd.DataFrame(data, columns = ['name', 'age', '...
from django.test import TestCase from .models import StopWord class SimpleTest(TestCase): def test_serialization(self): """Tests the serialization of a StopWord """ s = StopWord(word='test') self.assertEqual(s.get_stopword_dict(), {'id': s.id, 'user': '', 'query': '', 'word': s.wo...
# -*- coding: utf-8 -*- import sys reload(sys) sys.setdefaultencoding('utf-8') def ex3(): testlist = [] n = int(raw_input()) for i in range(0, n+1): testlist.append(fibo(i)) print testlist[n] def fibo(n): if n == 0: return 0 elif n == 1: return 1 else: ...