text
stringlengths
38
1.54M
from settings.models import system_settings from settings.models import system_settings from nginx.views import * from functools import reduce import iptc def ip_into_int(ip): return reduce(lambda x,y:(x<<8)+y,map(int,ip.split('.'))) def is_internal_ip(ip): ip = ip_into_int(ip) net_a = ip_into_int('10.2...
from prime import Prime def ans(): circular_primes = set([2]) for p in Prime.gen_nums(1000000): if any(x in str(p) for x in '02468'): continue is_circular = True for i in range(len(str(p))): if not Prime.contains(int(str(p)[i:] + str(p)[:i])): is...
try: from lapjv import lapjv # from scipy.optimize import linear_sum_assignment segment = False except ImportError: print('Module lap not found, emulating with much slower scipy.optimize.linear_sum_assignment') segment = True from scipy.optimize import linear_sum_assignment import random import...
# Copyright 2019 Google Inc. 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 a...
# Deep-Learning:Training via BP+Pseudo-inverse import pandas as pd import numpy as np import my_utility as ut # Softmax's training def train_softmax(x,y,param): w=ut.iniW(y.shape[0],x.shape[0]) costo=[] for i in range(param[0]): G=ut.softmax_grad(x,y,w,param[2]) gradW=G[0] ...
import numpy as np import pandas as pd import pylab as plt from studyResults import customaxis, ratio # These are the "Tableau 20" colors as RGB. cols = [(3,43,122),(31,119,180),(174,199,232),(255,186,120),(177,3,24),(31, 119, 180), (174, 199, 232), (255, 127, 14), (255, 187, 120), (44, 160, 44),...
from sys import stdin def main(): adapters = [int(line) for line in stdin] adapters.sort() nums = [0] + adapters + [adapters[-1] + 3] diffs = [nums[i] - nums[i - 1] for i in range(1, len(nums))] print(diffs.count(1) * diffs.count(3)) if __name__ == "__main__": main()
## # Nathália Harumi Kuromiya - RA 175188 # Assignment 1 # # This file is responsible for executing the problem to get statistics and # compare searchers. ## from modeling import * p1 = robot((10, 10), (50, 50)) p2 = robot((50, 50), (10, 10)) p3 = robot((10, 50), (50, 10)) p4 = robot((50, 10), (10, 50)) p5 = robot((1...
from python.util import reverseComplement class Node: def __init__(self, value): self.value = value self.path = None self.edges = set() def __add__(self, other): self.edges.add(other) return self def __str__(self): return self.value de...
import sys import T21 import T50 import queue import threading class TIS_100: def __init__(self): # Nodes self.nodes={} # Clock tick self.tick=threading.Condition() def add_T21_node(self, name, code): '''Add a computation node named name, with code.''' new_node=T21.T21() new_node.name=name new_n...
from wardmetrics.core_methods import eval_events, eval_segments from wardmetrics.utils import * from wardmetrics.visualisations import * from metric.MyMetric import testMyMetric ground_truth_test = [ (40, 60), (70, 75), (90, 100), (125, 135), (150, 157), (187, 220), ] detection_test = [ (...
#!/usr/bin/python3 import configparser import pprint import sys from pymongo import MongoClient config = configparser.ConfigParser() config.read('mongoConf.ini') src = config['PRIME'] dst = config['SECONDARY'] def check_db(client, db): if not db in client.list_database_names(): sys.exit("On host: '{}'...
# Generated by Django 2.2.4 on 2019-10-22 06:16 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('androidApis', '0002_remove_transactions_car'), ] operations = [ migrations.RenameField( model_name='customer', old_n...
# Este codigo é referente ao exercicio 5 # Criado em: 09/12/2019 # Criadora: Caroline Salgado Alves # Versão: 1.0 medida = float(input("Digite uma medida em cm: ")) nova = medida/100 print("A nova medida em metros é: ", nova)
#!/usr/bin/python ''' File: arguments.py Author: Matt Welch Description: implified functionality for getting arguments (Matlab style) and selecting files ''' import sys import os # file select dialog DEBUG_MODE = False def getArgs(): # gets command line arguments & count Matlab style nargin = len...
import falcon import scrypt from base64 import b64decode from os import urandom from kartotek.config import config from kartotek.db import Database _db = Database() def new_password(password): salt = urandom(256) full_salt = salt + config['password_secret'].encode('utf-8') return (salt, scrypt.hash(pa...
import cdat_info import cdms2 import ESMP import numpy import unittest import sys class TestGridTypes(unittest.TestCase): """ All test interpolate to the same grid or to curvilinear grid """ def setUp(self): pass def test_test1(self): """ 2D gsRegrid """ u ...
import matplotlib.pyplot as plt import sys def process(fileName): # read in data from file history = [] f = open(fileName) i = 0 curGen = [] for line in f: data = map(float, line.split()) curGen.append(data) i += 1 if i == 100: history.append(curGen) ...
#!/usr/bin/env python3 # Created by:Euel Yirga # Created on:October 2019 # This makes sound on the pybadge SCREEN_X = 160 SCREEN_Y = 120 SCREEN_GRID_Y = 16 SCREEN_GRID_X = 8 SPRITE_SIZE = 16 FPS = 60 SPRITE_MOVEMENT_SPEED = 1 # using for button state button_state = { "button_up": "up", "button_just_pressed": "just ...
import json import re from datetime import datetime from http import HTTPStatus from urllib.request import urlopen from django.http import JsonResponse from django.shortcuts import get_object_or_404 from config.settings.utils import get_env_var from grid.models import Grid from menu.models import Menu def get_dong...
from PIL import Image import numpy as np from scipy.ndimage import filters from matplotlib.pylab import * #Sobel滤波器 im=np.array(Image.open('C:\\Users\\T\\Downloads\\5.jpg').convert('L')) #计算x方向的导数 imx=np.zeros(im.shape) filters.sobel(im,1,imx) #计算y方向的导数 imy=np.zeros(im.shape) filters.sobel(im,0,imy) #计算图像的梯度 magnitude...
# -*- coding: utf-8 -*- # Generated by Django 1.9.11 on 2017-05-23 08:37 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('application', '0001_initial'), ] operations = [ migrations.RenameField( ...
import media import fresh_tomatoes # construct six movie objects titanic = media.Movie( "Titanic", "The World's Most Beloved and Acclaimed Film", "https://upload.wikimedia.org/wikipedia/en/2/22/Titanic_poster.jpg", "https://www.youtube.com/watch?v=2e-eXJ6HgkQ") harry_potter = media.Movie( ...
"""create stakeholders Revision ID: 9ccd4437c1e5 Revises: Create Date: 2020-04-29 18:23:46.443633 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = "9ccd4437c1e5" down_revision = None branch_labels = None depends_on = None def upgrade(): # ### commands aut...
#-*- coding: utf-8 -*- import sqlite3 import sys import re import mechanize import urllib2 import cookielib from bs4 import BeautifulSoup import telepot # telepot 로 텔레그램 메시지 준비 YOUR_ACCESS_TOKEN = "" bot = telepot.Bot(YOUR_ACCESS_TOKEN) #print bot.getMe()["username"] #print bot.getMe()["first_name"] #bot.sendMessa...
# -*- encoding = utf8 -*- from pyglet.gl import * class Viewer: def __init__(self, width=400, height=400): self.window = pyglet.window.Window(width=width, height=height) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) def render(self, geome...
# -*- coding: utf-8 -*- import random import re import os import requests import sys import lxml import time from logger import logger from bs4 import BeautifulSoup from generateExcel import generateExcel from agentAndProxies import hds from agentAndProxies import GetIpProxy from model.elementConstant import elementCo...
from datetime import datetime, timedelta from earnmi.data.MarketImpl import Market2Impl from earnmi.uitl.utils import utils from vnpy.trader.object import BarData def is_same_day(d1: datetime, d2: datetime) -> bool: return d1.day == d2.day and d1.month == d2.month and d1.year == d2.year def isPostMinitu...
import json import os import pathlib import urllib.request import pytest from sunpy.tests import hash hashfile = 'https://raw.githubusercontent.com/sunpy/sunpy/master/sunpy/tests/figure_hashes_py36.json' hashfile = urllib.request.urlopen(hashfile) hashes = json.load(hashfile) figpath = pathlib.Path(os.path.abspat...
import collections import string class Solution(object): def ladderLength(self, start, end, arr): arr = set(arr) # avoid TLE q = collections.deque([(start, 1)]) visted = set() alpha = string.ascii_lowercase # 'abcd...z' while q: word, length = q.popleft() ...
# Homework 5 # For this homework, we will be doing some bug fixing. # In this program, there will be many bugs and I will be providing some hints # for you. # IMPORTANT: the bugs will be labeled on the line above with a FIXME comment # Do your best! ########### Section 1: printing some stuff # this print line is fin...
#!/usr/bin/python3 import pynn.array as array from pynn.element import Element class Mixer(Element): class _Context(Element._Context): def __init__(self, size, accum, node): Element._Context.__init__(self, node) self.accum = accum def newContext(self, factory): return self._Context(self.size, factory.em...
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import with_statement # This isn't required in Python 2.6 import os import subprocess import sys import hashlib import re from copy import deepcopy import xml.etree.cElementTree as xml def getText(nodelist): """Get text from an XML node""" rc = []...
from setuptools import setup, find_packages version = '0.9dev' setup(name='git-svn-helpers', version=version, description="Command-line tools to make git-svn simple", long_description = ( open('README.rst').read() + '\n' + 'Change history\n' '**************\n' + '\...
import pygame class ActiveInfoArea(object): def __init__(self, info_area_type, resource_manager): self._frame = -1 self._active = True self._text = ActiveInfoArea._get_text_from_type(info_area_type) font_white = resource_manager.get('font_white') self._text_size = len(self....
from __future__ import absolute_import, unicode_literals import time from celery import shared_task MIN = 60 @shared_task(priority=0) def task_01(): print("TASK 01 (priority=0) - Started") time.sleep(30) print("TASK 01 (priority=0) - Finished") @shared_task(priority=5) def task_02(): print("TASK 02...
''' import tensorflow as tf from numpy.random import RandomState data_size = 128 batch_size = 8 loss_more = 1 loss_less = 10 STEP = 5000 x = tf.placeholder(tf.float32, shape = (None, 2), name = 'input-x') y_ = tf.placeholder(tf.float32, shape = (None, 1), name = 'input-y') w1 = tf.Variable(tf.random_normal([2, 1], ...
from django.conf.urls import url,include from . import views from rest_framework import routers from django.conf.urls.static import static from django.conf import settings router = routers.DefaultRouter() router.register('users',views.UserViewSet) router.register('posts',views.PostViewSet) router.register('profile',vi...
import tensorflow as tf import numpy as np import matplotlib.pyplot as plt plt.switch_backend('agg') from emoji_cnn import EmojiCNN K = 5 with tf.Session() as sess: model = EmojiCNN(sess, data=str(K), batch_size=100, name='baseline', embedding=50, kernel_widths=[3,4,57], kernel_filters=[64...
from django.db import models # Create your models here. class DebitCard(models.Model): Card_ID = models.AutoField(primary_key=True) Card_Number = models.fields.CharField(max_length=20, unique=True) First_Name = models.fields.CharField(max_length=30) Last_Name = models.fields.CharField(max_length=30) ...
''' You have n bags numbered from 0 to n - 1. You are given two 0-indexed integer arrays capacity and rocks. The ith bag can hold a maximum of capacity[i] rocks and currently contains rocks[i] rocks. You are also given an integer additionalRocks, the number of additional rocks you can place in any of the bags. Retu...
# Generated by Django 3.1.1 on 2020-09-15 09:12 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('catalog', '0001_initial'), ] operations = [ migrations.AddField( model_name='camera', name='carcass', fi...
import random import items import money class Outcome(object): def __init__(self, state, msg, add_item=False, # USAGE: items.item_name remove_item=False, # USAGE: items.item_name remove_all_items=False, clove...
#!/bin/python3 import math import os import random import re import sys # Complete the powerSum function below. def powerSum(X, N, num=1): if pow(num, N) < X: return powerSum(X, N, num+1) + powerSum(X-pow(num, N), N, num+1) elif pow(num, N) == X: return 1 else: return 0 if __name...
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from rasa_sdk import Action from rasa_sdk.events import SlotSet class MyCustomAction(Action): def name(self): return "my_custom_action" def run(self, di...
import torch from latent_rationale.snli.util import get_z_counts, get_n_correct def evaluate(model, criterion, data_iter): model.eval() n_eval_correct, n_eval_total, eval_loss = 0, 0, 0 # kuma statistics p2h_0, p2h_c, p2h_1 = 0, 0, 0 h2p_0, h2p_c, h2p_1 = 0, 0, 0 with torch.no_grad(): ...
# Generated by Django 3.0.4 on 2020-04-24 11:34 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('user', '0002_auto_20200415_1340'), ] operations = [ migrations.AlterField( model_name='profile'...
from critical_projects import INCLUDED_PLATFORMS if __name__ == "__main__": for platform in INCLUDED_PLATFORMS: print(f"CREATE INDEX FOR (n:{platform}) ON (n.Name);")
#!/usr/bin/env python3 """how to calculate a shape of matrix""" def matrix_shape(matrix): """shape of matrix""" x = [len(matrix)] while isinstance(matrix[0], list): x.append(len(matrix[0])) matrix = matrix[0] return x
# U05_EX15_ExamScores_BarChart.py # # Author: Will Baschab # Course: Coding for OOP # Section: A2 # Date: 19 Dec 2018 # IDE: PyCharm # # Assignment Info # Exercise: 15 # Source: Python Programming # Chapter: 05 # # Program Description # This program will take a text file as input with the number of s...
import threading import time import unittest from os import path import apps import core.config.config import core.controller from core.case.callbacks import WorkflowExecutionStart, WorkflowPaused, WorkflowResumed from core.helpers import import_all_filters, import_all_flags from tests import config from tests.util.ca...
""" Welcome to the GTK+3 GUI interface for the Tadman package manager! I'm really proud with how this is all turning out. But for the time being, this interface will not be updated until some interest is shown in having one. NOTE: This does NOT work with the current version of Tadman. It is here for historical and fut...
import cadquery as cq # 1. Establishes a workplane that an object can be built on. # 1a. Uses the named plane orientation "front" to define the workplane, meaning # that the positive Z direction is "up", and the negative Z direction # is "down". # 2. Creates a 3D box that will have geometry based off it late...
import json import scrapy class KanmaincSpider(scrapy.Spider): name = 'kanmainc' start_urls = ['https://kanmainc.com/collections/all'] def parse(self, response): """This function should extract and loop item urls. @url https://kanmainc.com/collections/all @returns items 0 ...
# prac20 import matplotlib.pyplot as plt import networkx as nx def graf(): input2 = open("./graph_input2-4.txt","r") list2 = input2.readlines() G = {} for i in range(len(list2)): list2[i] = list2[i].rstrip() a, b = list2[i].split() if a not in G: G[a] = {b} el...
class subnet: def __init__(self, ec2_service): self.ec2_service = ec2_service self.sub_name ='' self.sub_id = '' self.sub_vpc = '' self.sub_cidr = '' self.route_table_id = '' self.route_name = '' self.route_table = '' # subnet_id is list type ...
import unittest import time import datetime import os from ddt import ddt, file_data, data, unpack from selenium import webdriver from pages.csadmin_page import Csadmin_Page from selenium.webdriver.common.action_chains import ActionChains from poium import Page, PageElement, PageSelect from testdata.read_excel...
import AutoEncoder import sys import os from os import listdir import theano import numpy as np from os.path import isfile, join import cv2 from utils import tile_raster_images import pickle import random import time from ConvImage import Conv def getFiles(dir_path): """getFiles : gets the file in specified directory...
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not...
import numpy as np import matplotlib.pyplot as plt import os def plotCumulativeReward(train_episodes, training_rewards,path): x = range(train_episodes) plt.plot(x, training_rewards) plt.xlabel('Episode') plt.ylabel('Training total reward') plt.title('Total rewards over all episodes in tr...
# -*- coding: utf-8 -*- import sys import math import urllib import os from lxml import etree import requests import json from bs4 import BeautifulSoup import xlsxwriter def read_html(url): try: file1 = urllib.request.urlopen(url, timeout=5) data = file1.read() return data except: ...
#!/usr/bin/python ########################################################### # # This python script is used for mysql database backup # using mysqldump and tar utility. # # Written by : MmrDev # Tested with : Python 2.7.15 & Python 3.5 # ########################################################## import os import ...
from django.core.management.base import BaseCommand from openhumans.models import OpenHumansMember from main.models import DataSourceMember from django.conf import settings from datauploader.tasks import process_github # import vcr class Command(BaseCommand): help = 'Import existing users from legacy project' ...
from firebase import firebase class FirebaseManager: firebase = firebase.FirebaseApplication("https://qless-74979.firebaseio.com", None) def get_queues(self): return self.firebase.get('queues', '') def get_walk_in_queue(self): return self.firebase.get('queues/walk_in', '') def get_doctor_queue(self, doctor_...
import numpy as np import load_data as ld import functions as fun training = ld.get_data('Training') testing = ld.get_data('Testing') biz_test = ld.get_data('Dissimilar') weights = fun.fit(training) for i in range(testing.shape[0]): print('initial', testing[i]) test_output = fun.predict(wei...
# Author: Daniel Eynis # ML HW1: Perceptrons import perceptron import numpy as np p = perceptron.Perceptron(learn_rate=0.1) w_m, t_a_h, tr_a_h, c_m = p.learn() f = open("data.txt", "w") f.write(np.array_str(c_m) + "\n") f.write("Test acc: " + str(t_a_h) + "\n") f.write("Train acc: " + str(tr_a_h) + "\n") f.close()
from unittest.mock import patch, create_autospec from web.companies.services import DnbServiceClient from web.core.notify import NotifyService from web.grant_management.flows import GrantManagementFlow from web.grant_management.models import GrantManagementProcess from web.grant_management.tests.helpers import GrantMa...
from __future__ import print_function import time import os import tensorflow as tf import numpy as np import matplotlib.pyplot as plt import adversarial as ad from sklearn.utils import shuffle def loss(g, Y, mean=True, add_other_losses=True): """Cross-entropy loss between labels and output of linear activation...
# Generated by Django 3.1 on 2021-04-24 13:04 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('tour', '0005_player_booked_sent_off'), ] operations = [ migrations.RemoveField( model_name='player', name='team_id', ...
#calculate tips subtotal, gratuity = input("please enter subtotal and gartuity:").split( ) subtotal , gratuity = [float(subtotal), float(gratuity)] gratuity= (subtotal* gratuity) /100 total = subtotal+gratuity print("The gratuity is", format(gratuity,".2f"),"and the total is", format(total,".2f"))
from apps.settings.common import env DATABASES = { 'default': env.db(default='postgres://django:django@db:5432/django'), }
import os, sys import json import logging import re from uuid import uuid4, UUID from datetime import datetime from base64 import urlsafe_b64encode, urlsafe_b64decode from harvest.drivers.cognito_driver import CognitoDriver from harvest.controllers.role_controller import RoleController COGNITO_USER_POOL_ID="ap-northe...
""" Basic module to handle launching the relevant tests from within the script. """ import unittest import os def run_tests(test_subdir): if '*' in test_subdir or not test_subdir: test_subdir = '' # Run all tests in directory. print("Running %s tests" % (test_subdir if test_subdir else 'all')) base_dir = os.pa...
def move_zeros(array): array = sorted(array, key=lambda x: x is 0 or type(x) is float) return (array)
from collections import namedtuple import itertools FindAndReplaceData = namedtuple('FindAndReplaceData', ['orig', 'sub']) remove_stop_pattern = r'\b(a |an |the |in |of |)*\b{0}\b( scan| image)*\b' remove_stop = [FindAndReplaceData(remove_stop_pattern.format(device), device) for device in ['ct', 'mri', 'mra', 'cta'...
import pygame import Global_vars def make_platforms(): i = 0 while Global_vars.platforms > 0: if Global_vars.platforms > 0: width.append(random.randrange(Global_vars.SCREEN_WIDTH - 200, Global_vars.SCREEN_WIDTH + 400)) gap = random.randrange(120, Global_vars.player_jump_length) ...
#%% import os import pickle import time from pathlib import Path import colorcet as cc import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns from sklearn.decomposition import PCA from sklearn.feature_selection import VarianceThreshold from sklearn.model_selection import train_tes...
import threading import adns import logging import Queue # rr = adns.rr.A def worker(q, c, f, n): print q.qsize() with n: if q.empty(): print "Nothing in the queue" f.set() else: host = q.get() # print host c.submit(host, adns.rr.A) ...
#!/usr/bin/python3 # this script is used for build a decision tree for satellites in chapter6 exercises7 and exercise8 # exercise7 from sklearn.datasets import make_moons X, y = make_moons(n_samples=10000, noise=0.4, random_state=42) from sklearn.model_selection import train_test_split, GridSearchCV X_train, X_test, y_...
"""Add roles, users tables Revision ID: d2a98f6fa6e6 Revises: 1b7bd3b61539 Create Date: 2020-02-09 17:55:38.749448 """ import sqlalchemy as sa from alembic import op # revision identifiers, used by Alembic. revision = 'd2a98f6fa6e6' down_revision = '1b7bd3b61539' branch_labels = None depends_on = None def upgrade(...
"""Given a string s and a list of words words, where each word is the same length, find all starting indices of substrings in s that is a concatenation of every word in words exactly once. For example, given s = "dogcatcatcodecatdog" and words = ["cat", "dog"], return [0, 13], since "dogcat" starts at index 0 and "cat...
import matplotlib.pyplot as plt import pandas as pd import numpy as np from sklearn.linear_model import LinearRegression def q1(): # 1 data = pd.read_csv('./specs/marks_question1.csv') # print(data) axe = plt.subplot(1, 1, 1, facecolor='white') x = np.arange(0, 12, 1) y1 = data.get('midterm') ...
from django.core.management.base import BaseCommand, CommandError import logging import urllib2 import json from .basic import * logger = logging.getLogger('django') token_file = "/root/wechat_server/files/token_file.txt" wechat_token = "mytoken" class Command(BaseCommand): def handle(self, *args, **options): l...
# encoding:utf-8 import time import readwrite_operate as rwo import networkx as nx import numpy as np import matplotlib.pyplot as plt from Queue import Queue #全局变量(逻辑需要)--------------------------------------------- time_list = [] #用于统计累加算法核心各段的时间 remove_list = [] ...
""" 246. Strobogrammatic Number A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down). Write a function to determine if a number is strobogrammatic. The number is represented as a string. For example, the numbers "69", "88", and "818" are all strobogrammatic. """ ...
#!/user/bin/python #-*- coding:utf-8 -*- import sys from gensim.models import word2vec import logging logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO) # 今どれくらい処理が進んでるか確認する用 sentences = word2vec.Text8Corpus('data/wakati_bocchan.txt') model = word2vec.Word2Vec(sentences, size=20...
from kafka import KafkaProducer producer = KafkaProducer(bootstrap_servers=['localhost:9092'], api_version=(0, 10)) csvFilePath = 'stat.csv' data = [] with open(csvFilePath, "rb") as csvfile: data = csvfile.readlines() for rec in data: print("sending record",rec) producer.send('csvda...
''' SERVO CONTROL SAMPLE THROUGH THE USE OF 4 BUTTONS (2 for each servo, on pins 15, 4, 22 and 23) The servos are controlled through PWM enambled pins 5 and 21 ''' import machine import time #button declarations: button0 = machine.Pin(15, machine.Pin.IN, machine.Pin.PULL_UP) button1 = machine.Pin(4, machine.Pin.IN, ...
import time import unittest from vika import Vika from . import TEST_API_BASE, TEST_API_TOKEN, TEST_TABLE class TestUpdateRecords(unittest.TestCase): def setUp(self): vika = Vika(TEST_API_TOKEN) vika.set_api_base(TEST_API_BASE) self.dst = vika.datasheet(TEST_TABLE) def test_record_u...
from django.urls import path, include from django.conf.urls import url from . import views urlpatterns = [ path('study/', views.study, name='uploader-uploaderStudy'), path('studyInfo', views.studyInfo, name='uploader-uploaderStudyInfo'), path('info/', views.info, name='uploader-uploaderInfo'), path('ex...
#!/usr/bin/env python import re import sys rgx_num = re.compile('^(\d+)$') rgx_val = re.compile('^(\S+) -> (\S+)$') rgx_and = re.compile('^(\S+) AND (\S+) -> (\S+)$') rgx_or = re.compile('^(\S+) OR (\S+) -> (\S+)$') rgx_lsh = re.compile('^(\S+) LSHIFT (\d+) -> (\S+)$') rgx_rsh = re.compile('^(\S+) RSHIFT (\d+) -> (\...
from game import Game # first take input print("Please enter two sizes line by line") x = int(input()) y = int(input()) tot = x * y print("Please enter bomb amount. Must be less than %d." % (tot)) num_bombs = int(input()) # generate the game g = Game(x, y, num_bombs) g.print_board() result = 0 while result == 0: ...
# 01_fruits.py # 利用CNN实现图像分类 # 数据集:爬虫从百度图片搜索结果爬取 # 内容:包含1036张水果图片 # 共5个类别(苹果288张、香蕉275张、葡萄216张、 # 橙子276张、梨251张) ################## 数据预处理 ################## import os name_dict = {"apple": 0, "banana": 1, "grape": 2, "orange": 3, "pear": 4} data_root_path = "data/fruits/" # 数据集所在目录 # 测试集、训练集文件路...
from nltk import Tree def rec(t): if(type(t)==Tree or type(t)==list): for x in t: rec(x) else: return t def rec_p(t): if(type(t)==Tree or type(t)==list): for x in t: rec_p(x) else: print(t)
from cmc.worker import WorkerCircularQueue, Worker class TestWorkerCircularQueue: def test_wcq_init(self): k = WorkerCircularQueue() assert len(k) == 0 def test_wcq_len(self): wq = WorkerCircularQueue() for i in range(10): wq.add(Worker()) assert len(wq) ==...
s=int(input("enter the first interval")) a=int(input("enter the second interval")) for i in range(s,a+1): if i%2!=0: print(i)
import config import telebot from telebot import types from bot import utils from bot.call_types import CallTypes from bot.states import States from backend.models import BotUser, ShopCard from backend.templates import Messages, Keys def start_command_handler(bot: telebot.TeleBot, message): chat_id = message.c...
# Generated by Django 2.0 on 2018-01-06 16:50 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('song_load', '0003_song_image_url'), ] operations = [ migrations.CreateModel( name='Album', fields=[ ('...
#!/usr/bin/env python #import vonvif #import onvif_wrap from vonvif import request_cmd __all__ =["vonvif"]
# coding: utf-8 # _Autor:_ __Jesús Casado__ <br> _Revisión:_ __16/07/2018__ <br> # # __Introducción__<br> # En este código se incluyen las funciones generadas para desagregar un hidrograma en sus dos componentes: flujo rápido (escorrentía superficial) y flujo lento (flujo base). # # __Funciones__<br> # Evento: #...