text stringlengths 38 1.54M |
|---|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Jan 7 00:35:16 2018
@author: Magnus Tarle
Description:
Contains functions and simplified test functions for vrep_fastslam.py
"""
import numpy as np
import matplotlib.patches as mpatches # used for legend, ellipses and rectangles
from scipy.stats ... |
import segmentation_models
from segmentation_models import Unet, PSPNet
from segmentation_models import metrics
from segmentation_models.losses import (
dice_loss, jaccard_loss, categorical_focal_loss, categorical_crossentropy
)
from farmer.ncc.models import xception, mobilenet, Deeplabv3, Model2D
from ..model.tas... |
from ... import weather as rk_weather
from .solar_workflow_manager import SolarWorkflowManager
def openfield_pv_merra_ryberg2019(placements, merra_path, global_solar_atlas_ghi_path, module="WINAICO WSx-240P6", elev=300, tracking="fixed", inverter=None, inverter_kwargs={}, tracking_args={}, output_netcdf_path=None, ou... |
#Answer to Mod Divmod
a = int(input())
b = int(input())
print(a//b)
print(a%b)
print(divmod(a,b))
"""
>>> print divmod(177,10)
(17, 7)
Here, the integer division is 177/10 => 17 and the modulo operator is 177%10 => 7.
""" |
import tensorflow as tf
import numpy
import matplotlib.pyplot as plt
import random
from PIL import Image
from CNN import CNN
def get_data():
train_data = []
for i in range(14):
image_label = numpy.zeros(14)
image_label[i] = 1
for j in range(200):
image = Image.open('./TRAI... |
#!/usr/bin/python
import socket
import sys
if len(sys.argv) != 2:
print "Usage: vrfy.py <username>"
sys.exit(0)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Create a socket
connect = s.connect(('192.168.15.215',25)) # Connect to the server
|
import unittest
import textwrap
from pseudo import generate
from pseudo.pseudo_tree import Node
import suite
class TestRuby(unittest.TestCase, metaclass=suite.TestLanguage): # dark magic bitches
_language = 'ruby'
_import = 'require'
_parse_import = lambda self, line: line[9:-1]
# make declarative st... |
import os
# change to dir of script
os.chdir(os.path.dirname(os.path.abspath(__file__)))
try:
with open("input.txt") as f:
# with open("input_small.txt") as f:
data = f.read() # entire file as string
lines = data.splitlines()
except:
print("no input.txt")
data, lines = "", []
lin... |
#from hungaryCard import HungaryCard, GetCards
from hungaryCard import hungaryCard
from enum import Enum
import os,sys
from PIL import Image
from random import shuffle
import random
from django.http import HttpResponse
def index(request):
list_tuple = tuple(hungaryCard.HungaryCard)
#return HttpResponse("Hell... |
shopping_list = []
def show_help():
print("What should we pick up at the store?")
print("""
Enter 'DONE' to stop adding items.
Enter 'HELP' for this help.
Enter 'SHOW' to see your current shopping list.
""")
def add_to_list(item):
shopping_list.append(item)
print("You've just added {} to the ... |
"""empty message
Revision ID: 0010_events_table
Revises: 0009_created_by_for_jobs
Create Date: 2016-04-26 13:08:42.892813
"""
# revision identifiers, used by Alembic.
revision = "0010_events_table"
down_revision = "0009_created_by_for_jobs"
import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects imp... |
from __future__ import unicode_literals
from django.contrib import admin
from models import Service, AmcReport, Status
class AmcReportAdmin(admin.ModelAdmin):
model = AmcReport
list_display = ('customer_name', 'project_name', 'milestone_name', 'Due_date', 'AMC_end_date', 'status', 'notification')
admin.site.regist... |
#!/usr/bin/env python
import os
for i in range(110, 135):
if i % 5 == 0:
continue
os.system('python scaleCards.py --xsbr --ddir . %i' % i)
|
import unittest
from LogInfo import LogInfo
class LogInfoTests(unittest.TestCase):
def setUp(self):
mock_log = dict()
mock_log["ip_address"] = "222.64.146.118"
mock_log["datetime"] = "19/Jun/2005:06:44:17"
mock_log["zone"] = "+0200"
mock_log["method"] = "GET"
mock_l... |
"""
Given an array of ints length 3,
figure out which is larger between
the first and last elements in the
array, and set all the other elements
to be that value. Return the changed array.
"""
from test import Tester
def max_end3(nums):
max_end = max(nums[0],nums[-1])
for i in range(len(nums)):
nu... |
import json
filename = 'favorite_number.json'
with open(filename) as f:
fav_number = json.load(f)
print(f"I know you favorite number, its {fav_number}!") |
# -*- coding: utf-8 -*-
tuple1 = ('a','b',['A','B'])
print(tuple1)
a = input('替换tuple中的A元素')
b = input('替换tuple中的B元素')
tuple1[2][0] = a
tuple1[2][1] = b
print('修改后的tuple 为:%s'%str(tuple1)) |
from LibraryClass import *
if __name__ == "__main__":
print("\nHey, Welcome to GG'LIBRARY'MANAGEMENT'SYSTEM.....\n")
while True:
choice = input("how may i help you? ")
choice = choice.lower()
if "help" in choice or "intstruct" in choice or "assist" in choice:
print("hey, yo... |
from math import floor
import random
list = [random.randrange(0,100) for i in range(100)]
list.sort()
num = random.randrange(0,100)
def binaryS(list, num):
start = 0
end = len(list)
while start <= end:
mid = floor((start+end)/2)
if list[mid] == num:
return mi... |
try:
x = 2
y = 10
z = y/x
print(z)
except Exception as e:
print(e)
else:
m = x + y
print(m) |
import get_prices as hist
import tensorflow as tf
from preprocessing import DataProcessing
# import pandas_datareader.data as pdr if using the single test below
import pandas_datareader.data as pdr
import yfinance as fix
import numpy as np
#import matplotlib.pyplot as plt
fix.pdr_override()
start = "2003-01-01"
end =... |
#-*- coding: utf-8 -*-
from selenium import webdriver
import os
import time
import unittest
import sys, traceback
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver import ActionCha... |
import numpy as np
from collections import Counter
import pickle
import pathlib
import json
import os,sys
HERE = pathlib.Path().absolute().parent.__str__()
sys.path.append(os.path.join(pathlib.Path().absolute().parent,"card_db")) # Hax lol
import caffeinate
#pathlib.Path(__file__).parent.absolute()
import pandas as p... |
__author__ = 'Administrator'
import re
class Grep_match:
def __init__(self, grep_exp, matched_str):
self.grep_exp = grep_exp
self.matched_str = matched_str
def exec_grep(self):
wordre = re.compile(self.grep_exp)
list = wordre.findall(self.matched_str)
return list |
import sys
import pygame
def check_keydown_events(event, ship):
"""response to the keydown"""
if event.key == pygame.K_UP:
ship.moving_up = True
elif event.key == pygame.K_DOWN:
ship.moving_down = True
def check_keyup_events(event, ship):
"""response to the keyup"""
... |
def matchor(instance, association):
def takeTwo(elm):
return elm[1]
# count = 0
results = None
# for instance,association in zip(ins_predictions,ass_predictions):
# count +=1
objects = [ i for i,v in enumerate(instance.pred_classes) if v == 1]
shadows = [i for i,v in enumerate(inst... |
Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51) [MSC v.1914 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> x=int(input("Enter a number : "))
Enter a number : 56
>>> if x>17:
v=2*(x-17)
print(v)
else:
v1=(17-x)
print(v1)
78
>>> #Write a Python pr... |
import unittest
from lib.ebook import Ebook, InvalidPercentageError
"""
Naming convention: test_functionName_input/TestState_expectedResult
"""
class MyTestCase(unittest.TestCase):
def setUp(self) -> None:
self.ebook = Ebook("What a wonderful world", 73)
def test_pagesRead_getsPagesRead(self) -> No... |
# -*- coding: utf-8 -*-
# """
# Created on Tue Jul 30 10:02:48 2019
# @author: Wenyang Lyu and Shibabrat Naik
# Compute unstable peridoic orbits at different energies using turning point method
# """
# For the DeLeon-Berne problem
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate im... |
#Biggest Number Using Array
def BigArr(arr):
x=arr[0]
for i in arr:
if(i>x):
x=i
return x
arr=[8,9,11,5,10,12]
print(BigArr(arr))
|
import os
import shutil
import MySQLdb as mysql
from django.core.management.base import BaseCommand, CommandError
from django.conf import settings
from apps.achievements.models import Record, RecordProof
from apps.utils import upload_to
"""
`kmp_members` (
0 `id` int(11) NOT NULL AUTO_INCREMENT,
... |
'''
Take input a number ‘N’ and an array as given below.
Input:- N=2
Array =1,2,3,3,4,4
O/p : 2
Find the least number of unique elements after deleting N numbers of elements from the
array.
In the above example , after deleting N=2 elements from the array.
In above 1,2 will be deleted.
So 3,3,4,4 will be remaining so,
... |
from __future__ import division
from collections import deque
from Event import Event
from ExponentialRandomVariableGenerator import ExponentialRandomVariableGenerator
from Packet import Packet
AVERAGE_PACKET_LENGTH = 2000
SIMULATION_TIME = 1000
TRANSMISSION_RATE = 1000000 # 1 Mbps
class DiscreteEventBufferSimulator:... |
'''
This script uses the CCSD-LPNO response code
to compute the MP2-level energy correction
to the PNO/PNO++ method by including the
external (truncated) space
'''
import numpy as np
import psi4
import ccsd_lpno
import argparse
import time
import json
parser = argparse.ArgumentParser()
parser.add_argument("--j", defa... |
import numpy as np
from tools import gauss
def calc_probaprio_gm(signal, w):
"""
Cete fonction permet de calculer les probabilité a priori des classes w1 et w2, en observant notre signal non bruité
:param signal: Signal discret non bruité à deux classes (numpy array 1D d'int)
:param w: vecteur dont la... |
import os
def f(arr):
if len(arr) == 1:
return True
i = 1
while i < len(arr) and arr[i] == arr[i - 1]:
i += 1
if i == len(arr):
return True
if arr[i] < arr[i - 1]:
while i < len(arr) and arr[i] <= arr[i - 1]:
i += 1
else:
while i < len(arr... |
from src import detect_faces, show_bboxes
from PIL import Image
# img = Image.open('images/office1.jpg')
# bounding_boxes, landmarks = detect_faces(img)
# im = show_bboxes(img, bounding_boxes, landmarks)
# img.show()
# im.show()
# img = Image.open('images/office2.jpg')
# bounding_boxes, landmarks = detect_faces(img)... |
import tkinter
screen = tkinter.Tk()
entry = tkinter.Entry(screen, width=50, bg="aquamarine", borderwidth=5)
entry.insert(0, "Enter your name")
entry.pack()
button = tkinter.Button(text="Submit", command=lambda: tkinter.Label(text=entry.get()).pack())
button.pack()
screen.mainloop()
|
import os
from pathlib import Path
import numpy as np
import cv2 as cv
MIN_NUM_KEYPOINT_MATCHES = 50 # constant for minimum number of keypoint matches
def main():
"""loop through 2 folders with paired images, register & blink images."""
night1_files = sorted(os.listdir(
'C:/Users/austi/Documents/pyt... |
from .entity import Entity
from .vector import Vector
from .pickup import PickupType
from .sandbox import builtins
from .color import Color3
from .event import Event, EventType
from .util import *
from .path import Path
from .game_config import GameConfig as gc
from .enemy_type import EnemyType
from functools import p... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017-10-23 15:36
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import mptt.fields
class Migration(migrations.Migration):
dependencies = [
('conversationtree', '0011_auto_20171023_1... |
def format_real(number_ext):
if number_ext == 'um':
return '{} {}'.format(number_ext, 'real')
else:
return '{} {}'.format(number_ext, 'reais')
def format_centavo(number_ext):
if number_ext == 'um':
return '{} {}'.format(number_ext, 'centavo')
else:
return '{} {}'.format(... |
from utils import *
inp = get_input(2020, 3)
rows = [r for r in inp.split("\n") if r != ""]
def get(x, y):
return rows[y][x % len(rows[y])]
def calc(dx, dy):
x = 0
y = 0
trees = 0
while y < len(rows):
trees += 1 if get(x, y) == "#" else 0
x += dx
y += dy
return tree... |
# Copyright 2016 Joel Dunham
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writi... |
"""
functional
----------
Functional programming utilities.
"""
from collections import deque
from operator import itemgetter
from .compat import viewkeys
def complement(f):
def not_f(*args, **kwargs):
return not f(*args, **kwargs)
return not_f
def keyfilter(f, d):
return {k: v for k, v in d.i... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from apicultur.service import Service
class AleatoriasNivel(Service):
# http://apicultur.io/apis/info?name=WordsbyFreq_Word_Molino_es&version=1.0.0&provider=MolinodeIdeas
version = '1.0.0'
endpoint = 'molinodeideas/freq/es/words'
method = 'GET'
argumen... |
import sys
from math import sqrt
from math import floor
def h_ascii(key, n):
"""
This function hashes a key using the ascii value method
discussed during lecture.
Parameters:
- key(str): The key we wish to hash
- n(int): The size of the hast table
Returns:
- The hash value of the key... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
next step: R
'''
import codecs,re
def splitJointmorph(jointMorph):
cas = '_'
num = '_'
gen = '_'
verbform = '_'
tense = '_'
if jointMorph!='_':
t5 = jointMorph.strip()
ms = t5.split('|')
for m in ms:
if m.st... |
from django.contrib.auth.models import AbstractUser
from django.db import models
import decimal
class Costumer(AbstractUser):
telephone = models.CharField(max_length=30,blank=True)
street = models.CharField(max_length=30,blank=True)
city = models.CharField(max_length=30,blank=True)
district = model... |
#! /bin/env python
# -*- coding: utf-8 -*-
import sys
import argparse
from harvester.couchdb_init import get_couchdb
from harvester.couchdb_sync_db_by_collection import delete_id_list
from harvester.post_processing.couchdb_runner import CouchDBCollectionFilter
def confirm_deletion(count, objChecksum, cid):
prompt... |
import requests, bs4
import sys, os, subprocess
import tempfile
from termcolor import *
from urllib.parse import quote
from time import sleep
BASE_URL = "http://www.allitebooks.com/"
def send_request(url):
try:
r = requests.get(url)
r.raise_for_status()
return r
except requests.exceptions.ConnectionError:
c... |
import math
def cos_sen_tan(angulo):
seno = math.sin(math.radians(angulo))
print('O seno de {} é {:.2f}'.format(angulo, seno))
cosseno = math.cos(math.radians(angulo))
print('O cosseno {} é {:.2f}'.format(angulo, cosseno))
tangente = math.tan(math.radians(angulo))
print('A tangente {} é {... |
# -*- coding: utf-8 -*-
from odoo.tests.common import TransactionCase
from odoo.tests.common import SingleTransactionCase
import datetime
from .commissiondata import CommissionData as cd
from .commissiondata import TestCase1 as t1
from .commissiondata import TestCase2 as t2
from .commissiondata import TestCase3 as t3... |
fname = raw_input("File Name")
f = open(fname+'.csv', 'r')
lines = f.readlines()
array = []
for s in range(1,len(lines)):
data = lines[s].split()
array.append(data[len(data)-2][5:])
with open(fname+'.txt', 'w') as fw:
for j in array:
fw.write(j + '\n')
|
#! /usr/bin/python
# Written by Dan Mandle http://dan.mandle.me September 2012
# License: GPL 2.0
# edited by estheim telkom institute teknologi
import os
from gps import *
from time import *
import time
import threading
GpsData = None #seting the global variable
class GpsPoller(threading.Thread):
def __init__... |
from sambandid import app
def datetimeformat(value):
return value.strftime('%d.%m.%y %H:%M')
app.jinja_env.filters['datetimeformat'] = datetimeformat
|
import matplotlib.pyplot as plt
import pandas as pd
import statistics
plt.style.use('seaborn-whitegrid')
df=pd.read_csv('NSE-TATAGLOBAL11.csv')
x = df['Open']
y = df['Close']
plt.figure(figsize=(16,8)) plt.title('Open vs Close Price History') plt.plot(x, y, 'o')
plt.xlabel('Open Price INR(₹)', fontsize=14) ... |
import argparse
import os
from ase.db import connect
import subprocess
from ase.io import read
ATAT_GENERATED = 'atat_generated'
SCRIPT_NAME = '.str2cif_wrapper.sh'
def str2cif_sh_script():
return "str2cif < $1 > $2\n"
def transfer_to_db(folder, db, structure_file):
print("Transferring structures from ATAT f... |
from .context import Context
from .run_remote_script import Runner
from .service import Provision
from .service_util import adduser
class BuildUser(Provision):
name = "user(build)"
deps = ["start"]
def __call__(self, ctx: Context) -> None:
runner = Runner(ctx.root_conn)
adduser(ctx, runne... |
"""
Let us call an integer sided triangle with sides a ≤ b ≤ c barely acute if the sides satisfy a2 + b2 = c2 + 1.
How many barely acute triangles are there with perimeter ≤ 25,000,000?
""" |
from bokeh.plotting import figure, show
#add data
x = [1, 2, 3, 4, 5, 6, 7]
y = [4, 9, 7, 2, 3, 1, 8]
#create a new plot with a title and axis label
p = figure(title="Dans plot", x_axis_label='x', y_axis_label='y')
#add a line redner with legend and line thickness to the plat
p.line(x, y, legend_label="Temp", line_w... |
# Generated by Django 2.0.5 on 2018-07-02 02:07
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('books', '0010_auto_20180702_1058'),
]
operations = [
migrations.AlterField(
model_name='book',
name='ISBN',
... |
import machine
import micropython
import time
import cet_time
import display
import efa
import timer
micropython.alloc_emergency_exception_buf(100)
class View:
def __init__(self):
self.error = None
self.departures = []
self.processing = False
self.message = None
@staticm... |
import pandas as pd
import math
from sklearn import linear_model
df = pd.read_csv('homeprices1.csv')
median_bedrooms = math.floor(df.bedrooms.median())
df.bedrooms = df.bedrooms.fillna(median_bedrooms)
print(df)
# create the model and train it.
model = linear_model.LinearRegression()
model.fit(df[['area', 'bedrooms... |
"""Example script that demonstrates features of the Video4Linux device adapter.
Kyle M. Douglass, 2018
kyle.m.douglass@gmail.com
"""
import numpy as np
import MMCorePy
# Initialize the camera
mmc = MMCorePy.CMMCore()
mmc.loadDevice("camera", "video4linux2", "Video4Linux2")
mmc.initializeAllDevices()
mmc.setCameraDev... |
import requests
from key import BINANCE_API_KEY
session = requests.Session()
def get_coinbase_trade(symbol, after_id):
if after_id == 0:
url = "https://api.pro.coinbase.com/products/{symbol}/trades".format(symbol=symbol)
else:
url = "https://api.pro.coinbase.com/products/{symbol}/trades?after... |
import cv2
import numpy as np
import math
origen = cv2.VideoCapture('CarsDrivingUnderBridge.mp4')
ret, cam = origen.read()
ret2, cam2 = origen.read()
kernel = np.ones((5,5), np.uint8)
nCarros = 0
contador = 0
while(origen.isOpened()):
if ret == False or ret2 == False:
break
imgGris = cv2.cvtColor(ca... |
# Standard Library imports
# Core Flask imports
from flask import render_template, redirect, url_for, request
from flask_login import login_user, logout_user, current_user, login_required
# Third-party imports
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy import select
def init_routes(app, db):
"""... |
#!/usr/bin/env python
import os, sys, cv2
os.environ['GLOG_minloglevel'] = '2'
import _init_paths
from fast_rcnn.config import cfg
from fast_rcnn.test import im_detect
from fast_rcnn.nms_wrapper import nms
from utils.timer import Timer
import matplotlib.pyplot as plt
import numpy as np
import scipy.io as sio
import a... |
import py_vollib.black_scholes.implied_volatility as iv
import py_vollib.black_scholes as bs
import py_vollib.black_scholes.greeks.numerical as greek
import pandas as pd
import numpy as np
import time
def get_vol(option_price, spot, strike, T, r=0, option_type='p'):
"""
Calculates the implied volatility of an ... |
# -*- coding: utf-8 -*-
def create(config_dict):
if config_dict['type'] == 'bubble':
lower = config_dict['lower']
return BubbleSort(lower)
elif config_dict['type'] == 'select':
lower = config_dict['lower']
return SelectSort(lower)
elif config_dict['type'] == 'insert':
... |
"""moonlight URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-bas... |
import os
import requests
from flask import Flask, request
import logging
import json
import random
start = True
app = Flask(__name__)
sessionStorage = {}
logging.basicConfig(level=logging.INFO)
# создаем словарь, в котором ключ — название города,
# а значение — массив, где перечислены id картинок,... |
# coding: utf-8
from enum import Enum
from six import string_types, iteritems
from bitmovin_api_sdk.common.poscheck import poscheck_model
from bitmovin_api_sdk.models.retry_hint import RetryHint
import pprint
import six
class ErrorDetails(object):
@poscheck_model
def __init__(self,
code=None... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Project: Azimuthal integration
# https://forge.epn-campus.eu/projects/azimuthal
#
# File: "$Id$"
#
# Copyright (C) European Synchrotron Radiation Facility, Grenoble, France
#
# Principal author: Jérôme Kieffer (Jerome.Kieffer@ESRF.eu)
#
# ... |
import scrapy
import requests
from urllib.parse import urlparse
import news_crawler#如果找不到,至檔案夾將Mark Directory as改成root
from items import ScrapyCaseItem
class GoogleNewsSpider(scrapy.Spider):
name = "googlenews"
USER_AGENT = "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.... |
from django.db import models
# Create your models here.
class Categorie(models.Model):
name = models.CharField(max_length=100, unique=True)
class Formation(models.Model): # will inherit the feature of a model
name = models.CharField(max_length=100)
img = models.ImageField(upload_to='pics')
desc = ... |
"Python Program to Add Two Matrices"
a = [[1,2,3],
[4,5,6],
[7,8,9]]
b =[[1,4,3],
[5,2,7],
[9,6,8]]
r = [[0,0,0],
[0,0,0],
[0,0,0]]
for i in range(len(a)):
for j in range(len (a[0])):
r[i][j]=a[i][j]+b[i][j]
print r
for c in r:
print c
|
if __name__ == '__main__':
n = int(input())
student_marks = {}
for _ in range(n):
name, *line = input().split()
scores = list(map(float, line))
student_marks[name] = scores
student_name = input()
a= student_marks[student_name]
b=sum(a)/3
c= round(b,2)
print("{0:.2... |
# -*- coding:utf-8 -*-
from mako import runtime, filters, cache
UNDEFINED = runtime.UNDEFINED
STOP_RENDERING = runtime.STOP_RENDERING
__M_dict_builtin = dict
__M_locals_builtin = locals
_magic_number = 10
_modified_time = 1456180775.315844
_enable_loop = True
_template_filename = '/Users/Jordan/Documents/BYU/0 - Senior... |
from flask_restful import Resource, marshal_with, fields
from flask import current_app, request
import base64
import re
import unittest
import random
#
from libs.cutoms import testtools
from layers.use_case_layer.actors import SomeoneActor
from libs.cutoms import ex_reqparse
from layers.ui_layer.rest import arguments
... |
#引入模块
import sys
print(sys.argv)
# 获取命令行参数列表
for i in sys.argv:
print(i)
# 从cmd执行并输入参数
name = sys.argv[1]
age = sys.argv[2]
hobby = sys.argv[3]
print(name,age,hobby)
# 查找模块所需模块的路径的列表
print(sys.path) |
import time
import sys
import select
class pumpkin_driver:
def __init__(self):
self.viper1 = [2, 3, 4, 17]
self.action_time = 0
def parse_line(self, line_in):
'''
This function takes in a command string `line_in`.
Allowed strings are:
- 'forward'
... |
import requests
from bs4 import BeautifulSoup
from prac import create_category_folder
from detail_page import extract_img_info as extract_product_info
url = "https://marketb.kr/"
DataBASE = []
headers = {'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 11_2_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4... |
"""
Dataset/Corpus related modules
"""
from .auto import ONLINE_EVAL_DATA_REGISTRY, get_auto_dataset
|
# -*- coding: utf-8 -*-
__author__ = 'bert'
WEIXIN_API_PROTOCAL = 'https'
WEIXIN_API_DOMAIN = 'api.weixin.qq.com'
WEIXIN_API_V3_DOMAIN = 'api.mch.weixin.qq.com'
API_GET= 'get'
API_POST= 'post'
API_CLASSES = {
'query_order': 'pay.weixin.api.api_pay_queryorder.WeixinPayQueryOrderApi',
'get_unifiedorder... |
from random import seed, choice, randint
seed()
dictionary = {}
list_of_sources=["concrete_noun","title","adjective","abstract_noun"]
for source in list_of_sources:
with open ("{}.txt".format(source)) as f:
dictionary[source] = f.readlines()
with open ("patterns.txt") as file:
patterns = file.readlin... |
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import estimators
from interfazbd import InterfazBD
def calcular_performances_intermedias(metodo_testeable, metodo_perfecto, valores_consultas):
res = []
for i in valores_consultas:
real = metodo_perfecto(i)
estimado = metodo_testeable(... |
import pygame
import os
class Paddle(pygame.sprite.Sprite):
# Constructor. Pass in the color of the block,
# and its x and y position
def __init__(self, images, width, height):
# Call the parent class (Sprite) constructor
pygame.sprite.Sprite.__init__(self)
# Create an image of the bl... |
from sys import stdin
from tqdm import tqdm
import numpy as np
insts = stdin.readlines()
insts = [inst.strip().split() for inst in insts]
def compile(inst):
if inst[1] == 'on' or inst[1] == 'off':
a = list(map(int, inst[2].split(',')))
b = list(map(int, inst[4].split(',')))
return " ".join... |
import json
from collections import OrderedDict
from brine.api import get_dataset_for_info
def info(dataset_name):
response = get_dataset_for_info(dataset_name)
ordered = OrderedDict()
ordered['name'] = response['name']
ordered['description'] = response['description']
ordered['versions'] = respon... |
def function_names(name):
'''
(io.TextIOWrapper) -> list of str
Will take in the name of a file,open it and read it.
It wil then return the function names in that file.
REQ: File needs to be in PEP8 format
'''
# Open the file and read it
file = open(name, "r")
# Open the file a... |
__author__ = 'mac'
class Solution():
def longestPalindrome(self, s):
length = len(s)-1
end_index = 0
i = 0
longest_sub = ""
longest_len = 0
if length == 0 or length == -1:
return s
while i < length:
temp = i
while s[temp+1... |
#!/usr/bin/env python
#
# Copyright 2012 Rafe Kaplan
#
# 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... |
# Generated by Django 3.1.4 on 2020-12-09 17:50
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('App_Video', '0002_auto_20201209_1748'),
]
operations = [
migrations.CreateModel(
name='Category... |
from collections import deque
from sys import maxsize, stdin
def parse_node(line):
digit_line = ''.join(c if c.isdigit() else ' ' for c in line)
x, y, _, used, avail, _ = [int(s) for s in digit_line.split()]
return (x, y), (used, avail)
def main():
_, _, *node_lines = stdin.read().splitlines()
n... |
import sys
import json
import datefinder
import requests
import datetime
from gcal_uplink import *
from watson_developer_cloud import NaturalLanguageUnderstandingV1
from watson_developer_cloud.natural_language_understanding_v1 import Features, KeywordsOptions, ConceptsOptions, EntitiesOptions
def get_nlu_data(samples)... |
#Tipado dinamico
'''
el tipado dinamico es que puedes cambiar el tipo de variable
'''
valor=10
print(valor)
valor="Emanuel"
print(valor)
|
from django.contrib import admin
from models import Feed, Article, Tag
admin.site.register(Feed)
admin.site.register(Article)
admin.site.register(Tag)
|
from django.db import models
class BookInfoManager(models.Manager):
"""图书模型管理类"""
# 应用1.改变查询的结果集
def all(self):
# 1.调用父类的all方法,获取所有数据集Queryset
books = super().all()
# 2.对数据进行过滤
books = books.filter(bisDelete=False)
# 3.返回过滤后的数据集
return books
# 应用2.封装函数:操... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.