text
stringlengths
38
1.54M
from abc import abstractmethod from abc import ABCMeta import numpy as np import cv2 from utils import crop_image, expand_bbox class ImageSample: __metaclass__ = ABCMeta """Image interface""" @property @abstractmethod def bgr_data(self): pass @property @abstractmethod def id(s...
#! /home/fyh/anaconda3/envs/NERpy3/bin/python import random import nltk from util import HPOTree,HPO_class,getNames, containNum obo_file_path="../data/hpo.json" # wiki_file_path="../models/wikipedia.txt" # none_list=[] # # wiki中无意义的短语 # with open(wiki_file_path, "r", encoding="utf-8") as wiki_file: # max_length=10...
import os import numpy as np import pickle class NeuralNetwork: def __init__(self, train_x, train_y, hidden_layer_size, train_validation_ratio): self.train_size = train_x.shape[0] # shuffle samples s = np.arange(self.train_size) np.random.shuffle(s) train_x = train_x[s] ...
import pytest @pytest.fixture def headers(): return {'user-agent': 'my-app/0.0.1'} @pytest.fixture def main_url(): return "https://rabota.by/search/vacancy?L_is_autosearch=false&area=16&clusters=true&enable_snippets=true&text=python&page="
from bezmouse import * import pyautogui import time import random import importlib.machinery visitor_lib = importlib.machinery.SourceFileLoader('visitor_lib', 'visitor_lib/visitor_lib.py').load_module() def bitearn(): captcha_reps = 0 while True: visitor_lib.browser_open_url('https://bitearn.io/page/dashboard/...
from django.db import models from datetime import datetime from django.contrib.auth.models import AbstractUser # Create your models here. class UserProfile(AbstractUser): birthday=models.DateField(verbose_name=u'生日',null=True,blank=True) gender=models.CharField(verbose_name=u'性别',max_length=10,choices=(("male...
#!/usr/bin/env python '''This program should take a BAM file produced by Bismark and a list of adjacent CpG sites (one line per read and _one_ eligible pairs) for which the methylation statuses will be reported in a pairwise manner. ''' import sys import argparse import getopt import pysam import os import doctest im...
# -*- coding:utf-8 -*- #Get method: headers, param import requests import json import glob,os host = "http://httpbin.org/" endpoint = "get" url = ''.join([host,endpoint]) headers = {"User-Agent":"test request headers"} params = {"show_env":"1"} r = requests.get(url=url,headers=headers,params=params) print (r.text) ...
import numpy as np import sklearn.cluster as sk import sklearn.manifold as mf import matplotlib.pyplot as plt from matplotlib import cm from matplotlib import colors as mplc from mpl_toolkits.mplot3d import axes3d from scipy.cluster.hierarchy import ward, fcluster from scipy.cluster.hierarchy import dendrogram, linka...
import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "bookmanager.settings") import django django.setup() from app01 import models #################基于对象的查询############ # 正向查询 # book_obj = models.Book.objects.get(pk=1) # print(book_obj.publisher) # 关联的出版社对象 # print(book_obj.publisher_id) # 关联的出版社的id # 反向查询 #...
import sys import time import RPi.GPIO as GPIO # Use BCM GPIO references # instead of physical pin numbers #GPIO.setmode(GPIO.BCM) mode=GPIO.getmode() print " mode ="+str(mode) GPIO.cleanup() # Define GPIO signals to use # Physical pins 11,15,16,18 # GPIO17,GPIO22,GPIO23,GPIO24 StepPinForward=11 StepPinBackward=15 ...
# v2dump.py 20100914 # Author: Peter Sovietov import sys Prefix = '' def dw(buf, d): return (ord(buf[d + 3]) << 24) | (ord(buf[d + 2]) << 16)| \ (ord(buf[d + 1]) << 8) | ord(buf[d]) def delta(buf, d, num): return ord(buf[d]) | (ord(buf[d + num]) << 8) | \ (ord(buf[d + 2 * num]) << 16...
import requests, sys, re, json, mne, pickle, os, ctypes import DogSchemaView_UI043 as view from mne.viz import circular_layout, plot_connectivity_circle import numpy as np import matplotlib.pyplot as plt import PySimpleGUI as sg import mne.viz.utils as utils from functools import partial class analyseInput():...
sexo = str(input("Digite a inicial do seu sexo: (M para masculino ou F para feminino) ")) if sexo == 'M' or sexo == 'm': print("O sexo selecionado foi Masculino") elif sexo == 'F' or sexo == 'f': print("O sexo selecionado foi Feminino") else: print("Sexo Indefinido")
import bpy from .utils.global_settings import SequenceTypes # TODO: Use a handler to auto move the fades with extend # and the strips' handles class FadeStrips(bpy.types.Operator): """ ![Demo](https://i.imgur.com/XoUM2vw.gif) Animate a strips opacity to zero. By default, the duration of the fade...
def golf(m):d=[1e9]*len(m);d[0]=0;r(m,d,0);return 0 if d[-1]==1e9 else d[-1] def r(m,d,i): for j,c in enumerate(m[i]): b=d[i]+c if c and b<d[j]: d[j]=b;r(m,d,j)
class Sirket(): def __init__(self,calisansayisi,sirketismi,mudurler,muduryrd,faaliyet): self.calısansayisi = calisansayisi self.sirketismi = sirketismi self.mudurler = mudurler self.muduryrd = muduryrd self.faaaliyet = faaliyet def calısanAl(self,sayi): ...
#from typing import List, Dict from . import settings #NodeEdgesDict = Dict[int, Dict[str, int]] def check_dep_lemma(sentence, dep_dict, dep, lemma) -> bool: if(dep not in dep_dict): return False target_list = dep_dict[dep] for targetID in target_list: token = sentence.token[targetID] if(t...
import math import sys seen = dict() count = 0 first = 0 nums = [] for line in sys.stdin: if(line[0] == '-'): a = int(line[1:]) nums.append(-a) else: nums.append(int(line)) while True: for n in nums: count += n if count in seen: first = count print("seen " + str(first) ) ...
import uuid from django.db import models from django.utils.translation import ugettext_lazy as _ # Create your models here. class BaseModel(models.Model): """Base model for providing uuid, updated_at, created_at fields""" id = models.UUIDField(default=uuid.uuid4, primary_key=True) update_at = models.Date...
import numpy as np from numpy.polynomial import polynomial as P import matplotlib.pyplot as plt x = np.linspace(0, 8 * np.pi, 50) y1 = np.cos(x) y2 = np.sin(x - np.pi) # Fitting data coeff, stats = P.polyfit(x, y1, 20, full=True) roots = np.real(P.polyroots(coeff)) fit = P.Polynomial(coeff) yf1 = fit(x) ...
# https://projecteuler.net/problem=10 # The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. # Find the sum of all the primes below two million. def check_primness(prime_candidate): for i in xrange(prime_candidate - 1, 1, -1): if prime_candidate % i == 0: return False return True def run_test(): primes = ...
import cv2 import matplotlib.pyplot as plt import numpy as np from matplotlib import cm road=cv2.imread(r'/home/abhilash/Coding/computervision/objectDetectionWithOpenCVandPython/DATA/road_image.jpg') roadCopy=np.copy(road) markerImage=np.zeros(road.shape[:2],dtype=np.int32) segments=np.zeros(road.shape,dtype=np....
# Automate the Daily Bing Search # # from selenium import webdriver from selenium.webdriver.firefox.firefox_binary import FirefoxBinary import time binary = FirefoxBinary('C:\Program Files (x86)\Mozilla Firefox\Firefox.exe') browser = webdriver.Firefox(firefox_binary=binary) browser.get("https://login.liv...
import random while True: x = random.randint(0,20) y = random.randint(0,20) error = random.randint(-2,2) operator = ["+","-","*","/"] op = random.choice(operator) if op == "+": r = x + y + error elif op == "-": r = x - y + error elif op == "*": r = x * y + erro...
# Question Link : https://www.hackerrank.com/challenges/non-divisible-subset/problem from collections import Counter, defaultdict def nonDivisibleSubset(k, S): S = list(map(lambda x : x % k, S)) dic = defaultdict(lambda : 0, Counter(S)) # This size is always less than k( < 100). for i in range(k/...
# Generate a Verilog sin table module. import math SAMPLES = 256 OUTMAX = 255 print("module sinTable(") print("input [7:0] in,") print("output [7:0] out);") print("") print("assign out = ") for sample in range(SAMPLES): angle = (sample * 180) / SAMPLES -90 sine = math.sin(math.radians(angle)) re...
import boto3 import botocore import paramiko import sounddevice import numpy as np import time import gc from botocore.client import Config duration = 0.01 # seconds sample_rate=44100 ACCESS_KEY_ID = 'AKIAI3GG45ZOXLW5C2XA' ACCESS_SECRET_KEY = 'Qd+blzLHW8ea+PLCiyl/JPtPAIfuHlJOJDmDgOHP' BUCKET_NAME =...
# -*- coding: utf-8 -*- import datetime from flask import g from portfelo.contrib.models import RootDocument class User(RootDocument): collection_name = u'users' structure = {'email': unicode, 'first_name': unicode, 'last_name': unicode, 'password': unico...
# coding: utf-8 # # Copyright 2021 The Oppia Authors. 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 requi...
from unittest import TestCase from core.models import User, connection, Question from .base import DatabaseTestCaseMixin class ModelsTestCase(TestCase, DatabaseTestCaseMixin): def setUp(self): self.db = connection.test super(ModelsTestCase, self).setUp() self.setup_connection() def te...
#!/usr/bin/env python # coding=utf-8 # author:jingjian@datagrand.com # datetime:2019/4/19 下午2:43 import os, sys, re, json, traceback from uuid import uuid4 as uuid import requests from conf import conf from pydocx import PyDocX def get_file_names(file_dir, fileType): ''' 得到某个目录下所有的文件名 :param file_dir:文件夹路...
from os import mkdir from os.path import join from shutil import copy from libw3g.util import get_replay_id from libdota.tests.util import get_replay_path def add(replay_file): target_fn = get_replay_path(get_replay_id(replay_file).read()) copy(replay_file, target_fn) print 'added replay %s' % target_fn ...
#!/usr/bin/python #!/apps/python/3.4.3/bin/python3 # Toshiyuki Gogami # Dec 20, 2019 import sys import time, os.path from subprocess import call #import concurrent.futures #from logging import StreamHandler, Formatter, INFO, getLogger #from concurrent.futures import ThreadPoolExecutor #from concurrent.futures.proces...
import sys import numpy as np import pandas as pd from sklearn.model_selection import train_test_split from sklearn.preprocessing import MinMaxScaler from keras.models import Sequential from keras.layers import Dense from keras.optimizers import Adam import matplotlib.pyplot as plt from numpy.random import seed from ...
import argparse import gym import gym_gvgai from player import Player import pdb import numpy as np parser = argparse.ArgumentParser(fromfile_prefix_chars='@') parser.add_argument('-trial_num', default = 1, required = False) parser.add_argument('-batch_size', default = 32, required = False) parser.add_argument('-lr',...
#!/usr/bin/env python # -*- coding:utf-8 -*- import rospy from geometry_msgs.msg import Pose2D, Twist from tms_msg_rc.srv import rc_robot_control, rc_robot_controlResponse from tms_msg_db.srv import TmsdbGetData, TmsdbGetDataRequest import datetime import pymongo from math import sin, cos, atan2, pi, radians, degrees...
x = input("\nEnter the kilometer distance : ") a = int(x) b = int(a / 1000) c = (float(a / 1000) - b) * 1000 c = int(c) print("\nDistance is : " + str(b) + " Km and " + str(c) + " cmeter")
#!/usr/bin/env python3 """Initial script.""" from brain_games.gameplay import play_game from brain_games.games import prime def main(): """Define main code.""" game_type = prime play_game(game_type) if __name__ == '__main__': main()
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import csv import re import os import tweepy import time import random import datetime import pyautogui import cv2 consumer_key = consumer_key consumer_secret = CONSUMER_SECRET_KEY access_key = ACCESS_KEY access_secret = ACCESS_SECRET_KEY ...
# coding=utf-8 # Copyright 2019 The Tensor2Tensor Authors. # # 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...
# -*- coding: utf-8 -*- ''' # Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. # # This file was generated and any changes will be overwritten. ''' from __future__ import unicode_literals from ..one_drive_object_bas...
import json import bs4 import requests import urllib.request from pprint import pprint stats_passing = {} def schedule_url(year, stype, week): """ Returns the NFL.com XML schedule URL. `year` should be an integer, `stype` should be one of the strings `PRE`, `REG` or `POST`, and `gsis_week` should be ...
import asyncio import re import time from collections import OrderedDict from contextlib import suppress from typing import Any, AsyncIterator, Iterable, Mapping, Optional, Tuple from cashews._typing import Key, Value from cashews.serialize import SerializerMixin from cashews.utils import Bitarray, get_obj_size from ...
from ecs.entity import Entity from ecs.time import Time from ecs.world_clocks import WorldClocks from core.inventory import Inventory clocks = WorldClocks( Time(minutes=1), systems=[ ] ) player = Entity( Inventory() )
from datetime import datetime from django.db import models # Create your models here. # 课程对应多个章节、每个章节对应多节课、每节课对应多个视频 每个课程对应多个课程资源 如前端代码 # 课程信息表 class Course(models.Model): DEGREE_CHOICES = ( ("cj", "初级"), ("zj", "中级"), ("gj", "高级") ) name = models.CharField(max_length=50, verbo...
""" coding:utf8 @Time : 2020/8/1 17:21 @Author : cjr @File : get_ip.py """ from . import errors import requests def get_ips(): """ github上的免费IP池:https://github.com/jiangxianli/ProxyIpLib.git 响应消息格式: { "code":0, "msg":"成功", "data":{ "current_page":1, "dat...
import os from nose.tools import assert_true, assert_false from nerds.util.file import mkdir, rmdir def test_mkdir(): directory1 = "data" directory2 = "data/foo" mkdir(directory1) mkdir(directory2) assert_true(os.path.exists(directory1)) assert_true(os.path.exists(directory2)) def test_r...
#!/usr/bin/env python # -*- coding: gb2312 -*- # # pi_function.py # # Copyright 2017 Administrator <Administrator@WIN-84KOMAOFRMQ> # # 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 Foundat...
import pandas as pd from sec.sql import create_connection from sec.tickers import Tickers from sec.cluster import StringCluster CONN = create_connection('sec.db') TICKERS = Tickers() data = pd.read_sql( sql="select * from holdings where report_pd == '12-31-2020';", con=CONN ) data['company'] = data['company'...
# A simple random arc function by @bmheades # You may not use it commerically import amulet from amulet.api.selection import SelectionGroup from amulet.api.data_types import Dimension from amulet.api.level import BaseLevel from amulet.api.level import World from amulet.api.block import Block from amulet_nbt ...
#!/usr/bin/python3 """ Reviews """ from api.v1.views import app_views import json import models from flask import jsonify, request from models.place import Place from models.review import Review from models.user import User @app_views.route( '/places/<place_id>/reviews', methods=['GET'], strict_slashes=Fa...
from django.urls import path,include from .views import * urlpatterns = [ # path('student/', student), # path('signup/', signup), path('login/', login), path('logout/', logout), path('adminsite/', adminsite,name="admin site"), path('addstudent/', studentRegister,name="studentRegister"), pat...
import sys import entityx class UpdateTest(entityx.Entity): updated = False def update(self, dt): # Should only be called with one entity. assert self.entity.id.index == 0 assert self.entity.id.version == 1 self.updated = True
try: from setuptools import setup except ImportError: from distutils.core import setup config = [ 'description':'My project', 'author':'MY', 'url':'where to get', 'download':'Where to download', 'auter_email':'My email', 'version':'0.1', 'install_require':['nose'], 'packages':['NAME'], 'scripts':[], 'name'...
# # @lc app=leetcode.cn id=126 lang=python3 # # [126] 单词接龙 II # # @lc code=start from collections import defaultdict,deque class Solution: def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]: res,dic = [],defaultdict(list) queue1,queue2 = deque([(beginWord,[b...
# -*- coding: utf-8 -*- from schedulingsystem import db from schedulingsystem.errors.schedulingexception import SchedulingException from schedulingsystem.meetingroom.models import MeetingRoom import schedulingsystem.meetingroom.repository as meeting_room_rep import schedulingsystem.scheduling.repository as scheduling_...
import torch import yaml import config import numpy as np from . import keys,crann from src.basemodel.basemodel import BaseModel from .quadObject import quadObject from .opImage import genRotateAroundMatrix, rotateImageByMatrix import base64 import cv2 import json from skimage import io import logging class CrannRecM...
''' goetia@sentineldr.com check log for TOR relays in past connections. ''' import urllib.request import sys import re def main(args): usage = "Usage: extor.py logfile IP_column# date_column#" if '-h' in args or '--help' in args: print("extor.py: check log for TOR relays in past connecti...
import pandas as pd from sklearn.preprocessing import MinMaxScaler from sklearn.cluster import KMeans from sklearn.metrics import silhouette_score import matplotlib.pyplot as plt from sklearn.manifold import TSNE # read the data file data = pd.read_csv('pubs.txt', sep='\t') data2 = data.iloc[:-1,1:] #Remove names of c...
from unittest import TestCase, main import pickle, json from datetime import datetime from from_email import parse_message_parts, Post from curate_video import poster_filename_for import sitebuilder from main import is_sender_whitelisted, filter_whitelist class ParseEmailTests(TestCase): def test_parse_subject(se...
from kivymd.app import MDApp from kivy.lang.builder import Builder from kivy.core.window import Window from kivy.uix.screenmanager import ScreenManager,Screen #Window.size=(720,1280) home_page_helper=""" ScreenManager: LoginScreen: SignupScreen: DashboardScreen: <LoginScreen>: name:'login_page' Ima...
from django.shortcuts import render, HttpResponseRedirect, Http404 from django.core.urlresolvers import reverse from django.core.mail import send_mail, EmailMultiAlternatives, EmailMessage from django.contrib.sites.shortcuts import get_current_site from django.conf import settings from django.template.loader import get...
from .base import * # noqa DEBUG = False DATABASE_URL = str(os.getenv("DATABASE_URL")) DATABASES = { 'url': dj_database_url.parse(DATABASE_URL, conn_max_age=600), } DATABASES['default'] = DATABASES['url']
# std imports from typing import Set, Dict, Type, Mapping, TypeVar, Iterable, Optional, OrderedDict # local from .terminal import Terminal _T = TypeVar("_T") class Keystroke(str): def __new__( cls: Type[_T], ucs: str = ..., code: Optional[int] = ..., name: Optional[str] = ..., ...
''' You are given a node that is the beginning of a linked list. This list always contains a tail and a loop. Your objective is to determine the length of the loop. For example in the following picture the tail's size is 3 and the loop size is 11. ''' def loop_size(node): temp = {} n = 0 while...
from main.models import ( Neighborhood, Zipcode, BlockGroup, Listing, Amenity, Crime ) from rest_framework import viewsets from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.decorators import detail_route, list_route from rest_framework impo...
# Enter your code here. Read input from STDIN. Print output to STDOUT import calendar ip = input().split() m = int(ip[0]) d = int(ip[1]) y = int(ip[2]) caldays=list(calendar.day_name) wk=[calendar.weekday(y, m, d)][0] print(caldays[wk].upper())
import dace import dace.graph.labeling import sys import time print(time.time(), 'loading') a = dace.SDFG.from_file(sys.argv[1]) print(time.time(), 'propagating') dace.graph.labeling.propagate_labels_sdfg(a) print(time.time(), 'drawing') a.draw_to_file() exit() a.apply_strict_transformations() a.apply_strict_transfo...
#!/usr/bin/python3 '''This module contains a LockedClass class''' class LockedClass: '''This class defines a class with only one attribute''' __slots__ = ['first_name'] def __init__(self, value=""): '''Constructor method''' self.first_name = value
from django.conf.urls import url from board import views urlpatterns = [ url(r'^$', views.mainIndex, name ='index'), url(r'^([0-9]+)/$', views.boardDetail), url(r'^create/$', views.boardCreate), url(r'^update/([0-9]+)/$', views.boardUpdate), url(r'^delete/([0-9]+)/$', views.boardDelete), ]
#-*_coding:utf8-*- import requests import re import sys reload(sys) sys.setdefaultencoding('utf-8') class spider(object): def __init__(self): print 'Spider Starts...' def getsource(self,url): html = requests.get(url) return html.text def changepage(self,url,total_page): n...
#!/usr/bin/env python # -*- coding: utf-8 -*- # This file is part of the SPORCO package. Details of the copyright # and user license can be found in the 'LICENSE.txt' file distributed # with the package. """ Convolutional Dictionary Learning ================================= This example demonstrating the use of :cla...
import os import random import tempfile from controller.helpers import get_player_colour from data import consts from data.enums import ResponseFlags as rF from data.interpreter import Interpreter from state import helpers from state.context import context PROX_LIMIT_X = 5 PROX_LIMIT_Y = 3 class Callbacks: def ...
#Python Program to Find the Largest Number in a List li = [] n = int(input("How many numbers to be added in the list = ")) for i in range(n): li.append(float(input("enter number "))) print(li) def check_largest_no(): largest = li[0] for i in range(len(li)): if (li[i] > largest): larg...
#!/usr/bin/python import pymongo # Import Python modules import os import sys current_dir = os.path.dirname(os.path.abspath(__file__)) pygeo_dir = os.path.join(current_dir, "../../") sys.path.append(pygeo_dir) import pygeo from pygeo.time.standardtime import attrib_to_converters class mongo_import: def __init_...
import maya.cmds as mc import pcCreateRig00AUtilities from pcCreateRig00AUtilities import pcCreateRigUtilities as CRU reload(pcCreateRig00AUtilities) sels = mc.ls(sl=True) sel = sels[0] if len(sels) == 1: if CRU.checkObjectType(sel) == "mesh": if sel[:2] == "l_": toReplace = "...
# -*- coding utf-8 -*- import click import time import pyodbc as odbc from flask import Flask, request, jsonify from flask_cors import CORS from db.initDB import initDB, initIndex from handler import * import processbar app = Flask(__name__) CORS(app, supports_credentials=True) connection = odbc.connect('DRIVER={SQL ...
result = [12, 46, 23, 12, 56, 78] print(result) rating = [0] * len(result) place = 1 while place <= len(result): for idx, num in enumerate(result): if num == max(result) and result.count(num) == 1: result[idx] = 0 rating[idx] = place place += 1 elif num ...
import discord from discord.ext import commands import datetime import typing from functools import wraps from config import Config if typing.TYPE_CHECKING: from bot import CodinGameBot def setup(bot: "CodinGameBot"): bot.add_cog(Moderation(bot=bot)) def moderation(func: typing.Callable): @wraps(func...
m = float(input('Digite seu valor em metros(m): ')) c = m * 100 mm = m * 1000 print(f'Sua conversão para centímetros é {c:.1f}cm e sua conversão para milímetros é {mm:.1f}mm')
import os import test_main from os import path import pytest def check_file(name): return path.exists(name)
#!/usr/bin/env python # -*- coding: utf-8 -*- # FileName : router_to_req.py # Author : wuqingfeng@ import time import random from threading import Thread import zmq import zhelpers NBR_WORKERS = 10 #LRU def worker_thread(context=None): context = context or zmq.Context() worker = context.socket(zmq.REQ)...
class HouseholdEvolutionSpecification(object): def __init__(self, idSpec, agentType, hhldAttribs=None, personAttribs=None, evolutionAttribs=None): self.idSpec = idSpec self.agentType = agentType self.hhldAttribs = hhldAttribs self.personAttribs = personAttribs self.evolutionAttribs = evolution...
import brownie import pytest def test_harvest(strategy, ethFundManager, admin, eth_whale): whale = eth_whale fundManager = ethFundManager # deposit into fund manager deposit_amount = 10 ** 18 eth_whale.transfer(fundManager, deposit_amount) # transfer to strategy strategy.deposit(2 ** 25...
__all__ = ('command_upgrade',) from hata import Embed from hata.ext.slash import P, abort from scarletio import copy_docs from sqlalchemy.sql import select from ...core.constants import ( STAT_NAME_FULL_BEDROOM, STAT_NAME_FULL_CHARM, STAT_NAME_FULL_CUTENESS, STAT_NAME_FULL_HOUSEWIFE, STAT_NAME_FULL_LOYALTY, S...
from pricehunters.store import get_stores def test_get_targets(): stores = get_stores() assert len(stores['stores']) > 0
from django.forms import ModelForm from .models import * from django.contrib.auth.forms import UserCreationForm class RegistrationForm(UserCreationForm): class Meta: model = User fields = "__all__" def clean_email(self): email = self.cleaned_data['mail'].lower() try: ...
import requests import colorama from requests.adapters import HTTPAdapter from tools.base import config from tools.base import matcher from tools.base import util LOG = util.get_logger('router') def get_lobby_route(feature=None, insecure=False): payload = {'appId': config.APP_ID} if config.FEATURE is not Non...
def solve(input): steps = int(input) items = [0] currentIndex = 0 for num in range(50000000): if num > 0: for num2 in range(steps): currentIndex += 1 if currentIndex == len(items): currentIndex = 0 currentIndex += 1 ...
from django.urls import path from . import views app_name = 'Match' urlpatterns = [ # /Match/ path('match/', views.match, name='match'), path('matching/', views.matching, name='matching'), ]
class Queue(object): def __init__(self): self.items = [] def enqueue(self, item): self.items.insert(0, item) def dequeue(self): return self.items.pop() def is_empty(self): return self.items == [] def size(self): return size(...
import pymongo, csv from bson.objectid import ObjectId import datetime client = pymongo.MongoClient('mongodb://trendr01:letmeconnect@ds047988-a0.mongolab.com:47988/weareplayingit') db = client.weareplayingit #This is the genres to search, in case you want to make this a callable function genres = ["FPS","Shooter"] #...
from django.db import models class Network(models.Model): number = models.CharField( max_length=35, verbose_name=u'Номер сети') class Meta: verbose_name = 'Защищенная сеть' verbose_name_plural = 'Защищенные сети' def __str__(self): return f'{self.number}' class ...
from random import randint import matplotlib.pyplot as plt stepsList = [] xnList = [] listOfR = [] def atomsMove(xn, L): for atom in range(0,L): x = 0 y = 0 for item in range(1, xn): R =randint(0, 4) if R == 0: x = x + 1 elif R == 1: ...
#!/usr/bin/env python """ Usage: qc-spikecount <nifti> <output> <bval> nifti -- input 4D nifti image (fMRI or DTI) output -- output .csv file bval -- bval file (for DTI) Calculates the mean and standard deviation of each axial slice over all TRs. Counts the number of outliers across all slices, and pr...
""" input returns dictionary mapping word to it's occurence value "olly olly in come free" returns { olly:2, in:1, come:1, free:1 } """ def dictionary(sentence): number = 0 lists = sentence.split(" ") store= {} for i in lists: number = lists.count(i) store[i] = number return sto...
import requests import time import json TOKEN_VK_api = '958eb5d439726565e9333aa30e50e0f937ee432e927f0dbd541c541887d919a7c56f95c04217915c32008' class Backup_Data: def __init__(self, id, token, num): self.id = id self.token = token self.header = {'Content-Type': 'application/json', ...
class ElectronicDeviec: feature = ["High Performance","Non-Portable"] class PocketGadget(ElectronicDeviec): features = ["Low Performance","Portable"] def ft(self): return f"{self.feature[0]} and {self.feature[1]}" class Phone(PocketGadget): AverageFeature = ["Medium Performance","Portable"] B...
from django import forms from gifts.models import GiftSubscription class GiftSubscriptionForm(forms.Form): gifter = forms.EmailField(label="Your e-mail") giftee = forms.EmailField(label="Recipient's e-mail")