text
stringlengths
8
6.05M
def isAnagram(test, original): """ is_anagram == PEP8 (forced mixedCase by CodeWars) """ return sorted(a for a in test.lower() if a.isalnum()) \ == sorted(b for b in original.lower() if b.isalnum())
import hashlib import os import requests import exifread from pathlib import PurePath from datetime import datetime url = 'http://192.168.0.114:8880/photos/' sourceDir = 'BookLive/Public/Shared Pictures/Scan' destDir = '/volume1/photo' def hash_file(filename): """"This function returns the SHA-1 hash of th...
from skimage import io from skimage.transform import downscale_local_mean from skimage.filters import threshold_sauvola as threshold from skimage.segmentation import clear_border, random_walker from skimage.measure import label, regionprops from skimage.morphology import binary_opening, square, remove_small_objects fr...
#!/usr/bin/env python import math import rospy from myturtle.srv import * from nav_msgs.msg import Odometry class LandmarkMonitor(object): def __init__(self): self._benda = { "Cube":(0.31,-0.99), "Dumpster":(0.11,-2.42), "Cylinder":(-1.14,-2.88), "Barrier":(-2.59,-0.83), "Bookshelf":(-0.09,0.53) ...
# https://github.com/hflabs/dadata-py from dadata import Dadata token = "" # Токен с сервиса DaData secret = "" # Секретный ключ с сервиса DaData def check(name,query): dadata = Dadata(token, secret) # Данные для авторизации в сервисе DaData infoCompany = dadata.find_by_id(name, query) # Поиск информации о ...
s = 0 v = 0 for c in range(1, 7, 1): n = int(input(f'Digite o {c}° valor: ')) if n % 2 == 0: s += n v += 1 print(f'A soma de todos os {v} valores vale {s}')
import urllib.request # 웹브라우저에서 html문서를 얻어오기 위한 모듈 from bs4 import BeautifulSoup # html문서 검색 모듈 import os from selenium import webdriver # 웹 애플리케이션의 테스트를 자동화하기 위한 프레임 워크 from selenium.webdriver.common.keys import Keys import time filename = '학사공지' chrome = 'c:\\data\\chromedriver.exe' browse...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2018-07-09 22:37:34 # @Author : Your Name (you@example.org) # @Link : http://example.org # @Version : $Id$ import os class Solution: def intersection(nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: List[int] """ set1 ...
#!/usr/bin/env python """Test suite for the ``accuracy`` module""" import numpy as np from pytest import raises from accuracy import accuracy def test_error_length(): y_pred = np.array([False, True, True]) y_true = np.array([True, False]) raises(AssertionError, accuracy, y_pred, y_true) def test_basic(...
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author:hua # !/usr/bin/env python # -*- coding:utf-8 -*- # Author:hua from flask import Flask, jsonify from flask import request from scipy.stats import ttest_ind app = Flask(__name__) # 接口路由地址 @app.route('/sklearn', methods=['POST']) def index(): import numpy as np...
#!/usr/bin/python import time import numpy as np import sys #tos stuff from DecodedMsg import * from tinyos.message import MoteIF class MyClass: def __init__(self,N): self.prevtime = time.time() self.N = N self.A = make_A_matrix(self.N) self.counter = 0; self.perform_svd = 0; # Create a MoteIF self.mi...
""" Description: Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if: Open brackets must be closed by the same type of brackets. Open brackets must be closed in the correct order. NOTE: An empty string is also consi...
#专门做小写字母 import pandas as pd from Bio import SeqIO ​ ​ df=pd.read_excel('ldes/sample4.xlsx') stseq=[] site=[] nn = 0 ​ for row in df.itertuples(): aimid = row[1] aimseq = row[3] if (aimseq.find('c')>-1) and (aimseq.find('h')==-1): a=aimseq.find('c') b=len(aimseq)-a c=aimseq.upper() ...
# -*- coding: utf-8 -*- """ #define X 0 #define Y 1 #define Z 2 __device__ __forceinline__ void add3d_local(float *a_local, float *b) { a_local[X] += b[X]; a_local[Y] += b[Y]; a_local[Z] += b[Z]; } """ import numpy as np import pycuda.driver as drv import pycuda.autoinit from pycuda.compiler import Sour...
class Demo: def __init__(self, v1=11, v2=22): self.__a = v1 self.__b = v2 def get_a(self): return self.__a def get_b(self): return self.__b def set_a(self, value): self.__a = value def set_b(self, value): self.__b = value def do_something(self): return self.__a + self.__b ...
def communication_module(packet): p1 = int(packet[8:12]) p2 = int(packet[12:16]) a = {'0':p1+p2, 'B':p1-p2, 'C':p1*p2} t = a[packet[4]] if t > 9999: t = str('9999') elif t < 0: t = str('0000') else: t = str(t) return packet[0:4] + 'FFFF' + str((4-len(t)) * '0')...
""" http://2018.igem.org/wiki/images/0/09/2018_InterLab_Plate_Reader_Protocol.pdf """ import json import sys from urllib.parse import quote import sbol3 from tyto import OM import labop import uml from labop.execution_engine import ExecutionEngine from labop_convert import MarkdownSpecialization def render_kit_coor...
from flask import Flask, render_template, request from flask_bootstrap import Bootstrap app = Flask(__name__) Bootstrap(app) @app.route('/') def index(): return render_template('index.html') @app.route('/query', methods = ['POST']) def query(): query = request.form['q'] # execute amazon asin read codes ...
class Inventory(object): def __init__(self, stuff=[]): self.items = [] self.equips = {0:0, 1:0, 2:0, 3:0, 4:0, 5:0, 6:0, 7:0, 8:0} # 1 equip slots: # 2 head # 3 torso/arms # 4 hands # 5 fingers # 6 weapon (stuff you actually hold) # 7 legs # 8 feet for i in stuff: self.items.append(i) def...
import scipy.io import numpy as np import matplotlib.pyplot as plt import aux_functions import EM file = scipy.io.loadmat('./observed.mat') X = file['observed'] N = np.shape(X)[0] # number of sequences 10 D = np.shape(X[0][0])[0] # dimension of sequences 6 T = np.shape(X[0][0])[1] # length of each sequence 100 ...
def solution(prices): answer = [0 for i in range(len(prices))] index = [] for i in range(len(prices)): for j in index.copy(): if prices[j] > prices[i]: answer[j] = i - j index.remove(j) if i == len(prices)-1: answer[j] = le...
from azureml.widgets import RunDetails RunDetails(run).show() run.wait_for_completion(show_output=True)
# Generated by Django 3.1.2 on 2020-11-06 15:51 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Episode', fields=[ ...
import csv ''' ESCREVE OS LUGARES places_file = open("/home/mateus/Documents/TESIIII/versao_final_en/places.txt", "r").read().splitlines() with open('/home/mateus/Documents/TESIIII/mydata.csv', 'w') as mycsvfile: writer = csv.writer(mycsvfile, quoting=csv.QUOTE_ALL) writer.writerow(["PLACES:"]) for pla...
""" Infix parsing with operator precedence (inefficient implementation). """ from parson import Grammar, recur, seclude, either, fail def PrececedenceParser(primary_expr, table): return foldr(lambda make_expr, subexpr: make_expr(subexpr), primary_expr, table) def LeftAssoc(*pair...
import datetime import pickle import os.path from googleapiclient.discovery import build from google_auth_oauthlib.flow import InstalledAppFlow from google.auth.transport.requests import Request import requests import json import os # If modifying these scopes, delete the file token.pickle. SCOPES = ['https://www.goog...
from .parse import parse_config
import multiprocessing import time testNUM = 0; def worker(interval,lock): n = 5; while n > 0: print("The time is {0}".format(time.ctime())); time.sleep(interval); n -= 1; testNUM += 1; print("testNUM is %d"%(testNUM)); if __name__ == "__main__": lock = multiprocess...
print('mod_1 loaded!') def mod_1_pr(): print('This is a function in mod_1!')
import numpy as np a = np.array([1, 2, 3], dtype = complex) print(a)
# -*- coding: utf-8 -*- import SocketServer from StringIO import StringIO from avro import schema from avro.datafile import DataFileReader from avro.io import DatumReader FILE_SCHEMA = schema.parse(open("../../avro/herring-box-data.avpc").read()) OUT_DIRECTORY = "backup/" fileDict = dict() class MyTCPHandler(Socket...
# Generated by Django 2.2.6 on 2019-11-25 08:37 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('work', '0041_auto_20191125_0813'), ] operations = [ migrations.RenameModel( old_name='Headline', new_name='Resolution', ...
import heapq import threading from six import BytesIO from six.moves import map import numpy from smqtk.algorithms.nn_index.hash_index import HashIndex from smqtk.representation import get_data_element_impls from smqtk.utils import merge_dict, plugin from smqtk.utils.bit_utils import ( bit_vector_to_int_large, ...
__author__ = 'Elisabetta Ronchieri' import commands import os from tstorm.utils import utils class Grep: def __init__(self, fn='/var/log/storm/storm-frontend-server.log'): self.ifn = fn self.cmd = { 'name':'grep' } self.ipt_strings = 'Cannot add or update a child ro...
# Generated by Django 3.2.7 on 2021-09-22 17:09 from django.db import migrations, models import uuid class Migration(migrations.Migration): dependencies = [ ('api', '0001_initial'), ] operations = [ migrations.RemoveField( model_name='targetfile', name='file_name...
""" calcular el factorial de un numero """ def factorial(n): if n==0: return 1 else: res=n for conta in range(1,n): res=res*conta return res print(factorial(0)) #1 print(factorial(1)) #1 print(factorial(3)) #6 print(factorial(5)) #120 print(factorial(9)) #362,8...
import pymysql pymysql.install_as_MySQLdb() # 默认情况下, sqlalchemy使用mysqldb连接数据库, python2中会安装mysqldb的包, python3中不会安装, 可安装pymysql, 里面切成mysqldb() from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String, ForeignKey DB_CONNECT_STRING = "mysql://root:mysql@127.0.0.1:3306/sqlalchemy_study" engine = crea...
#!/usr/bin/env python3 from ..lib import keyword_utils from ..feature_analyzer.casual_analyzer import get_chkval_cond ''' "causality": { "pre.call": { "func_name": { used_as_arg: false, share_argument: true, }, ... } "post.call": { "func_name": { ...
from typing import Tuple from torch import nn, Tensor from torch.nn import MultiheadAttention from parseridge.parser.modules.add_and_norm_layer import AddAndNormLayer from parseridge.parser.modules.data_parallel import Module class SelfAttentionLayer(Module): def __init__(self, model_size: int, num_heads: int, ...
import random aluno = [0, 1, 2, 3] for x in range(4): aluno[x] = input('Digite o {}º aluno: '.format(x + 1)) print('Foi sorteado(a) {}'.format(aluno[random.randint(0, 3)]))
#!/usr/bin/env python # coding: utf-8 # In[ ]: a = 1 def x(): return 2
from django.shortcuts import render from common.models import Injection, CRI, Prescription def info(request): """Displays all medications in the db.""" inj = Injection.objects.all() cri = CRI.objects.all() pre = Prescription.objects.all() return render(request, 'info/info.html', {'navbar': 'info...
# Generated by Django 2.1.5 on 2019-01-18 07:34 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('advertisement', '0004_auto_20190116_1354'), ] operations = [ migrations.RemoveField( model_name='advertisement', name='total...
# def add(am1, am2): # test_suite_matrix(am1, am2) # # length_outer = len(am1) # length_inner = len(am1[0]) # # result_matrix = [] # result_matrix = [[result_matrix for i in range(length_inner)] for j in range(length_outer)] # # for o in range(length_outer): # for i in range(length_inner...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Dec 10 16:26:36 2018 @author: andr """ import os from datetime import datetime, timedelta import numpy as np import matplotlib.pyplot as plt os.system("rm res_iter_coords.txt") with open('0943_fk_start.par', 'r') as file: lines = file.r...
''' Funciones ''' import math # Module file: funciones.py def detectaDiferenciaPosicion(p1, coords2): '''Calcula la distancia radial entre un''' puntoX, puntoY = coords2 if math.hypot((p1.x-puntoX),(p1.y-puntoY))<=p1.size: return 1 else: return 0 def sumaFuerzas(f1,f2): '''Sum...
import json import hashlib class My_iterator: def __init__(self, file_name: str): self.start = -1 with open(file_name, 'r', encoding='utf8') as file: self.countries = json.load(file) def __iter__(self): return self def __next__(self): self.start += 1 i...
from pico2d import * # C:\Users\enjcat\AppData\Local\Programs\Python\Python36\lib\site-packages\pico2d import game_framework import random import game_world import random import Wepon dicts = {0:Wepon.stick,1:Wepon.sword,2:Wepon.ice,3:Wepon.fire,4:Wepon.wand,5:Wepon.heal} class Tower: def __init__(self): ...
from urllib.request import urlopen from bs4 import BeautifulSoup html = urlopen("http://pythonscraping.com/pages/page1.html") def main(): """ Starting out with BeautifulSoup :return: """ obj = BeautifulSoup(html.read(), "lxml") print(obj.h1) return None if __name__ == "__main__": m...
import requests as r import json import time URL='http://127.0.0.1:8001/api/studios' def bodrder(): print("\n-----------------------") print('Просмотр всех записей;') print(r.get(URL).text) bodrder() print('Просмотр конкретной записи(успешно)') print(r.get(URL+'/7').text) bodrder() print('Просмотр конкретной запис...
#!/usr/bin/env python import numpy as np import cv2 import cv2.cv as cv from video import create_capture from common import clock, draw_str import facedetect as fd import Train_Common as tc help_message = ''' USAGE: facedRec_LBP.py [--cascade <cascade_fn>] [--nested-cascade <cascade_fn>] [--model-name <ModelName>] ...
#!/usr/bin/python3 import sys, socket, os, subprocess if sys.platform == 'linux-i386' or sys.platform == 'linux2' or sys.platform == 'darwin': SysCls = 'clear' symlink = 'ln -s / 1.txt' pwd = ('pwd') create = ('mkdir sym') cd = ('cd sym') passwd = ('ln -s /etc/passwd passwd.txt') print "\n|--...
import pandas as pd i = 0 df = pd.read_excel("Puzzel 2.xlsx") # Clean Up df["Policy"] = df["Policy"].str.strip() df["Password"] = df["Password"].str.strip() # Convert columns from Object to String df['Policy'] = df['Policy'].convert_dtypes() df['Password'] = df['Password'].convert_dtypes() # Getting ...
from flask import Flask, request, jsonify, make_response from PIL import Image import PIL from flask_cors import CORS, cross_origin from io import BytesIO import base64 import pretrained_example app = Flask(__name__) cors = CORS(app) app.config['CORS_HEADERS'] = 'Content-Type' @app.after_request def after_request...
# Generated by Django 2.2 on 2019-04-12 15:35 from django.db import migrations, models import django.db.models.deletion import yohbiteapp.models class Migration(migrations.Migration): dependencies = [ ('yohbiteapp', '0008_driver_location'), ] operations = [ migrations.CreateModel( ...
from sklearn.cluster import KMeans from sklearn import manifold import matplotlib.pyplot as plt import numpy as np from sentence_transformers import SentenceTransformer model = SentenceTransformer('paraphrase-TinyBERT-L6-v2') n_clusters = 20 # Read file and make embedding f = open('../final.txt', 'r') words = [] whi...
import SimpleITK as sitk def printst(step,flow_field_x1, ed_source, flow_field_x2, es_source): # pt = source[0, 0, :, :, :].data.cpu().numpy() # # pt = np.transpose(pt, (2, 1, 0)) # out = sitk.GetImageFromArray(pt) # out.SetSpacing((1.00, 1.00, 1.00)) # sitk.WriteImage(out, './state/source' + str(...
# a=['banana','apple','microsoft'] # for i in a: # print(i) # b=[20,10,5] # for j in b: # print(j) # s=0 # for i in b: # s+=i # print(s) # c=list(range(1,5)) # print(c) s=0 for i in range(1,5): s+=i print(s) s1=0 for i in range(1,8): if i%3==0: s1+=i print(s1)
for total_budget in range(1, 11): fileresult = [[], [], []] for setting in range(2, 3): if setting == 1: data_name = "email" product_name = "prod_r1p3n1" num_ratio, num_price = 1, 3 elif setting == 2: data_name = "email" product_name = ...
#This is challenge # define a function take any no of list containing number l1,l2,l3=[1,2,3], [4,5,6],[7,8,9] #return average #(1+4+7)/3,(2,5,8)/3,(3,6,9)/3 # try to make this anonymous function in one line using lambda #def func(*args): # promedios=tuple(map(lambda x: sum(x)/len(x),args)) # return promedios #prin...
def conjugate(verb, pronoun, tense): verbs = ["ayudar", "bailar", "buscar", "comprar", "dibujar", "escuchar", "estar",
from django.conf.urls.defaults import * urlpatterns = patterns('devices.views', (r'^$', 'index'), (r'^(?P<device_id>\d+)/wipe/$', 'wipe'), (r'^(?P<device_id>\d+)/trackfrequency', 'update_track_frequency'), (r'^(?P<device_id>\d+)/send/$', 'send_c2dm'), )
import os, sys, time, copy, datetime from flask import Flask, render_template, request, jsonify, current_app import argparse import subprocess import pytesseract import json import wget import time from detect_rectangle import detect_rect from barcode import readBar from detect_region import detect_region from detect...
class VolSmileData: def __init__(self, pillar_date, rd, rf, vols): self.pillar_date = pillar_date self.rd = rd self.rf = rf self.vols = vols # Sticky Strike class VolSurfaceData: def __init__(self, underlying_name, market_date, spot_date, spot, strikes, smiles): self.und...
#set of character actions for game play import random def say(noun): return 'You said "{}"'.format(noun) def attacknow(noun): ca=char_actions.character("Pauly","Elf") return ca.attack("Elf")
# Copyright (c) 2020 Adam Souzis # SPDX-License-Identifier: MIT """ Classes for managing the local environment. Repositories can optionally be organized into projects that have a local configuration. By convention, the "home" project defines a localhost instance and adds it to its context. """ import os import os.pat...
# -*- coding: utf-8 -*- import importlib.util spec = importlib.util.spec_from_file_location("piepompt.part", "/home/markl/.config/pieprompt/hipart.py") foo = importlib.util.module_from_spec(spec) spec.loader.exec_module(foo)
import numpy as np import cv2 from scipy.ndimage.filters import convolve from scipy.spatial.distance import cdist from cv2.ximgproc import guidedFilter def Guided(I, p, r, eps): return guidedFilter(I, p, r, eps) def GuidedOptimize(G, P, r, eps): N = len(G) W = [] for i in range(N): # MOS...
import pymysql from logger import Logger class PyMQLHelper: """ PyMySQL帮助类 """ def __init__(self, db_address: str, db_username: str, db_password: str, db_name: str): try: self.__connection = pymysql.connect(db_address, db_username, ...
# -*- coding: utf-8 -*- import itertools from typing import List class Solution: def runningSum(self, nums: List[int]) -> List[int]: return list(itertools.accumulate(nums)) if __name__ == "__main__": solution = Solution() assert [1, 3, 6, 10] == solution.runningSum([1, 2, 3, 4]) assert [1,...
#!/usr/bin/python3 name = input("hello please input your name:") print("hello",":"+name)
from time import sleep def rowinput(row): # Inputting rows. Invoked in sudinput(). try: rowlist = [int(i) for i in str(row)] assert len(rowlist) == 9 return rowlist except: rowinput(input("Invalid input. Try again: ")) def sudinput(): # Creation of 9 rows and...
#!/usr/bin/python import sys import codecs from pyarmory import char # usage if len(sys.argv) < 3: print sys.argv[0] + " [zone] [realm] [character name]" print print "Example: " + sys.argv[0] + " eu Zuluhed Ixell" exit() # open output file rep.<region>.<realm>.<char>.py filename = "rep." + sys.argv[...
#Enhancement import cv2 img=cv2.imread('sal.png') clahe=cv2.createCLAHE t=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) cv2.imshow('save.png',t) if cv2.waitKey(0) & 0xFF == ord('q'): cv2.destroyAllWindows()
from kivy.app import App from kivy.uix.boxlayout import BoxLayout class AnmeldenWindow(BoxLayout): def __init__(self, **kwargs): super().__init__(**kwargs) def validate_user(self): user = self.ids.username_field pwd = self.ids.pwd_field info = self.ids.info uname = use...
#Write a Python program to convert temperatures to and from celsius, fahrenheit. Go to the editor #[ Formula : c/5 = (f-32)/9 [ where c = temperature in celsius and f = temperature in fahrenheit ] #Expected Output : #60°C is 140 in Fahrenheit #45°F is 7 in Celsius #32 + 9*c/5 = f c = 60 f = 32 + 9 * c/5 print(f)...
from django.conf.urls import url, include from django.urls import path from rest_framework.routers import DefaultRouter from .views import FileUploadAPIView, FileUploadOldVersionAPIView urlpatterns = [ # --Общая характеристика path('api/isu_v1/upload/csv/', FileUploadOldVersionAPIView.as_view()), ]
import time import numpy as np import matplotlib.pyplot as plt import scipy import predictionData import functions test_x = predictionData.inputData[:, 4000:4600] test_y = predictionData.outputData[:, 4000:4600] print(np.shape(test_y)) initial_val = test_x[:, 1] def MovingAverage(inputArray): #we...
import os from keras.preprocessing.text import Tokenizer from keras.preprocessing.sequence import pad_sequences import numpy as np from keras.models import Sequential from keras.layers import Embedding, Flatten, Dense, LSTM, Dropout from keras import layers import pickle from myUtility import preprocessImdb ...
# Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ # number on...
"""Core middlewares.""" from django import http from django.urls import reverse from django.utils.deprecation import MiddlewareMixin from . import models class LocalConfigMiddleware(MiddlewareMixin): """A middleware to inject LocalConfig into request.""" def process_request(self, request): """Injec...
""" Logic for dashboard related routes """ from flask import Blueprint, render_template,redirect,url_for,flash from .forms import LogUserForm, secti,masoform,TestForm,HryForm,VyvojarForm from ..data.database import db from ..data.models import LogUser,Emaily,Hry,Vyvojari blueprint = Blueprint('public', __name__) @blue...
import unittest '''test_dir="./tudou" suits=unittest.defaultTestLoader.discover(test_dir,pattern="test*.py") if __name__=="__main__": runner=unittest.TextTestRunner() runner.run(suits)''' class Mytest(unittest.TestCase): @unittest.skip def test_skip(self): print("aaa") @unittest.skipIf(3>2...
from collections import Counter from nltk.tokenize import word_tokenize import nltk import itertools import numpy as np from syntatic.parsing import * import cPickle as pickle ## Find unique tokens in the corpus and returns token dictionary def create_unigram_tokens(corpus, corpus_frequencies_filename = None): freqs...
# -*- coding: UTF-8 -*- # 列表生成式 列表生成器里面可以用函数 yield def f(n): return n * n print([f(x) for x in range(10)]) # 列表 元组等可以一次性取出赋值 a ,b , c = (1,2,3) 此时 a b c 三个值分别等于 1 2 3
# Implementation borrowed from https://github.com/gvishal/rank_text_cnn # MAP and MRR metrics for learning to rank results evaluation from collections import defaultdict import numpy as np from sklearn import metrics def ap_score(cands): """ Calculates average precision score for all candidates cands. ...
# -*- coding: utf-8 -*- from django.conf.urls import url from admina import views urlpatterns = [ url(r'^index$', views.index), url(r'^check_news$', views.check_news), url(r'^add_admin$', views.add_admin), url(r'^check_admin$', views.check_admin), url(r'^col_page1$', views.col_page1), url(r'^c...
from django.shortcuts import render, HttpResponse from api.libs.base import CoreView from account.models import UserProfile from django.contrib.auth.models import User from django.contrib.auth.models import Group from django.db.utils import IntegrityError # Create your views here. class Account(CoreView): """ ...
#-*- coding:utf-8 -*- #这是api 1.0版 from flask import Blueprint api=Blueprint('api',__name__) from . import authentication,posts,users,comments,errors
def half_fib(n): if n == 1 or n == 2: return 1 else: sum = (half_fib(n - 1) + half_fib(n - 2)) % 1000000007 if n % 3 == 0: return sum - 1 else: return sum FIVE_SQUARED = 5 ** 0.5 FI = (1 + FIVE_SQUARED) / 2 PSI = (1 - FIVE_SQUARED) / 2 def half_fib2(n): ...
from autodisc.systems.statistics.observationdifference import ObservationDifferenceStatistic
from abc import ABC, abstractmethod from pathlib import Path from typing import Dict, List, Optional, Union import json import jsonschema from flint import LintContext, Lintable JSON = Dict[str, Union[str, int, List["JSON"], "JSON"]] JsonPathElement = Union[str, int] class JsonRule(ABC): """ A linting ru...
import time import random import numpy as np import pandas as pd import math import sys import os.path import matplotlib import matplotlib.pyplot as plt TTABLE_IDX_ACTIONS_COUNT = 1 TTABLE_IDX_TABLE = 0 class TreeData: def __init__(self): # solver params self.LEARNING_RATE = 0.01 ...
M, D = input().split() print("yup" if (M == "OCT" and D == "31") or (M == "DEC" and D == "25") else "nope") if M == "sdfoijsdfoij": print("LOL this isn't correct") k = {} k["sdf"] = 5 print(K["sd"])
import datetime import json import os import uuid import tornado.escape import tornado.ioloop import tornado.web import tornado.websocket class ChatWebSocket(tornado.websocket.WebSocketHandler): clients = [] def open(self): print("websocket opened") self.ID = str(uuid.uuid4()) self.n...
# Generated by Django 2.2.13 on 2020-07-10 05:58 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('shop', '0031_auto_20200710_1127'), ] operations = [ migrations.AlterField( model_name='contactmessage', name='title...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This module plots hloc data. """ import os import argparse import pandas as pd import matplotlib.pyplot as plt from matplotlib.finance import candlestick2_ohlc, volume_overlay import logger class PlotChart(object): """ This class plot the hloc btc data. ...
import time from dnsdumpster.DNSDumpsterAPI import DNSDumpsterAPI from simplydomain.src import core_serialization from simplydomain.src import module_helpers from simplydomain.src import core_scrub # use RequestsHelpers() class to make requests to target URL class DynamicModule(module_helpers.RequestsHelpers): ...
import msvcrt import playsound while True: if msvcrt.kbhit(): key = msvcrt.getch() #print(key) # just to show the result if (key == b'\r' or key == b'\n' or key == b'\r\n' or key == b'\n\r'): playsound.playsound('./sound.mp3', True) print(key)
# -*- coding: utf-8 -*- import os import requests from tqdm import tqdm def download(src, url): file_size = int(requests.head(url).headers['Content-Length']) header = { 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/' '70.0.3538.67 Safa...