text
stringlengths
38
1.54M
import fitz class PdfHandler(): def __init__(self, filename): self.pdf = fitz.open(filename) self.pages = [None] * len(self.pdf) for pageNum in range(len(self.pdf)): self.pages[pageNum] = self.pdf[pageNum].getDisplayList() def getImage(self, pageNum = 0): page = se...
import FWCore.ParameterSet.Config as cms process = cms.Process("VALID") # Include the RandomNumberGeneratorService definition process.load("IOMC.RandomEngine.IOMC_cff") # Famos sequences process.load("FastSimulation.Configuration.CommonInputsFake_cff") process.load("FastSimulation.Configuration.FamosSequences_cff") ...
import numpy as np def agregar_imagen(fondo, imagen, x, y): # verificar si la imagen tiene informacion de opacidad alto = imagen.shape[0] ancho = imagen.shape[1] if imagen.shape[-1] == 4: # normalizar la opacidad opacidad = imagen[:,:,3]/255 # alpha blending # g...
#!/usr/bin/env python3 import numpy as np import copy as cp from tqdm import tqdm try: import lib.metrics as metrics except ModuleNotFoundError: import metrics import sklearn.model_selection as sk_modsel import sklearn.metrics as sk_metrics __all__ = ["kFoldCrossValidation", "MCCrossValidation"] class __CV...
def cube_odd(arr): sum = 0 for i, k in enumerate(arr): if isinstance(k, (int, float, complex)): if k%2 != 0: sum += pow(k, 3) else: return None return sum if __name__ == "__main__": cube_odd([1,2,3,4])
# Generated by Django 2.1.3 on 2018-11-30 09:29 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('users', '0003_auto_20181130_1459'), ('quiz', '0002_auto_20181125_1616'), ] operations = [ migration...
########## CHANGE THIS TO SET CONFIGURATION FILE NAME ########### config_file_name = "config.txt" from TwitterFollowBot import TwitterBot from twitter import Twitter, OAuth, TwitterHTTPError from random import randint import time from time import sleep import colorama from colorama import Fore, Style, Back, ini...
import logging LOG = logging.getLogger(__file__) import os import tarfile import shutil def init_path(full_path): """ Initializes full path and recreate if already exists """ dir_path = os.path.dirname(full_path) LOG.info('Initializing data folder: %s ...', full_path) if os.path.exists(dir_p...
print("how many cats do you have?") numCats= input() try: if int(numCats)>=4: print("That is a lot of cats.") elif int(numCats)<0: print("That is no cat at all.") else: print("That is not that many cats.") except ValueError: print("You did not enter a number.")
# -*- coding: utf-8 -*- """ Created on Thu Jan 16 16:35:39 2020 @author: Administrator """ import os import pandas as pd path = 'd:/Test' os.chdir(path) list_df = [] df1 = pd.DataFrame({'eNodeB' : range(729600,731648),'manufacturers' : '混合'}) list_df.append(df1) df2 = pd.DataFrame({'eNodeB' : range(1019136,1019392)...
import sys from PyQt5.QtWidgets import * from PyQt5.QtGui import QIcon from PyQt5.QtCore import QSize class Player(QWidget): def __init__(self): super().__init__() self.setWindowTitle("Music Player") self.setGeometry(450,150,600,800) self.UI() self.show() def UI(self):...
from bs4 import BeautifulSoup read_files = open('listfiles.txt', 'r') file_names = read_files.readlines() write_file = open('articles.txt', 'a') for file in file_names: file = file.strip() try: f = open(file, 'r') soup = BeautifulSoup(f, 'html.parser') txt = soup.get_text() pr...
class Solution: def numRookCaptures(self, board: List[List[str]]) -> int: # find rook flag = 0 for i in range(8): for j in range(8): if board[i][j] == "R": x = i y = j flag = 1 break ...
import urllib from pyquery import PyQuery as py url = 'https://cart.jd.com/cart.action#none' headers = { 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', # 'Accept-Encoding: gzip, deflate, br 'Accept-Language': 'en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7', 'Cache-Control': ...
import pytest @pytest.fixture(params=['1','2','3']) def data(request): return request.param class Test_Add: @pytest.fixture(scope='class', autouse=True) def click_con_list(self): #执行一次 #点击联系人 print('11111') @pytest.fixture(autouse=True) def click_add_con(self): # 执行三次 #点击 ...
#!/usr/bin/env python import argparse import os import sys import json import random as rnd import string import math import random import subprocess import time import pwd import os.path as op from termcolor import colored from boutiques.evaluate import evaluateEngine from boutiques.logger import raise_error, print_i...
""" Revision ID: 0338_add_notes_to_service Revises: 0337_broadcast_msg_api Create Date: 2021-01-13 11:50:06.333369 """ import sqlalchemy as sa from alembic import op revision = "0338_add_notes_to_service" down_revision = "0337_broadcast_msg_api" def upgrade(): # ### commands auto generated by Alembic - please ...
from flask import render_template, redirect, url_for, current_app, session from app.main import bp from app.main.forms import SearchForm import pandas as pd from datetime import datetime, timedelta # authlib version 13 + from authlib.integrations.requests_client import OAuth2Session from app import client from bs4 imp...
#!/home/cheshire/cheshire3/install/bin/python # -*- coding: utf-8 -*- """Clean up the character encoding problems when moving from C2 to C3 (June 2009)""" import sys import os import re import time sys.path.insert(1, '/home/cheshire/cheshire3/code') from cheshire3.web import www_utils from cheshire3.web.www_utils i...
from random import randint class Node(object): def __init__(self,v): self.value = v self.left = None self.right = None def build_Bitree(n): assert n > 0 lb = 0 ub = 29 if n < 29 else n nums = [] for _ in range(n): trial = randint(lb,ub) while trial in nu...
import random from bokeh.plotting import figure, show def tirar_dado(num_tiros): secuencia_tiros = [] for _ in range(num_tiros): tiro = random.choice([1, 2, 3, 4, 5, 6]) secuencia_tiros.append(tiro) return secuencia_tiros def simulacion(num_tiros, num_intentos): tiros = [] for _ i...
# Test that default values do not change. # Test that settings can be imported without the DJANGO_SETTINGS_MODULE # environment variable set. # Test that default values can be changed by the DJANGO_SETTINGS_MODULE.
import numpy as np from tools.utils import Helper, INFO, ERROR, NOTE import sys import argparse def main(train_set: str): centroids = np.load(f'data/{train_set}_anchor.npy') print(NOTE, f'Now anchors are :\n{centroids}') def parse_arguments(argv): parser = argparse.ArgumentParser() parser.add_argument...
# -*- coding: utf-8 -*- import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn.model_selection import GridSearchCV from sklearn.metrics import mean_squared_error from sklearn.metrics import r2_score from sklearn.preprocessing import scal...
# Generated by Django 3.0 on 2020-11-27 03:20 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('Contests', '0001_initial'), ] operations = [ migrations.RemoveField( model_name='contests', name='created', ...
from setuptools import setup setup( name="todo", version="0.3.1", author="hit9", author_email="nz2324@126.com", description=""" Cli todo tool with readable storage. """, license="MIT", keywords="todo readable commandline cli", url='https://github.com/secreek/todo', packages=...
import numpy import math # S def mag(vec): # Pythagoras return numpy.array(math.sqrt(vec[0] ** 2 + vec[1] ** 2)) # S def mag1(vec): return numpy.linalg.norm(vec) # T def unit(vec): x = vec[0] y = vec[1] length = mag(vec) print(length) return numpy.array([x/length, y/length]) # ...
class Jugada: @classmethod def toInstance(cls, mensaje): for subclass in cls.__subclasses__(): if subclass.mensaje == mensaje: return subclass() raise RuntimeError() def __str__(self): return str(self.to_message()) def to_message(self): retu...
# class Vehicle(object): # """docstring""" # def __init__(self, color, doors, tires, vtype): # """Constructor""" # self.color = color # self.doors = doors # self.tires = tires # self.vtype = vtype # def brake(self): # """ # Stop the car # ...
#/###################/# # Import modules # #import import ShareYourSystem as SYS #define MyLifer=SYS.LiferClass( ).lif( _StationaryExternalCurrentMeanFloat=15., _StationaryExternalCurrentNoiseFloat=21. ) #print print('MyLifer is') SYS._print(MyLifer)
# -*- coding: utf8 -*- # author: ronniecao # time: 2021/03/22 # description: environment of drawing import copy import json import math import numpy import cv2 class Env: """ 环境类:控制环境 """ def __init__(self, option): # 读取配置 self.option = option # 初始化颜色 self.color_dict =...
from django.shortcuts import render, redirect import serial arduino = serial.Serial('COM3', 9600) def home(request): if(request.GET.get('led1on')): led = '1' print(led) arduino.write(led.encode('ascii')) return redirect(home) elif(request.GET.get('led1off')): #led1 off button clicked led = "2" prin...
"""Extract games from 20 Questions game HITs. See ``python extractgames.py --help`` for more information. """ import json import logging import click from scripts import _utils logger = logging.getLogger(__name__) # main function @click.command( context_settings={ 'help_option_names': ['-h', '--hel...
import os; import types from project.tools.spider.spider_text import * from pathlib import Path; from project.spider_enterprise_site.spider.SpiderCssFile import SpiderCssFile from project.spider_enterprise_site.spider.SpiderJsFile import SpiderJsFile from project.spider_enterprise_site.spider.SpiderImageFile import Sp...
from datetime import datetime from voluptuous import Schema, Required, MultipleInvalid import traceback def Date(fmt='%Y-%m-%d'): return lambda v: datetime.strptime(v, fmt) Schema = Schema({Required('ad_network'): str, Required('date'): Date(), Required('app_name'): str, ...
def get_summ(one, two, delimiter='&'): one= one.capitalize() two=two.capitalize() return (f'{one} {delimiter} {two}') print(get_summ ("lEARN","pyTHOn"))
# 进程间的通信 # 队列:先进先出 from multiprocessing import Queue from multiprocessing import Process import time # q.put('') # 放元素 # q.get() # 取元素 # q.full() # 判断队列是否是满的 # q.empty() # 判断队列是否是空的 # q.qsize() # 获取队列长度 def download(q): images = ['girl.jpg', 'boy.jpg', 'man.jpg'] for image in images: print('正在下载:', i...
# Реализовать функцию my_func(), которая принимает # три позиционных аргумента и возвращает сумму наибольших # двух аргументов def int_func(x, y, z): a = x+y b = y+z if a > b: x+y return a else: y+z return b print (int_func(20, 10, 30))
import nltk from nltk import sent_tokenize from nltk.tokenize import word_tokenize import re from num2words import num2words from autocorrect import Speller spell_corrector = Speller(lang='en') def getProcessedContentsByLineFromFiles(filep, filen): with open(filep, encoding="utf-8_sig") as fp: linesp = fp...
"""change relationships for user and tags Revision ID: 2094e9ee194d Revises: 39ce44cc5447 Create Date: 2020-03-07 22:21:10.509935 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '2094e9ee194d' down_revision = '39ce44cc5447' branch_labels = None depends_on = Non...
#!/usr/bin/env python # -*- coding:utf-8 -*- # @Time : 2018/8/16 2:03 PM # @Author: jasmine sun # @File : DNR.py # PIL验证码图片预处理: https://www.jianshu.com/p/41127bf90ca9 from PIL import Image # 灰度化 def dnr_img(): # convert(): 将当前图像转换为其他模式,并且返回新的图像 img = Image.open('origin.jpg').convert('L') img.save('1.jp...
# -*- coding: utf-8 -*- from phanterweb.helpers import ( DIV, H3, FORM, I ) from phanterweb.materialize import ( MaterializeInputText, MaterializePreloaderCircle, MaterializeInputHidden, MaterializeButtonForm ) html = DIV( DIV( DIV( I("close", _class="material-i...
__author__ = 'luocheng' import os fout = open('run.sh','w') for f in os.listdir('./bleu'): fout.write('python CorrelationAnlysis.py ./bleu/'+f+"\n") fout.close()
# coding=UTF-8 from cloudify import ctx from fcntl import lockf, LOCK_EX, LOCK_UN from os import getpid from socket import getfqdn import uuid class FileLock(object): """A file lock to prevent race conditions.""" def __init__(self, lock_file=None, log_file=None, lock_details=None): """ Regi...
positivos=0 for i in range(6): numero=float(input()) if numero > 0: positivos=positivos+1 print(f'{positivos} valores positivos')
import paho.mqtt.client as MQTT import requests import telepot import time import json import os import datetime class DoSomething(object): def __init__(self): #self.clientID=None #self.msg=None self.fifo=None self.timer=None self.weights_vector=None self.products=None self.remove_product=None self...
# next idea: look at assigning tons of work and letting the computer figure out what to do. # lets make a directory with lots of little files that the process needs to open, # write to, and close. import multiprocessing as mp import numpy as np import glob import time def fileWriter(path): with open(path,'w') as ...
## <compile_data2.py> ## Author: Kai Bonsol ## This program will access new cases per day, test count, ## acutely ill, hospitalized, recovered, deceased ## ## import pickle import bs4 as bs import requests from twilio.rest import Client def update(text): print(text) account_sid = "AC1360cea428da...
from django.db import models class Card(models.Model): # A specific Hearthstone Card name = models.CharField(max_length=100, default="noName") @classmethod def create(cls, name): card = cls(name = name) return card class Deck(models.Model): # A Hearthstone deck containing a bunch of cards def __str__(sel...
from src.models.user import User from src.models.user_roles import UserRoles from src.models.roles import Roles
# -*- coding: utf-8 -*- """ Created on Wed Jul 3 06:45:38 2019 @author: night """ from collections import defaultdict import pandas as pd import networkx as nx import itertools import matplotlib.pyplot as plt import heapq import pydot import dill import graphviz def save_pkl(df, filename): with open('data/'+fil...
from rest_framework import serializers from coupon.models import Coupon class CouponSerializer(serializers.ModelSerializer): id = serializers.IntegerField(required=False) class Meta: model = Coupon fields = ['code', 'discount_type', 'discount_value', 'valid_from', 'valid_till', 'status', 'id...
Boston, MA 509953 # all 41145 # pneumonia 20577 # < 1 yr old 309257 # 65+ Bridgeport, CT 113119 8921 2546 78218 Cambridge, MA 63708 6778 629 47786 Albany, NY 142275 6252 5699 94558 Hartford, CT 156735 8483 5700 98414 Lowell, MA 72723 5691 1131 52267 New Haven, CT 126447 7547 5626 79803 Providence, RI 163598 1...
from django.conf.urls import url, include import xadmin from rest_framework.documentation import include_docs_urls from rest_framework.routers import DefaultRouter from cmdb.views import ZonesViewSet, ServersViewSet, BusinessViewSet from databases.views import InstancesGroupViewSet, InstancesViewSet, MysqldbsViewSet, ...
import time import scipy import scipy.optimize import scipy.sparse import scipy.sparse.linalg from scipy.spatial import cKDTree import core class BoundElementPoint: def __init__(self, element_id, xi, data_label, data_index=None, fields=None, weight=1): self._class_ = 'elem' self....
#!/usr/bin/python ### import guacamole libraries import avango import avango.gua from avango.script import field_has_changed class SceneScript(avango.script.Script): #input field sf_button8 = avango.SFBool() ## #output field sf_room_number = avango.SFInt() ## constructor def __init__(self): ...
import copy class Solution: def findWords(self, board: List[List[str]], words: List[str]) -> List[str]: trie = {} ans = {} if not board: return [] board_height = len(board) board_width = len(board[0]) total_size = board_height * board_width # Con...
from .views import home_view,detail_view,tagged,TagDetailView from django.contrib import admin from django.urls import include, path urlpatterns = [ path('',home_view), path('article/<slug:slug>',detail_view,name='detail'), # path('tagged/<slug:slug>',tagged,name='tagged') path('tagged/<slug:slug>',Ta...
from django.conf.urls import url from django.contrib import admin from API.views import * from API.web_view import * urlpatterns = [ url(r'^update_location_and_parameters/', update_location_and_parameters), url(r'^update_stop_location/', update_stop_location), url(r'^get_bus_data_current_time/', get_bus_...
""" Convenience wrapper to handle Oauth authentication """ import requests class LiveAuth(object): """ Live Oauth authentication helper """ _base_url = 'https://login.live.com/' _authorize_uri = 'oauth20_authorize.srf' _token_url = 'oauth20_token.srf' def __init__(self, client_id, client_se...
#This script has not been formatted for external use import copy import open3d as o3d import numpy as np import matplotlib.pyplot as plt #Data Path #path = "../../../Data/DATA_FROM_EARLIER_PHOTOS/Textured_OBJ/" path = "../../../Data/DanielHess_Dataset2/" detPath = "../../../Data/detrital_mesh2.obj" path_out = "out/cla...
from tealight.net import connect, send import tealight.utils import random userId= int(tealight.utils.now()) +random.randint(0,1000000) connect("racetracksix") send("connected") #def regisrtation_handler(message): #for i in range (0, carNumber): #call draw car function and increment placement #horizontally? also ...
''' Given an array nums of n integers where nums[i] is in the range [1, n], return an array of all the integers in the range [1, n] that do not appear in nums. ''' numss = [4,3,2,7,8,2,3,1] # [5,6] # Approach 1 # Intuitive: Compare unique values, return difference # Time: O(n) to find different between sets, where n...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Apr 20 19:53:40 2021 @author: joel """ # load the required functions import sys import numpy as np import pandas as pd import matplotlib.pyplot as plt from numpy.random import seed from numpy.random import multivariate_normal import statsmodels.api as ...
#!/usr/bin/env python # Ipred1 script is intended to get kmers from fasta file of viral or human proteome # and predict their binding affinity to MHC via netMHCpan in parallel import os, sys, subprocess, argparse, tempfile, shutil import pandas as pd from tqdm import tqdm, trange from Bio import SeqIO if __name__ ==...
import qsim import qgates from random import randint from math import sqrt # number of bits on which f operates n = 6 # secret element for which f(x) = 1 iff x = c c = randint(0, 2**n-1) print("Secret:", c) # define f(x) = 1 iff x = c def f(x): return 1 if x == c else 0 # create unitary operator...
""" FIDUCEO FCDR harmonisation Author: Arta Dilo / NPL MM Date created: 06-12-2016 Last update: 20-03-2017 Version: 10.0 Harmonisation functions for a pair-wise implementation and for all the sensors together using odr package. Functions implement weighted ODR (an EIV method) for a ...
import torch import os.path def load_data(sys_name, file_index): filename_list = os.listdir('../data/{0}'.format(sys_name)) if file_index >= len(filename_list): return False elif filename_list[file_index][-3:] != 'txt': return False else: filename = filename_list[file_index] ...
from .models import Formador from django_datatables_view.base_datatable_view import BaseDatatableView from django.db.models import Q from formacion.models import Grupo,ParticipanteEscuelaTic, SoporteEntregableEscuelaTic, Masivo, MasivoDocente, Actividad, EvidenciaEscuelaTic, Entregable from formacion.models import Grup...
def dest(mneumonic): dst, _, _ = _destruct(mneumonic) ins = 0 if dst: if "M" in dst: ins |= 0x1 if "D" in dst: ins |= 0x2 if "A" in dst: ins |= 0x4 return f"{ins:03b}" def comp(mneumonic): instructions = { "0": "0101010", ...
# -*- coding: utf-8 -*- # Generated by Django 1.10.1 on 2017-02-05 08:06 from __future__ import unicode_literals from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('routeoptimizer', '0001_initial'), ] operations = [ ...
from flask import Flask, render_template, request import helpers # Init # ---------------------------------- app = Flask(__name__) app.config.update(blog=helpers.get_config()) app.config.update(SERVER_NAME=app.config['blog']['host']) app.debug = app.config['blog']['debug'] # ---------------------------------- # Ro...
import os import sys import tarfile import time import pyprind import pandas as pd import pandas as pd from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler import numpy as np import matplotlib.pyplot as plt from sklearn.decomposition import PCA from matplotli...
import sys from PIL import Image import math import queue as Q import time # import matplotlib.pyplot as plt import copy ''' These variables are determined at runtime and should not be changed or mutated by you ''' start = (0, 0) # a single (x,y) tuple, representing the start position of the search algorithm end = (0...
from bs4 import BeautifulSoup import urllib.request,urllib.parse,urllib.error from selenium import webdriver import sqlite3 driver=webdriver.Firefox() driver.get('https://www.reddit.com/r/india/') driver.execute_script("window.scrollTo(0,document.body.scrollHeight);") html=driver.execute_script("return document.docu...
import re class LCDData: """ Holds global data for the plugin, as well as some global functions """ def __init__(self, lcd): # type (Adafruit_CharLCD) self.perc2 = unichr(1) self.perc4 = unichr(2) self.perc6 = unichr(3) self.perc8 = unichr(4) self.p...
# https://www.w3resource.com/python-exercises/geopy/python-geopy-nominatim_api-exercise-6.php import geocoder import socket from geopy.geocoders import Nominatim geolocator = Nominatim(user_agent="geoapiExercises") def get_city(host): if host == "127.0.0.1:8000": ip_address = "me" else: ip_add...
#!/usr/bin/env python """ Sensor class for the arudino_python package Created for the Pi Robot Project: http://www.pirobot.org Copyright (c) 2012 Patrick Goebel. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public...
''' Created on 2 Oct 2016 @author: MetalInvest ''' ########################################## Trade param ######################################## stop_loss = dict( stop_loss_conservative = 0.98, stop_loss_aggressive = 0.93, stop_loss_normal = 0.95 ...
import random, time def partition(arr, low, high): i = (low - 1) pivote = arr[high] for j in range(low, high): if arr[j] <= pivote: i = i + 1 arr[i], arr[j] = arr[j], arr[i] arr[i + 1], arr[high] = arr[high], arr[i + 1] return (i + 1) def Qui...
class Activator: def __init__(self): self.is_on = False def on(self): print("Setting {} ON".format(self.__class__.__name__)) self.is_on = True def off(self): print("Setting {} OFF".format(self.__class__.__name__)) self.is_on = False
from django.dispatch import receiver from django.conf import settings from django_rest_passwordreset.signals import reset_password_token_created from sendgrid import SendGridAPIClient from sendgrid.helpers.mail import Mail sg_client = SendGridAPIClient(settings.SENDGRID_API_KEY) @receiver(reset_password_token_create...
#print('\tPrimul meu string pentru \ncurs 2') #\t pune un tab #print('Primul meu string pentru curs 2. ' * 2) #print(2+2*2-2/1) #ridicare putere: ** #a = "String" #a += "String1" #print(type(a)) #concatenare cu format #a = "String1" #b = "String2" #c = "{1} {0} {1}".format(a, b) #c = a + ' ' + b #c =...
import json none = "d3043820717d74d9a17694c176d39733" # region Subscription class Subscription: """ # Arguments resource_id: str protocol: str endpoint: str event_type: str event_format: dict """ def __init__( self, resource_id=none, protocol=none, endpoint=none, event_type=none, event_format=non...
"""Battles Models. This module contains all the classes and methods regarding our battles blueprint models. """ import pickle from copy import deepcopy from marshmallow import (Schema, fields, validates, post_dump, ValidationError) from dino_extinction.infrastructure import redis class BattleSchema(Schema): ""...
def digitsProduct(product): count = 9 res = 1 while res < 10000: count += 1 res = 1 for i in str(count): res = res * int(i) if res == product: break else: return -1 return count product = 450 print(digitsProduct(product)) # = 26
from graph import * brushColor("yellow") circle(250,250,200) brushColor("red") circle(150,210,50) brushColor("red") circle(350,210,40) brushColor("black") circle(150,210,30) brushColor("black") circle(350,210,25) a=[[55,100],[45,110],[190,210],[205,200]] polygon(a) b=[[400,100],[405,110],[300,210],[280,200]] polygon(b...
__author__ = 'schien' from fabric.api import * import os, time, boto import ConfigParser CONFIG_FILE = "ep.cfg" ep_ubuntu_14_04 = "ami-47a23a30" config = ConfigParser.RawConfigParser() # If there is no config file, let's write one. if not os.path.exists(CONFIG_FILE): config.add_section('ec2') config.set('e...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Nov 28 16:24:59 2017 @author: yan Load pre-trained network to segment a new image Code v0.01 """ # %% Resnet blocks in U-net import argparse import datetime import nibabel as nib import numpy as np import os from os import path from scipy import ndi...
#if num=int(input("Enter positive integer: ")) if num>0: print("Hello") print(num) print("Welcome")
class MeasureList: def __init__(self, num_commits, calc_metric_func, name): # LOC # Added LOC / TOTAL # deleted LOC / TOTAL # num times changed? basically 1 or 0? normalized over time? so earlier changes get less weight # newer changes weighted more heavily # given c...
import pytest from faker import Faker from tests.AbstractTest import AbstractTest fake = Faker() class TestCIText(AbstractTest): @classmethod @pytest.fixture(scope='class', autouse=True) def setup_class(cls, Student): super(TestCIText, cls).setup_class() cls.email_upper = fake.email().up...
n = int(input()) s = input().strip() # in a form "3 4 5 6 2" def reverse(s, a, b): if a == b: return s[a] elif a > b: return '' else: left_number = s[a:b+1][:s[a:b+1].index(" ")] right_number = s[a:b+1][s[a:b+1].rindex(" ") + 1:] return right_number + ' ' + reverse(...
import logging from django.contrib.auth.models import (AbstractBaseUser, PermissionsMixin, BaseUserManager) from django.core.mail import send_mail from django.db import models from django.db.models import signals from django.utils import timezone from django.utils.translation im...
# 2. Given a non-empty array of digits representing a non-negative integer, increment one to the integer. # -- The digits are stored such that the most significant digit is at the head of the list, and each element in the array contains a single digit. # -- You may assume the integer does not contain any leadin...
from parse.ast import Node import re from antlr4 import * def graphviz(t, is_root_node, node_text, get_children, relations=[], labels={}, node_key=0): child_key = node_key labels[node_key] = sanitize_graphviz_label(node_text(t)) if is_root_node(t): return node_key, relations, labels for chil...
# Generated by Django 3.1.3 on 2020-11-14 02:45 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('tickets', '0001_initial'...
import filter import matplotlib.pyplot as plt import matplotlib as mpl import numpy as np import os from collections import OrderedDict, defaultdict import seaborn as sns plt.style.use('default') mpl.rcParams['pdf.fonttype'] = 42 mpl.rcParams['ps.fonttype'] = 42 mpl.rcParams['font.size'] = 7 mpl.rcParams['font.family'...
class Solution: def convertToTitle(self, n: int) -> str: ans="" while n: a=chr((n-1)%26+65) ans=a+ans n=(n-1)//26 return ans x=Solution() result=x.convertToTitle(26) print(result)
import cv2 import numpy as np img = cv2.imread("image/wheel.jpg",0) # cv2.imshow("img",img) # kernel = np.array([[0, -1, 0], [-1, 5, -1], [0, -1, 0]], np.float32) # img = cv2.filter2D(img,-1,kernel) # img = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,11,2) cv2.imshow("img1",img) i...