text
stringlengths
38
1.54M
import cv2 import numpy as np img= cv2.imread("./input/rc-1.png") hsv=cv2.cvtColor(img, cv2.COLOR_BGR2HSV) original=img.copy() def empty(a): pass def remove_bad_contours(conts): new_conts = [] for cont in conts: bound_rect = cv2.minAreaRect(cont) length, breadth = float(...
from flask import Flask from .middlewares import after_request_middleware, before_request_middleware, teardown_appcontext_middleware from .middlewares import response from .controllers import register_modules from app.config import DB, App def create_app(): # initialize flask application application = Flask(_...
from random import random from time import sleep from time import perf_counter def cached_property(method): """decorator used to cache expensive object attribute lookup""" prop_name = '_{}'.format(method.__name__) def wrapped_func(self, *args, **kwargs): # print(self) if not ha...
from socket import * import time from threading import * import struct import colorama import scapy.all class Server: def __init__(self): '''constructor for the server that initalize the the data structures for the game''' self.clients = [] self.group1 = {} self.score1 = 0 ...
# # @lc app=leetcode id=523 lang=python3 # # [523] Continuous Subarray Sum # # https://leetcode.com/problems/continuous-subarray-sum/description/ # # algorithms # Medium (24.24%) # Likes: 1107 # Dislikes: 1559 # Total Accepted: 110K # Total Submissions: 449.6K # Testcase Example: '[23,2,4,6,7]\n6' # # Given a li...
import sys, os, Queue import cPickle as pickle import numpy as np from os.path import join as pathjoin import pixel_reg.doExtract as doExtract """ Yolo bad target extract paths: yolo_s2_074/yolo_s2_074-020.png yolo_s2_074/yolo_s2_074-044.png yolo_s3_086/yolo_s3_086-032.png yolo_s2_074/yolo_s2_074-083.png yolo_s2_07...
from sys import argv script, user_name = argv prompt = '> ' print "Hi %s" %user_name print "I'd like to ask you some questions." print "Do you like me?" likes = raw_input(prompt) print "Where do you live %s?" %(user_name) lives = raw_input(prompt) print "What kind of computer do you have %s?" %(user_name) computer ...
import argparse # Needs python2.7+ def check_positive(value): "Check if a variable entered to argparse is positive" ivalue = int(value) if ivalue <= 0: raise argparse.ArgumentTypeError("%s is an invalid positive int value" % value) return ivalue parser = argparse.ArgumentParser(description='Ru...
import numpy as np import os os.chdir('C:/Users/DELL/Desktop/Quant_macro/Pset4/hand') import matplotlib.pyplot as plt import Rep_agent_labor2 as ral #The basis functions are in the class as self.func ###parameters para = {} para['theta'] = 0.679 para['beta'] = 0.988 para['delta'] = 0.013 para['kappa'] = 5.24...
#! /usr/bin/python import util largest_num = 0 i=200000000 while(True): i += 1 for j in range(1, 21): if not i % j == 0: break if j == 20: largest_num = i if largest_num > 0: break print(largest_num)
Arrow1 = Arrow() my_view1 = GetRenderView() AnimationScene1 = GetAnimationScene() my_view0 = GetRenderViews()[1] RenderView2 = CreateRenderView() RenderView2.CompressorConfig = 'vtkSquirtCompressor 0 3' RenderView2.UseLight = 1 RenderView2.LightSwitch = 0 RenderView2.RemoteRenderThreshold = 3.0 RenderView2.LODThreshol...
# !/usr/bin/python # -*- coding: utf-8 -*- # @time : 2020/5/7 20:43 # @author : Mo # @function: FastText [Bag of Tricks for Efficient Text Classification](https://arxiv.org/abs/1607.01759) from macadam.base.graph import graph from macadam import K, L, M, O class FastTextGraph(graph): def __init__(self, hyper...
# -*- coding: utf-8 -*- """ Created on Sun Apr 15 21:48:29 2018 @author: Riko """ from agents.parcel import Parcel import matplotlib.pyplot as plt def graph_function(model, simulation_time, execution_time): parcel_age = [p.age / model.get_steps_per_hour() for p in model.schedule.agents_by_type[Parcel]] ...
class Solution(object): def integerReplacement(self, n): if n == 1: return 0 if n % 2 == 0: return 1 + self.integerReplacement(n/2) else: return 1 + min(self.integerReplacement(n + 1), \ self.integerReplacement(n - 1)) """ ...
import smtplib import logging from datetime import datetime from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.image import MIMEImage logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(__name__) username = "ngtthanh1010@gmail.com" password = "xxxxxxx"...
# -*- mode:python -*- # # Copyright (c) Dimitry Kloper <kloper@users.sf.net> 2002-2012 # Distributed under the Boost Software License, Version 1.0. # (See accompanying file LICENSE_1_0.txt or copy at # http://www.boost.org/LICENSE_1_0.txt) # # This file is part of dgscons library (https://github.com/kloper/dgs...
from django import forms from django.contrib.auth.models import User class LoginForm(forms.Form): username = forms.CharField(widget=forms.TextInput) password = forms.CharField(widget=forms.PasswordInput) def clean(self): username = self.cleaned_data['username'] password = self.cleaned_da...
import random import numpy as np from math import log from netcal.metrics import ECE from scipy.optimize import fmin_bfgs from scipy.special import expit, xlogy from sklearn.linear_model import LogisticRegression from sklearn.metrics import accuracy_score, log_loss import warnings warnings.filterwarnings('once') def s...
from lib.walletConnection import Connection from lib.utils import sha_256 from lib.address import Address import os def showDetails(wallet): print(wallet.user_ID) #wallet.checkUpdate() print(str(wallet.addr) + " => " + str(wallet.count)) print("\n\n\nIt's possible that this value was not up-to-date. Pl...
''' ------------------------------------------------------------------------------------------------ DAY THREE ------------------------------------------------------------------------------------------------ PROBLEM: Santa is delivering presents to an infinite two-dimensional grid of houses. He begins by deliveri...
"""Chats app.""" # Django from django.apps import AppConfig class ChatsConfig(AppConfig): """Chats app config.""" default_auto_field = 'django.db.models.BigAutoField' name = 'app.chats'
from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^validate/(?P<route>\w+)$', views.validate, name='validate') ]
print("Enter the first number add") first = input() print("Enter the second number add") second = input() print("Enter the third number add") third = input() print("The sum is " + int(first) + int(second) + int(third))
L = float(input('Largura da parede em metros:')) Al = float(input('Altura da parede em metros')) a = L * Al p = a/2 print('Sua parede tem dimensão de {}x{} e sua área é de {}m²'.format(L, Al, a)) #A CADA 2m² DE PAREDE PRECISA DE 1L DE TINTA print('Para pintar essa parede você precisará de {}L de tinta'.format(p))
#=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- #1 load model and load data #numpy大量矩陣維度與矩陣運算, log import numpy as np #Paython上Excel所有操作, 欄位的加總、分群、樞紐分析表、小計、畫折線圖、圓餅圖 import pandas as pd #畫圖範圍框架 import matplotlib.pyplot as plt #seaborn直方圖, heatmap import seaborn as sns #=-=-=-=-=-=-=...
base_num=int(input('Give me the base number:')) power_num=int(input('give me the power number:')) # result = base_num**power_num result=pow(base_num,power_num) print('Your result is',result)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # filename: client.py # modified: 2019-10-25 __all__ = ["WxApiClient"] from requests.sessions import Session from ..const import WXAPI_PROFILE _APP_ID = WXAPI_PROFILE["appID"] _APP_SECRET = WXAPI_PROFILE["appSecret"] _DEFAULT_TIMEOUT = WXAPI_PROFILE["client"]["default...
""" thread_server 基于线程的并发模型 重点代码 创建监听套接字 循环接收客户端连接请求 当有新的客户端连接创建线程处理客户端请求 主线程继续等待其他客户端连接 当客户端退出,则对应分支线程退出 """ from socket import * from threading import Thread import sys # 全局变量 HOST = '0.0.0.0' PORT = 8888 ADDR = (HOST, PORT) # 客户端处理函数 def handle(c): while True: data = c.recv(1024).decode() if n...
#===============================MOTIVATION================================ # This code was created for the semester project of Agent-Based Systems # course (SAG_2020L) of master studies programme at the Warsaw University # of Technology - Faculty of Electronics and Information Technology. # # Supervision and m...
import pytest from game.hungarian_deck import HungarianDeck, HungarianCard, card from game.hungarian_deck.deck import OutOfCardsException def test_deck_can_be_created(): deck = HungarianDeck() assert True, "couldn't initialize deck" def test_new_deck_contains_32_cards(deck: HungarianDeck): assert len(de...
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 import numpy as np import functools from src.save_dataset import save_dataset from sklearn.preprocessing import LabelBinarizer def generate_synthetic_data(numdims, noise, numsamples=1000, num_group_types=1, ...
# Generated by Django 3.1.7 on 2021-03-04 08:27 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('shopping_cart_app', '0004_auto_20210211_1518'), ] operations = [ migrations.RemoveField( model_name='category', name='desc',...
from num2words import num2words total = 0 for i in range(1,1001): total += len(num2words(i)) - ((num2words(i)).count(" ")) - ((num2words(i)).count("-")) print(total)
from math import log10 n, d = 3, 2 tot = 0 for i in xrange(1000): if int(log10(n)) > int(log10(d)): tot += 1 n,d = n+2*d, n+d print tot ## It is possible to show that the square root of two ## can be expressed as an infinite continued fraction. ## ## 2 = 1 + 1/(2 + 1/(2 + 1/...
# Copyright (c) 2013, Fortylines LLC # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, # this list of conditions an...
from presidio_analyzer import Pattern, PatternRecognizer # pylint: disable=line-too-long,abstract-method class UsSsnRecognizer(PatternRecognizer): """ Recognizes US Social Security Number (SSN) using regex """ PATTERNS = [ Pattern("SSN (very weak)", r"\b(([0-9]{5})-([0-9]{4})|([0-9]{3})-([0-9...
""" File for database utilities Authors: Edward Mattout & Daniella Grimberg """ import logging import sys import mysql.connector from config import HOST, DATABASE, USER, PASSWORD, LOG_FILE_FORMAT, LOG_FILE_NAME formatter = logging.Formatter(LOG_FILE_FORMAT) logger = logging.getLogger('database') logger.setLevel(log...
from django import forms from .models import ModelosClustering ''' class ModelosForm(forms.ModelForm): class Meta: model = Modelos fields = ['modelo'] def __init__(self, *args, **kwargs): super().__init__(*args **kwargs) self.fields['modelo'].widget.attrs.update({ ...
m,n=map(int,input().split()) string = list(input()) string = [int(x) for x in string] for i in range(1,m): k=i-1 while (i-k)!=n and k>=0: string[i]^=string[k] k-=1 print(''.join(map(str,string[:m])))
from abc import ABC import geopandas as gpd import pandas as pd from coord2vec.common.db.postgres import get_df, connect_to_db from coord2vec.feature_extraction.feature import Feature class BasePostgresFeature(Feature, ABC): def __init__(self, **kwargs): """ Args: table_filter_dict:...
""" define classe to describe information about density in cell """ __author__ = 'ikibalin' __version__ = "2019_07_09" import os import numpy import f_mem.cl_atom_density import f_common.cl_variable class CellDensity(dict): """ Class to describe all information concerning the density in cell """ de...
# coding: utf-8 # In[ ]: import argparse, datetime, os, json import statistics parser = argparse.ArgumentParser(description='Averge number') parser.add_argument('--search_term', help='search term') parser.add_argument('--min_date', help= 'min day in yyyy-mm-dd') parser.add_argument('--max_date', help= 'max day in...
#!/usr/bin/env python import subprocess import sys import os import time import psutil import appindicator import gtk import gobject import notify2 import natsort import pyxhook as hook import atexit as at_exit import pickle import threading statefile = os.path.expanduser('~/.vlcwrapy-nix/vlcdatabase.p') show_notificat...
from __future__ import print_function from django.conf import settings from rest_framework.response import Response from rest_framework.decorators import api_view, permission_classes from rest_framework.permissions import AllowAny from django.core import serializers core_serializers = serializers from django.http impor...
# -*- coding: utf-8 -*- import pymysql import time import re class LightMysql: _dbconfig = None _cursor = None _connect = None _error_code = '' # error_code from pymysql TIMEOUT_DEADLINE = 30 # quit connect if beyond 30S TIMEOUT_THREAD = 10 # threadhold of one connect ...
#백준 11049 - 행렬 곱셈 순서 import sys import math input = sys.stdin.readline n = int(input()) arr = [list(map(int,input().split())) for _ in range(n)] dp = [[0 for _ in range(n)] for _ in range(n)] for gap in range(1,n): # dp[start][end] 일때 start와 end의 차이 1부터 3까지 기록한다는 뜻 ex) dp[1][2], dp[2][3], dp[3][4] start = 0 #스타트 ...
from gym_pybullet_drones.envs.single_agent_rl.BaseSingleAgentAviary import ObservationType, ActionType from track import TrackV1 import numpy as np from gym_pybullet_drones.utils.Logger import Logger # Create the environment gui = True obs = ObservationType.RGB # Define what type of observation your agent should intak...
# -*- coding: utf-8 -*- from bkz.settings import * DEBUG = False TEMPLATE_DEBUG = False DATABASES['default'] = { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'bkz', # Or path to database file if using sqlite3. 'USER': 'bkz', # Not used with sqlite3. 'PASSWORD': 'bkz', # Not used with sq...
#Калькулятор для множеств instruction = str(input()) sets = [str(i) for i in input().split()]
# Generated by Django 2.0.2 on 2018-09-03 17:09 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('miapp', '0002_auto_20180903_1708'), ] operations = [ migrations.AddField( model_name='admincc',...
import glfw import numpy as np from OpenGL.GL import * class Window: def __init__(self, width: int, height: int, title: str): if not glfw.init(): raise Exception("glfw cannot be initialized.") self.win = glfw.create_window(width, height, title, None, None) if not self...
selection = input("1 - gaussian filter" + '\n' + "2 - median filter" +'\n' + "Enter your option number : " ) import numpy as np import cv2 if( selection == "1" or selection =="2"): print("processing") if(selection == "1"): import numpy as np import cv2 img = cv2.im...
#introuce random import random #建立随机单词库 dictionary=("cat","dog","rabbit","bear","sheep") def hangman(word): #関数を定義 wrong = 0#エラー数 HP = ["", "_______ ", "| | ", "| | ", "| | ", "| | ", ...
#!/usr/bin/env python3 #-*- coding:utf-8 -*- import requests import re from bs4 import BeautifulSoup import database #可以使用的url list=[15335287,13495332,12438452,10167348,7704150,15081291,13754755,13754608,15230833] #不可以使用的url ll=[20960386,10050485,9848063,10595949,10771117,9987189,21639667,21403332] #http://www.edewakar...
""" An example of tmap visualizing data gathered in a flow cytometry experiment. The k-nearest neighbor graph is constructed using the Annoy library. Data Source: https://journals.plos.org/plosone/article?id=10.1371/journal.pone.0057002 """ import numpy as np import flowkit as fk import tmap as tm from faerun impor...
import level_data import main import cache import pygame from os.path import join import resources pygame.init() levels = level_data.get_levels() for level in levels: print level maskfile = join(resources.IMG_DIR, level[2]) bboxes = cache.get_cache(maskfile, main.get_bboxes) print "bboxes done" pygame....
from .models import Zipcode import django_filters class ZipCodeFilter(django_filters.FilterSet): JURISDICTION_NAME = django_filters.CharFilter(lookup_expr='icontains') class Meta: model = Zipcode fields = ['JURISDICTION_NAME', 'COUNT_FEMALE', 'COUNT_MALE', ]
daftarharga = {"apel" : 5000, "jeruk" : 8500, "mangga" : 7800, "duku" : 6500} def rataharga(): jumlahBuah = 0 jumlahHarga = 0 Rata = 0 for key,value in daftarharga.items(): jumlahHarga += value jumlahBuah += 1 Rata = jumlahHarga / jumlahBuah print("Rata-Rata Har...
{ 'targets': [ { 'target_name': 'liblibaxtls', 'type': 'static_library', 'sources': [ 'crypto/aes.c', 'crypto/bigint.c', 'crypto/crypto_misc.c', 'crypto/hmac.c', 'crypto/md2.c', 'crypto/md5.c', 'crypto/rc4.c', 'crypto/rsa.c', 'crypto/sha1.c', 'ssl/asn1.c', ...
##################################################### # # WebScarping Data Camp Course Details # ##################################################### # # Import scrapy library import scrapy from scrapy.crawler import CrawlerProcess # # DC Spider class class DCSpider( scrapy.Spider ): # variable name name = "...
import cv2 img1 = cv2.imread('joji.jpg') img2 = cv2.imread('luci.png') img3= img1[1:353,1:201,:] print(img3.shape) print(img2.shape) print(img1.shape) dst = cv2.addWeighted(img3,0.7,img2,0.3,0) cv2.imshow('dst',dst) #cv2.imwrite('dst.png',dst) cv2.waitKey(0) cv2.destroyAllWindows()
import json from os import path import matplotlib.pyplot as plt import numpy as np import pandas as pd import torch from scipy import stats from scipy.io import loadmat from sklearn import model_selection from tools import draw_neural_net, train_neural_net script_dir = path.dirname(__file__) # <-- absolute dir the ...
# 2019/12/24 n,m=map(int,input().split()) cnt=0 for i in range(1,n+1): cnt+=(i**2)%m print(cnt%m)
""" Read in the "show_version.txt" file. From this file use regular expressions to extract the os_version, serial_number, and configuration register value. Your output should look as follows: OS Version: 15.4(2)T1 Serial Number: FTX0000038X Config Register: 0x2102 """ from __future__ i...
import sys sys.stdin = open("D3_8457_input.txt", "r") T = int(input()) for test_case in range(T): N, B, E = map(int, input().split()) data = list(map(int, input().split())) ans = 0 for i in data: temp = (B // i - 1) * i for _ in range(3): temp += i if temp <= (B ...
# -*- coding: utf-8 -*- """ Created on Mon Oct 16 11:12:40 2017 Data is from the reviews of movies in 'data/labeledTrainData.tsv' Two Model: 1. Common CNN Model 2. Complex CNN Model from Yoon Kim's Paper. Merge multiple filters. It proves the second model preforms better. @author: teding """...
from browser import ajax, bind, document, html, timer def on_complete(request): document['response'] <= html.P(request.text) def request_simulation(): ajax.get('/page-dynamic/data', oncomplete=on_complete) timer.set_timeout(request_simulation, 2000) request_simulation()
from django.shortcuts import render <<<<<<< HEAD from django.utils import timezone from models import Donation ======= from django.template import Context from models import Donation from forms import DonationForm >>>>>>> 1506909a0a168091856c108e091a09dbc075cc7b from django.views.decorators.csrf import csrf_protect, ...
# -*- coding: utf-8 -*- import time import datetime import os import pandas as pd import numpy as np from db_operation import DBOperations from db_credential import credentials, oracle_credentials # 连接数据库 db_opt_wind = DBOperations(**oracle_credentials) # ====================================================...
__copyright__ = """\ (c). Copyright 2008-2013, Vyper Logix Corp., All Rights Reserved. Published under Creative Commons License (http://creativecommons.org/licenses/by-nc/3.0/) restricted to non-commercial educational use only., http://www.VyperLogix.com for details THE AUTHOR VYPER LOGIX COR...
import requests import lxml import os #需求爬取三国演义的所有章节 from bs4 import BeautifulSoup if __name__ == "__main__": url = 'https://www.shicimingju.com/book/sanguoyanyi.html' headers = { 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/...
# Generated by Django 3.1.1 on 2020-11-13 16:22 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('product', '0023_auto_20201113_1419'), ] operations = [ migrations.RenameField( model_name='product', old_name='height_unit',...
#!/usr/bin/python from os import listdir, getcwd import pandas as pd import matplotlib.pyplot as pl from matplotlib.ticker import MaxNLocator from matplotlib.backends.backend_pdf import PdfPages c = {'ph3p3':'r', 'ph4p7':'g', 'ph7p4':'b'} psz = 4 # scatter plot marker size raw = pl.figure(figsize=(8.5,11)) # figsize...
xpected = [1,"F", 5, 6, "DFG", 7, 3, 9, 34, 3] actual = ["F", 2, 3, "ASFFSA", 5, 2, 3] i = 0 j = 0 missing = [] extra = [] try: while True: found = False try: while expected[i] != actual[j]: i+=1 else: found = True except: i...
import spira.all as spira class Resistor(spira.PCell): width = spira.NumberParameter(default=spira.RDD.R1.MIN_WIDTH, doc='Width of the shunt resistance.') length = spira.NumberParameter(default=spira.RDD.R1.MIN_LENGTH, doc='Length of the shunt resistance.') def validate_parameters(self): if self...
import random import json ZE_ZASEDENO = "Z" NAPACEN_ZNAK = "#" NAPACEN_UGIB = "&" KONEC = "E" NADALJUJ = "C" TRI = "T" seznam = [1,2,3,4,5,6,7,8,9] ZACETEK = "S" def transponiraj(matrika): #transponira sudoku, ki je v obliki matrike transponiranka = [] for i in range(len(matrika[0])): ...
##Group 8: Álvaro Alfayate, Andrea de la Fuente, Carla Guillén y Jorge Nuevo. def ReadFasta(FileName): ##Definimos una función que lea el archivo FASTA elegidoy extraiga la información requerida MyFile=open(FileName,'r') ReadSeq='' #Una variable vacia que va a almacenar el Fasta leído for Line in MyFile: #...
from PIL import Image, ImageDraw import os import numpy as np from sklearn import neighbors import sklearn from sklearn.datasets import load_iris def createData1(path='../data/single_code/'): xx = [] yy = [] lists = os.listdir(path) # 列出目录的下所有文件和文件夹保存到lists lists.sort() for i in lists: i...
import datetime import pytest from django.contrib.contenttypes.models import ContentType from apps.history.metrics import (total_group_count_over_time, total_idol_count_over_time) from apps.people.factories import GroupFactory pytestmark = pytest.mark.django_db def test_total_group_count_over_time(): targe...
#!/usr/bin/python3 """Alta3 Research | Zach Feeser List - An example of working with python lists""" # define our main function (run time code goes here) def main(): # create a list to contain IPs to ban ban = [] # create an empty list # ban = list() # does the same thing as the line above # add...
class Solution: def searchInsert(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ ans = self.binary_search(nums, 0, len(nums)-1, target) if ans == len(nums)-1 and target > nums[-1]: ans += 1 return ans ...
from botocore.vendored import requests import os import json import gzip from StringIO import StringIO MAX_LINE_LENGTH = 32000 MAX_REQUEST_TIMEOUT = 30 def lambda_handler(event, context): key, hostname, tags, baseurl = setup() cw_log_lines = decodeEvent(event) messages, options = prepare(cw_log_lines, hos...
import pandas as pd from pandas import DataFrame import matplotlib.pyplot as plot target_url = ("https://archive.ics.uci.edu/ml/machine-learning-" "databases/undocumented/connectionist-bench/sonar/sonar.all-data") data = pd.read_csv(target_url, header=None, prefix="V") dataRow2 = data.iloc[0:208, 1] dataR...
import os import socket import threading from Position import Position class GPSReceiver: def __init__(self, deviceIP, devicePort): self.deviceIP = deviceIP self.devicePort = devicePort #we use TCP self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.bind((deviceIP, devicePort)) #manag...
# list vs strings # srtring are immutable # lists are mutable # in ruby string is mutable s = "string" # t=s.title() # print(t) # print(s) l = ['word1','word2','word3'] l.pop() l.append('word3') print(l)
import random score_dict = {} def main(): while True: prompt = 'Enter command:1. data entry, ' prompt += '2. query, 3. exit >>' s = input(prompt) if not s: break cmd = int(s) if cmd == 3: break if cmd == 1: ...
# dictionary with three importants rivers rivers = {'Amazonas': 'Brasil', 'San Francisco': 'Eua', 'Tamisa': 'England'} for river, country in rivers.items(): print(f'The {river} flows through {country}') for river in rivers: print(river) for country in rivers.values(): print(country)
""" 取消功能允许我们要求取消期货或协程: """ import asyncio async def myCoroutine(): print("My Coroutine") async def main(): current = asyncio.Task.current_task() print(current) loop = asyncio.get_event_loop() try: task1 = loop.create_task(myCoroutine()) task2 = loop.create_task(myCoroutine()) task3 = loop....
def add_positive_numbers(x, y): assert x > 0 and y > 0, "Both numbers must be positive!" return x + y print(add_positive_numbers(1,2)) #3 # print(add_positive_numbers(1,-3)) #Assertion Error def eat_junk(food): assert food in ["pizza", "ice cream", "candy", "fried butter"], "Food must be in 'junk food' ...
#!/usr/bin/env python #Client #imports import sys import socket from threading import Thread from queue import Queue class Client: def __init__(self, log, message_queue): self.message_queue = message_queue self.log = log self.packet_size = 1024 self.info = "" self.sock = No...
from sklearn.externals import joblib import os, numpy as np, sys vsm = '/tmp/event_analaysis_output/modeling/TfIdfMatrix_False_False_doc_matrix_term_2016-11-07_2017-01-01.model' index = joblib.load(vsm) feature_m = index["matrix"] for dirpath, dirnames, filenames in os.walk("/tmp/event_analaysis_output/evaluation/"):...
def exec(instn, pch, reg, var): opc = instn[:5] if opc == "00010": movI(instn, pch, reg) elif opc == "00101": store(instn, pch, reg, var) elif opc == "10010": je(instn, pch, reg) elif opc == "00000": add(instn, pch, reg) elif opc == "00001": sub(instn, pch...
from BitVector import BitVector from constants import Constants from utils import Utils from typing import * import copy import logging class Key: NO_OF_ROUNDS = 10 # NO_OF_ROUNDS + 1 keys needed including original. So 'NO_OF_ROUNDS' key expansions are needed. def __init__(self, key_string: str): se...
"""create users table Revision ID: 39e93e7ef50b Revises: None Create Date: 2012-08-09 21:33:28.187794 """ # revision identifiers, used by Alembic. revision = '39e93e7ef50b' down_revision = None from alembic import op import sqlalchemy as sa from sqlalchemy.schema import CreateSequence, DropSequence def upgrade(): ...
from flask.ext.wtf import Form from wtforms import TextField, BooleanField, IntegerField from wtforms.validators import Required class LoginForm(Form): openid = TextField('openid', validators = [Required()]) remember_me = BooleanField('remember_me', default = False) class NewTaskForm(Form): task = TextField('task'...
foods = ["dosa", "chapathi", "beef", "chicken", "mutton"] for f in foods [1:3]: print (f) print (len(f))
import pandas as pd import numpy as np import fdb import time import os import sys import shutil import zipfile from datetime import datetime from unicodedata import normalize if os.path.exists(os.getcwd() + '\\VSCyber.FDB'): os.remove(os.getcwd() + '\\VSCyber.FDB') shutil.copyfile(os.getcwd() + '\\_.FDB', os.get...
# https://atcoder.jp/contests/tessoku-book/tasks/tessoku_book_bd # https://github.com/E869120/kyopro-tessoku # 入力 N, Q = map(int, input().split()) S = input() queries = [ list(map(int, input().split())) for i in range(Q) ] # print(queries) # 文字を数値に変換(ここでは書籍とは異なり、0-indexed で実装しています) # ord(c) で文字 c の文字コード(ASCII コード)を取得 ...
#!/usr/bin/env python # # Titanium API Coverage Merger # # Initial Author: Jeff Haynie, 06/03/09 # import os, sys, types import simplejson as json def dequote(s): if s[0:1] == '"': return s[1:-1] return s def is_leaf(obj,defvalue=False): if type(obj) == types.DictType and (obj.has_key('property') or obj.ha...
"""Module for the sample adapter classes.""" import os import sys import time from multiprocessing import Manager, Process import six from activities_python.common.action_support.base import BaseAction from activities_python.common.constants.controller import ControllerConstants class ActionQuery3(BaseAction): ...