text
stringlengths
38
1.54M
import os from CoreScripts.CfgParserFactory import CfgParserFactory from ParametersParsing import GeneralParameters from LogParser import LogParser, TableType from Logger import Logger from CoreFunctions import CreateConfigParser, WriteStringToFile, MakeTableInPercents, PrintTableToFile class ComparisonResu...
from django.conf import settings from django.db.models import Sum from django.shortcuts import render from poyosei.models import * from django.views.decorators.csrf import csrf_exempt @csrf_exempt def operation(request): continuer = 'init' mouvements = "" planteurs = Planteur.objects.all() for p in planteurs...
"""def countCC(M): row= len(M) col= len(M[0]) visited = [[False]*col]*row count = 0 for i in range(0,row): for j in range(0,col): if (M[i][j]==1 and visited[i][j]==False): dfs(M, i, j ,visited) print (i,j) count =count+1 ...
import wolframalpha import wikipedia import PySimpleGUI as sg import pyttsx3 #for text to speech client = wolframalpha.Client("RT85GL-4VV66LR9G6") sg.theme('DarkBlack') layout =[[sg.Text('Enter a command'), sg.InputText()], [sg.Button('Ok'), sg.Button('Cancel')]] window = sg.Window('PVA', layout) engine = pyttsx3.in...
import os from datetime import timedelta class Config(object): DEBUG = False USE_FAKE_SERVICES = False SQLALCHEMY_DATABASE_URI = 'sqlite:///../data/bark.db' UDB_URL = 'https://cgi.cse.unsw.edu.au/~csesoc/udb/' UDB_USER = 'udb' LDAP_HOST = 'ldap://ad.unsw.edu.au' EVENT_LEEWAY = timedelta(ho...
import re import graphbrain.constants as const from graphbrain import hedge from graphbrain.hyperedge import UniqueAtom def _edge2text(edge, parse): atoms = [UniqueAtom(atom) for atom in edge.all_atoms()] tokens = [parse['atom2token'][atom] for atom in atoms if atom in parse['atom2token']] if len(tokens...
define wt_N = 1100000 define speed = 80 define acc_grav = 9.8 define mass_kg = 1100000/9.8 input weight_ mass_ = weight_/9.8 allowed_speed = 80*9.9*mass_/110000 input speed_actual if curve: input r input theta speed_max = sqrt(r*9.8*tan(theta))*3.6 else: allowed_speed = speed_max speed_critical = minimum(all...
# -*- coding: utf-8 -*- """ Created on Tue Dec 4 09:52:19 2018 @author: alunoic """ import cv2 import numpy as np #%% im1 = cv2.imread("lena.png", cv2.IMREAD_GRAYSCALE) im2 = cv2.imread("baboon.png", cv2.IMREAD_GRAYSCALE) x_range, y_range = im1.shape im_res = np.zeros([x_range, y_range], dtype=np.uint8) #%% LOOP...
import sys import hashlib input_file = open(sys.argv[1]) input_lines = input_file.readlines() for line in input_lines: private_key = line.lstrip().rstrip() counter = 1 magic_number_1st_half = -1 magic_number_2nd_half = -1 adventcoin = private_key + str(counter) while True: digest =...
# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- """Azure S...
# Use arguments with move statements to move farther. hero.moveRight(3) hero.moveUp() hero.moveRight() hero.moveDown(3) hero.moveRight(2)
import os import boto3 def handler(event, context): s3 = boto3.resource("s3") content = "You are the best!" s3.Object(os.environ.get("BUCKET_NAME"), "hourly.txt").put(Body=content)
print y_train1 binarizer = MultiLabelBinarizer().fit(y_train1) y_train = binarizer.transform(y_train1) print y_train print binarizer.inverse_transform(y_train)
# Playstation controller Code # For controller pairing: # In the terminal place the following code: # setup sudo apt-get install bluetooth libbluetooth3 libusb-dev sudo systemctl enable bluetooth.service sudo usermod -G bluetooth -a pi # pairing wget http://www.pabr.org/sixlinux/sixpair.c gcc -o sixpair sixpair.c -...
from models import Calendar class Events: def __init__(self): self.events = Calendar.objects.all()
/* Common elements in two sorted lists with duplicates (return all duplicates if exists) */ a = [1, 1, 2, 2, 3, 5, 8, 13, 21, 34, 55, 89] b = [1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] c = [] for i in a: if i in b and i not in c: c.append([i]) print(c) def common_member(a, b): a_set = set(a) ...
testCaseNums = list() def getLastNum(num): multiple = 1 num_basket = list() realnum = num while(len(num_basket)<10): num = 0; num = realnum*multiple num = str(num) for i in range(len(num)): num_basket.append(num[i]) num_basket = list(set(num_bask...
def find_cycle(connections): def findloop(point, route, startpoint, lastpoint, connections): for (i,j) in connections: if point in (i,j): if point == j: i,j = j,i if j != lastpoint: if j == startpoint: ...
## Unconditional Deviation instructions ## # # Opcode | Symbolic representation | Description # 00001101 | JUMP M(X,0:19) | Apanha a próxima instrução da metade esquerda de M(X) # 00001110 | JUMP M(X,20:39) | Apanha a próxima instrução da metade direita de M(X) class UnconditionalDeviation(): de...
def ejemplo_for(): #x es una variable que toma los valores comprendidos en #el rango i=input("Introduzca un numero: ") if(i%2==0): if(i%3==0): print i, "es par" print i, "es multiplo de 3" else: print i, "es impar" ...
# # import requests # # from flask-test import users # # # res = requests.get("https://api.exchangeratesapi.io/latest?base=USD") # # # data = res.json() # # # results = data['rates'] # # # currency_value = results['ILS'] # # # x = float(input("Please enter an amount of Shekeles to convert to Dollars: ")) # # # print(x...
#-*-coding:utf8;-*- #qpy:3 #qpy:console print("This is console module") a=(' * ') b='' for i in range(1,15): b=a*i print(b)
""" This module acts as the task scheduler. Coroutine functions can be spawned, joined or killed """ import Queue import collections from .task import Task __author__ = 'stevet' _ready_queue = Queue.Queue() _job_registry = {} _signal_list = {} _join_list = collections.defaultdict(list) _await_list = collections.def...
from gmpy2 import * print('m1=m+p1') print('m2=m+p2') n=int(input("n(hex):")[2:],16) c1=int(input("c1(hex):")[2:],16) p1=int(input("p1(hex):")[2:],16) c2=int(input("c2(hex):")[2:],16) p2=int(input("p2(hex):")[2:],16) print('m1=a*m2+p1-p2') a=int(input("a(hex):")[2:],16) b=p1-p2 m=((3*b*((a**3)*c2-b**3)*invert(c1-c2*(a*...
# -*- coding: utf8 -*- #快速排序 # # 算法思想 # 快速排序的核心思想在于:首先在这个序列中随便找一个数作为基准数,然后将这个序列中所有比基准数大的数放在该数字的右边,比基准数小的数放在该数字的左边。 # 第一轮排序结束之后,再分别对已经好的基准书左边(比基准数小)和基准书右边(比基准书大)的数字序列重复上述操作,用递归形式即可实现快速排序,完成对整个序列的排序。 # # 算法步骤 # 为了清晰地展示快速排序的原理,这里使用一个例子来具体说明快速排序算法排序的过程。 # 假定现在要对数字序列 [4, 2, 7,8, 0,1, 5,23] 进行快速排序。 # 我们假设最左边的编号为i,最左边的编号为j,不...
def get_sent_message(bot): send_message_args = bot.mock_calls[0][1] text = send_message_args[1] return text
# https://atcoder.jp/contests/abc161/tasks/abc161_d import sys def input(): return sys.stdin.readline().rstrip() sys.setrecursionlimit(10 ** 7) K = int(input()) nums = [] def make_num(keta, str_num): if len(str_num) == keta: nums.append(str_num) return if str_num[-1] == '0': ...
# Import required library import pandas as pd # Import the CSV file into Python A_data = pd.read_csv("../input/hr-ana/train.csv") A_data = A_data.dropna() # Directly assigning individual field columns different integer value # # gender A_data.gender[A_data.gender == 'm'] = 1 #male -> 1 A_data.gender[A_data.gender ==...
#!/usr/bin/Python # Filename: backup_ver1.py #是是不是还需要安装什么压缩软件啥的 import os import time source =[r'D:\IDM下载文件\考研辅导班\电子科大本科软件工程上课PPT'] target_dir = r'D:\MyDrivers\hotfix' target = target_dir + time.strftime('%Y%m%d%H%M%S') + '.zip' zip_command = "zip -qr '%s' %s" % (target, ' '.join(source)) # Run the backup ...
from werkzeug.security import generate_password_hash, check_password_hash from itsdangerous import TimedJSONWebSignatureSerializer as Serializer from flask import current_app from flask_login import UserMixin from . import db class Fenxi(db.Model): __tablename__ = 'pingjufenxi' id = db.Column(db.Integer, prim...
from sanic import Sanic from sanic.response import json from wym.playlist import Playlist app = Sanic() playlist = Playlist() queue = [] @app.route("/add", methods=['POST']) async def add_url(request): return json({"hello": "world"}) @app.route("/playlist", methods=['GET']) async def show_playlist(request): ...
import logging from multiprocessing import Process import zmq from zmq.eventloop import ioloop, zmqstream from config import c from base import ZMQProcess from handler import AgentStreamHandler from puppet import Puppet from utils import import_from_string log = logging.getLogger(__name__) class Agent(ZMQProcess)...
import codecs import xml.etree.ElementTree as ET import re def more(f, n=10): with open(f) as c: lines = c.readlines() while lines: print(' '.join(lines[:n])) lines = lines[n:] if input('more?') != 'y': break #with codecs.open('rates', 'rb', 'cp1251') as f: #co...
def read_input(): # open file for reading in_file = open('word.in', 'r') # read m and n coords = in_file.readline().strip().split() m = int(coords[0]) n = int(coords[1]) # skip blank line in_file.readline() # read the grid of characters word_grid = [] for _ in range(m): ...
# Generated by Django 2.1 on 2019-02-27 10:19 import datetime from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('users', '0001_initial'), ] operations = [ migrations.AlterField( model_name='userprofile', name='add_t...
class Node: def __init__(self, val, next = None): self.val = val self.next = next def getval(self): return self.val def getnext(self): return self.next class LinkedList: def __init__(self, list): previous = Node(list[0]) self.head = previous ...
import scrapy from handReqPro.items import HandreqproItem scrapy手动请求发送实现全站数据爬取 - yield scrapy.Request(url=,callback=) callback指定解析函数,用于解析数据 - yield scrapy.FormRequest(url=,callback=,formdata=):POST fordata:字典,请求参数 class DuanziSpider(scrapy.Spider): name = 'duanzi' # allowed_domains = ['www.xxx.com'] ...
from ..Backend.webAdapter import * print("StartupManager global space") def initializeBackendStartup(): print("\n\n\nStartup initialized") n = NoosAdapter() print("Startup complete\n\n\n")
from ophyd import Component as Cpt from ophyd import Device, EpicsSignal, EpicsSignalRO from .interface import BaseInterface from .pv_positioner import PVPositionerIsClose EVR_TICK_NS = 8.3 class EvrMotor(PVPositionerIsClose): """ PV Positioner for adjusting an EVR channel. Moves that are less than one...
#-*- coding: UTF-8 -*- import tornado.web import tornado.websocket import json import uuid import tornado.ioloop import os g_machines = {} g_commanders = {} def JsonResponser(code, result, msg): response = {} response['code'] = code response['result'] = result response['msg'] = msg return jso...
''' Created on Dec 17, 2016 @author: Mark ''' import md5, copy lplen = 0 spath = [] splen = 1e6 paths = [] passw = "bwnlcvfs" def opened(digest): return [False if int(x, 16) <= 10 else True for x in digest[:4]] def move(state): nextstates = [] md = md5.new() md.update(state["pass"] + state["...
# -*- coding: utf-8 -*- # @Time : 2018/8/7 09:34 # @Author : Xiaoyu Xing # @File : feature_pu_model.py import torch import torch.nn as nn from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence import numpy as np import copy from torch.autograd import Variable import argparse from utils.data_uti...
from django.contrib.gis.db import models ESTADO_CHOICES = ( ('EJC1', 'EN EJECUCION CON 1ER. DESEMBOLSO'), ('EJC2', 'EN EJECUCION CON 2DO. DESEMBOLSO'), ('EJC3', 'EN EJECUCION CON 3ER. DESEMBOLSO'), ('IR', 'INTERVENIDO CON RESOLUCION'), ('LIQ', 'PROYECTOS LIQU...
import pyaes import os import math from datetime import datetime as dt class AES_GCM_128: def __init__(self, i_key): assert len(i_key) == 16, 'This class supports 128-bit key only!' self.i_key = i_key # Plain text and aad size self.plt_size = 0 self.aad_size = ...
# # Grab a single image # store it on the desktop (name: "NdBx-00000.jpg") and display it # try: isight = ximport("isight") except: isight = ximport("__init__") reload(isight) import os destfolder = os.path.expanduser( "~/Desktop" ) imagepath = isight.grab( destfolder=destfolder ) w, h = imagesize(ima...
# Javier Gálvez Obispo import random import hashlib from aritmetica_modular import * def knapsack_llave_privada(n, cota): """Genera una llave privada para la función mochila (knapsack). Input: n, tamaño de la secuencia. cota, máxima diferencia entre a_i y a_(i+1). Output: secuencia, secuencia ...
# parse Twitter streaming API results (background corpus) # write log probabilities each word, tab-delimited, one per line import sys, json, re, gzip from math import log counter = {} total = 0.0 def legal(w): return not (len(w) == 0 or w[0] == '@') # saves memory CS_DICT = {} def CS(s): return CS_DICT.setd...
# coding: utf-8 # Standard Libraries import asyncio import logging # Dopplerr from dopplerr.config import DopplerrConfig log = logging.getLogger(__name__) class PeriodicTask(object): job_id: str = None job_type = 'interval' job_default_kwargs = {'max_instances': 1} scheduler = None seconds: int...
#_author:leo gao #encoding:utf-8 from Utils.common import ci_url video_command_url = '%s/#/spzhsystem/spzh' % ci_url
f = open('a.txt','r') f_read = f.readlines() f_display = [lines.strip() for lines in f_read] for i in f_display: print(i) f.close()
from django.contrib import admin from django.urls import path from django.conf.urls import url from . import views urlpatterns = [ path('ROE-valuation-Calculator', views.ROE_valuation.as_view(), name='ROE_valuation'), ]
import sys import logging if sys.version_info >= (3, 0): from configparser import ConfigParser else: from ConfigParser import ConfigParser _LOG = logging.getLogger('__main__.' + __name__) class Config(object): ip = '' port = 0 debug_interval = -1 flush_queue_interval = 0 @classmethod ...
from django.shortcuts import render from bs4 import BeautifulSoup import requests from requests.compat import quote_plus from .models import Search import datetime Base_Mentor_Url="https://www.codementor.io/experts?q={}" Base_Post_Url = "https://www.codementor.io{}" def home(request): return render(requ...
import simplejson as json a={"name":"Divid", "class":"I", "age":18 } with open("json_object.json","w")as f: json.dump(a,f,indent=6)
########################################### # Let's Have Some Fun # File Name: 648.py # Author: Weilin Liu # Mail: liuweilin17@qq.com # Created Time: Tue Feb 19 19:40:48 2019 ########################################### #coding=utf-8 #!/usr/bin/python #648. Replace Words class TrieNode: def __init__(self): ...
import sys import os import platform import djcelery djcelery.setup_loader() from django.contrib.messages import constants as messages # =========================== # = Directory Declaractions = # =========================== SITE_ROOT = os.path.dirname(os.path.realpath(__file__)) CURRENT_DIR = os.path.dirname(__...
from state import State import random from utils import cprint, clear_screen from utils import ( BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE ) class MiniMaxAgent: """ TicTacToe agent that implements Minimax choice criteria """ def choice(self, state: State, tur...
""" """ # Classes class City: """ Represents a city in an input file. Properties: grid (int, int): (number of rows, number of columns) vehicles (list of Vehicle): list of all available vehicles rides (list of Ride): list of all rides ride_num: number of rides bonus: p...
from django.shortcuts import render, redirect from django.views.decorators.http import require_http_methods from django.http import JsonResponse import json from ..models.product import Product from ..models.order import Order, OrderItems @require_http_methods(["POST"]) def create_order(request): """ View to crea...
import sqlite3 class User: def __init__(self, _id , name , username): self.id = _id self.name = name self.username = username @classmethod def find_by_username(cls ,username, password): connection = sqlite3.connect("data.db") cursor = connection.cursor() resul...
# Generated by Django 3.2.3 on 2021-07-17 11:58 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('secureadmin', '0003_usedoffer'), ] operations = [ migrations.AddField( model_name='usedoffer', name='is_ordered', ...
import os import resource import sys import time import pdb sys.path.append("../utils") import snap import testutils if __name__ == '__main__': if len(sys.argv) < 3: print """Usage: """ + sys.argv[0] + """ <srcfile> <dstfile> postsfile: posts.tsv file from StackOverflow dataset dstfile: d...
from django.db import models from django.contrib.auth.models import User from mindfinder.settings import MEDIA_ROOT from django.core.files.storage import FileSystemStorage DEFAULT_AVATAR_IMAGE = 'avatars/no_photo_icon.png' class UserProfile(models.Model): user = models.OneToOneField( User, on_de...
from .models import Category # For return the all categories def categories(request): return { 'categories' : Category.objects.all() }
import ServerConnection run = True while(run): num = ServerConnection.openConnection() #Create a connection with the frontend if (num == None): run = False
#!/usr/bin/env python from __future__ import print_function import sys import os import random import networkx as nx import numpy as nm import community import time import gc import eigen_graph as eg import graph_utils as gu sys.path.append("twoK") from twok_simple import joint_degree_graph sys.path.append("twofiveK"...
from rest_framework import serializers from wallet_core.models import UserPHPWallet, PHPWalletTransaction __author__ = 'kaushal' class PHPWalletListSerializer(serializers.ModelSerializer): """ Provide list of accounts for payment recipient list requested All, fields are read only """ owner = seri...
def dele(key): myDict.pop(key) print(myDict) myDict = {'java':100,'python':20,'c':300, 20:22, 32:42} dele('java') dele('python')
score1 = int(input('숫자를 입력하세요.')) if score1 > 10 : if score1 % 2 == 0: print("입력한 숫자 %d 는 10보다 큰 짝수 입니다." % score1) else : print("입력한 숫자 %d 는 10보다 큰 홀수 입니다." % score1) else : if score1 % 2 == 0: print("입력한 숫자 %d 는 10보다 크지않은 짝수 입니다." % score1) else : print("입력한 숫자 %d 는 ...
# Имя: GetTelegramChatMembers.py # Автор: Klachkov (reserfodium) Valery from telethon import TelegramClient, errors from telethon.tl.functions.channels import GetParticipantsRequest from telethon.tl.types import ChannelParticipantsSearch import getpass import sys # Вывод помощи def usage(): print( ...
import requests from django.conf.urls import url from django.contrib import admin from django.shortcuts import redirect from nested_inline.admin import NestedStackedInline, NestedModelAdmin from cmdb.admins import * from cmdb.models import * from deploy_manager.models import * from saltjob.salt_https_api import salt_a...
#! /usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function import os ''' Default configurations of model train and test ''' ##### LOG_DIR = 'result_exp' # where checkpoints, logs are saved RUN_NAME = 'hl_tes...
# This file is part of Booktype. # Copyright (c) 2012 Aleksandar Erkalovic <aleksandar.erkalovic@sourcefabric.org> # # Booktype is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the Li...
from odoo import models, fields, api from odoo.exceptions import ValidationError from .belonging import CATEGORIES from Crypto.PublicKey import RSA class User(models.Model): _inherit = "res.users" rrn = fields.Char('RRN Code') req_categ = fields.Selection(CATEGORIES, 'Desired category') req_price = f...
class Solution(object): def searchMatrix(self, matrix, target): """ :type matrix: List[List[int]] :type target: int :rtype: bool """ m, n = len(matrix), len(matrix[0]) def find(target, left, right): if matrix[left / n][left % n] == target or matri...
import tkinter as tk from typing import List, Tuple from unittest import mock from picpick import widgets from picpick.model import Tag class FileList(widgets.FileList): def __init__(self, master): super().__init__(master) self._callback = mock.Mock() self.bind('<<FileListSelect>>', lamb...
import torch import torch.nn as nn cfg = { 'A': [64, 'M', 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'], 'B': [64, 64, 'M', 128, 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'], 'D': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'M', 512, 512, 512, 'M', 512, 512, 512, 'M'], 'E': [6...
# -*- coding: utf-8 -*- """ Created on Fri Aug 23 21:24:10 2019 @author: dabing """ import numpy as np import csv import loadData from RBM import rbm #--------------准备--------------- #-----读取数据----- allData = loadData.allData allFeatures = allData[:,0:77] contentFeatures = allData[:,0:34] traffi...
# %load q01_plot_deliveries_by_team/build.py import pandas as pd import numpy as np import matplotlib.pyplot as plt plt.switch_backend('agg') ipl_df = pd.read_csv('data/ipl_dataset.csv', index_col=None) # Solution def plot_deliveries_by_team(): plt.figure() plt.bar(ipl_df.index.ipl_df) plt.xlabel('battin...
""" Instrument widget """ # Standard library modules. # Third party modules. # Local modules. from pyhmsa_gui.spec.condition.condition import _ConditionWidget from pyhmsa_gui.util.parameter import TextAttributeLineEdit from pyhmsa.spec.condition.instrument import Instrument # Globals and constants variables. clas...
#!/usr/bin/python import pygame class tzone(pygame.sprite.Sprite): def __init__(self,x, y, width, height, color): super().__init__() #это используется self.image = pygame.Surface([width, height]) #создание поверхности self.image.fill(color) #заполнить цветом self.rect = self.image.get_rect() sel...
from DataLoader import RetinaDataset #Show cropping and rotation with low probability test = RetinaDataset(file_path="/data/targets", transforms=[Rotate(p=0.5), RandomCrop(p=0.5, height=300, width=300)]) sample = test[0] print(sample['image']) plt.imshow(sample['image'], cmap='gray') plt.show()
# -*- coding: utf-8 -*- """ Created on Sat Dec 2 17:18:14 2017 @author: oliver.cairns """ import csv data = [] with open("input_2.txt", newline="") as inputfile: for row in csv.reader(inputfile): data.append(row) # data = [["2x3x4"]] # data = [["1x1x10"]] clean_data = [[int(y) for y in x[0].split("x")...
from class1 import course1 dayo = course1("temi",32) biodun = course1("lola",45) print(dayo.name)
# import requests # import json # # # send_url = "http://api.ipstack.com/check?access_key=f8847d936deb1c40496b1d6dd89e51b1" # geo_req = requests.get(send_url) # geo_json = json.loads(geo_req.text) # latitude = geo_json['latitude'] # longitude = geo_json['longitude'] # city1 = geo_json['city'] # # # print(city1) import...
from Q1_30.Q9 import isPalindrome __author__ = 'Varun Nayyar' __date__ = "24/02/13 12:33 AM" __copyright__ = "Company Confidential. Copyright (c) Cochlear Ltd 2012." if __name__ == "__main__": palSum = 0 for i in xrange(int(1e6)): if isPalindrome(i) and isPalindrome(bin(i)[2:].lstrip("0")): ...
"""Commands to facilitate conversion to PDF.""" from copy import copy from pathlib import Path import asyncio from .utils import _error def html_to_pdf(html_file, pdf_file): """ Convert arbitrary HTML file to PDF using pyppeteer. Parameters ---------- html_file : str A path to an HTML fi...
import functools @functools.lru_cache(None) def decode(num_str): if not num_str: return 1 if len(num_str)==1: return 1 if num_str[0]!='0' else 0 if int(num_str[0]) > 2: return decode(num_str[1:]) else: return decode(num_str[1:]) + decode(num_str[2:]) import functools @functools.lru_ca...
import csrgraph as cg from nodevectors.embedders import BaseNodeEmbedder class GGVec(BaseNodeEmbedder): def __init__(self, n_components=32, order=1, learning_rate=0.1, max_loss=10., tol="auto", tol_samples=30, exponent=0.33, threads=0, negative_ratio=0.15, ...
# from django.http import HttpResponse # from django.views.decorators.csrf import csrf_exempt # from rest_framework.renderers import JSONRenderer # from rest_framework.parsers import JSONParser # from rest_framework.decorators import api_view # from django.http import Http404 # from rest_framework.views import APIView ...
#!/usr/bin/env python3 # coding=utf-8 """Model dec """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import subprocess import json import time import codecs import logging import _pickle as pkl from tqdm import tqdm from gen_ner import read_data...
import uuid from django.db import models from django.db.models import Q from .Media import Media from .maiofields import FixedCharField #: Quick way of saying "NULL" for Django models NULL = {'null': True, 'blank': True} class Playlist(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4...
import sqlite3 from random import randint import string import enum class Permission(enum.Enum): NONE = 0 HIGH = 3 MEDIUM = 2 LOW = 1 class Database: def __init__(self, name="database.db"): self.name = name self.db = sqlite3.connect(self.name) def create_table(self): ...
''' Say you have an array for which the ith element is the price of a given stock on day i. If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit. Example Given array [3,2,3,1,2], return 1. ''' class Solution: d...
import pandas as pd import matplotlib.pylab as pl import numpy as np import os import matplotlib.pyplot as plt from patsy import dmatrices from sklearn.linear_model import LogisticRegression from sklearn.cross_validation import train_test_split from sklearn import metrics from sklearn.cross_validation import cross_val_...
""" Code Challenge Name: Operations Function Filename: operation.py Problem Statement: Write following functions for list operations. Take list as input from the User Add(), Multiply(), Largest(), Smallest(), Sorting(), Remove_Duplicates(), Print() Only call Print() function to display the r...
# -*- coding: utf-8 -*- # 图片数据 # 20180330 from flask import Flask, Response, jsonify, current_app import re from app.model.image import * from . import api from flask_uploads import UploadSet, IMAGES, configure_uploads, ALL from flask import request, Flask, redirect, url_for, render_template from manage import photos i...
# Generated by Django 3.2.7 on 2021-09-09 16:33 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('api', '0005_contact_emails'), ] operations = [ migrations.AlterModelOptions( name='contact', options={'ordering': ['...
from queue import Queue import threading from .http_common import * import simple_http_client import utils def pack_headers(headers): out_list = [] for k, v in headers.items(): if isinstance(v, int): out_list.append(b'%s: %d\r\n' % (utils.to_bytes(k), v)) else: out_lis...
import asyncio from functools import reduce from pathlib import Path import pytest import aioftp @pytest.mark.asyncio async def test_patched_sleep(skip_sleep): await asyncio.sleep(10) assert skip_sleep.is_close(10) SIZE = 3 * 100 * 1024 # 300KiB @pytest.mark.parametrize("times", [10, 20, 30]) @pytest.m...