text
stringlengths
38
1.54M
#!/usr/local/bin/python3 # -*- conding: UTF-8 -*- # Filename:primeNum.py # author by : Lexi # 质数判断 # 一个大于1的自然数,除了1和它本身外,不能被其他自然数(质数)整除(2, 3, 5, 7等),换句话说就是该数除了1和它本身以外不再有其他的因数。 while True: try: num = int(input('输入一个整数:')) except ValueError: print("...
#!/usr/bin/env python from setuptools import find_packages, setup setup( name='drongo', version='1.2.0', description='A nano web-framework for python.', author='Sattvik Chakravarthy, Sagar Chakravarthy', author_email='sattvik@gmail.com', classifiers=[ 'Development Status :: 5 - Produc...
#!/usr/bin/env python # # glvector_funcs.py - Functions used by glrgbvector_funcs and # gllinevector_funcs. # # Author: Paul McCarthy <pauldmccarthy@gmail.com> # """This module contains logic for managing vertex and fragment shader programs used for rendering :class:`.GLRGBVector` and :class:`.GLLin...
A, B = map(int, input().split()) sum = A + B print(A, '+', B, '=', sum) """ Вычислить A+B, где A и B целые числа в диапазоне -1017<A,B<1017 Формат входных данных В первой строке входных данных даны два числа A и B –(-1017<A,B<1017) Формат выходных данных Cтрока содержащая сумму двух чисел. """
# 4. Write a Python program to get a single string from two given strings, separated # by a space and swap the first two characters of each string. # Sample String : 'abc', 'xyz' # Expected Result : 'xyc abz' word1 = input("Enter the first string : ") word2 = input ("Enter the second string : ") first = word1.rep...
# -*- coding: utf-8 -*- """ Created on Tue May 29 17:20:30 2018 @author: likkhian """ import numpy as np import tensorflow as tf import os from random import shuffle tf.logging.set_verbosity(tf.logging.INFO) def cnn_model_fn(features,labels,mode): '''model function for cnn''' #input layer input_layer=tf...
from getAngles_cffi import ffi,lib def getAngles(angleX, angleY, hauteur): # forcing variable to be doubles anglex = ffi.cast("double",float(angleX)) angley = ffi.cast("double",float(angleY)) hauteur = ffi.cast("double",float(hauteur)) anglesMoteurs = ffi.new("double[3]") # computing lib.g...
from myPackage import tools as tl from myPackage import preprocess from myPackage import minutiaeExtraction as minExtract from enhancementFP import image_enhance as img_e from os.path import basename, splitext, exists import time from numpy import mean, std import os from imutils import paths import numpy as np from ke...
# -*- coding: UTF-8 -*- # author:yuliang import time from threading import RLock,Thread import serial #龙岗IO class LongGangIO(Thread): def __init__(self,COM): Thread.__init__(self) self.com = COM self.IN_STATUS = {} self.isRunning =False self.serialPortLock=RLock() sel...
from django.http import JsonResponse # Create your views here. def home(request): return JsonResponse({'message': 'Welcome to the E-commerce API'})
list1 = ['Google', 'Runoob', 'Taobao'] list1.insert(1, 'Baidu') print ('列表插入元素后为 : ', list1)
import os if __name__ == '__main__': print('当前进程(%s)启动...'%(os.getpid())) pid = os.fork() if pid < 0 : print('fork 出现错误') elif pid == 0: print('我是子进程(%s),父进程是(%s)'%(os.getpid(),os.getppid())) else: print('我(%s)创建了一个子进程(%s)'%(os.getpid,pid))
#global default = "hey" class color: # # Part one: To be used as : # from pylinux-colors import * # print color.red + "your-text" # default = '\033[39m' black = '\033[30m' red = '\033[31m' green = '\033[32m' yellow = '\033[33m' blue = '\033[34m' magenta = '\033[35m' cyan = '\033[36m' white = '\033[00m' # # ...
import struct, socket # Simple usage Example: WakeUp("AA:AA:AA:AA:AA:AA") def WakeUp(mac_address): addr_byte = mac_address.split(':') hw_addr = struct.pack('BBBBBB', int(addr_byte[0], 16), int(addr_byte[1], 16), int(addr_byte[2], 16), int(addr_byte[3], 16), int(addr_byte[4], 16), int(addr_byte[5], 16)) pay...
# This Python file uses the following encoding: utf-8 # Copyright 2015 Tin Arm Engineering AB # 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 ...
import ADC0832 import space def init(): ADC0832.setup() def loop(): while True: res = ADC0832.getResult() - 80 if res < 0: res = 0 if res > 100: res = 100 print 'res = %d' %res time.sleep(0.2) if __name__ =='__main__': init() try: loop() except KeyboardInterrupt: ADC0832.destroy(...
dict1 = {"a": "1", "b": "b", "c": "c"} dict2 = {"a": "2", "b": "b", "c": "c"} dict3 = {"a": "3", "b": "b", "c": "c"} list = [dict1, dict2, dict3] dada = [dict["b"] for dict in list if dict["a"] == "2"] print(dada)
import time from odoo import models, fields, api, _ from datetime import date,datetime,timedelta from odoo.exceptions import except_orm, Warning, RedirectWarning import math class Fees_Line(models.Model): """ Fees Lines """ _name = 'fees.line' _description = 'Fees Line' name = fields.Many2one(...
# -*- coding: UTF-8 -*- #! /usr/bin/python import csv import sys reload(sys) sys.setdefaultencoding('utf8') import MySQLdb.connector from MySQLdb.connector.constants import ClientFlag from MySQLdb.connector.constants import SQLMode import MySQLdbdb MySQLdb_config = { 'host':'localhost', 'user':'sddivid', ...
from conftest import driver from selenium import webdriver from pages.vacancies_page import VacanciesPage class TestVacation: def test_choose_region(self,driver): needed_region = 'Кубинка' vacancies_main_page = VacanciesPage(driver) vacancies_main_page.go_to_vacancies() vacancies_...
# -*- coding: utf-8 -*- # Copyright 2017-TODAY LasLabs Inc. # License MIT (https://opensource.org/licenses/MIT). from .abstract_product_endpoint import AbstractProductEndpoint from ..models.extract import Extract class Extracts(AbstractProductEndpoint): """This represents the ``Extracts`` Endpoint. https:/...
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # --------------------------------------------------------------------...
# -*- coding: utf-8 -*- { 'name': "GeProMi Documentacion Digital", 'summary': """ La Documentacion Digital será soporte para el Expediente Digital. """, 'description': """ Este archivo tiene la funcion de brindar soporte para el expediente digital. Se destacan las ...
# Generated by Django 2.0.5 on 2018-09-04 07:59 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Diagram', fields=[ ...
from django import forms from . import models class createform(forms.ModelForm): class Meta: model = models.STATE fields = ('title', 'slug', 'body', 'image')
# Copyright 2018 Google LLC # # 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 writing, softw...
#!/usr/bin/env python3 """Shuffle data in two matrices in the same way""" import numpy as np def shuffle_data(X, Y): """Shuffle data in two matrices in the same way""" shufflidx = np.random.permutation(X.shape[0]) return X[shufflidx], Y[shufflidx]
from neuron import * from neuron import h as nrn from numpy import * from pylab import * soma = h.Section() soma.L = 25 soma.insert('hh') soma.nseg = 10 soma1 = h.Section() soma1.L = 25 soma1.insert('hh') soma1.nseg = 10 stimNc = h.NetStim() stimNc.noise = 1 stimNc.start = 5 stimNc.number = 1 stimNc.interval = ...
from staff.models import Staff, Employee, Driver from utils.models import TypeDocument from django.shortcuts import render_to_response, render from django.template import RequestContext from django.contrib.auth.decorators import login_required from django.conf import settings from django.core.paginator import Paginato...
import main import unittest class ComposeTest(unittest.TestCase): def testing(self): self.assertEqual(main.compose("byGt\nhTts\nRTFF\nCnnI", "jIRl\nViBu\nrWOb\nNkTB"), "bNkTB\nhTrWO\nRTFVi\nCnnIj") self.assertEqual(main.compose("HXxA\nTGBf\nIPhg\nuUMD", "Hcbj\nqteH\nGbMJ\ngYPW"), ...
class MyClass: variable = "blah" def foo(self): print('Hello from MyClass') myObjX = MyClass() myObjY = MyClass() myObjY.variable = "Giggity goo" print(myObjX.variable) print(myObjY.variable)
import pytest import logging import yaml from asgi_lifespan import LifespanManager from httpx import AsyncClient from app.main import app from app import messages from tests import test_constants config = yaml.safe_load(open("config.yml")) logger = logging.getLogger(__name__) def pytest_generate_tests(metafunc): ...
while True: pass # Busy-wait for keyboard interrupt (Ctrl+C) class MyEmptyClass: pass def initlog(*args): pass # Remember to implement this!
__author__ = 'k22li' ) import re import os #print callable(getattr(str, 'split')) # test functions of filter & map pat = re.compile('st$') availableChoice = ['a', 'b', 'c', 'test'] print filter(pat.search, availableChoice) testFunc = lambda x : os.path.splitext(x)[0] print map(testFunc, ['a', 'a.b', 'a.b.c', 'tes...
# include <stdio.h> # include <conio.h> # define rafik main void rafik() { clrscr(); printf("Main function is not used here"); getch(); }
import colors as col import random # Source for algorithms: Kooi B. 'Yet another mastermind strategy', https://www.rug.nl/research/portal/files/9871441/icgamaster.pdf used on and before 19-02-2020 def evaluateColors(guessedColors: list,secretCode) -> dict: tempColors = secretCode[:] tempGuessedColors = guessed...
import csv import requests import pandas as pd from zipfile import ZipFile from io import StringIO URL = 'https://www.quandl.com/api/v3/databases/%(dataset)s/codes' def dataset_url(dataset): return URL % {'dataset': dataset} def download_file(url): r = requests.get(url) if r.status_code == 200: ...
# -*- coding: UTF-8 -*- # Copyright 2013-2016 by Luc Saffre. # License: BSD, see LICENSE for more details. """A library for `fabric <http://docs.fabfile.org>`__ with tasks I use to manage my Python projects. NOTE: This module is deprecated. Use :mod:`atelier.invlib` instead. .. contents:: :local: .. _fab_commands...
# Oppgave 6) #Lag et program som får brukeren til å skrive inn 2 navn med 2 tilhørende bursdager. #La så brukeren søke på navnet og tilhørende bursdag skrives ut. navn = "" #Lager variabelen navn som en tom string/"" index = 0 #Lager variabelen index som har verdien 0 liste = {} #Lager en ordbok som er lagret i variab...
def valid(s): s = s.lower() s = s.strip().split(' ') s = "".join(char for char in s if char.isalnum()) return s == s[::-1] print(valid("Race car")) print(valid("fat")) print(valid(":racecar"))
import numpy as np import pandas as pd from scipy.io.arff import loadarff # functions to prep dataset import sklearn.datasets as skdata from sklearn.datasets import fetch_openml from sklearn.model_selection import train_test_split from sklearn.experimental import enable_iterative_imputer from sklearn.impute import Simp...
import random p = random.randint(1, 6) print(p) # para saber o n correto antes r = int(input('N: ')) while not(r == p): print ('incorreto' if not(r == p) else 'correto') r = int(input('N: '))
class Hashtable: def __init__(self, lst=None): if lst: self._hashtable = self.hashing(lst) @classmethod def hashing(cls, lst): """" group's number count watched elements the group / / 20000: [{22341: True, ...}, ...
#!/usr/bin/env python #_*_coding:utf-8_*_ #作者:Paul哥 import urllib2,cookielib,random,urllib,json,time,re,datetime import LoginAccount,TrainNumQuery,BookingSeat from PIL import Image from PIL import ImageFont from PIL import ImageDraw import ssl,sys ssl._create_default_https_context = ssl._create_unverified_context reloa...
#!/usr/bin/env python """ wrapper for JSLint using Spidermonkey engine TODO: * support for JSLint options """ import os from subprocess import Popen, PIPE try: from json import loads as json except ImportError: from simplejson import loads as json try: from pkg_resources import resource_filename except ImportE...
from django.urls import path from . import views urlpatterns = [ path('', views.products_view, name="products"), path('create_product/', views.product_create_view, name='create_product'), path('create_categorie/', views.categorie_create_view, name='create_categorie'), ]
import time from selenium import webdriver validateText = "Haroon" driver = webdriver.Chrome(executable_path="C:\\Users\\Haroon\\Downloads\\chromedriver.exe") driver.get("https://rahulshettyacademy.com/AutomationPractice/") driver.maximize_window() checkboxes = driver.find_elements_by_xpath("//input[@type='checkbox'...
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'Bob' import os,sys,platform if platform.system() == 'Windows': BASE_DIR = '\\'.join(os.path.abspath(os.path.dirname(__file__)).split('\\')[:-1]) else: BASE_DIR = '/'.join(os.path.realpath(__file__).split('/')[:-2]) sys.path.append(BASE_DIR)...
class UserModel(Tower): @model_property def inference(self): # Create some wrappers for simplicity def conv2d(x, W, b, s, name, padding='SAME'): # Conv2D wrapper, with bias and relu activation x = tf.nn.conv2d(x, W, strides=[1, s, s, 1], padding=padding, name=name + '_c...
from dazer_methods import Dazer from collections import OrderedDict from numpy import empty, random, median, percentile, array, linspace, zeros, std from scipy import stats from uncertainties impor...
#!/usr/bin/env python import pprint import sys import yaml def get_yaml(file_name=None): """Basic function that returns a Python data structure from a YAML file. Parameters: File name of YAML file """ if file_name is None: raise ValueError("No YAML file passed to function!") try: ...
from unittest import mock import pytest from antareslauncher.data_repo.idata_repo import IDataRepo from antareslauncher.remote_environnement.remote_environment_with_slurm import ( RemoteEnvironmentWithSlurm, ) from antareslauncher.remote_environnement.slurm_script_features import ( SlurmScriptFeatures, ) from...
from components import time from tests import base import unittest class TestTime(base.TestBase): def setUp(self): super().setUp() self.time = time.Time(self.cfg['TIME']) def test_config(self): self.assertEqual(self.cfg['TIME']['format'], '%a %d/%m %R') def test_time(self): ...
# -*- coding: utf-8 -*- """ Created on Tue May 16 17:37:45 2017 @author: Anuj """ import numpy as np def gauss_seidel(phi, phi_bdry, source, epsit, max_iters, omega, coeff, coeff_p, resid): nx = phi.shape[1] ny = phi.shape[0] iter_count = 0 iter_update = 10 * epsi...
import math import logging import numpy as np from statsmodels.tsa.seasonal import seasonal_decompose def generate_linear_series_from_model(time_series_len, model): res = list() predict = np.poly1d(model) for i in range(time_series_len): res.append(predict(i)) return res def generate_arma_ser...
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class AlipayMerchantWeikeBilltaxModifyModel(object): def __init__(self): self._actual_tax = None self._alipay_trans_serial_no = None self._bill_month = None self._bill_n...
import time import json import random import requests tournament_dict = { "identifier": "4nidzmunvpvxk1ir9b6m8mpay", "tournamentName": "Ukrainian Football League", "location": "Ukraine", "stadium": "Dynamo", "league": "Ukrainian Football", "startDate": "2016-07-11 19:00:00 GMT-0000", "sportName": "footb...
# Generated by Django 2.0 on 2018-12-03 15:15 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('home', '0005_remove_expenses_test'), ] operations = [ migrations.AlterField(...
#!/usr/bin/env python #-*-coding:utf-8-*- US=[4,1,5,3,6,9,2,8] def heap_sort(lst): for start in range((len(lst)-2)/2,-1,-1): sift_down(lst,start,len(lst)-1) print lst for end in range(len(lst)-1,0,-1): lst[0],lst[end] = lst[end],lst[0] sift_down(lst,0,end-1) print lst def sift...
#!usr/bin/env python3.6 """Write a file of trees without extremely low branch lengths. The idea is that these are the trees that orthofinder estimated incorrectly. """ import re import sys import my_module as mod def get_args(): """Get user arguments.""" if len(sys.argv) == 4: return sys.argv[1:] ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from neodroid.environments.droid_environment import SingleUnityEnvironment from neodroid.utilities.exceptions.exceptions import SensorNotAvailableException from neodroid.utilities.snapshot_extraction.camera_extraction import ( extract_camera_observation, extract_fr...
#!/usr/bin/env python import numpy as np from scipy.linalg import expm from lab3_header import * """ Use 'expm' for matrix exponential. Angles are in radian, distance are in meters. """ def Get_MS(): # =================== Your code starts here ====================# # Fill in the correct values for S1~6, as well as ...
import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import streamlit as st # @st.cache class plot: # @st.cache(suppress_st_warning=False) def Count_Record(self,data): sns.set(font_scale=1.5) st.header("Overview of dataset.") st.write(data.head(10)) fig, ax...
import matplotlib.pyplot as plt from math import sqrt from typing import Tuple, List import numpy def load_data() -> Tuple[List[int], List[int], List[float]]: """Carrega o arquivo data2.txt e prepara os dados para serem utilizados. Returns: Dados definindo o tamanho da casa o número de quartos e o preço da...
#MenuTitle: Delete guidelines # -*- coding: utf-8 -*- __doc__=""" Delete all local guidelines in selected glyphs. """ import GlyphsApp selectedLayers = Glyphs.font.selectedLayers def process( thisLayer ): thisLayer.guideLines = [] for thisLayer in selectedLayers: thisGlyph = thisLayer.parent print "Deleting guid...
from random import * import eval def generate_quiz(): # Hint: Return [x, y, op, result] x = randint(1,10) y = randint(1,10) a_list = ["+", "-", "*", "/"] op = choice(a_list) res = eval.cal(x, y, op) error = [-1, 0, 0, 1] ran_er = choice(error) result = res + ran_er return [x,...
import os from django.contrib.gis.utils import LayerMapping from . models import CadastralCommunity, cadastralcommunity_mapping cc_shps = os.path.abspath( os.path.join( os.path.dirname(__file__), 'data', 'iad', 'AT.shp') ) def import_shapes(verbose=True): lm = LayerMapping( CadastralCommunity...
from django.contrib import admin from commanderie.models import Bureau, Chevalier, Commanderie # Register your models here. admin.site.register(Commanderie) admin.site.register(Chevalier) admin.site.register(Bureau)
#!/usr/bin/python3 # tests evaluation of expressions in ranges x = 5 for i in range((x//2)+1,x*2): print(i)
perg = 'S' cont = soma = media = 0 while perg == 'S': num = int(input('Digite um número: ')) perg = str(input('Deseja continuar? [S/N]: ')).upper().strip() soma += num cont += 1 if cont == 1: maior = menor = num else: if num > maior: maior = num if num < menor...
import os from urllib.parse import urlparse import pytest import factory from demo_app import factories, models from tests.utils import init_postgresql_database, drop_postgresql_database class AppConfigTest(factories.AppConfig): DEBUG = False TESTING = True SQLALCHEMY_DATABASE_URI = os.environ.get('DB_...
#Going to use Flask, going to upload through heroku # Text is done through HTML, # Embedding is done through Trinket.io # Bootstrap 4 should make it look nice #To activate virtual env, type virtual/Scripts/activate # # https://virtual-tic-tac-toe.herokuapp.com/ | https://git.heroku.com/virtual-tic-tac-toe.git # # To ...
from functools import partial import logging import os from kaon.parsers import KaonLECParser from pion.parsing.lec import PionLECParser from su2.models import PionLECSU2, KaonLECSU2 log = logging.getLogger(__name__) def parse_pion_lecs_from_folder(folder): all_data = PionLECParser().get_from_folder(folder) ...
#!/usr/bin/env python3 import collections import json import os from urllib import parse from flask import (Flask, render_template, request) import redis url = parse.urlparse(os.environ.get('REDISCLOUD_URL', "redis://localhost:6379/0")) db = redis.Redis(host=url.hostname, port=...
from flask import Flask, render_template, request, redirect, url_for, flash from config import app from model import Contacts, db @app.route('/') @app.route('/index.html') def index(): return render_template("index.html") @app.route('/about_me.html') def about_me(): return render_template("about_me.html") @a...
#!/usr/bin/env python from sys import argv from parsers import parse_fasta, LongFastaID from writers import write_fasta if __name__ == "__main__": fasta = argv[1] out_file = argv[2] fasta_dict = parse_fasta(fasta) prot_id_to_seq = {} for fasta_id, sequence in fasta_dict.items(): fasta_id...
import json import Queue import settings import time import threading import yaml import commands import serial import sys import spidev import RPi.GPIO as GPIO #from thirtybirds.Logs.main import Exception_Collector from thirtybirds.Network.manager import init as network_init def network_status_handler(msg): prin...
#!/usr/bin/python3 # -*- coding: utf-8 -*- import numpy as np import sympy as sp import matplotlib.pyplot as plt from collections import Counter from prettytable import PrettyTable def create_sample(n, a, b): X = [] Y = [] Xi = np.random.uniform(0, 1, n) for i in range(n): X.append(round(Xi[i...
import pymongo def mongo_connect(): try: connection = pymongo.MongoClient() print "MongoDB is connected!" return connection except pymongo.errors.ConnectionFailure, e: print "Could not connect to MongoDB: %s" % e connection = mongo_connect() db = connection['twitter_stream'] co...
#!/usr/bin/python3 """Lockboxes. Given a box full of boxes full of keys to open other boxes, determine if all boxes can be opened. """ def canUnlockAll(boxes): """canUnlockAll. Determine if all boxes inside boxes can be opened. Arguments: -- boxes: A box full of boxes, which may contain keys. ...
# Write a class to hold player information, e.g. what room they are in # currently. class Player: def __init__(self,name,location,items=[]): self.name=name self.location=location self.items=items def change_location(self,direction): if direction =='w': self.locatio...
"""Run an example script to quickly test any SimpliSafe system.""" # pylint: disable=protected-access import asyncio from aiohttp import ClientSession from pikrellcam_python import PiKrellCam from aiohttp.client_exceptions import ClientError, ClientResponseError async def exercise_client( host: str, port: ...
import base64 import json import os from datetime import datetime import babel import numpy as np import pandas as pd import pytz from dateutil.relativedelta import relativedelta from odoo import api, fields, models, tools, _ from odoo.exceptions import ValidationError, UserError from odoo.tools import config from sta...
import boto3 import hashlib import moto import os.path import qarnot from pathlib import Path from qarnot.bucket import Bucket from unittest import TestCase from unittest.mock import patch, Mock def mock_connection_base(mock_s3buckets=None): mock_connection = Mock({'other.side_effect': KeyError}) mock_conne...
import operator ttL = [ ('토마스', 5), ('헨리', 8), ('에드워드', 9), ('토마스', 12), ('에드워드',1)] tD = {} tL = [] tR, cR = 1,1 for tmpTup in ttL: tName = tmpTup[0] tWeight = tmpTup[1] if tName in tD: tD[tName] += tWeight else: tD[tName] = tWeight print(list(tD.items())) tL = sorted(tD.items(), k...
from rest_framework.routers import DefaultRouter from . import views router = DefaultRouter() router.register(r'tags', views.SkillTagsViewSet, basename='tags') router.register(r'skills', views.SkillViewSet, basename='skills') router.register(r'projects', views.ProjectViewSet, basename='projects') router.register(r'wo...
""" Inorder Traversal of a tree """ class Node: def __init__(self, val): self.data = val self.left = None self.right = None def printInorder(root): if root: printInorder(root.left) print(root.data, end = " ") printInorder(root.right) r...
#!/usr/bin/env python # -*- coding: utf-8 -*- def search_a_2d_matrix_ii(matrix, target): """ 给定一个m*n的矩阵,请在该矩阵中找到一个目标数值,请注意,该矩阵有如下特性: 1.每行中的整数从左到右是依次增大的 2.每列中的整数从上到下是依次增大的 :param matrix: List[List[int]] :param target: int :return: bool """ if not matrix: return False row...
from distutils.core import setup from distutils.extension import Extension import sys import numpy #Determine whether to use Cython if '--cythonize' in sys.argv: cythonize_switch = True del sys.argv[sys.argv.index('--cythonize')] else: cythonize_switch = False #Find all includes numpy_include = numpy.get_...
''' Convert image to grayscale ''' import tensorflow as tf import matplotlib.image as mpimg import matplotlib.pyplot as plt filename = "../lesson3/MarshOrchid.jpg" raw_image_data = mpimg.imread(filename) image = tf.placeholder(tf.int32, [None, None, 3]) # Reduce axis 2 by mean (= color) # i.e. image = [[[r,g,b], ......
from typing import Generic, TypeVar, Callable T = TypeVar("T") class JSONStorageItem(Generic[T]): def __init__(self, _key: str, _default: Callable[[], T], /): ... def get(self) -> T: ... def set(self, value: T) -> None: ... def invalidate_cache(self) -> None: ...
import torch import numpy as np class MyQuantize(torch.autograd.Function): @staticmethod def forward(ctx, inputs,args): ctx.args = args x_lim_abs = args.enc_value_limit x_lim_range = 2.0 * x_lim_abs x_input_norm = torch.clamp(inputs, -x_lim_abs, x_lim_abs) if args.qu...
from django.contrib import messages from django.contrib.auth import get_user_model from django.contrib.auth.decorators import login_required from django.db.models import Q from django.shortcuts import render, redirect, get_object_or_404 from feed.models import Post from .forms import UserRegisterForm, ProfileUpdateFor...
print('{} DESAFIO 9 {}'.format('='*10, '='*10)) n = int(input('Digite um número: ')) print('\n\033[31mTABUADA DO {}\033[m'.format(n)) print('{} X {:2} = {:2}'.format(n, 0, n * 0)) print('{} X {:2} = {:2}'.format(n, 1, n * 1)) print('{} X {:2} = {:2}'.format(n, 2, n * 2)) print('{} X {:2} = {:2}'.format(n, 3, n * 3)) pr...
__author__ = 'mike' import numpy as np import matplotlib.pyplot as plt def scatter_xy(ax, m_obj, x_dtype, y_dtype, x_component, y_component, **plt_opt): pass def generate_plots(n=3, xsize=5., ysize=5., tight_layout=False): """ Generates a number of subplots that are organized i a way to fit on a landscape...
from lib.message.base_message import base_message from lib.util.error import DiscordError from lib.util.parameter import parameter class list_tags(base_message): length = { 'min': 0, 'max': 0 } def run(self, client): self.assert_length() p = parameter.getInstance() ...
class Workset(WorksetPreview,IDisposable): """ Represents a workset in the document. """ @staticmethod def Create(document,name): """ Create(document: Document,name: str) -> Workset Creates a new workset. document: The document in which the new instance is created. name: The wo...
from django.shortcuts import render from .models import SiteLoc, User from math import ceil from django.core.mail import send_mail # Create your views here. from django.http import HttpResponse def index(request): # products = Site.objects.all() # print(products) # n = len(products) # nSlides = n//4 ...
import dna import unittest class Test(unittest.TestCase): def test_dna(self): d = 'AGCTTTTCATTCTGACTGCAACGGGCAATATGTCTCTGTGTGGATTAAAAAAAGAGTGTCTGATAGCAGC' actual = dna.count_nucleotides(d) self.assertEqual([20, 12, 17, 21], actual) if __name__ == "__main__": unittest.main()
from util import * from copy import deepcopy class Instance: def __init__(self, coord, datum): self.coord = coord self.datum = datum self.unknown = False def Coord(self): return [self.coord.x, self.coord.y, self.klass()] def klass(self): return self.datum[-1] class InstanceCollection: ...