text
stringlengths
38
1.54M
from django.contrib import admin from Pingme.models import FollowUser, MyPost, MyProfile, PostComment,PostLike from django.contrib.admin.options import ModelAdmin class FollowUserAdmin(ModelAdmin): list_display = ["profile", "followed_by"] search_fields = ["profile", "followed_by"] list_filter = ["profile"...
f=open("Questions.txt","a") f.write("How many vowels are there?\n") f.write("How many prime numbers are there within 100?\n") f.write("How many alphabets are there?\n") f.write("How many sense organs are there?\n") f.write("How many consonants are there?\n") f.close() g=open("Answers.txt","a") g.write("5\n") g.write("2...
import pyrealsense2 as rs import numpy as np import cv2 pipeline = rs.pipeline() config = rs.config() config.enable_stream(rs.stream.color, 640, 480, rs.format.bgr8, 15) # 10、15或者30可选,20或者25会报错,其他帧率未尝试 config.enable_stream(rs.stream.infrared, 1, 640, 480, rs.format.y8, 15) config.enable_stream(rs.stream.i...
import typer from typing import Optional from .. import config # Program program = typer.Typer() def version(value: bool): if value: typer.echo(config.VERSION) raise typer.Exit() @program.callback() def version( version: Optional[bool] = typer.Option(None, "--version", callback=version), )...
# -*- encoding: UTF-8 -*- dStrings = { "fr": { "title": u"Orthographe française", "choose": u"Choisissez un dictionnaire", "select": u"Utiliser ce dictionnaire", "moderne": u"“Moderne”", "classique": u"“Classique” (recommandé)", "...
class CreditCard: def __init__(self, number=""): self.number = str(number) def checkLength(self): if len(self.number) == 16 or len(self.number) == 15: return True else: return False def determineCardType(self): if self.checkLength: if self.number[0] == '4': return "Visa" elif self.number[0:...
# Generated by Django 3.2 on 2021-05-11 17:45 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('backend', '0003_alter_user_tasktype'), ] operations = [ migrations.RemoveField( model_name='user', name='name', ...
class Userinfo: def __init__(self, name, gender, age, weight, height, objective, preferred_time, use_DNA_data, use_wearable_data, term): self.name = name self.gender = gender self.age = age self.weight = weight self.height = height self.objective = objective s...
from rest_framework import serializers class EmailValidSerializer(serializers.Serializer): """Сериализация email.""" email = serializers.EmailField()
from django.contrib import admin from portfolio.models import ImageGallery # Register your models here. admin.site.register(ImageGallery)
from hackman_notifier import api as notification_api from django.core.management.base import BaseCommand from django_redis import get_redis_connection from hackman_rfid import api as rfid_api from hackman import api as hackman_api import json class Command(BaseCommand): def handle(self, *args, **kwargs): ...
from django.contrib import admin from django.urls import include, path from django.views.generic.base import RedirectView urlpatterns = [ path('basic_calc/', include('basic_calc.urls')), path('', RedirectView.as_view(url='/basic_calc/')), path('admin/', admin.site.urls), ]
import json import math with open("ml_model.json", "r") as json_file: json_data = json.load(json_file) def predict_num(image_data): closest = [(math.inf, None) for i in range(7)] for num in range(10): num = str(num) for image_index, pixels in enumerate(json_data[num]): dista...
from django.conf.urls import url from profiles import views urlpatterns = [ url( regex=r"^edit/$", view=views.ProfileEditUpdateView.as_view(), name="profile_edit" ), url( regex="^confirm_role/(?P<membership_id>[-\w]+)/(?P<action>verify|deny)/$", view=views.profile_c...
#!/usr/bin/python # -*- coding: utf-8 -*- import sys from pyqtgraph.Qt import QtGui, QtCore import pyqtgraph as pg #~ __NAME = '..\opengl\samples.txt' #~ __NAME = '..\\opengl\\test.txt' __NAME = 'haired2.dat' __DIVK = 1. def main(): app = QtGui.QApplication([]) file = open(__NAME,"r") legends=['g...
breakfast = [['French', 'toast'], ['blueberry', 'pancakes'], ['scrambled', 'eggs']] print(breakfast) answer = breakfast[-2][-2] print(answer) breakfast[-2][-2]
from TwitterAPI import TwitterAPI #gove required details CONSUMER_KEY = '' CONSUMER_SECRET = '' ACCESS_TOKEN_KEY = '' ACCESS_TOKEN_SECRET = '' b=1 while True: b=b+1 api = TwitterAPI(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN_KEY, ACCESS_TOKEN_SECRET) file = open('/home/pi/cam/imgs/'+str(b)+'...
#!/usr/bin/env python # coding: utf-8 """Display LIDAR data from specific node. Attributes ---------- ANGLE_MAX : int maximum angle ANGLE_MIN : int minimum angle angles : list list of available angles ctr : int counter of displayed data sets intensities : list intensities from scan data INTENSITY_...
""" Before running the program, enter your specifications into SETUP_focalMechMap.txt """ ######################################################################### import matplotlib.pyplot as plt from mpl_toolkits.basemap import Basemap import netCDF4 import numpy as np import obspy from obspy import read from obspy.cl...
from itertools import combinations x1,y1=input().split() x=str(x1) y=int(y1) z=[] a=combinations(x,len(x)-y) for i in list(z): a.append(''.join(i)) print(min(a))
"""Test combination of all sources.""" from textwrap import dedent import pytest from docoptcfg import docoptcfg from tests import DOCSTRING_FAM, EXPECTED_FAM def test_config_file_in_env(monkeypatch, tmpdir): """Test specifying a config file using only env variables. :param monkeypatch: pytest fixture. ...
import tflearn import numpy as np from tflearn.layers.conv import conv_2d, max_pool_2d from tflearn.layers.core import input_data, dropout, fully_connected from tflearn.layers.estimator import regression import os #print('abuuuuuuuuuuuuuuuuuu') import matplotlib.pyplot as plt #print('babuuuuuuuuuuuuuuu') import tensorf...
import qrcode def create(): qr = qrcode.QRCode( version = 5, box_size = 3, border = 2 ) qr.add_data("Name: Shikhar\nAge: 16\nGender: Male") qr.make(fit=True) img = qr.make_image(fill = "black", back_color = "white") img.save("MyQRcode.png") create()
# Difficulty: trivial # https://www.hackerrank.com/challenges/ctci-is-binary-search-tree/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=trees def check_BST(root): current = None for x in in_order_traversal(root): if current != None and current >= x: ...
# DRF Imports from django.shortcuts import render from rest_framework.viewsets import ViewSet, ModelViewSet from rest_framework.response import Response from rest_framework.views import APIView from django.db.models import Q from rest_framework.generics import ListAPIView from rest_framework.status import ( HTTP_201_CR...
# -*- coding: utf8 -*- # # Copyright 2011-2012, Intel Inc. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; version 2 of the License. # # This program is distributed in the hope that it will be...
# Return the length of the longest palindromic subsequence given a sequence x[1...n] def longestPalindrome(x): n = len(x) lengths = [[0 for i in range(n)] for j in range(n)] for i in range(n): lengths[i][i] = 1 for s in range(2,n+1): for i in range(n-s+1): j = i...
#!C:/python36/python.exe #!/usr/bin/env python3 ##demo code provided by Steve Cope at www.steves-internet-guide.com ##email steve@steves-internet-guide.com ##Free to use for any purpose ##If you like and use this code you can ##buy me a drink here https://www.paypal.me/StepenCope import asyncio import os impor...
""" leetcode 148. Sort List 문제 링크 https://leetcode.com/problems/sort-list/ """ from Linked_list.listnode import ListNode class Solution: def sortList(self, head: ListNode) -> ListNode: # time : n log n # memory : 1 # 1. 중간 찾기 : runner harf, slow, fast = None, head, head whi...
def create_random_array(n, m): import random random_array = [[0] * m for i in range(n)] for i in range(n): for j in range(m): random_array[i][j] = random.randint(-100, 100) return random_array def negative_array_values_arith_mean(n, m): get_array = create_random_arr...
class Solution(object): def removeDuplicateLetters(self, s): """ :type s: str :rtype: str """ # s=set(list(s)) # # print(list(s)) # b=list(s) # b.sort() # return "".join(b) #思路,一个字典,保存当前出现的字符和位置;一个字符串,保存着所有字符的一个排列: #遇到一个字符不在集合...
#Q-2 ) Palindrome Linked List #Answer:- # Definition for singly-linked list. class ListNode(object): def __init__(self, val=0, next=None): self.val = val self.next = next class Solution(object): def isPalindrome(self, head): if not head or not head.next: return True ...
# third-party imports import os from flask import Flask, request, jsonify, abort from sqlalchemy import exc import json from flask_cors import CORS # local imports from .database.models import db_drop_and_create_all, setup_db, Drink from .auth.auth import AuthError, requires_auth app = Flask(__name__) setup_db(app) C...
#!/usr/local/python3/bin/python3 import sys sys.path.append("..") sys.path.append("../..") import tushare as ts import re import datetime import basicdata.basic_mgr as sk import time import os import pandas as pd from lib.time import (strtime_convert, strtime_delta_n_day) save_dir='./moneyflow-data/' g_start_date='201...
import requests from bs4 import BeautifulSoup as bs import os, sys import re from tqdm import tqdm from datetime import datetime import time import pandas as pd import csv import pickle # My functions import planning_functions as pf import master_planning_wrapper as mpw import functions as mf import json dataf...
# Copyright 2014 Huawei Technologies Co. Ltd # # 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...
import pandas as pd import numpy as np import pickle import matplotlib.pyplot as plt from collections import Counter import pprint #from sklearn.covariance import EllipticEnvelope#调用离群点检测算法 #from sklearn.ensemble import IsolationForest#孤立森林算法异常检测 #from sklearn.neighbors import NearestNeighbors from sklearn.neighbors im...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 20/1/6 14:41 # @Author : Chaos # @File : tasks.py import json import datetime import re import sys import os import socket sys.path.append(os.path.dirname(os.path.dirname(__file__))) from plugin.BBScan.bbscan import check_white_list, Web, check_black_list ...
from geopy.geocoders import Nominatim def get_location(uni): a = "University of" b = "University" geolocator = Nominatim(user_agent="my_map") location = geolocator.geocode(uni) location2 = geolocator.geocode(a + uni) location3 = geolocator.geocode(uni + b) if location is not None: return(location) ...
# Generated by Django 2.2.6 on 2020-01-25 17:01 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('history', '0001_initial'), ] operations = [ migrations.AlterField( model_name='history', name='agent', f...
#!/usr/bin/env pybricks-micropython import sys import os from pybricks import ev3brick as brick from pybricks.ev3devices import (Motor, TouchSensor, ColorSensor, InfraredSensor, UltrasonicSensor, GyroSensor) from pybricks.parameters import Port, Stop, Direction, Button, Color from pybric...
import os import pytest from . import db_setup @pytest.fixture(scope='session', autouse=True) def session_fixture(): # print("テスト全体の前処理") os.environ['ENV'] = 'local' os.environ['ENDPOINT'] = 'http://localhost:4566' os.environ['CORS'] = 'http://localhost:3001' db_setup.for_local() yield #...
import argparse import logging def add(x, y): return x + y def subtract(x, y): return x - y def multiply(x, y): return x * y def devide(x, y): return x / y def main(): parser = argparse.ArgumentParser() parser.add_argument("number1", type = int, help = "add first number") parser.add_arg...
# import math # # # def solution(progresses, speeds): # answer = [] # days = [] # for i in range(len(progresses)): # days.append(math.ceil((100 - progresses[i]) / speeds[i])) # # stack = [] # for day in days: # if len(stack) == 0: # stack.append(day) # else: # ...
# Naive algorithm which is O(n^2) def integers_sum(S, x): for i in range(0, len(S)): for j in range(i+1, len(S)): if S[i] + S[j] == x: return True return False # Binary search. if not found return -1 def binary_search(A, p, q, v): if p > q: return -1 mid = (p...
import socket from hashlib import sha1 from random import randint from struct import unpack from socket import inet_ntoa from threading import Timer, Thread from time import sleep from bencode import bencode, bdecode address=[ ("router.bittorrent.com", 6881), ("dht.transmissionbt.com", 6881), ...
# coding: utf-8 from dext.common.meta_relations import logic as meta_relations_logic from the_tale.forum.models import Category, SubCategory from .. import conf from .. import prototypes from .. import meta_relations def prepair_forum(): forum_category = Category.objects.create(caption='category-1', slug='categ...
bl_info = { "name": "Rename outputs", "author": "Tal Hershkovich ", "version": (0, 1), "blender": (2, 72, 0), "location": "View3D > Tool Shelf > Render > Rename Outputs", "description": "replace strings of outputs in render output and compositing output nodes", "warning": "", "wiki_url":...
# -*- coding: utf-8 -*- # Generated by Django 1.10.8 on 2019-05-08 00:53 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('wildlifecompliance', '0187_callemail_number'), ] o...
import mysql.connector import sys import os #import pdb;pdb.set_trace class createdb: def __init__(self): self.username='root' self.passwd="root@123" self.IP_addr='localhost' self.database_name='CevaShipmentDetails' self.db_list=[] self.connection='' self.c...
''' Write a function that takes an unsigned integer and return the number of '1' bits it has (also known as the Hamming weight). Example 1: Input: 00000000000000000000000000001011 Output: 3 Explanation: The input binary string 00000000000000000000000000001011 has a total of three '1' bits. Example 2: Input: 0000000...
# Activate virtualenv import sys import settings activate_this = getattr(settings, 'VENV', None) if (sys.version_info > (3, 0)): # Python 3 with open(activate_this) as file_: exec(file_.read(), dict(__file__=activate_this)) else: # Python 2 if activate_this: execfile(activate_this, dict...
# Import numpy library import numpy as np # Reorganising arrays before = np.array([[1, 2, 3, 4], [5, 6, 7, 8]]) after_1 = before.reshape(2, 2, 2) print("after_1: ", after_1) """ RESULT after_1: [[[1 2] [3 4]] [[5 6] [7 8]]] """ after_2 = before.reshape(4, 2) print("after_2: ", after_2) """ RESULT after_2: [[1 ...
import copy results = [] with open('part1Input') as inputfile: for line in inputfile: results.append(int(line.strip())) helpResults1 = copy.deepcopy(results) helpResults2 = copy.deepcopy(results) product= 0 for x in results: helpResults1.remove(x) helpResults2.remove(x) for y in helpResults1...
from emitted import Client from Tkinter import * import sys sys.path.append("C:/Users/perceptual/Waldo") from waldo.lib import Waldo HOSTNAME = '127.0.0.1' PORT = 8195 games = ["bang","lucky","ducks"] full = ["Bang!", "Kill Dr. Lucky", "Sitting Ducks"] count = [0,0,0] EXITSTRING = "exit" QUITSTRING = "quit" REFRESH = 1...
import CoreFoundation from PyObjCTools.TestSupport import TestCase, min_os_level import objc class TestData(TestCase): def testTypes(self): try: NSCFData = objc.lookUpClass("__NSCFData") except objc.error: NSCFData = objc.lookUpClass("NSCFData") self.assertIs(CoreF...
#!/usr/bin/python """ Copyright (c) 2018 Ian Shatwell The above copyright notice and the LICENSE file shall be included with all distributions of this software """ import sys import signal import time import os import psutil import RPi.GPIO as GPIO def signal_handler(signal, frame): GPIO.cleanup() sys.exit...
import unittest from datetime import datetime, timedelta from project import get_last_value_date today = datetime.now() yesterday = (today - timedelta(1)).strftime('%Y-%m-%d') class LastValueDateTestCase(unittest.TestCase): def test_value(self): result = get_last_value_date() self.assertEqual(yes...
from math import fabs,sqrt import pygame import time import constants as c import collision screen = pygame.display.set_mode((c.gamew, c.gameh)) pygame.font.init() font = pygame.font.SysFont("monospace",32) letter = font.render("A",1,(255,255,255)) class Node: def __init__(self,cost,start,goal,parent = 0): ...
#!/bin/python3 import math import os import random import re import sys import bisect import math # Complete the minTime function below. def minTime(machines, goal): # 13개의 Test Case 중에서 4개 Time out """ machines = sorted(machines) machines_dict = {} # Making Hashmap for removing duplicates f...
from django.conf.urls import url,include #from django.contrib import admin # urlpatterns = [ url(r'^myadmin/', include('myadmin.urls')), url(r'^', include('web.urls')), ]
# Imports the monkeyrunner modules used by this program from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice import time import sys PKG_NAME = 'com.twitter.' ACTIVITY = '.LoginActivity' DEV_PRE_SCRIPT = '/data/data/adafs/dev_pre.sh facebook' DEV_CLEAR_SCRIPT = '/data/data/adafs/dev_clear.sh facebo...
from datasets.facial_yaml import FacialYaml import numpy as np facial_yaml = FacialYaml('facial_feature.yaml') facial_dict = facial_yaml.return_facial_attr_info_dict() selected_facial_fea = facial_dict['facial_fea'] selected_facial_fea_len = facial_dict['facial_fea_len'] selected_attrs = facial_dict['facial_fea_attr'...
from django import forms # ================================================= ФОРМА СВЯЗИ ПРОЕКТОВ =============================================== class Linked_Projects_Form(forms.Form): url_rm = forms.CharField(label="url_rm", help_text="Enter Redmine project url") url_gh = forms.CharField(label="url_gh", ...
# -*- coding: utf-8 -*- import numpy as np import os from PIL import Image import math import json import scipy.io as scio import sqlite3 # path_save = r'D:\for_locate_point\user5-8_final_label_0703' # image_list = [] # file_list = ['D:/for_locate_point/user5_1', 'D:/for_locate_point/user6_1', 'D:/for_l...
from django.urls import path from . import views app_name= 'dashboard' urlpatterns = [ path('', views.index, name='index'), path('clientDash/', views.clientDash, name='clientDash'), path('allClientData/', views.allClientData, name="data"), path('clientsData/', views.ClientData, name='data'), pat...
from bs4 import BeautifulSoup as bs import re import os import urllib.error from urllib.request import urlopen, urlretrieve, HTTPCookieProcessor, build_opener, install_opener, Request from urllib.parse import urlencode from http.cookiejar import CookieJar import urllib.request def getHTML(posturl): hea...
message = 'Hello world' print(message.lower()) print(message.upper()) print(message.swapcase()) print(message.find("world")) print(message.count("o")) print(message.capitalize()) print(message.replace("Hello", "Hi"))
def find_anagrams(word, candidates): word = word.lower() sorted_word = sorted(word) anagrams = [] for candidate in candidates: if len(word) == len(candidate): #O(1) if word != candidate.lower(): if sorted_word == sorted(candidate.lower()): anagrams...
import os import sys import unittest import datetime from unittest.mock import patch sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))) from seriesbr import bcb # noqa: E402 def mocked_json_to_df(url, *args): """Instead of parsing the JSON, just return the URL""" return url...
import string arr = [] for _ in range(int(input())): x=input().split() cmd = x[0] args = x[1:] if cmd !="print": cmd += "("+ ",".join(args) +")" eval("arr."+cmd) else: print(arr)
# A collection of functions that spawn openstack clients import keystoneclient.v2_0.client as ksclient from keystoneclient import session from keystoneclient.auth.identity import v2 import glanceclient.v2.client as glclient from novaclient import client from swiftclient import Connection def create_keystone_client...
class ClaseDecoradora: def __init__(self, fnc): self.fnc = fnc def __call__(self, *args, **kwargs): print('se llama a la clase decorradora') self.fnc(*args, **kwargs) @ClaseDecoradora def hablar(mensaje): print(mensaje) hablar('Hola')
from tokenizer import Tokenizer from tokenizer import Token from token_type import TokenType from number import Number class ExprParser(object): ''' Parser for grammar specified in 'language_definition.txt' See: https://en.wikipedia.org/wiki/Recursive_descent_parser Note: Need paranthesis to enforce p...
# -*- coding: utf-8 -*- """ Created on Thu Jul 04 19:57:11 2013 @author: drewhill """ #from AbilListClass.py import AbilListClass import os class ability: #for both skills and interests def __init__(self,newID,val,kind): #constructor self.id = newID self.name = val self.type = kind #Skill ...
import argparse import subprocess import unittest.mock from argparse import Namespace from get_ip_addresses import IpAddresses class TestStringMethods(unittest.TestCase): def setUp(self): self.ip_addresses_all = IpAddresses().ip_addresses_all() self.ip_addresses_with_prefix = IpAddresses().ip_add...
# Time complexity: O(N) def moveElementToEnd(array, element): left = 0 right = len(array) - 1 while left < right: while left < right and array[right] == element: right -= 1 if array[left] == element: array[left], array[right] = array[right], array[left] left ...
''' Myanna Harris 9-11-16 asgn2.py Normalize and check Zipf's Law on Jane Austen's novel, Emma. To run: python asgn2.py "path/to/austen-emma.txt" ''' import sys import re import numpy as np import matplotlib.pylab as plt # normalize(filePath) def normalize(file): f = open(file,'r') iter = re.find...
# Copyright (c) Alibaba, Inc. and its affiliates. from collections.abc import Mapping import torch from torch import distributed as dist from modelscope.metainfo import Trainers from modelscope.trainers.builder import TRAINERS from modelscope.trainers.optimizer.builder import build_optimizer from modelscope.trainers....
# The number, 1406357289, is a 0 to 9 pandigital number because it is made up of each of the digits 0 to 9 # in some order, but it also has a rather interesting sub-string divisibility property. # # Let d1 be the 1st digit, d2 be the 2nd digit, and so on. In this way, we note the following: # # d2d3d4=406 is divisi...
from Robinhood import Robinhood rb = Robinhood() rb.login_prompt() watchlist = rb.watchlist() symbols = ' '.join([instrument['symbol'] for instrument in watchlist]) print(symbols) with open("watchlist.txt", "w") as text_file: text_file.write("{0}".format(symbols))
message = "Hello India" if message == "Hello India": print("vales are Equal") else: print("values are not Equal") values = [1, 10, 11, 3, 4, 5] # for i in values: # print(i) sum = 0 for i in range(1, 6): sum = sum + i print(sum) print('***************************') for j in range(1, 10, 2): print(j) ...
from enum import Enum from os import path from typing import List import typer from colorama import init from ..utils import STATUS_ARROW from .dashboard import create from .data import aggregate_results, parse_simulation_report from .plotters import metric_corr, plot_miss_freq, plot_num_miss_after_del class PlotTy...
import itertools, utils, re from collections import defaultdict from defense.models import Player, Country, Team, \ Stadium, City, Region, StadiumTeam, TournamentTeam, \ GameTeam, Goal, GamePlayer, PlayerTeam from difflib import SequenceMatcher from django.core.exceptions import ObjectDoesNotExist num_patte...
# -*- coding: utf-8 -*- # Generated by Django 1.10 on 2016-10-22 03:19 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('main', '0002_userinfo_type'), ] operations = [ migrations.RenameField( ...
import pygame import os import sys sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__)))) from Objects.chessBoard import ChessBoard from Objects.player import Player from Objects.ai import AI from Framework.sceneManager import Scene, SceneManager from Framework.simpleImage import SimpleImage cl...
print("Advent of Code - Day 3") f = open("input3-1", "r").read() wire1_moves = f.split(',') f = open("input3-2", "r").read() wire2_moves = f.split(',') from math import* def manhattan_distance(x,y): # distance += abs(x_value - x_goal) + abs(y_value - y_goal) return sum(abs(a-b) for a,b in zip(x,y)) # Tes...
import os import sys import glob usage = """ Cython .pyx files as well as the created .cpp files are included in the source distribution. The following information is useful for developers working on the Cython source code. Install in development mode. Will cythonize .pyx files first if needed. python s...
# -*- coding: utf-8 -*- # Generated by Django 1.9.6 on 2017-08-24 20:22 from __future__ import unicode_literals import blogger.apps.principal.models from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('principal', '0006_institucionslider'), ] operat...
# tests/__init__.py import os import time import tempfile import pytest from caten_music import CreateApp @pytest.fixture def client(): app = CreateApp.Test() # db_fd, app.config["SQLALCHEMY_DATABASE_URI"] = tempfile.mkstemp() client = app.test_client() yield client # os.close(db_fd) #...
# -*- coding: utf-8 -*- __author__ = 'liupeiyu' from watchdog.utils import watchdog_info CLOUD_USER_SESSION_KEY = 'clouduid' def get_request_cloud_user(request): #假设经过了CloudSessionMiddleware中间件的处理 return request.cloud_user if hasattr(request, 'cloud_user') else None def get_session_cloud_user_nam...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @Author : yanyongyu @Date : 2021-03-23 00:20:51 @LastEditors : yanyongyu @LastEditTime : 2021-03-23 00:21:18 @Description : None @GitHub : https://github.com/yanyongyu """ __author__ = "yanyongyu" from typing import Optional from . i...
#Seth Jones #11/07/2019 #Period 1/2 import random from time import sleep divideLines = "------------------------------------------------" #--------------------------Options----------------------# def options(): while True: print(divideLines) sleep(0.5) options = """ Welco...
from openpyxl import Workbook from openpyxl import load_workbook if __name__ == '__main__': excel_data = Workbook() excel_data = load_workbook("C:/Users/Owner/Documents/GitHub/TATADataChallenge2017/NBTC_Tata_Challenge.01.xlsx") #excel_data.create_sheet("video_game_data", 0) print(excel_data.get_sheet_n...
#!/usr/bin/python3 from typing import List import json from bplib.butil import TreeNode, arr2TreeNode, btreeconnect, aprint class Solution: def findTheDifference(self, s: str, t: str) -> str: arr = [0] * 26 for c in s: arr[ord(c)-ord('a')] += 1 for c in t: arr[ord(...
from django.test import TestCase, Client from django.db.models import Max from .models import Category, Item, CartItem, OrderItem, Order, User # pylint: disable=no-member # Create your tests here. class OrdersTestCase(TestCase): def setUp(self): # Create users. user_1 = User.objects.create(...
def choosepivot_first(A): ''' Use first element as pivot. ''' return 0 def choosepivot_last(A): ''' Use last element as pivot. ''' return len(A) - 1 def choosepivot_median(A): ''' Use median of [first, last, middle] elements as pivot. Note: if A is even length, rounds *d...
#!/usr/bin/env python from vector import vector DIRECTIONS = ('E', 'W', 'N', 'S', 'F') TURNINGS = ('R', 'L') nav_ins = list((ins[0], int(ins[1:])) for ins in open('input.txt')) ship = vector(0, 0, 'E') print(ship.get_pos()) for ins in nav_ins: if ins[0] in DIRECTIONS: ship.change_position(ins) elif ins[0] in TU...
#import random import secrets #min = 1 #max = 6 foo = ['1','2','3','4','5','6'] roll_again = "yes" while roll_again == "yes" or roll_again == "y": print ("Rolling the dices...") print ("The values are....") # print (random.randint(min, max)) # print (random.randint(min, max)) print (secrets.choice(fo...
''' Python tem duas funções muito interessantes: ANY e ALL. -> A função 'ANY' recebe uma lista (ou outro objeto interável) e retorna 'True' se algum dos elementos for avaliado como 'True'. -> Já 'ALL' só retorna 'True' se todos os elementos forem avaliados como 'True' ou se ainda se o iterável está vazio. Veja: >...