text
stringlengths
8
6.05M
from operator import ne import os from flask import Flask, request, abort, jsonify from flask_sqlalchemy import SQLAlchemy from models import setup_db, Movies,Actors, db_drop_and_create_all from flask_cors import CORS from auth import AuthError, requires_auth def create_app(test_config=None): # create and configur...
import os postgres_endpoint = os.environ['DP_ACCTMGMT_POSTGRES_URL'] bucket_name = os.environ['DP_ACCTMGMT_S3_BUCKET'] bucket_file_name = os.environ['DP_ACCTMGMT_EXPORTED_FILENAME'] aws_access_key_id = os.environ['DP_ACCTMGMT_AWS_ACCESS_KEY_ID'] aws_secret_access_key = os.environ['DP_ACCTMGMT_AWS_SECRET_ACCESS_KEY'] ...
# -*- coding: utf-8 -*- # Copyright (c) 2019, DBF and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe.model.document import Document class AccommodationPackagePricingItem(Document): def add_or_update_item(self): items = [fr...
# COMP90024 Team 1 # Albert, Darmawan (1168452) - Jakarta, ID - darmawana@student.unimelb.edu.au # Clarisca, Lawrencia (1152594) - Melbourne, AU - clawrencia@student.unimelb.edu.au # I Gede Wibawa, Cakramurti (1047538) - Melbourne, AU - icakramurti@student.unimelb.edu.au # Nuvi, Anggaresti (830683) - Melbourne, AU - na...
# ----------User Defined Function------------ def product(): n1 = int(input("Enter first number: ")) n2 = int(input("Enter second number: ")) prod = n1*n2 print(n1, " X ", n2, " = ", prod) product() # ------------Return statement-------------- def sum(): n1 = int(input("Enter first number: ")) ...
import pygame import random def main(): WIDTH = 600 HEIGHT = 400 WHITE = (255, 255, 255) loop = 0 starting_point = (WIDTH // 2, HEIGHT // 2) positions = [starting_point] separation = int(input('Type the separation between dots(int):')) frequency = int(input('Select the frequency o...
from django.conf import settings from django.db import models from django.shortcuts import reverse from products.models import Product # LABEL_CHOICES = ( # ('P', 'primary'), # ('S', 'secondary'), # ('D', 'danger') # ) # class Order(models.Model): # order_no = models.CharField(max_length=10, unique=...
import sys from rosalind_utility import parse_fasta from math import factorial if __name__ == "__main__": ''' Given: A collection of k (k≤100) DNA strings of length at most 1 kbp each in FASTA format. Return: A longest common substring of the collection. (If multiple solutions exist, you may return any ...
#!/usr/bin/env python # # See LICENSE file for copyright and license details. """Setup.py: build, distribute, clean.""" import os import sys from distutils import log from distutils.core import setup from glob import glob setup( name='qt4reactor', version='1.0', license='MIT', author='Glenn H. Tarb...
#!/bin/python vowels = ("a", "A", "e", "E", "i", "I", "o", "O", "u", "U") sentence = raw_input("Enter your sentence: ") words = sentence.split() for character in words: if character[0] in vowels: print character + "way", else: print character[1:] + character[0] + "ay",
#!/usr/bin/python3 """ adds all arguments to a Python list, and then save them to a file """ import sys save_to_json_file = __import__('5-save_to_json_file').save_to_json_file load_from_json_file = __import__('6-load_from_json_file').load_from_json_file open("add_item.json", "a") try: l = load_from_json_file("ad...
import nltk.lm.preprocessing as prep from nltk.util import bigrams def freq(text): freq_dict = {} for word in text: if word in freq_dict: freq_dict[word] += 1 else: freq_dict[word] = 1 return freq_dict def bigr_freq(text): freq_dict = {} for sent in text: ...
# -*- coding:utf-8 -*- import json import requests from celery_config import cry from config import xinlang_url, msg_url_1, rts from robot.dao import update_user_role, dao_find, dao_sql, dao_add import service_index from robot.util.oss import itchat_upload_images_to_oss def xin_lang_convert_short_url(surl): pri...
""" Scrapes information from the icd9data.com website. Python 2.7.x """ import json import requests from bs4 import BeautifulSoup base_url = "http://www.icd9data.com" root_path = "/2015/Volume1/default.htm" icd9_data = requests.get(base_url + root_path) icd9_bs = BeautifulSoup(icd9_data.text, "lxml") # first level...
import math from typing import List import numpy as np import io def input_transpose(sents, pad_token): """ This function transforms a list of sentences of shape (batch_size, token_num) into a list of shape (token_num, batch_size). You may find this function useful if you use pytorch """ max_...
class Pokemon: def __init__(self, attack, defense, health): self.attack = attack self.defense = defense self.health = health self.is_picked = False if __name__ == "__main__": n, k = map(int, input().split()) pokemon = [] for _ in range(n): A, D, H = map(int, in...
#!/usr/bin/env python # Funtion: # Filename: import pymysql conn = pymysql.connect(host = '127.0.0.1', port = 3306, user = 'root', passwd = 'lemaker', db = 'test_20180122', charset = 'utf8') # cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) # 以字典形式显示 ...
#!/usr/bin/python import csv import string import re with open('../files/feature1_train.txt', 'rb') as f1: feature1_train_as_list = f1.read().splitlines() f1.close(); with open('../files/feature2_train.txt', 'rb') as f2: feature2_train_as_list = f2.read().splitlines() f2.close(); with open('../files/feature...
"""Author Arianna Delgado Created on May 15, 2020 """ """For multiple lines Comments use """ # I can use this three 'symbols' to comments (#, ''' or """) print('We can use \'single quote\' or \"double quote to print\".') # Indentation is used as 4 space; it is mandatory in python to recognize a block of code!
import unittest from selenium import webdriver import time class TestsLessonTen(unittest.TestCase): def test_1(self): link = "http://suninjuly.github.io/registration1.html" browser = webdriver.Chrome() browser.get(link) input1 = browser.find_element_by_xpath("//input[@class='form-...
# redis #1---连接方式 ''' import redis r=redis.Redis(host='127.0.0.1',port=6379,db=0) r.set('name','baby') print(r.get('name')) print(r.dbsize()) ''' #2--连接池 import redis pool = redis.ConnectionPool(host='127.0.0.1', port=6379) r = redis.Redis(connection_pool=pool) r.set('name', 'zhangsan') #添加,覆盖前面的baby值 print (r.g...
from functools import cmp_to_key import numpy as np class Point(object): __slots__ = ('x', 'y') center = Point() def cmp_by_clockwise(a_point, b_point): cmp = lambda a,b : (a > b) - (a < b) a_x, a_y = a_point b_x, b_y = b_point if a_x - center.x >= 0 and b_x - center.x < 0: ...
# ================================================================================================== # Copyright 2014 Twitter, Inc. # -------------------------------------------------------------------------------------------------- # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use thi...
""" Default SVG cover image generator @author: GauravManek """ import plugins, io; from PIL import Image, ImageDraw, ImageFont; from math import floor; class DefaultPNGCover(plugins.BaseCover): def __init__(self): # A short string used to report this name in the style. self.name = "Default PNG Cover"...
#!/usr/bin/env python # ==================================================================================== # # # Copyright (c) 2017 Raffaele Bua (buele) # # 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...
import os from testconfig import config from gocdapi_utils.go_launcher import GoAgentLauncher from gocdapi_utils.go_launcher import GoServerLauncher go_instances = {} static_instances = config.get('static_instances', False) def setUpPackage(): if not static_instances: version = "16.5.0-3305" sy...
import os class SignExpiries: """Expirations members of module""" REGISTRATION_EMAIL = 60 * 60 * 24 # 1 day class ErrorCodes: """User errors return codes""" INVALID_PASSWORD = 1 INVALID_SIGN = 2 INVALID_TOKEN = 3 PASSWORDS_DO_NOT_MATCH = 4 USER_EXIST = 5 USER_NOT_CONFIRMED = 6 ...
from datetime import date from datetime import timedelta from freezegun import freeze_time from onegov.agency.collections import ExtendedAgencyCollection from onegov.agency.collections import ExtendedPersonCollection from onegov.agency.pdf import AgencyPdfAr from onegov.agency.pdf import AgencyPdfDefault from onegov.ag...
from __future__ import print_function import boto3 import json import logging logger = logging.getLogger() logger.setLevel(logging.INFO) def handler(event, context): logger.info(event) ##print("Received event: " + json.dumps(event, indent=2)) operation = event['operation'] if 'table...
#!/usr/bin/env python3 # # Format a spec # import jsontemplate import pscheduler import sys from validate import spec_is_valid try: format = sys.argv[1] except IndexError: format = 'text/plain' json = pscheduler.json_load(exit_on_error=True) valid, message = spec_is_valid(json) if not valid: pschedule...
""" Author: Dan Zelenak Date: 3/8/2017 Purpose: Take a color table exported from ArcMap and convert it into XML as a new .txt file to be used by GDAL. """ from argparse import ArgumentParser def main_work(ffile, newfile): """ :param ffile: :param newfile: :return: """ with open(ffile, 'r') a...
from django.urls import path from . import views # URLConf Module (URL Configurations) Rememner to import into main config ventureinsight_prj/urls.py urlpatterns = [ path('', views.home), path('signup/', views.signup), path('login/', views.login), path('profile/', views.profile), path('dashboard/',...
#!/usr/bin/env python #-*- coding: utf-8 -*- # Copyright (c) 2016 Shota Shimazu # This program is freely distributed under the MIT, see LICENSE for detail. # Import required library import os import sys import subprocess, shutil # Variables target_path = "Default" st_qo = "##############################" ed_qo = "#...
class Node: def __init__(self,data = None, next = None): self.data = data self.next = next class Linkedlist: def __init__(self): self.head = None def insert_at_begining(self,data): node = Node(data,self.head) self.head = node def print(self): ...
# Задача 1. Вариант 6. # Напишите программу, которая будет сообщать род деятельности и псевдоним под # которым скрывается Йоханнес Бруфельдт. После вывода информации программа # должна дожидаться пока пользователь нажмет Enter для выхода. # Ivanov S. E. # 15.09.2016 print('Йоханнес Бруфельдт - финский писатель, ...
# 環 # 積についてモノイド # 加法についてアーベル群 from Algebra.Monoid import Monoid from Algebra.AdditiveGroup import AdditiveGroup from typing import TypeVar RingType = TypeVar('RingType', bound='Ring') class Ring(Monoid, AdditiveGroup): # 分配法則 def testDistributive(self: RingType, a: RingType, b: RingType) -> bool: re...
from django.shortcuts import render from django.http import HttpResponse # Create your views here. def links(requst): return HttpResponse('links')
# -*- coding: utf-8 -*- # Generated by Django 1.10.1 on 2017-04-24 16:23 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.Crea...
import requests from lxml import etree from bs4 import BeautifulSoup as bs import queue as Queue import threading import time,re from func import gene_headers # write proxy def writeproxy(porxyinfo): now_time = time.strftime('%Y%m%d') with open('proxy/proxyinfo_%s.txt'%now_time,'a+') as f: ...
from flask import Flask, redirect, render_template, request, session, url_for, flash from flask_dropzone import Dropzone from flask_uploads import UploadSet, configure_uploads, IMAGES, patch_request_class import os from functools import wraps from sqlalchemy.orm import sessionmaker, scoped_session from sqlalchemy impor...
import random class Card: HEARTS = "Hearts" DIAMONDS = "Diamonds" SPADES = "Spades" CLUBS = "Clubs" VALUES = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A'] SUITS_RANK = ["Spades", "Clubs", "Diamonds", "Hearts"] def __init__(self, value, suit): sel...
#! /usr/bin/env python # -*- coding: utf-8 -*- # Title :demo_summary.py # Description : # Author :Devon # Date :2018/6/1 # Version :1.0 # Platform : windows # Usage :python test4.py # python_version :2.7.14 #========================================================...
import inspect from Dto import Student from Dto import Classroom from Dto import Course class _Courses: def __init__(self, conn): self._conn = conn def insert(self, course): self._conn.execute(""" INSERT INTO courses (id, course_name, student, number_of_students, class_id, co...
import matplotlib.pyplot as plt from os import chdir from iris import load_cube, Constraint from iris.analysis import MEAN, STD_DEV from iris.analysis.maths import abs from iris.time import PartialDateTime import cartopy.crs as ccrs from cartopy.feature import LAND from numpy import sqrt from numpy.ma import masked fro...
class Timer: def __init__(self, font: object, init_value: dict = None) -> None: self.font = font self.active = False if init_value: self.value = init_value else: self.value = {'h': '00', 'm': '00', 's': '00', 'ms': '000'} def reset(self) -> None: ...
import socket import time client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client_socket.connect(('localhost', 8000)) a = client_socket.send('From client_1'.encode('utf-8')) print(a) time.sleep(10) data = client_socket.recv(100) print(data) while True: b=1 client_socket.close()
# -*- coding: utf-8 -*- ############# # # Copyright - Nirlendu Saha # # author - nirlendu@gmail.com # ############# import inspect import sys from app_core import core_interface as core from libs.logger import app_logger as log def new_person( user_name, person_name, ): """New Person Primary ...
import plyvel from tqdm import tqdm db = plyvel.DB("artist.ldb", create_if_missing=False) r = [] for k, v in tqdm(db): if v == b"Japan": r.append(k.decode("utf-8")) for k in r: print(k) print("Total: {}".format(len(r)))
from brownie import * from time import sleep import itertools from variables import * import itertools import json import os import concurrent.futures COUNTER = itertools.count() ACC_LIST = [] ACC_INDEX = itertools.count() # Expectations def _bnb_price(): assert chain.id == 56, "_bnbPrice: WRONG NETWORK. This fu...
#import sys #input = sys.stdin.readline def main(): H = int( input()) W = int( input()) N = int( input()) if H < W: H, W = W, H ans = N//H if N%H != 0: ans += 1 print(ans) if __name__ == '__main__': main()
#!/usr/bin/env python # Funtion: # Filename: ######################################################################################### ''' 购物车程序: 1、启动程序后,输入用户名密码后,如果是第一次登录,让用户输入工资,然后打印商品列表 2、允许用户根据商品编号购买商品 3、用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒 4、可随时退出,退出时,打印已购买商品和余额 5、在用户使用过程中, 关键输出,如余额,商品已加入购物车等消息,需高亮显示 6、用户下一次登录后,输入用户...
from ED6ScenarioHelper import * def main(): # 卢安 CreateScenaFile( FileName = 'T2400 ._SN', MapName = 'Ruan', Location = 'T2400.x', MapIndex = 1, MapDefaultBGM = "ed60015", Flags = 0, Ent...
from django.contrib import admin from Auth.models import Company # Register your models here. admin.site.register(Company)
# Generated by Django 3.0.1 on 2020-01-11 04:14 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('library_app', '0005_remove_album_public'), ] operations = [ migrations.AddField( model_name='album', name='my_image'...
from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import Select cities = ['Delhi-Noida', 'Gurgaon', 'Kolkata', 'Mumbai', 'Pune', 'Ahmedabad-Gandhinagar', 'Bangalore', 'Hyderabad', 'Chennai'] def get_cookie(city): driver = webdriver.Firefox() driv...
import argparse import os import matplotlib.pyplot as plt import numpy import pandas # @author: Gursimran Singh # directories DIR_NAME = os.path.dirname(os.path.abspath(__file__)) CSVs_DIR_NAME = 'converted_pcaps' CSV_DIR = os.path.join(DIR_NAME, CSVs_DIR_NAME) PLOTs_DIR_NAME = 'plotted_graphs' PLOT_DIR = os.path.jo...
""" app.extensions.sqla ~~~~~~~~~~~~~~~~~~~~~~~~~~ 拓展Flask-SQLAlchemy模块 新增软删除功能 新增对象CRUD功能 核心部分从一个flask-restful项目中摘录出来,现在已经找不到了 """ from .db_instance import db from .errors import CharsTooLong, DuplicateEntry from .model import Model from .surrogatepk import SurrogatePK
import os import sys import OpenSSL from twisted.application import internet, service from twisted.internet import reactor, ssl from twisted.web.wsgi import WSGIResource from twisted.web.server import Site from config.config import Config from ssl_util import CustomOpenSSLContextFactory import server config = Confi...
import itertools c = list(map("".join, itertools.permutations('0123456789'))) d = 0 c.sort() for i in c: d += 1 if d == 1000000: print(i) break
from django import forms class UploadForm(forms.Form): CHOICES = (('0','Fruits'), ('1','Diseases'),) mode = forms.ChoiceField(widget=forms.Select, choices=CHOICES,label="") image=forms.ImageField(label='',)
import os import re import logging from typing import Set import aiohttp import discord from discord.ext import commands from potato_bot.db import DB from .context import Context log = logging.getLogger(__name__) initial_extensions = ( "potato_bot.cogs.utils.errorhandler", "potato_bot.cogs.utils.response...
import sys from rosalind_utility import parse_fasta def calculate_gc_content(string): ''' Calculate GC content :param string: string to calculate GC content for (string) :return: GC content (float) ''' count_gc = string.count("G") + string.count("C") gc_content = count_gc / len(string) ret...
from TGA_analyse_aliq2 import TGA_AnalyseAliq2 # from TGA_analyse_aliq3 import TGA_AnalyseAliq3 import simplejson as json from TGA_plot_surf import TGA_Plot import numpy as np if __name__ == '__main__': analyse = TGA_AnalyseAliq2() # analyse3 = TGA_AnalyseAliq3() analyse.load() analyse.analyseAll() # analyse3.l...
from typing import Callable, Generic, TypeVar, TYPE_CHECKING if not TYPE_CHECKING: reveal_type = print from example.functions import flow, identity _ValueType = TypeVar('_ValueType', covariant=True) _NewValueType = TypeVar('_NewValueType') # Functor definition: class Wrapper(Generic[_ValueType]): def __in...
# -*- coding: utf-8 -*- # Author: kelvinBen # Github: https://github.com/kelvinBen/HistoricalArticlesToPdf from PIL import Image import sys class QrcodeTools(object): def qrcode_to_str(self,qrcode_path): image = Image.open(qrcode_path) width = int(image.width * 0.3) height = int(image.he...
import sys from PyQt5.QtWidgets import * from PyQt5.QtCore import * from PyQt5 import QtCore from PyQt5.QtGui import * class AppWidget(QWidget): def __init__(self, parent=None): super(AppWidget, self).__init__(parent) horizonlLayout = QHBoxLayout() self.styleLabel = QLabel('Set Style:') ...
import math def v_sub(a, b): result = [] for i in range(len(a)): result.append(a[i] - b[i]) return result def v_len(a): s = 0; for i in range(len(a)): s += a[i]*a[i] return math.sqrt(s) def v_cross(v1, v2): x = v1[1]*v2[2] - v1[2]*v2[1]; y = v2[0]*v1[2] - v2[2]*v1[0]; ...
#import sys #input = sys.stdin.readline def main(): N, K = map( int, input().split()) W = [ tuple( map( int, input().split())) for _ in range(N)] dp = [[0,0] for _ in range(K+1)] dp[1][0] = W[0][0] dp[1][1] = W[0][0]*W[0][1] print(dp) for w, p in W[1:]: g = w*p for k in range...
""" vulkit wrapper generator Copyright (c) 2016, Ben Russell 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 Software without restriction, including without limitation the rights to use, copy, modify, merg...
from tkinter import * import random import time def UP_ (event): global di di = 'w' def DOWN_ (event): global di di = 's' def LEFT_ (event): global di di = 'a' def RIGHT_ (event): global di di = 'd' def RAND_F (): global t, P, X flag = 0 while flag == 0: i, j = rand...
#!/usr/bin/env python3 # YAPTB Bluetooth keyboard emulator DBUS Service # # Adapted from # www.linuxuser.co.uk/tutorials/emulate-bluetooth-keyboard-with-the-raspberry-p # https://gist.github.com/ukBaz/a47e71e7b87fbc851b27cde7d1c0fcf0#file-btk_server-py import os import signal import socket import sys import dbus impo...
#!/usr/bin/env python # coding: utf-8 import numpy as np import os.path import matplotlib.pyplot as plt from epics import caget, caput import time # load the FSM origin # Elena Manjavacas IDL to Python transcription def loadfsmori(filename): print('Reading /kroot/rel/ao/qfix/data/fsm_origin.dat') fxpos0 = ...
from hummingbot.client.settings import CONNECTOR_SETTINGS from hummingbot.core.event.events import TradeFeeType from hummingbot.client.config.config_methods import new_fee_config_var def fee_overrides_dict(): all_dict = {} # all_connector_types = get_exchanges_and_derivatives() for name, setting in CONNEC...
#!/usr/bin/python #Relax Dynamixel servos (set all PWMs to zero). from dxl_cranex7 import * #Setup the device crane= TCraneX7() crane.Setup() crane.EnableTorque() crane.SetPWM({jname:0 for jname in crane.JointNames()}) #crane.DisableTorque() crane.Quit()
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'sai27' import time, uuid from orm import Model, StringField, BooleanField, FloatField, TextField, IntegerField def next_id(): return '%015d%s000' % (int(time.time() * 1000), uuid.uuid4().hex) class User(Model): __table__ = 'users' id ...
from fsm import FSM from state import * from transition import * Char = type("Char", (object,), {}) class RobotCat(Char): def __init__(self): self.FSM = FSM(self) # States self.FSM.addState("Sleep", Sleep(self.FSM)) self.FSM.addState("Walk", Walk(self.FSM)) self.FSM.addSt...
"""Initialization Module"""
cont = total = menor = cont1 = nomem = 0 while True: nome = str(input('Digite o nome do produto: ')) preço = float(input('Digite o preço do produto: ')) cont1 += 1 if cont1 == 1: menor = preço nomem = nome if preço > 1000: cont += 1 if preço < menor: menor = pre...
""" Crie um programa que leia nome, sexo e idade de várias pressoas, guardando os dados em um dicionário e todos os dicionários em uma lista. No final, mostre: A - Quantas pessoas foram cadastradas. B - A média de idade do grupo. C - Uma lista com todas as mulheres. D - Uma lista com todas as pessoas com idade acima da...
# -*- coding:utf-8 -*- class Solution: def FindNumbersWithSum(self, array, tsum): """ 输入一个递增排序的数组和一个数字S,在数组中查找两个数, 使得他们的和正好是S,如果有多对数字的和等于S, 输出两个数的乘积最小的。 """ # write code here res_list = [] low = 0 high = len(array)-1 while True: ...
#! /usr/bin/env python # -*- coding: utf-8 -*- # # Interpreter version: python 2.7 # # Imports ===================================================================== from BTrees.OOBTree import OOBTree import transaction from ..zeo_conf_wrapper import ZEOConfWrapper # Functions & classes ==============================...
# coding: utf-8 # In[10]: import argparse as ag import ConfigParser import numpy as np from Bio.Seq import Seq import Bio.Alphabet import Bio.Alphabet.IUPAC # MPI parallelism from mpi4py import MPI import h5py from copy import copy np.set_printoptions(threshold='nan') natoms = ('OP1', 'OP2', 'O1P', 'O2P', 'N4'...
import datetime import json import pprint import re import traceback from gi.repository import Gtk, Gdk, GObject from gramps.gen.plug import Gramplet from gramps.gui.plug import tool from gramps.gui.utils import ProgressMeter from gramps.gen.db import DbTxn from gramps.gen.lib import Place, PlaceRef, PlaceName, Place...
import sys import numpy as np from numpy import linalg as LA stringMatrix = sys.argv[1] dimension = int(sys.argv[2]) stringMatrix = stringMatrix.replace('[', '') stringMatrix = stringMatrix.replace(']', '') stringMatrix = stringMatrix.replace(',', ' ') stringMatrix = np.array(stringMatrix.split()) intMat...
import numpy as np from more_itertools import chunked from math import ceil from itertools import chain from collections import Counter, defaultdict from multiprocessing import Pool, cpu_count import re import os import pickle import fastText as ft from keras.preprocessing.sequence import pad_sequences import spacy f...
# Usage # Run the animation in "pacman.gif" for 5 total cycles. When loading from an animated GIF file, the timing of each frame is automatically loaded from the file but if a different, constant time is needed the "fps" or "sleep" parameters of run() can be used. # # ```python # import bibliopixel.image as image # ani...
from django.db import models from django.contrib.auth.models import User # Create your models here. class Blog(models.Model): title = models.CharField(max_length = 200) pub_date = models.DateTimeField('data published') body = models.TextField() writer=models.ForeignKey(User, on_delete=models.CASCADE, ...
from time import sleep def filtr(ls): if ls['message'].get('chat_id') != None: if ls['message']['chat_id'] == 1: return True else: return False else: return False def filtr2(ls): if ls['message'].get('user_id') != None: if ls['message']['user_id'] =...
import requests, urllib3, threading, urllib.parse as urlparse, atexit, time from urllib.parse import parse_qs from datetime import date, datetime from bs4 import BeautifulSoup from viberbot.api.messages import URLMessage from viberbot.api.messages.text_message import TextMessage from apscheduler.schedulers.background ...
#find digits t = int(input()) c = 0 res = [] for i in range(t): n = input().strip() temp = int(n) for i in n: if int(i) != 0: if temp % int(i) == 0: c += 1 res.append(c) c = 0 for c in res: print(c)...
from data_preprocessor import snd_ns_data_prepocessor as data_preprocessor import subprocess from sys import platform from score_calculator import score_calculator from plotter import ROC_AUC_plotter def main(): snd_folder_names = ['snd-cert', 'snd-unm'] syscalls_file_dir = 'negative-selection/syscalls' c...
import numpy as np import perturbations as PB import math G = 4.32275e-3 # (km/s)^2 pc/Msun G_pc = G*1.05026504e-27 # (pc/s)^2 pc/Msun kmtopc = 1.0/(3.086*10**13) MNS = 1.4 # Msun RNS = 10*kmtopc # pc from scipy.interpolate import interp1d from scipy.integrate import quad, cumtrapz from scipy.special import...
# get 请求 import requests import sys import io sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='utf8') # Change default encoding to utf8 r = requests.get('https://www.baidu.com/') print(type(r)) print(r.status_code) print(type(r.text)) print(r.text) print(r.cookies)
#!/usr/bin/env python3 # -*- encoding: utf-8 -*- import pytest from unittest.mock import patch from niacin.text.en import char @pytest.mark.parametrize( "string,p,l", [("", 0.0, 0), ("", 1.0, 0), ("bob", 0.0, 3), ("bob", 1.0, 6)] ) def test_add_characters(string, p, l): res = char.add_characters(string, p)...
import turtle import random swidth, sheight, pSize, exitCount = 300, 300, 3, 0 r, g, b, angle, dist, curX, curY = [0] * 7 turtle.title('거북이가 맘대로 다니기') turtle.shape('turtle') turtle.pensize(pSize) turtle.setup(width = swidth + 30, height = sheight + 30) turtle.screensize(swidth, sheight) while True: r = random.ra...
# Generated by Django 3.1.6 on 2021-02-04 04:58 import datetime from django.db import migrations, models from django.utils.timezone import utc class Migration(migrations.Migration): dependencies = [ ('blogger', '0001_initial'), ] operations = [ migrations.AlterField( model_n...
#settings.py class Settings(): """ """ def __init__(self): """initialize game and screen settings.""" self.screen_width = 1200 self.screen_height = 800 self.bg_color = (135, 206, 250) #ship speed settings self.ship_limit = 3#numer of space ships per game # Bullet settings self.bullet_...
#!/usr/bin/python #\file rviz2.py #\brief certain python script #\author Akihiko Yamaguchi, info@akihikoy.net #\version 0.1 #\date Nov.25, 2019 import roslib; roslib.load_manifest('std_msgs') import rospy import tf import visualization_msgs.msg import geometry_msgs.msg import math #Convert x to geometry_msgs/...
# coding=utf-8 # 个人主页图片:包括个人照片和作品集 import json import threading from sqlalchemy import desc from BaseHandlerh import BaseHandler from Database.models import get_db from Database.tables import User, UserHomepageimg, UserCollection, UserLike from FileHandler.Upload import AuthKeyHandler from Userinfo.UserImgHandler imp...
""" This module is related to the usage of BigDFT with Fragment-related Quantities. Input as well as Logfiles might be processed with the classes and methods provided by it. The main two classes for this module are :class:`BigDFT.Fragments.System` and :class:`BigDFT.Fragments.Fragment`. A System is a named collection ...