text
stringlengths
38
1.54M
import hmac import hashlib digest_maker = hmac.new('secret-key', '', hashlib.sha256) f = open('sample-file.txt', 'rb') try: while True: block = f.read(1024) if not block: break digest_maker.update(block) finally: f.close() digest = digest_maker.hexdigest() print digest
from trax.supervised import training # UNQ_C4 (UNIQUE CELL IDENTIFIER, DO NOT EDIT) # GRADED FUNCTION: train_model def train_model(model, data_generator, batch_size=32, max_length=64, lines=lines, eval_lines=eval_lines, n_steps=1, output_dir='model/'): """Function that trains the model Args: model (t...
#Write your code below this row 👇 for num in range(1,100): if num % 3 == 0: print(f"{num} : Fizz") elif num % 5 == 0: print(f"{num} : Buzz") elif (num % 3) and (num%5) ==0: print(f"{num} : FizzBuzz") else: print(num)
import socket from Crypto.Util.number import long_to_bytes from hashlib import sha512 remoteip = "133.9.81.203" remoteport = 1337 def sock(remoteip, remoteport): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((remoteip, remoteport)) return s, s.makefile('rw', bufsize=0) def...
import json from domino.core import log from pages._base import Page as BasePage from pages._base import Title, Toolbar, Input, InputText, Button, Table, IconButton, Select, Row from tables.postgres.printer import Printer from tables.postgres.server import Server #from tables.dept import Dept from sqlalchemy import or_...
from flask import Flask from flask_wtf.csrf import CsrfProtect from views import Index app = Flask(__name__) CsrfProtect(app) app.add_url_rule('/', view_func=Index.as_view('index')) if __name__ == '__main__': app.run(debug=True)
from django.db import connections from django.conf import settings from django.http import HttpResponse from beans import ComputeNodeMana,InstanceManager,KeyStoneManager,NetWorkManager,EvaLog from django.shortcuts import render_to_response import json import checker import ks_auth from public import NOVA_DB,NEUTRON_DB...
# # abc165 c # import sys from io import StringIO import unittest sys.setrecursionlimit(100000) class TestClass(unittest.TestCase): def assertIO(self, input, output): stdout, stdin = sys.stdout, sys.stdin sys.stdout, sys.stdin = StringIO(), StringIO(input) resolve() sys.stdout.seek...
users = [ {"username": "samuel", "tweets": ["I love cake", "I love pie", "hello world!"]}, {"username": "katie", "tweets": ["I love my cat"]}, {"username": "jeff", "tweets": []}, {"username": "bob123", "tweets": []}, {"username": "doggo_luvr", "tweets": ["dogs are the best", "I'm hungry"]}, {"username": "guitar_g...
# NOTE: Generated By HttpRunner v3.1.4 # FROM: testcases\demo_testcase_request.yml from httprunner import HttpRunner, Config, Step, RunRequest, RunTestCase class TestCaseDemoTestcaseRequest(HttpRunner): config = Config("request methods testcase with functions").variables(**{'foo1': 'config_bar1', 'foo...
'''########################################################''' '''########################################################''' '''########################################################''' '''Hands On''' # Take your street address and make it a list variable myaddress # where each token is an element. # What would ...
import turtle window=turtle.Screen() window.bgcolor("blue") bepo=turtle.Turtle() bepo.forward(50) bepo.left(90) bepo.forward(100) bepo.left(90) bepo.forward(50) bepo.left(90) bepo.forward(100) window.mainloop()
import os from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_marshmallow import Marshmallow db = SQLAlchemy() ma = Marshmallow() def create_app(test_config=None): # create and configure the app app = Flask(__name__, instance_relative_config=True) app.config.from_mapping( ...
'print the last k lines from an input file' def getLastkLines(fpath, k): 'given a filepath, returns the last k lines from file' total = 0 currk, lastk = [None]*k, [None]*k csize = 0 fHandle = open(fpath) while True: line = fHandle.readline() if line == '': break ...
import os import subprocess import traceback class Git: def __init__(self): self.PATH_BASE = os.path.join(os.path.expanduser("~"), "repo_sync") if not os.path.isdir(self.PATH_BASE): os.mkdir(self.PATH_BASE) def repo_exists(self, name): return os.path.isdir(os.path.join(self...
#-*- coding:utf-8 -*- import urllib2 import json import string import time import signal def handler(signum, frame): raise AssertionError def get_url_data(url, num_retries = 2): try: print 'Downloading http...' request = urllib2.Request(url) response = urllib2.urlopen(request, timeout...
# -*- coding: utf-8 -*- """ Created on Thu Jun 30 16:48:10 2022 stock market analysis with pandas datareader - extract data - build candlestick chart """ from pandas_datareader import data import datetime start = datetime.datetime(2022,1,1) end = datetime.datetime(2022,6,30) df = data.DataReader(name="AAPL", data...
from operator import itemgetter with open("Data/Frequency(root).txt","w",encoding="utf-8") as outputfile: #print (outputfile) keyword = {} with open("Data/Separeted_word(root).txt","r",encoding="utf-8") as ins: for line in ins: if line=="</news>\n": #sorted(keyword.values()) #sorted(keyword.items(),...
from __future__ import unicode_literals from django.apps import AppConfig class AdminexConfig(AppConfig): name = 'adminex'
#Richard Xie """ A script that reads multiple monthly tick data csv files. Can be used to detect any flash crash based on the percent change of min and max ask price for each day’s ticks in 10 years of monthly tick data for each currency cross. It will return specific dates and the percent change of those ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Oct 28 15:03:04 2022 @author: Dartoon """ import numpy as np import astropy.io.fits as pyfits import matplotlib.pyplot as plt import glob import pickle import copy run_folder = 'stage3_all/' #!!! filt = 'F150W' files = glob.glob(run_folder+'fit_ma...
#%% import logging import yaml import os #if you want to utilize a config file try this. def parse_config(): config_path = "./conf/config.yml" current_path = os.path.dirname(os.path.abspath(__file__)) with open(os.path.join(current_path, config_path)) as file: cfg = yaml.load(file, Loader=yaml.Ful...
import time from time import sleep import RPi.GPIO as GPIO import getWindowStatus windowStatus = getWindowStatus.windowStatus() rainSensor = 11 motorLeft = 37 motor2Right = 33 GPIO.setmode (GPIO.BOARD) GPIO.setup(rainSensor, GPIO.IN) GPIO.setup(motorLeft, GPIO.OUT) GPIO.setup(motor2Right, GPIO.OUT) GPIO.output(motor2R...
# -*- coding: utf-8 -*- # Copyright: (c) 2020, Ari Stark <ari.stark@netcourrier.com> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import (absolute_import, division, print_function) __metaclass__ = type import unittest from ansible_collections.ari_star...
# absolute.py # Lab 3.2 # This program takes in a number and gives its absolute value # Author: Amanda Murray number = float (input ("enter a number:")) absolutevalue = abs (number) print ('the absolute value of {} is {}'.format(number, absolutevalue))
#!/usr/bin/env python # encoding: utf-8 from peewee import * from playhouse.pool import PooledMySQLDatabase import config mysql_db = PooledMySQLDatabase(config.get('database_db_name'), max_connections=8, stale_timeout=300, **{'host': config.get('database_hos...
class Solution(object): def longestConsecutive(self, nums): """ :type nums: List[int] :rtype: int """ s=set(nums) # vis=set() best=0 for i in s: if i-1 not in nums: y=i+1 while y in s: ...
import bs #Created By MythB # http://github.com/MythB import bsInternal import bsPowerup import bsUtils import random import os import MythBAdminList as mbal class chatOptions(object): def __init__(self): self.MythBWasHere = True def checkDevice(self,nick):# check if in admin...
print('enter 1 for addition\nenter 2 for multiplication\nenter 3 for subtraction\nenter 4 for division') c = int(input("please enter number:")) number1 = int(input('give us a number ')) number2 = int(input('give us second number ')) if c == '1': print(number1 + number2) elif c == '2': print(num...
from history import * class Video: def __init__(self,name,uri,duration,desc,uid): self.__name = name self.__uri = uri self.__duration = duration self.__desc = desc self.__likes = 0 self.__views = 0 self.__uid = uid def disp(self): print(f"name: {s...
from email.mime.multipart import MIMEMultipart from email.mime.image import MIMEImage from email.mime.text import MIMEText import imaplib import smtplib import email import os class harpo: def __init__(self, email, password, server): """ @brief Config of email @param [email]: (...
import json import warnings import pipeline warnings.simplefilter('ignore') class serializer: def __init__(self, ques, results, error_text): self.query = ques self.results = results self.errorText = error_text def to_json(self): return json.dumps(self, default=lambda o: o.__d...
""" 1.1插入排序 基本思想:通过构建有序序列,对于未排序数据,在已排序序列中从后往前扫描,找到相应位置并插入; 算法步骤:1.将第一待排序序列第一个元素看做一个有序序列,把第二个元素到最后一个元素当成是未排序序列; 2.从头到尾一次扫描未排序序列,将扫描到的每个元素插入有序序列的适当位置。 (如果待插入元素与有序序列中的某个元素相等,则将待插入的元素插入到相等元素的后面《稳定》)。 """ def insert_sort(lists): count = len(lists) for i in range(1, count): key = lists[i] j = i - 1...
import threading local_school = threading.local() def process_student(): std = local_school.student print('Hello, %s (in %s)' % (std,threading.current_thread().name)) def process_thread(name:str): local_school.student = name process_student() t1 = threading.Thread(target=process_thread,args=("Peter",...
import json import requests from idgenie_django.models import IDGenieSession from django.contrib.auth import logout from django.http.response import JsonResponse from django.template import loader from django.shortcuts import get_object_or_404, render from rest_framework.decorators import api_view from django.conf imp...
num = int(input()) num_list = list(map(int,input().split(' '))) max = num_list[0] min = num_list[0] for i in num_list: if(max < i): max = i if(min > i): min = i print(min, max)
import copy, glob def func(filename): s=set() with open(filename) as fd: next(fd) for l in fd: line = l.strip() s.add(line) s2 = set() for l in s: r = l.split()[1]+" "+l.split()[0] if (r not in s2) and (l not in s2): s2.add(l) print(len(s), len(s2)) with open(filename, "w+") as fd: fd.write(...
#temp&RH import time from micropython import const import board import busio import adafruit_si7021 import csv i2c_port = busio.I2C(board.SCL, board.SDA) _USER1_VAL = const(0x3A) sensor = adafruit_si7021.SI7021(i2c_port) print('Temperature: {} degrees C'.format(sensor.temperature)) print('Humidity: {}%'.format(sensor...
import pandas as pd import numpy as np from tools import make_distr distrib = dict() containers = pd.read_csv('DS_1.csv', header=0, sep=';') containers['val'] = (containers['Container type'])**2 - 7/2*(containers['Container type']) + 7/2 distrib = make_distr(containers, 40000, 20, 1, 1, 1, 1, 1, 5000) #containers, Wp,...
from django.urls import path from . import views urlpatterns = [ path(r'', views.index,name='index'), #Acá redirigirá al index.html path(r'base_layout',views.base_layout,name='base_layout'), #Y acá al base.html ]
class Solution: def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]: graph = collections.defaultdict(set) weights = dict() visited = set() def bfs(start, end): if (start, end) in weights: return...
import matplotlib.pyplot as plt import numpy as np # 绘制直方图、饼图、箱线图 plt.rcParams['font.sans-serif'] = "SimHei" plt.rcParams['axes.unicode_minus'] = False data = np.load('../data/国民经济核算季度数据.npz') name = data['columns'] values = data['values'] label = ['第一产业', '第二产业', '第三产业'] plt.figure(figsize=(6, 5)) # 绘制直方图 plt.bar(...
from django.urls import path, re_path from . import views app_name = "newsletters" urlpatterns = [ path("subscription/", views.SubscriptionCreateView.as_view(), name="subscription"), re_path( r"^subscription/confirm/(?P<key>[-:\w]+)/$", views.SubscriptionConfirmView.as_view(), name="su...
from django.urls import path from doctors.views import DoctorView, ListDoctorsView from rest_framework import permissions from drf_yasg.views import get_schema_view from drf_yasg import openapi schema_view = get_schema_view( openapi.Info( title="Doctor Store APIs", default_version='v1', descripti...
from PIL import Image import glob for file in glob.glob("*.png"): img = Image.open(file) rgb_im = img.convert('RGB') rgb_im.save(file.replace("png", "bmp"), quality=95)
import plistlib, sys, os parameters = dict( hipay=dict( username = os.environ.get('HIPAY_FULLSERVICE_API_USERNAME', 'xxxxxx'), password = os.environ.get('HIPAY_FULLSERVICE_API_PASSWORD', 'xxxxxx') ), hockeyapp=dict( app_identifier = os.environ.get('HOCKEY_APP_IDENTIFIER', 'xxxxxx'),...
import logging from app.config_common import * DEBUG = False LOG_LEVEL = logging.ERROR LOG_MAXBYTES = 1000000 LOG_BACKUPS = 30
#-------------------------------------------------- # limits.py # this file serves to hold the important limits # that are used in the project # introduced on R2 (pyFlask) #-------------------------------------------------- ################################################################ # Essential Limits (to be used...
class Solution: def isInterleave(self,s1,s2,s3): if len(s1)+len(s2) != len(s3): return False else: return self.helper(s1,s2,s3) def helper(self,s1,s2,s3): if s1 and s2: if s1[0] == s3[0] and s2[0] == s3[0]: return self.helper(s1[1:],s...
u, v = list(map(int, input().split())) arr = [v-1, 1] for i in range(0, v): # length of array if sum(arr) == v: base = val[0] for j in range(1, len(arr)): base ^= arr[j] if base == u: print(len(arr), " ".join(arr)) break arr[0] -= 1 arr[1] += 1
from neopixel_helpers import cycle, bounce, fade_in_out, np_setup, COLORS np = np_setup() for i, color in enumerate(COLORS): cycle(np, color) bounce(np, COLORS[i-1]) fade_in_out(np, COLORS[i-2])
import os os.environ["CUDA_VISIBLE_DEVICES"]="-1" import numpy as np from func_utils import * config = tf.ConfigProto() config.gpu_options.allow_growth = True session = tf.Session(config=config) keras.backend.set_session(session) if __name__ == "__main__": #data processing prefix = "Thesis Dataset" ...
import requests import matplotlib.pyplot as plt import networkx as nx from time import sleep print('This program is designed to build a graph of the friendship relations between users of social network VK.\n' 'ATTENTION!!! If you choose a depth of search greater than 1, be ready to face a lack of RAM.\n' ...
from car import Car class UberX(Car): """ UberX Class """ brand = str model = str def __init__(self,license,driver,brand,model): super(UberX,self).__init__(license,driver) #super.__init__(license,driver) """ si ocurre el error descriptor '__init__' requires a 'super' ob...
import pandas as pd from preprocessing_util import * def processing_for_both(data): # fill blank entries in the following columns nan_columns = ["Age", "SibSp", "Parch"] data = nan_padding(data, nan_columns) # drop columns not_concerned_columns = ["PassengerId","Name", "Ticket", "Fare", "Cabin", "Embarked"] d...
import albumentations as albu from albumentations.pytorch import ToTensor import numpy as np import cv2 import torch from .transforms import AlbuRandomErasing, ResizeWithKp, MultiScale def get_training_albumentations(size=(256, 256), pad=10, re_prob=0.5, with_keypoints=False, ms_prob=0.5): h, w = size train_...
# Animation clip demonstrating solution of points when they're near parallel and orthogonal # FILEID: H4 from manimlib.imports import * import numpy as np from decimal import Decimal class Scene1(LinearTransformationScene): CONFIG = { "include_background_plane": True, "include_foreground_plane": Fa...
two = 2 print(f"""Es gibt {two:b} Arten von Leuten. Diejenigen die Binärzahlen verstehen. Und die anderen.""") zahl = 255 print(f"255 hexadezimal {zahl:x}") e = 2.718281828459045 print(f"Eulersche Zahl: {e:5.2f}") vorname = "Heidi" print(f"Liebe {vorname}")
from django.templatetags.static import static from django.utils.html import format_html from wagtail.core import hooks @hooks.register("insert_global_admin_js", order=100) def global_admin_js(): return format_html( '<script src="{}"></script>', static("app/js/prototype.js") )
# if you need pydot - install using below command # pip install pydot # install graphviz 'graphviz-2.38.msi' and set add install directory to path # add 'C:\Graphviz2.38\bin' to 'Path' environment (system variables), might need admin privileges import pandas as pd from sklearn import tree import pydot import io impor...
#!/usr/bin/env python """=========== %(PROG)s =========== ------------------------------------------------------- compute linear regression of two user-specified fields ------------------------------------------------------- :Author: skipm@trdlnk.com :Date: 2014-01-13 :Copyright: TradeLink LLC 2014 :Version: 0.1 :Ma...
def process_file(f): """ This function extracts data from the file given as the function argument in a list of dictionaries. This is example of the data structure you should return: data = [{"courier": "FL", "airport": "ATL", "year": 2012, "month": 12, ...
from abc import ABC, abstractmethod # Base Abstract Class class Animal(ABC): def __init__(self, group, color): self.mygroup = group self._mycolor = color print("My tone is",self._mycolor,"in colour") # common method def isgroup(self): ...
import time def find_routes(rows,columns): dictionary = {} for i in range (0,rows+1): for j in range (0,columns+1): current_point = (i,j) if j == 0 or i ==0: dictionary[current_point] = 1 else: val1 = i-1 val2 = j-1 ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render from rest_framework import viewsets from . import models from . import serializers class ProductViewSet(viewsets.ModelViewSet): """ API endpoint that allows products to be viewed or edited. """ querys...
import secret import twitter import time api = twitter.Api( consumer_key = secret.dict['consumer_key'], consumer_secret = secret.dict['consumer_secret'], access_token_key = secret.dict['access_token_key'], access_token_secret = secret.dict['access_token_secret'] )
from django.db import models from django.conf import settings from .cohort import Cohort from .project import Project from ...utilities.base_model import BaseModel class ProjectCohortManager(models.Manager): def get_all_active_project_cohort_details(self, project_id): project_cohorts = self.filter(is_acti...
import serial import matplotlib.pyplot as plt ser = serial.Serial('/dev/ttyUSB0') print(ser.name) plt.plot(0,0) plt.xlim(0,4096) plt.ylim(0,4096) try: while True: line = ser.readline().decode("utf-8") try: dt, ch1_x, ch1_y, ch2_x, ch2_y = line.split(',') except ValueError: ...
# Keypirinha launcher (keypirinha.com) import keypirinha_util as kpu import keypirinha as kp import time import os class Launchy(kp.Plugin): """ Populate catalog using Launchy's configuration format. This plugin allows you to populate your catalog the same way you would in Launchy. You can simply co...
while True: while True: try: num1 = int(input('\nEnter a number: ')) except ValueError: print("Please enter only number") else: ...
#!/usr/bin/env python ''' ================================================================================ ### Motif-Mark ### A program to convert sequences motifs to a visual representation of the locations of motifs in sequences. This script can take DNA or RNA sequence input. It requires a fasta file and a text ...
#!/usr/bin/env python3 import argparse import os import sys import tempfile import subprocess import json import jmespath from pprint import pprint from urllib.parse import urlparse def nagios_exit(message, code): print(message) sys.exit(code) severities = { 'LOW': 1, 'MEDIUM': 2, 'HIG...
import argparse from pathlib import Path # import sys # print(sys.path) # exit() import torch from gans import GAN, LSGAN, WGAN, WGAN_GP from libs import str2bool, make_gif_with_samples def parse_args(): parser = argparse.ArgumentParser(description="Personal implementations of GAN") # Specify GAN typ...
a = [10,40,30,10,70,40] print("a awal =",a) # Menghapus 10 dari list a.remove(10) # Menghapus 40 dari list a.remove(40) print("hasil =",a)
"""Variables for gallery.py.""" """root = '/Volumes/Local_stuff/zdjecia_ubranek/chlopiec_56' # path to jpgs or folders of jpgs and output root""" tmp = '/tmp' # temporary folder to move corrupt files to index = 'index.html' # filename for html files index_mini = 'index_mini.html' # index with only t...
import dropbox app_key = '8w7ts322hfkb9ek' app_secret = '8dp228du8qsvj46' access_token = 'kSVIwQWSbHMAAAAAAAAL64PmaxHp3J-LHwFp-f0XC9J2nx5Ef_MCNHYGbFAeG2LA' def upload_file_to_dropbox(file_location, filename): metadata = None with open(file_location, 'rb') as f: dbx = dropbox.Dropbox(access_token) ...
import json from typing import Dict, List, Sequence from opentelemetry.sdk.trace import ReadableSpan from opentelemetry.sdk.trace.export import SpanExporter, SpanExportResult class MemorySpanExporter(SpanExporter): """Implementation of :class:`SpanExporter` that saves spans in memory. This class can be used...
# Write a program that asks the user to enter a number and the number of multiplications of that number to display. # # Sample Output: # > Enter a number: 2 # > Enter the multiplication: 5 # > 2 x 1 = 2 # > 2 x 2 = 4 # > 2 x 3 = 6 # > 2 x 4 = 8 # > 2 x 5 = 10
from django.shortcuts import render, redirect from django.http import HttpResponse from .models import post from django.db import connection from collections import namedtuple from django.utils import timezone from django.contrib import messages from django.contrib.auth.decorators import login_required from datetime im...
"""Radicale extension forms.""" from django import forms from django.utils.translation import gettext_lazy from modoboa.lib import form_utils from modoboa.parameters import forms as param_forms class ParametersForm(param_forms.AdminParametersForm): """Global parameters.""" app = "modoboa_radicale" ser...
import mechanize import httplib import re import scraperwiki import xml.sax.saxutils as saxutils import json import urllib2 import urllib import time from BeautifulSoup import BeautifulSoup # Useful stuff for parsing rcs_pattern = re.compile("[0-9]{3} [0-9]{3} [0-9]{3}") name_pattern = re.compile("Nom commercial :") ...
import xml.etree.ElementTree as xmltree tree = xmltree.ElementTree(file='my.xml') root = tree.getroot() print(root.tag) for a in root: print('標籤', a.tag, ',屬性', a.attrib, ',值', a.text) for b in a: print('標籤', b.tag, ',屬性', b.attrib, ',值', b.text) for item in root.iter('item'): print(item.attrib , it...
from keras.models import load_model from utils import * import matplotlib.image as mpimg import sys dir_name=input("Enter images dir") original_data_dir = os.path.dirname(os.path.realpath(__file__))+"/"+str(dir_name) base_folder=os.path.basename(original_data_dir) print(original_data_dir+'/model_data/...
# All Rights Reserved. # # 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...
# -*- coding: utf-8 -*- import logging import os from pathlib import Path import click import pandas as pd from dotenv import find_dotenv, load_dotenv from src.constants import (TARGET_FEATURE) from src.models.model import SoilClassifier @click.command() @click.option('--input_filepath', type=click.Path(exists=True...
from django.urls import path from rest_framework.routers import DefaultRouter from rest_framework_simplejwt.views import ( TokenRefreshView, ) from .views import ( UserViewSet, PostViewSet, CommentViewSet, HistoryDestroyViewSet, HashtagGenericViewSet, LikeCreateViewSet, MyTokenObtai...
__author__ = 'adrian' from PyQt4 import QtCore, QtGui import sys class myWindow(QtGui.QWidget): def __init__(self, parent=None): super(myWindow, self).__init__(parent) myLayout = QtGui.QVBoxLayout(self) Button = QtGui.QPushButton('Resize') myLayout.addWidget(Button) Button....
#!C:\Python27 # -*- coding: utf-8 -*- import chardet from kitchen.text.converters import to_unicode from openpyxl import Workbook def normalize_name(name): """Convert name to camel case.""" # print name if name: name = get_unicode(name).strip().title() return name def write_ws(ws, record): ...
from Bio import AlignIO, SeqIO import copy import time from Bio.Phylo import BaseTree from Bio._py3k import zip, range import numpy as np import pycuda.autoinit import pycuda.driver as drv from pycuda.compiler import SourceModule from phyloGenie.DistanceMatrixCalculatorGPU import DistanceCalculator_GPU # perform mu...
#!/usr/bin/env python # coding: utf-8 import cv2 import numpy as np import shapely.geometry as geom import shapedetector as sd def detect_sq(image): gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) blurred = cv2.medianBlur(gray, 3) edges = cv2.Canny(blurred, 60, 200) # edges = cv2.Canny(gray, 100, 2...
from Tools.Initialize import initialize class Longin(object): def __init__(self): self.driver=initialize().driver def LonginName(self): LonginName=self.driver.find_element_by_xpath("//input[@id='loginName']") return LonginName def PassWord(self): PassWord=self.driver.find_ele...
def test_solution(): import solution assert solution.reverse('hello') == 'oellh' assert solution.reverse('') == ''
import sys # noqa import subprocess # noqa from pip.req import parse_requirements from setuptools import setup, find_packages commit = subprocess.Popen( 'git rev-parse --short HEAD'.split(), stdout=subprocess.PIPE, ).stdout.read().decode('utf-8').strip() install_reqs = parse_requirements('requirements.txt'...
# -*- coding: utf-8 -*- """ Created on Sun Oct 4 19:39:31 2015 @author: leben Simulate charged particle motion within magnetic field with axial gradient """ import numpy as np import matplotlib.pyplot as plt from plot_utility import extractData import settings import magnetic as mag from Fields import SmoothField cl...
def input_to_int(value): """ Checks that user input is an integer. Parameters ---------- n : user input to check Returns ------- integer : n cast to an integer Raises ------ ValueError : if n is not an integer """ if str(value).isdigit(): return int(value) ...
"""import random alphabet = "abcdefghijklmnopqrstuvwxyz" alphabet_list = [alphabet[i] for i in range(len(alphabet))] #alphabet_list = list(alphabet) print(alphabet_list) message_text = "what is a baggins" cipher_list = list(alphabet_list) random.shuffle(cipher_list) print(cipher_list) cipher_text = "" for x in ...
# Lambda : 함수 이름 없이, 함수처럼 쓸수 있는 익명함수 f = lambda x, y: x + y print(f(1, 4)) # Map & Reduce ex = [1, 2, 3, 4, 5] f = lambda x: x ** 2 print(list(map(f, ex))) # Reduce from functools import reduce print(reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]))
"""DCG_API URL Configuration The `urlpatterns` list routes URLs to viewsets. For more information please see: https://docs.djangoproject.com/en/2.1/topics/http/urls/ Examples: Function viewsets 1. Add an import: from my_app import viewsets 2. Add a URL to urlpatterns: path('', viewsets.home, name='home')...
#usr/bin/env python3 ''' __author__ = 'abba y abdullahi ,' ''' import turtle turtle.pencolor('red') turtle.forward(200) turtle.left(90) turtle.pencolor('blue') turtle.forward(150) turtle.left(90) turtle.forward(200) turtle.pencolor('green') turtle.forward(200) turtle.left(90) turtle.pencolor('black') turtle.forward(1...
''' Created on Oct 2, 2012 @author: Gary ''' import threading from housemonitor.lib.hmqueue import HMQueue from housemonitor.lib.base import Base from send import COSMSend from housemonitor.lib.constants import Constants class COSMOutputThread( Base, threading.Thread ): ''' This thread will remove the data...