text
stringlengths
38
1.54M
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'WindowUI.ui' # # Created by: PyQt5 UI code generator 5.13.0 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_MainWindow(object): def setupUi(self, MainWindow): MainW...
from django.shortcuts import render, redirect # Create your views here. from test_view.forms import ContactForm from django.views.generic.edit import FormView class ContactView(FormView): template_name = 'test_view/contact.html' form_class = ContactForm # success_url = 'test_view/posted.html' ...
from nltk.tokenize import sent_tokenize, word_tokenize import nltk from gutenberg.cleanup import strip_headers import re import heapq # ref: https://stackabuse.com/text-summarization-with-nltk-in-python/ class Summarization(object): # local variables textSummary = "" def __init__(self, text): # pa...
print('This program is all about for loop itration') for a in '12345': print(a) for b in "hana afsal": print(b) c=10 d=11 for x in [1, 2, 3, 4]: for y in [2, 3, 6, 7]: # for getting coordinates print(f"({x+1}, {y+10})") # print formatted string for z in [[1, 2, 3], [8, 7, 6], [1, 5, 4, 2...
import pandas import numpy as np import random from nltk.corpus import stopwords from nltk.tokenize import word_tokenize from nltk.stem import PorterStemmer import string from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfTransformer from sklearn.feature_selecti...
X = input() def check(s): if s == "": return True if s[0] in "oku": return check(s[1:]) if s[:2] == "ch": return check(s[2:]) return False if check(X): print("YES") else: print("NO")
# -*- coding:utf-8 -*- from helper import singleton @singleton class Configer: a = 0 def make_redis_config(self, config): a = config pass if __name__ == '__main__': c1 = Configer() c1.a = 10 print c1.a c2 = Configer() print c2.a
#Django code: import json def save_data(request): if request.method == 'POST': json_data = json.loads(request.body) # request.raw_post_data w/ Django < 1.4 try: data = json_data['data'] except KeyError: HttpResponseServerError("Malformed data!") HttpResponse("Got json data") def save_ev...
#Imports the class information from the cashRegister class import CashRegister ADD_MONEY = "a" REMOVE_MONEY = "r" TRANSFER_MONEY = "t" LOCK_REGISTER = "l" UNLOCK_REGISTER = "u" DISPLAY_STATE = "s" CLOSE_STORE = "c" OPTION_LIST = [ADD_MONEY,REMOVE_MONEY,TRANSFER_MONEY,LOCK_REGISTER,UNLOCK_REGIST...
import numpy as np import pyccl as ccl import pytest BEMULIN_TOLERANCE = 1e-3 BEMUNL_TOLERANCE = 5e-3 BEMBAR_TOLERANCE = 1e-3 def test_baccoemu_linear_As_sigma8(): bemu = ccl.BaccoemuLinear() cosmo1 = ccl.Cosmology( Omega_c=0.27, Omega_b=0.05, h=0.67, sigma8=0.83, n_s...
import os import torchvision.transforms as transforms import torchvision.datasets as datasets from torch.utils.data import DataLoader class Data: def __init__(self, args): pin_memory = False if args.gpus is not None: pin_memory = True scale_size = 299 if args.student_model.star...
path('persona/new', views.new_persona, name='create_persona'), nombre = models.CharField(max_length=30) apellido = models.CharField(max_length=30) tipodocumento = models.IntegerField(max_length=1) documento = models.IntegerField(max_length=15) residencia = models.CharField(max_length=100) ...
#!/usr/bin/python f = open('A-large.in', 'r') o = open('output', 'w') T = f.readline() S = "" out = "" def insertRight (letter): global out out += letter def insertLeft (letter): global out for x in range(len(S), 0): out[x+1] = out[x] out = letter + out[0:] for x in range(1, int(T)+1): S = f.next() out ...
#Finding an Observation's Nearest Neighbors #load libraries from sklearn import datasets from sklearn.neighbors import NearestNeighbors from sklearn.preprocessing import StandardScaler #load data iris = datasets.load_iris() features = iris.data target = iris.target #create standardScaler standardscaler = StandardScal...
from mrjob.job import MRJob class MRSpentByCustomers(MRJob): def mapper(self, _, line): (custid,itemid,amount) = line.split(',') yield custid,float(amount) def reducer(self,custid,amounts): yield custid, sum(amounts) if __name__ == '__main__': MRSpentByCustomers.run()
from utilities.config import db_config, finnhub_config, MAX_TRY from utilities.postgres_utils import cursor, connection from utilities.finnhub_utils import finnhub_connection from utilities.stringio_utils import buildStringIO from logging_conf import MyLogger from datetime import timezone, date, timedelta, datetime fro...
#coding:utf-8 from flask import jsonify ,request from . import api import json import os from random import randint @api.route('/eatwhat/', methods = ['GET']) def eatwhat(): items = ['东一', '东二', '学子', '桂香园', '博雅园', '外卖'] item = items[randint(0, 5)] return jsonify({ "location": item })
def solution(K, A): # write your code in Python 3.6 if len(A)<1: return 0 count=0 cLength=0 for i in A: cLength+=i if cLength>=K: cLength = 0 count +=1 return count
class Solution(object): def addBinary(self, a, b): """ :type a: str :type b: str :rtype: str 给定两个二进制字符串,返回他们的和(用二进制表示)。 输入为非空字符串且只包含数字 1 和 0。 示例 1: 输入: a = "11", b = "1" 输出: "100" """ if len(a) < len(b): a, b = b...
from typing import List class Solution: def solve(self, board: List[List[str]]) -> None: """ Do not return anything, modify board in-place instead. """ if not board: return rows = len(board) cols = len(board[0]) dummy = rows * cols p = {dummy: dummy} for row in range(rows): ...
class OldPhone: __brand = '' def setBrand(self, brand): self.__brand = brand def getBrand(self): return self.__brand def call(self, name): print(f"正在给{name}打电话...") class NewPhone(OldPhone): def call(self, name): print("语音拨号中...") super()....
def get_node_pool_oauth_scopes(oauth_scopes): oauth_scopes_list = [] for scope in oauth_scopes: oauth_scopes_list.append("https://www.googleapis.com/auth/" + scope) return oauth_scopes_list def generate_node_pools(cluster_properties): node_pools_properties = cluster_properties.get("nodePools")...
#!/usr/bin/env python from setuptools import setup from cron_conf import __version__ setup( name='cron_conf', version=__version__, description='Cronf conf', author='Sogeti AB', author_email='supportwebb@sogeti.se', classifiers=['License :: Other/Proprietary License'], url='https://github.c...
from django.db import models from model_utils.models import TimeStampedModel from api.models import Fleet, User, Machinery, Site from api.models.tools import Tool class FleetHistory(TimeStampedModel): history_type_choices = ( ('assignment', 'Assignment'), ('broken_down', 'Broken Down'), (...
# ------------------------------------------------------------ # Copyright (c) 2017-present, SeetaTech, Co.,Ltd. # # Licensed under the BSD 2-Clause License. # You should have received a copy of the BSD 2-Clause License # along with the software. If not, See, # # <https://opensource.org/licenses/BSD-2-Clause> # # ...
# Generated by Django 3.1.2 on 2020-10-26 13:10 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='CoAuthorship', fields=[ ('id', models.AutoF...
#!/usr/bin/env python3 from git import Repo import re import DingTalk import sys import os def getLastCommit(path): if not os.path.exists(path): return with open(path, 'r') as f: content =f.read() #re.match(r'^DVTSourceControlLocationRevisionKey$', content) result = re.findall(...
import matplotlib.pyplot as plt import numpy as np dense_path_length = np.loadtxt("dense_path_lengths.txt") p5_rf1_path_length_matrix = np.loadtxt("p5/RF1_pl_matrix_lmbda1.txt") p5_rf2_path_length_matrix = np.loadtxt("p5/RF2_pl_matrix_lmbda1.txt") p5_rf3_path_length_matrix = np.loadtxt("p5/RF3_pl_matrix_lmbda1.txt") ...
from django.test import TestCase from django.test import Client import json from applications.images.factories import ImageFactory from applications.images.models import Image class TestImagesApi(TestCase): def setUp(self): self.client = Client() super(TestImagesApi, self).setUp() def test_i...
# 2019/09/16 n=int(input()) a=sorted(list(map(int,input().split()))) cnt=0 res=set() for e in a: if e%2==0: while not e&1: e>>=1 res.add(e) print(len(res)) # ↓高速でうごくの見つけた # ABC019C - 高橋くんと魔法の箱 n=int(input()) a=list(map(int,input().split())) res=set() for i in a:...
# coding=UTF-8 from django.forms.fields import CharField, SlugField from django.forms.forms import Form from django.forms.models import ModelForm from JJEhr.lesson.models import Course class AddCourseForm(ModelForm): class Meta: model = Course class UpdateCourseForm(ModelForm): class Meta: ...
# Generated by Django 3.2.6 on 2021-08-28 12:49 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('accounts', '0004_auto_20210828_1758'), ] operations = [ migrations.AlterField( model_name='account', name='is_active...
# -*- coding: utf-8 -*- # K-Nearest Neighbors (K-NN) ## Importing the libraries import numpy as np from numpy import savetxt import matplotlib.pyplot as plt import pandas as pd import os from os import path import pickle model_name = 'k_nearest_neighbors' data_name = 'Breast_cancer_data' """## Training the K-NN mode...
''' Name & Student ID: Conall McCarthy, ********* Date: 20/02/18 Description: Assignment 11, Write a program that takes a file with each line being a row of a unsolved sudoku puzzle, create a board, solve the sudoku puzzle using 2 functions (1. solveBoard and 2. isValidMove) and print out a formatted board. 1.solveBoa...
class Solution: def maxProfit(self, prices: List[int]) -> int: @cache def dp(i:int) -> Tuple[int,int]: """Returns 1. Max profit after ith day. No stock hold, can buy. 2. Max balance after ith day. Holding a stock, can sell""" if i < 0: return 0, -10**9 ...
import inspect import numpy import sklearn.metrics from sklearn.preprocessing import LabelBinarizer class BaseCalculator(object): mapping = {} def __init__(self, clf, X_test, y_test, *args, **kwargs): self.clf = clf self.X_test = X_test self._binarizer = LabelBinarizer() self...
import unittest import wethepeople as wtp from wethepeople.objects import PetitionResponse, SignatureResponse from wethepeople.objects import Petition, Signature # No requests are made for this, this just silences the ua warning # These Tests make sure that Nationstates obj keeps concurrent all object values class...
from domains.domainConstructors import SimpleMDP def blockWorld(numOfBlockes, numOfSlots, initConfig, goalConfig): return SimpleMDP()
from django.urls import path from .views import home, general, tecnologia, programacion, videojuegos, tutoriales, signup urlpatterns = [ path('', home, name="index"), path('general/', general, name='general'), path('tecnologia/', tecnologia, name='tecnologia'), path('programacion/', programacion, name=...
from django.db import models from django.contrib.auth.models import Group from django.contrib.auth import get_user_model from django.contrib.auth.hashers import make_password from django.db.models.signals import post_save from django.dispatch import receiver User = get_user_model() # 3rd party import from PIL...
import gym import matplotlib import numpy as np from collections import defaultdict from BlackjackEnv import BlackjackEnv import plotting import sys if "../" not in sys.path: sys.path.append("../") def make_epsilon_greedy_policy(Q, epsilon, nA): def policy_fn(observation): A = np.ones(env.nA) * epsilon / nA ...
# -*- coding: utf-8 -*- """ Author: zero Email: 13256937698@163.com Date: 2019-11-01 """ import tushare as ts from thctools import Technical ts.set_token('24c7a5d5b40cd5db779cbc888ba4516d4be3384c0cf897caeaf2415b') pro = ts.pro_api() df = pro.query('daily', ts_code='603019.SH') df = df.rename(columns={'trade_date': 'd...
import subprocess import sys import requests import json import raidheroes_scraper as rs import discord_poster as dp import time boss_code_map = { 'Massive Kitty Golem': 'golem', 'Vale Guardian': 'vg', 'Gorseval the Multifarious': 'gorse', 'Sabetha the Saboteur': 'sab', 'Slothasor': 'sloth', 'M...
from PNS import * #--- Create unmyelianted axon first # Unmyelinated axon initialization parameter bunch initBunch = Bunch() initBunch.fiber_diam = 0.5 #[um] initBunch.rho_a = 100.0 # axioplasmic resistivity [ohm-cm] initBunch.rho_e = 500.0 # extracellular resistivity [ohm-cm] initBunch.cm = 1.0 #...
# -*- coding: utf-8 -*- # @Time : 2019/11/20 10:17 # @Author : zxl # @FileName: test.py import pandas as pd import numpy as np arr=np.array([1,2,3,4]) b=np.reshape(arr,newshape=(-1,1)) print(arr) print(b)
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'Setting.ui' # # Created by: PyQt5 UI code generator 5.11.3 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_Setting(object): def setupUi(self, Setting): Setting.setObj...
# -*- coding: utf-8 -*- class Welcome_Meli(): lbl_titulo_id = "com.mercadolibre:id/home_onboarding_step_title" lbl_subtitulo_id = "com.mercadolibre:id/home_onboarding_step_subtitle" texto_mensaje_1 = "Libera tus ideas" texto_subtitulo_1 = "Estás en el lugar perfect...
def base_site(request): """ Inject few template variables that we need in base template. """ from django.conf import settings context = {} context['STATIC_URL'] = '/static/' context['BASE_SIDEBAR'] = 'yui-t2' if hasattr(settings, 'STATIC_URL'): context['STATIC_URL'] = settings....
# as always we start with importing the libraries that we are going to need # brandonrose.com/clustering import re, nltk from pandas import DataFrame import numpy as numpy # to conduct the analysis we are going to need afew other libraries from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.metri...
from algorithm import quick_sort data = [5, 8, 3, 9, 0, 3, 6, 7] print(data) n_ops = quick_sort.sort(data) print(data) print("n_ops: %d" % (n_ops))
#! /usr/bin/env python from __future__ import print_function, division from collections import defaultdict from copy import copy """ 1. input color of current tile (0 = black, 1 = white) (all tiles start black) 2. program outputs color to paint tile (0 = black, 1 = white) 3. program outputs direction to turn (0 = 90d...
import numpy as np # linear algebra import os import scipy.ndimage import matplotlib.pyplot as plt import SimpleITK as sitk from skimage import measure, morphology from scipy.ndimage.morphology import binary_dilation,generate_binary_structure import pydicom as dicom def load_scan(path): #slices = [dicom.read_file(pat...
def is_float(value): try: float(value) return True except: return False def str2pair(x): nums = x.split(',') if (is_float(nums[0])): peso = float(nums[0]) llegada = int(nums[1]) return peso, llegada def LeeGrafo(filename): G = [] file = open(filename) for li...
__author__ = 'Daoyuan' from BaseSolution import * import math class PerfectSquares(BaseSolution): def __init__(self): BaseSolution.__init__(self) self.fuckinglevel = 9 self.push_test( params = (9453,), ) self.push_test( params = (9975,) ) ...
""" cache spacy @author: Carl Mueller """ from functools import partial from cachetools import cached, Cache from cachetools.keys import hashkey import spacy @cached(Cache(1), key=partial(hashkey, 'spacy')) def load_spacy(model_name, **kwargs): """ Load a language-specific spaCy pipeline (collection of data, m...
# -*- encoding: utf-8 -*- # Shaolin's Blind Fury # # Copyright: Hugo Ruscitti # Web: www.losersjuegos.com.ar import pilas import enemigo import random import golpe class Estrella(enemigo.Enemigo): """Una estrella ninja que vuela intentando golpear al shaolin.""" def __init__(self, x, y, direccion, shaolin): ...
""" Reference: - Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun. Deep Residual Learning for Image Recognition. arXiv:1512.03385 [cs.CV] - Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun. Identity Mappings in Deep Residual Networks. arXiv:1603.05027 [cs.CV] - F: residual function - h: identit...
#!/usr/bin/env python # -*- coding: utf-8 -*- from stream import Stream from peg import * from grammar import Grammar
from twilio.rest import Client import os def schedule_message(message,number): account_sid = 'ACc0418760bcc77f170e9210571dd1073b' auth_token = '687af050011e5f8d04e13ca1ad96b79e' client = Client(account_sid, auth_token) number = str(number) message = client.messages.create( ...
__authors__ = 'Antonio Ritacco' __email__ = 'ritacco.ant@gmail.com' import numpy as np import torch.nn as nn import torch # from torch_geometric.data import Data from collections import defaultdict from torch.nn.modules.distance import PairwiseDistance from helpers import pairwise_distances import networkx as nx '...
""" Introduction of Tuples in python. * It is immutable in nature. * we can not change or add value of tuples * we defined in ( ) """ size = (2,4) """ size[1] = 23 (TypeError: 'tuple' object does not support item assignment)""" print(size[1])
import QSTK.qstkutil.qsdateutil as du import QSTK.qstkutil.tsutil as tsu import QSTK.qstkutil.DataAccess as da import numpy as nu import datetime as dt import matplotlib.pyplot as plt import pandas as pd import os class Portfolio: #def equities = [] #def allocations = [] def __init__(self, equities,...
1. Let _propKey_ be the result of evaluating |PropertyName|. 1. ReturnIfAbrupt(_propKey_). 1. Let _exprValueRef_ be the result of evaluating |AssignmentExpression|. 1. Let _propValue_ be ? GetValue(_exprValueRef_). 1. If IsAnonymousFunctionDefinition(|AssignmentExpressi...
import glob def read_files(): folders = ["binarytrees", "binarytreesredux", "chameneousredux", "redux", "fasta", "fastaredux", "Include", "knucleotide", "mandelbrot", "meteor", "nbody", "regexdna", "revcomp", "spectralnorm", "threadring", "pidigits"] # "...
from django.shortcuts import render from django.views.generic import TemplateView, ListView,ListView, DetailView,View class OpenWeatherView(TemplateView): template_name = "weather.html"
import string, re class EncryptionMonitor: ''' Class for Encryption Monitoring based on dm-crypt ''' encryption = {'is_encrypted':"", 'cipher':""} def __init__(self): self.server = '150.162.63.32' def get_encryption_info(self): #Ubuntu default log_pat...
# Copyright Contributors to the Amundsen project. # SPDX-License-Identifier: Apache-2.0 from flask import current_app as app from amundsen_application.models.user import load_user, User TEST_USER_ID = 'test_user_id' def get_test_user(app: app) -> User: # type: ignore user_info = { 'email': 'test@email....
import boto3 import botocore def get_ddb_client(): dynamodb = boto3.resource('dynamodb', 'us-west-2') table = dynamodb.Table('agg_count') return table def process_image(ddb, name, image): key = { 'Id': image['Id']['S'], } if name == 'INSERT': update_expression = 'SET alert_co...
# -*- encoding: UTF-8 -*- ############################################################################## # # Odoo, Open Source Management Solution # Copyright (C) 2015-Today Laxicon Solution. # (<http://laxicon.in>) # # This program is free software: you can redistribute it and/or modify # it under the t...
#!/usr/bin/env python __name__ = 'fconv_txt2gti' __author__ = 'Teruaki Enoto' __version__ = '1.00' __date__ = '2018 June 7' import os import sys import astropy.io.fits as pyfits from optparse import OptionParser from datetime import datetime parser = OptionParser() parser.add_option("-i","--inputfile",dest...
import os import csv csv_data1 = os.path.join('raw_data','election_data_1.csv') with open(csv_data1,'r') as csvfile: csvreader1 = csv.reader(csvfile,delimiter=',') for row in csvreader1: totalVotes = sum(1 for row in csvfile) - 1 if row[2] = Roger: totalRoger = count if...
# irgend nen zeugs importieren from __future__ import division import nltk, re, pprint from nltk import word_tokenize # oeffne Textdatei f = open('test.txt', 'rU') # lese Textdatei raw = f.read() # txt umwandeln damit nltk damit arbeiten kann tokens = nltk.word_tokenize(raw) text = nltk.Text(tokens) # nltk methode ...
# Generated by Django 2.0.7 on 2018-07-16 23:51 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('guide', '0005_auto_20180716_2351'), ] operations = [ migrations.AlterField( model_name='jeu', name='genre', ...
from TN import * """ ####Algorithm ideas Orthogonal question: when to stop trying paths - when you can't find any more? Seems to use too many nodes - when there is a single failure? Seems to work, but still uses too many nodes - maybe s tries each neighbor once, then stops. Optimal performance looks not-so-good at...
# The only import you need! import socket, requests, re, random, time class TwitchBot: def __init__(self): # Options (Don't edit) self.SERVER = "irc.twitch.tv" # server self.PORT = 6667 # port # Options (Edit this) self.PASS = "oauth:Your Oauth" # bot password ...
from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker, aliased from sqlalchemy.orm.exc import NoResultFound from threading import Thread from werkzeug.exceptions import BadRequest from sqlalchemy.exc import IntegrityError from werkzeug.security import generate_password_hash,check_password_hash im...
""" Solution to Codeforces problem 282A Copyright (c) GeneralMing. All rights reserved. https://github.com/GeneralMing/codeforces """ n = int(input()) x = 0 for i in range(0,n): inp = str(input()) if('+' in inp): x = x+1 else: x = x-1 print(x)
# -*- coding: utf-8 -*- # Generated by Django 1.10.6 on 2017-03-03 16:27 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('shop_app', '0001_initial'), ] operations = [ ...
from __future__ import absolute_import, division, print_function, unicode_literals import tensorflow as tf from tensorflow import keras import tensorflow_datasets as tfds tfds.disable_progress_bar() import numpy as np print(tf.__version__) (train_data, test_data), info = tfds.load( # Use the version pre-encoded...
import numpy as np files = ['train_data.in', 'eval_data.in'] cnt = 0 for filename in files: with open(filename, 'r') as fin, open(filename + '.new', 'w') as fout: for line in fin: line = line.strip() fout.write('__label__{}'.format(cnt)) fout.write('\t') fo...
# ======================================================================================= # helpers/adapters.py # ======================================================================================= from . import morse_local_config as exp_settings from morse.builder import Component from morse.middleware.ros_reques...
import os import logging import argparse import json import cv2 import progressbar import numpy as np from keras.models import load_model import rle from unet import preprocess from ImageMaskIterator import ImageMaskIterator from PIL import Image from multiprocessing import Process, Queue def get_model_uid(model_file...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Feb 05 01:14:03 2017 @author: mheinl """ from google import search import requests, re, getopt, sys harvest = [] inputfile = '' outputfile = 'harvest.txt' googleSearchTerm = 'onion links' help = '\nUsage: onion_harvester.py [options]\n'\ 'Opti...
from selenium import webdriver from selenium.webdriver.chrome.options import Options import unittest class BaseTestFixture(unittest.TestCase): driver = None def setUp(self): print("Running SetUp") # declare chrome options chrome_options = Options() chrome_options.add_argumen...
# 키보드 제어, 마우스 제어, 편의점 주소 크롤링 from selenium import webdriver from selenium.webdriver.common.keys import Keys import time driver = webdriver.Chrome('chromedriver') url = 'https://map.naver.com' driver.get(url) search = driver.find_element_by_css_selector('input#search-input') # '씨유' 입력 후 ENTER키 작동 search.s...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu May 9 16:07:23 2019 @author: arnab """ from keras.models import model_from_json from pathlib import Path from keras.preprocessing import image import numpy as np from keras.applications import vgg16 import joblib # Load the json file that contains t...
import hashlib GRAVATAR_URL = ("https://www.gravatar.com/avatar/" "{hashed_email}?s={size}&r=g&d=robohash") def create_gravatar_url(email, size=200): """Use GRAVATAR_URL above to create a gravatar URL. You need to create a hash of the email passed in. PHP example: https...
""" https://edabit.com/challenge/A8gEGRXqMwRWQJvBf """ def tic_tac_toe(ls: list) -> str: a = ''.join((row[0] for row in ls if len(set(row)) == 1)) b = ''.join((row[0] for row in zip(*ls) if len(set(row)) == 1)) c = set([ls[0][0],ls[1][1], ls[2][2]]) d = set([ls[2][0], ls[1][1], ls[0][2]]) if len(a...
class like_provider(object): def insert_like(self, post_id, user_id ): pass def delete_like(self, post_id , user_id): pass def select_like_by_user(self, user_id): pass def select_like_by_post(self, post_id): pass
from sklearn.datasets import fetch_california_housing import numpy as np import tensorflow as tf import matplotlib.pyplot as plt n_epochs = 10000 learning_rate = 0.001 housing_data = fetch_california_housing(data_home='D:\\学习笔记\\ai\\dataSets', download_if_missing=True) data = housing_data.data m, n = data.shape housi...
import XPLMCamera controlCamera = XPLMCamera.XPLMControlCamera dontControlCamera = XPLMCamera.XPLMDontControlCamera isCameraBeingControlled = XPLMCamera.XPLMIsCameraBeingControlled readCameraPosition = XPLMCamera.XPLMReadCameraPosition ControlCameraUntilViewChanges = XPLMCamera.xplm_ControlCameraUntilViewChanges Contro...
# -*- coding: utf-8 -*- from datetime import datetime import pytest from elasticsearch_dsl import A from fiqs.aggregations import ( Avg, Count, DateHistogram, DateRange, Histogram, ReverseNested, Sum, ) from fiqs.fields import FieldWithRanges, GroupedField from fiqs.query import FQuery fr...
# -*- coding: utf-8 -*- from mylib.web import BaseHandler, route @route('/') class IndexHdl(BaseHandler): def get(self): self.render('index.html',{"hint_info":self.hint_info})
from django.conf.urls import patterns, url from core import views urlpatterns = patterns('', url(r'^$', views.ArticleListView.as_view(), name='article-list'), url(r'^posts/(?P<slug>[-_\w]+)/$', views.ArticleDetailView.as_view(), name='article-detail'), url(r'^categories/(?P<slug>[-_\w]+)/$', views.Catego...
# coding=utf-8 # Fix error "ImportError: cannot import name 'cached_property' from 'werkzeug'" import werkzeug werkzeug.cached_property = werkzeug.utils.cached_property from flask import Flask from app.backend.database import db from app.backend.database.models.oauth import security, user_datastore from app.config ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Aug 18 09:01:37 2019 @author: diogo """ import os #to use the new IEX cloud change this value to 'iexcloud-v1' (is also the default) os.environ['IEX_API_VERSION']='iexcloud-sandbox' os.environ['IEX_TOKEN']='Tsk_df0426c99cc64421ac28ac2745944a03' from ...
import os # os.environ.setdefault("SECRET_KEY", "'$(2@5_8ngk3y1k+y8)f8xkq$ahwu4+(l-86=optcp13%rs(r8x'") os.environ.setdefault("SECRET_KEY", "'$(2@5_8ngk3y1k+y8)f8xkq$ahwu4+(l-86=optcp13%rs(r8x'") os.environ.setdefault("EMAIL_ADDRESS", "commonholdproject@gmail.com") os.environ.setdefault("EMAIL_PASSWORD", "Commonhold")
import cherrypy import tornado import tornado.web import tornado.wsgi # http://localhost:8080/examples/wsgi/tornado/?q=/hello class MainHandler(tornado.web.RequestHandler): def get(self): self.write("Hello, world") app = tornado.wsgi.WSGIAdapter(tornado.web.Application([ (r"/hello", MainHandler), ...
import numpy as np import xgboost as xgb from pomegranate import BayesianNetwork import pandas as pd from matplotlib import colors as mcolors import seaborn as sns colors = dict(mcolors.BASE_COLORS, **mcolors.CSS4_COLORS) # '#539caf' is a good color ! name = 'train_FD001.txt' df = pd.read_csv(name, sep=' ', h...
import xml.etree.ElementTree as et def choropleth_svg(scores): tree = et.parse('data/us_counties.svg') root = tree.getroot() root.set('type', 'image/svg+xml') # Map colors colors = ["#F1EEF6", "#D4B9DA", "#C994C7", "#DF65B0", "#DD1C77", "#980043"] path_style = 'font-size:12px;fil...