text stringlengths 38 1.54M |
|---|
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class HighScore(models.Model):
player = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
score = models.IntegerField(null=True)
user_answer = models.JSONField(default=list)
created_date = mo... |
import time
import pdb
import sys
print sys.getdefaultencoding()
print range(17501, 100000)
def test():
now_time = time.time();
print now_time
a= 10
print a
# return
a += 1
print a
# exit
b = 'test string'
pdb.set_trace
print pdb
print b
print time.time()
if __nam... |
from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.contrib.auth.models import User
from django.db.models import Q
import operator
from django.views.generic import (
ListView,
DetailView,
CreateView,
... |
# Copyright (c) 2010, Trevor Bekolay
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions ... |
# Given some waypoints (with headings), make a bunch of arcs such that:
# Between each waypoint are two circlular arcs, tangent to each other and tangent
# to each heading at the waypoints and oriented such that there is a smooth flight path
# If desiredDuration and craft are specified, will scale about center until ... |
#
# Copyright 2021 Ocean Protocol Foundation
# SPDX-License-Identifier: Apache-2.0
#
import copy
import json
import logging
from eth_utils import add_0x_prefix
from ocean_lib.common.agreements.consumable import ConsumableCodes
from ocean_lib.common.agreements.service_agreement import ServiceAgreement
from ocean_lib.co... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-05-03 10:07
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('profiles', '0001_initial'),
]
operations = [
... |
from django.http import HttpResponse
# Create your views here.
def hello_world(request):
return HttpResponse('Hello, world')
|
from ftplib import FTP
import tarfile
from io import BytesIO
ftp = FTP('')
ftp.login("","")
ftp.pwd()
print(ftp.pwd())
# FTP Class
class FTPList:
def __init__(self, instr, years="all", months="all", days="all"):
self.instr = instr
self.years = years
self.months = months
self.... |
from datetime import timedelta, datetime
import time
# Simple cache mechanism that checks if a user query was made before and
# if yes, then returns that query
# if no, saves the query to a dict
# Every 24 hours cache clears itslef
class Cache():
rates_by_day = {}
sales_by_day = {}
refresh_time = 86400 ... |
"""
This file is the entrypoint of Bot application
"""
# Library includes
import firebase_admin
from firebase_admin import credentials
# App includes
import app.configuration as configuration
from app.logging.core import Log
from app.client import BotClient
def main() -> None:
"""
Main function of bot appl... |
#Nischal Shrestha
#9/19/2015
#MASTERMIND GAME
import random
alphabet = 'ABCDEF'
code = ''.join(random.sample(alphabet, 4))
print (code)
number_of_guesses_left = 10
code_broken = False
guess_number = 0
print('Welcome to MasterMind')
while number_of_guesses_left > 0:
print ('Guesses left:',(numb... |
class Consts:
FIRST_USER = {
'name': 'Matthew E. Taylor',
'user_id': 'edQgLXcAAAAJ'
}
VALID_DOMAINS = [
'artificial intelligence',
'intelligent agents',
'multi-agent systems',
'reinforcement learning',
'robotics',
'computer science',
... |
import collections
filename = "A-large"
#filename = "A-minimal"
with open(filename + ".in", 'r') as inputfile:
lines = inputfile.readlines()
with open(filename + ".out", 'w') as outputfile:
number_of_tests = 0
for linenumber, line in enumerate(lines):
if linenumber == 0:
number_of_tes... |
def scramble(s1, s2):
a = list(s1)
b = list(s2)
temp_list = set(a) & set(b)
if temp_list == set(b):
return True
else:
return False
scramble('rkqodlw','world')
scramble('cedewaraaossoqqyt','codewars')
scramble('katas','steak')
scramble('scriptjava','javascript')
scramble('scriptingj... |
#coding:utf-8
__author__ = 'vanxkr@gamil.com'
import urllib
import requests
class HtmlDownLoader(object):
def download(self,url):
if url is None:
return None
headers = {'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Accept-Language... |
import binascii
a = '1c0111001f010100061a024b53535009181c' # (cypher text)
b = '686974207468652062756c6c277320657965' # hit the bull's eye (key)
c = '746865206b696420646f6e277420706c6179' # the kid don't play
def xor_str(string1, string2):
return binascii.hexlify(
"".join(
chr(ord(leftChr)... |
class Rectangle2D:
def __init__(self, x, y, width, height):
self.x = x
self.y = y
self.width = width
self.height = height
def getX(self):
return self.x
def getY(self):
return self.y
def getHeight(self):
return self.height
def getWidth(self):
... |
import re
import cloudfront
# Lines 1 & 2 are header
# # Lines 3 & 4 don't include past field 26 (fle-encrypted-fields)
# Line 5 includes 7 additional fields as per https://aws.amazon.com/about-aws/whats-new/2019/12/cloudfront-detailed-logs/
# Line 6 includes extra "unknown field data"
EXAMPLE = """#Version: 1.0
#Fie... |
#!/usr/bin/env python
import logging
from contextlib import closing
import socket
import argparse
import select
import sys
from textwrap import wrap
import os
import subprocess
import irclib
from time import sleep
class Socket(object):
"""
Socket is a struct containing a socket and two handlers :
on_write... |
from django.db import models
from django.contrib.auth.models import AbstractUser
import datetime
"""
Class Account
Store the money balance between reload and transaction
"""
class Account(models.Model):
balance = models.FloatField()
name = models.CharField(max_length=50)
def __str__(self):
retu... |
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from slave import recipe_api
import collections
class ImmutibleMapping(dict):
def __init__(self, data):
super(ImmutibleMapping, self).__init__(data)
... |
import csv
import requests
import json
import logging as log
"""
Tools for migrating legacy lists from Openverse Beta to the CC Catalog platform.
"""
def import_lists_to_catalog(parsed_lists):
success = 0
errors = []
for _list in parsed_lists:
_list = parsed_lists[_list]
payload = {
... |
from mypy_extensions import TypedDict
from speclib import array
curve448_test = TypedDict('curve448_test', {
'private': str,
'public' : str,
'result' : str,
'valid' : bool}
)
curve448_test_vectors : array[curve448_test] = array([
{
'private' : '3d262fddf9ec8e88495266fea19a34d28882acef... |
# coding: utf-8
"""
SevOne API Documentation
Supported endpoints by the new RESTful API # noqa: E501
OpenAPI spec version: 2.1.18, Hash: db562e6
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import re # noqa: F401
# python 2 and... |
n = 100
sumOfSquares = 0
curSum = 0
for i in range(1,n + 1):
sumOfSquares += i ** 2
curSum += i
squareOfSums = curSum ** 2
print("Sum of Squares = " + str(sumOfSquares))
print("Square of Sums = " + str(squareOfSums))
print (curSum ** 2) - sumOfSquares
|
from flask import Flask
from flask import render_template
import forms
app = Flask(__name__)
@app.route('/')
def index():
comment_form = forms.CommentForm()
title = 'Curso Flask'
return render_template('index.html' , title = title, form ... |
######### NOP Selection #########
doc = Document.getCurrentDocument()
seg = doc.getCurrentSegment()
adr = doc.getCurrentAddress()
start, end = doc.getSelectionAddressRange()
for x in range(start,end):
seg.writeByte(x,0x90)
seg.markAsCode(x)
|
# -*- coding: utf-8 -*-
"""
配置文件
"""
import os
# 集成方法分类器
from sklearn.ensemble import AdaBoostClassifier
from sklearn.ensemble import BaggingClassifier
from sklearn.ensemble import ExtraTreesClassifier
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.ensemble import RandomForestClassifier
# 高斯过... |
def function1:
linecode line 1 chnage the same line from bigtrouble benach
linecode line 2
linecode line 3
linecode line 4
linecode line 5
linecode line 6
linecode line 7
linecode line 8
# Thanks
All my student
def function2:
linecode line 2-1 adding more code here from master branch
linecode line 2-2
... |
# -*-coding:utf-8-*-
"""样本A与样本B是两个n维向量,而且所有维度的取值都是0或1。
例如:A(0111)和B(1011)。
我们将样本看成是一个集合,
1表示集合包含该元素,0表示集合不包含该元素。
P:样本A与B都是1的维度的个数
q:样本A是1,样本B是0的维度的个数
r:样本A是0,样本B是1的维度的个数
s:样本A与B都是0的维度的个数
"""
from numpy import *
import scipy.spatial.distance as dist # 导入scipy距离公式
matV = mat([[1,1,0,1,0,1,0,0,1],[0,1,1,0,0,0,1,1,1... |
from .. import base
class IsAlpha(base.And):
''' Accepts only strings with alphabetical characters, spaces, underscores or dashes '''
def __init__(self):
super(IsAlpha, self).__init__(
base.types.ToType(unicode),
base.strings.IsRegexMatch(base.canonicals.ALPHA_RE),
error_message='The specified value "{va... |
import collections
import re
import jieba
words = ['液化气', '果味', '柚子', '绿茶', '住宿费', '果味', '柚子', '绿茶', '住宿费', '果味']
def build_dataset(words, n_words):
"""
函数功能:将原始的单词表示变成index
"""
print('words',words)
count = [['UNK', -1]]
count.extend(collections.Counter(words).most_common(n_words - 1))
print... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'main.ui'
#
# Created by: PyQt5 UI code generator 5.6
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Form(object):
def setupUi(self, Form): #setting up user int... |
#!/usr/bin/python2.6
# Client program
from socket import *
import os
# Create sending socket
s_host = "10.0.0.11"
s_port = 3157
s_addr = (s_host,s_port)
send_sock = socket(AF_INET,SOCK_DGRAM)
send_sock.connect(s_addr)
# Create receiving socket
r_host = "10.0.0.1"
r_port = 3158
r_buf = 9000 #BYTES
r_addr = (r_host... |
import subprocess
import sys
import math
# Process template with input parameters
def process_template(template, arguments):
processed_template = template
for arg in arguments:
processed_template = processed_template.replace("{{arg}}", arg ,1)
return processed_template
# Return template content
de... |
# 作者 yanchunhuo
# 创建时间 2018/01/19 22:36
# github https://github.com/yanchunhuo
from common.fileTool import FileTool
import os
import subprocess
import platform
def java_maven_init():
print('开始java maven更新......')
print('删除旧的maven依赖包......')
FileTool.truncateDir('common/java/lib/java/libs')
print('删除旧的m... |
def Trans_ChampN(ChampN):
EngName = ""
Kr = ["가렌", "갈리오", "갱플", "그라가스", "그브", "나르", "나미", "나서스", "노틸", "녹턴", "누누", "니달리",
"니코", "다리", "다이애나", "드븐", "라이즈", "라칸", "람머", "럭스", "럼블", "레넥", "레오나", "렉사이",
"렝가", "루시안", "룰루", "르블랑", "리신", "리븐", "리산", "마이", "마오", "말자", "말파", "모데", "몰가",
... |
from django.db import models
# Create your models here.
class Bed(models.Model):
name = models.TextField(max_length=80)
occupancy = models.IntegerField()
def __str__(self):
return self.name
class RoomType(models.Model):
name = models.TextField(max_length=80)
image = models.ImageField... |
import functools
import os
import flask
import google.oauth2.credentials
import googleapiclient.discovery
from app import db
from app.models.user import User
from app.models.army import Army, Upgrade
from dotenv import load_dotenv
from authlib.client import OAuth2Session
from flask_login import login_user, current_user... |
from wtforms import Form, TextField, TextAreaField, SubmitField, validators, ValidationError , IntegerField
class ContactForm1(Form):
empname = TextField("Employer name")
city1 = TextField("City")
state1 = TextField("State")
country1 = TextField("Country")
postitle = TextField("Position title")
startda... |
import datetime
import json
from xml.etree import ElementTree
from django.test import TestCase
from miscosas.models import Item, Feed, User, Profile, Vote
from miscosas.apps import MisCosasConfig as Config
VALID_YOUTUBE_KEY = "UC300utwSVAYOoRLEqmsprfg"
INVALID_YOUTUBE_KEY = "4v56789r384rgfrtg"
XML = "?format=xml"
J... |
def reverse(word):
out = ""
size = len(word)
idx = size - 1
while idx >= 0:
out += word[idx]
idx -= 1
return out
print(reverse("word"))
print(reverse("hockey")) |
from delivery_systemC.configs.config import NAME_PSW
from delivery_systemC.libs.login import Login
from delivery_systemC.libs.shop import Shop
#conftest放到哪一个包,只对这个包起作用!,比如当前是test_case包
import pytest
import os
'''
**scope**: ##有4个级别参数
"function" (默认), 在conftest作用域下,所有的def test_xxx测试方法运行前都会执行1次!
"class" ,在conf... |
import math
import os
import subprocess
import sys
def path_to_file(folder, file_name):
return ('%s/%s' % (folder, file_name))
def image_files_in_folder(folder, include_path=True):
path = lambda file: (path_to_file(folder, file_name)) if include_path else file
all_files = os.listdir(folder)
path_list ... |
import numpy as np
import pandas as pd
from sklearn.gaussian_process import GaussianProcessRegressor as gauss
from sklearn.model_selection import StratifiedKFold
from sklearn.metrics import mean_squared_error, explained_variance_score, mean_squared_log_error, r2_score, \
label_ranking_loss, log_loss, roc_auc_score
... |
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 21 21:52:08 2014
@author: mit
"""
"""
# This script generate sequence with hidden word with certain generative model
# Description taken from the assignment:
The following generative model generates K sequences of length N: s1,...,sk where
si = si1,...,siN. All sequence... |
#!/usr/bin/env python3.3
import argparse
import os
import copy
import utils
import fastn
import sam
import external_progs
import nucmer
def map_and_parse_sam(ref_index, tags_fasta, tag_counts, log_fh):
samfile = options.outprefix + '.maptags.sam'
#utils.syscall('smalt map -d -1 -y 1 -f samsoft -o ' + samfi... |
#Author: Scott Grether, Dustin Grady
#Function: Create GUI with TKinter and set up widgets. Clock and weather that updates
#Status: Working/ Tested
import time
import calendar
from weather import WeatherClass
try:
#python3
from tkinter import *
except:
#python2
from Tkinter import *
time1 = time.loca... |
from flask import Blueprint
from flask import jsonify
from yelp_beans.logic.metrics import get_meeting_participants
from yelp_beans.logic.metrics import get_meeting_requests
from yelp_beans.logic.metrics import get_subscribers
from yelp_beans.models import MeetingSubscription
metrics_blueprint = Blueprint("metrics", ... |
from django.contrib import admin
from models import Lobbyist, LobbyistCorporation, LobbyistsChange
from django.contrib.contenttypes import generic
from links.models import Link
class LinksInline(generic.GenericTabularInline):
model = Link
ct_fk_field = 'object_pk'
extra = 1
class LobbyistAdmin(admin.Mod... |
# 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... |
from django.shortcuts import render
from django_redis import get_redis_connection
from django.views import View
import json, time
from django.http import JsonResponse
from django.shortcuts import render
from homes.models import House
import datetime
from .models import Order
from ihome.utils.views import LoginRequiredJ... |
# Lesson2, Task4
# check the method id()
# id() method for integers
x = 2
y = x
print (x, y, id(x), id(y), id(2), id(3))
print ()
y = 3
print (x, y, id(x), id(y))
print ()
# python variables are references to the objects, but not objects itself
# when y=x - y becomes a number from the reference to number 2
# when y=3... |
"""Shared utility functions for testing suite."""
import os
from datetime import datetime
def parse_filing_document_header(file_path):
parsed = {
"ACCESSION NUMBER": [],
"CONFORMED SUBMISSION TYPE": [],
"COMPANY CONFORMED NAME": [],
"FILED AS OF DATE": [],
}
header = extra... |
__author__ = 'andi'
__scrabble_letters = {"a": 1, "c": 3, "b": 3, "e": 1, "d": 2, "g": 2,
"f": 4, "i": 1, "h": 4, "k": 5, "j": 8, "m": 3,
"l": 1, "o": 1, "n": 1, "q": 10, "p": 3, "s": 1,
"r": 1, "u": 1, "t": 1, "w": 4, "v": 4, "y": 4,
... |
from flask_login import UserMixin
from datetime import datetime
from . import db
class User(UserMixin, db.Model):
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(100), unique=True)
password = db.Column(db.String(100))
name = db.Column(db.String(1000))
class Orders(db.Model)... |
from ARappServer.DBinterface import AR_db
import pandas as pd
import numpy as np
def _prepareData(objectID,limit = 10):
'''
Извлечение данных и их подготовка для подачи на вход нейросети
:param objectID: id физического объекта
:param limit: колическтво данных, извлекаемых из БД
:return: извлечённы... |
from django.db import models
from .Item import Item
from .Attribute import Attribute
class ItemAttribute(models.Model):
item = models.ForeignKey(Item)
attribute = models.ForeignKey(Attribute)
class Meta: app_label = 'Core'
|
from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from cms.models.pluginmodel import CMSPlugin
from .models import TestimonialComponent, TestimonialItem
from .admin import TestimonialItemInline
@plugin_pool.register_plugin
class TestimonialComponentPlugin(CMSPluginBase):
model = T... |
import json
import datetime
def default(o):
if isinstance(o, (datetime.date, datetime.datetime)):
return o.strftime('%Y-%m-%d %H:%M')
def action_create(action_type, **kwargs):
return json.dumps({'forType': action_type, 'payload': kwargs}, default=default)
class Connection:
connection: dict = d... |
import random
import math
def sigmoid(x):
return 1 / (1 + math.exp(-x))
def derivativeSigmoid(x):
return sigmoid(x) * (1-sigmoid(x))
class Perceptron:
weights = []
input = []
learnRate = 0
bias = -1
def __init__(self, inputs, learnRate=0.1):
# Add a bias
self.input = inpu... |
from __future__ import unicode_literals
import re
from django.db import models
class UserManager(models.Manager):
def basic_validator(self, post_data):
errors = {}
EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$')
if len(post_data['first_name']) < 1:
... |
import sys
from guess import play , judge
ans = [];
def main(show):
while len(ans) != 1: tryAns(nextGuess() , show)
if show: print('ans is {}'.format(ans[0]))
def genAns(idx , cur):
global ans
if idx == 0: ans = [];
for i in range(0 , 10):
if i in cur: continue
elif idx != 3: genA... |
from setuptools import setup, find_packages
from ethocaissuerclient.core.version import get_version
VERSION = get_version()
f = open('README.md', 'r')
LONG_DESCRIPTION = f.read()
f.close()
setup(
name='ethocaissuerclient',
version=VERSION,
description='An API client allowing an Issuer to use Ethoca',
... |
from django import forms
from pyclass.todo.models import ToDoItem
class ToDoItemForm(forms.ModelForm):
class Meta:
model = ToDoItem
fields = ("name", "details", "excellence", "importance", "due", "interests", "tags")
|
'''
This file is HTTP test for search (GET)
Parameter: (token, query_str)
Return: {messages}
Steps to test search:
1. Register a user
2. The user login to the server
3. create a channel
4. send a message and search
5. test
1. search successfully
'''
from json import load, dumps
import url... |
// MIN_LEVEL = 5
// MAX_LEVEL = 15
// Light switch | Bulb brightness
// Dimmer level | 5 watt | 10 watt | 20 watt
// 5 | 0 | 0 | 0
// 10 | 2.5 | 5 | 10
// 15 | 5 | 10 | 20
// new dimmer_switch
// new light_bulb 20_watt
// connect... |
# Generated by Django 3.0.8 on 2020-07-09 15:06
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('brawler', '0002_auto_20200709_1348'),
]
operations = [
migrations.AlterField(
model_name='brawler',
name='name',
... |
# converts from JSON to db model format
from rest_framework import serializers
from user_trophies.models import user_trophy
class user_trophySerializer(serializers.ModelSerializer):
class Meta:
model = user_trophy
fields = ('userID', 'trophy')
|
import cv2
import numpy as np
#Greyscale
img = np.zeros((512, 512))
cv2.imshow("Image", img)
#RGB
img2 = np.zeros((512, 512, 3), np.uint8)
#Blue
#img2[:] = 255, 0, 0
#cv2.line(img2, (0,0), (300,300), (0, 255, 0), 3)
#cv2.line(image, (starting point), (ending point), (color), thickness)
cv2.line(img2, (0,0), (img.sha... |
# Generated by Django 3.0.4 on 2021-04-18 18:13
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('quizz', '0008_delete_result'),
]
operations = [
migrations.RemoveField(
model_name='choice',
name='question',
),
... |
from task.transformer_est import Classification
from models.transformer import bert
import tensorflow as tf
class transformer_mt:
def __init__(self, hp, voca_size, num_class_list, is_training=True):
config = bert.BertConfig(vocab_size=voca_size,
hidden_size=hp.hidden_units... |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def distributeCoins(self, root):
"""
:type root: TreeNode
:rtype: int
"""
global ... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.1 on 2017-06-24 01:26
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operation... |
#!/usr/bin/env python
from __future__ import print_function
PKG = 'rbe_3002'
NAME = 'a_star_test'
import sys
import unittest
import rospy
import rostest
from rbe_3002.srv import *
class TestAStar(unittest.TestCase):
def test_correct_response(self):
# When we setup access to the aStar service
ros... |
# encoding:utf-8
"""
1. 获取域名的IP地址以及地理位置,同时更新数据库,更新数据库规则如下:
1)若数据库中无该域名记录,则插入;
2)若数据库中有该域名记录,则与该域名最近一次的更新记录进行比较,若相同则不更新,不同则更新。
2. 获取域名的CNAME,同时更新数据库,规则与上相同
程亚楠
创建:2017.9.8
"""
import schedule
import time
import DNS
from db_manage import get_col
from ip2location import ip2region
from datetime import datetime
... |
NUMBER_ONE = "h_1"
NUMBER_TWO = "h_2"
NUMBER_THREE = "h_3"
NUMBER_FOUR = "h_4"
NUMBER_FIVE = "h_5"
NUMBER_SIX = "h_6"
NUMBER_SEVEN = "h_7"
NUMBER_EIGHT = "h_8"
NUMBER_NINE = "h_9"
NUMBER_TEN = "h_10"
NUMBER_ELEVEN = "h_11"
NUMBER_TWELVE = "h_12"
DESCRIPTOR_AFTER = "de_after"
DESCRIPTOR_BEFORE = "de_before"
DESCRIPTOR_... |
def resolve():
'''
code here
'''
import collections
N = int(input())
A_list = [[int(item) for item in input().split()] for _ in range(N)]
A_list.sort(key=lambda x:x[0])
def is_root(node):
root_check_que = collections.deque([node])
foot_print = [False for _ in range(N)]
... |
from collections import Counter
def find_it(seq):
counted = Counter(seq)
for item in counted.items():
if item[1] % 2 != 0:
return item[0]
# add k v pairs with number and count of number
# Idenitfy odd count
# Return number
|
from __future__ import division, print_function
import twitter
import json
from operator import itemgetter
import string
from gensim import corpora, models
import nltk
from nltk import word_tokenize, FreqDist
import pandas as pd
from time import sleep
import numpy as np
import pylab as pl
with open("../data/uber.js... |
# https://leetcode.com/problems/wildcard-matching/
# 如何优化匹配的速率
# 主要是遇到 * 时,后面的匹配需要一直遍历才行
class Solution:
def isMatch(self, s: str, p: str) -> bool:
chars = [""]
for char in p:
if char == "*" and chars[-1] == char:
continue
chars.append(char)
p = "".... |
import tensorflow as tf
import os
from xbrl import XBRLParser, GAAP, GAAPSerializer
num_steps = 500
batch_size = 128
data_x = []
data_y = []
test_x = []
test_y = []
for subdir, dirs, files in os.walk("data/"):
print(os.path.split(subdir)[-1])
for f in files:
xbrl_parser = XBRLParser()
print(subdir+"/"+f)
try:... |
import numpy as np
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
import matplotlib.pyplot as plt
from util2 import get_normalized_data, y2indicator
def error_rate(p, t):
return np.mean(p != t)
def main():
X_train, X_test, Y_train, Y_test = get_normalized_data()
max_iter = 10
print_perio... |
from django.shortcuts import render, redirect
from item.models import Item
from django.shortcuts import render
from .models import Cart, CartItem
from django.http import HttpResponse
from delivery.models import DeliveryBoy
def view_cart(request):
cart_id=request.session.get('cart_id',None)
user=request.user
... |
# Programming Exercise 3-2
#
# Program to find which of two rectangles has the greater area.
# This program will get two sets of lengths and widths from a user,
# use them to calculate and compare two area values,
# and display a message comparing those areas
# Local variables
# you need length, width and area... |
#! python3
# multiplicationTable - take a cmd line argument and create a multiplication table
import openpyxl, sys
from openpyxl.utils import get_column_letter
from openpyxl.styles import Font
userMultiplication = int(sys.argv[1])
wb = openpyxl.Workbook()
sheet = wb.active
for i in range(1, userMultiplication+1):
... |
# Generated by Django 2.2.6 on 2020-01-15 09:29
import datetime
from django.db import migrations, models
import django.db.models.deletion
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
('ventas', '0052_auto_20200115_0055'),
]
operations = [
... |
from tkinter import *
import random
import time
from tkinter.simpledialog import askstring
from tkinter import scrolledtext
import xlrd
b0=xlrd.open_workbook('b.xlsx')
a0=xlrd.open_workbook('a.xlsx')
c0=xlrd.open_workbook('c.xlsx')
b=b0.sheet_by_index(0)
a=a0.sheet_by_index(0)
c=c0.sheet_by_index(0)
def... |
from src.colorpredicate import ColorPredicate
hist_args = {
'color_space': 'hsv',
'ch_indexes': (0, 1, 2),
'bins': (8, 8, 8),
'target_sr': 1.0
}
gauss_hist_args = {
't_amp': 1.0,
't_cov': 0.01,
'threshold': 0.1
}
grass_color_predicate = ColorPredicate("grass", "../data/grass/images")
gras... |
# import re
# s = input('input > ')
# matched = re.match(r'[A-Z]',s[0])
# # print(matched)
# if matched:
# print(s[0] + s)
# else:
# print(s[0].upper() + s[1:])
s = input('input > ')
if s[0].islower():
s2 = s[0].upper() + s[1:]
else:
s2 = s * 2
print(s2) |
import os
import pickle
from xbmcswift2.cache import Cache, TimedCache
from unittest import TestCase
from datetime import timedelta
import time
def remove(filename):
try:
os.remove(filename)
except OSError:
pass
class TestCache(TestCase):
def test_pickle(self):
filename = '/tmp/... |
import tkinter as tk
import tkinter.ttk as ttk
class FundingSourceFrame:
def __init__(self, root):
source_of_funding_frame = tk.Frame(root)
source_of_funding_frame.pack(fill=tk.X, padx=5)
source_of_funding_label = tk.Label(source_of_funding_frame, text='Фінансування', width=14, anchor=tk.W... |
class Slide(object):
def __init__(self, title, content):
self.title = title
self.content = self.convert_line_breaks(content)
def convert_line_breaks(self, text):
return text.replace('\n', '<br>')
|
import scipy as sp
from scipy import interpolate
import txtreader as reader
import math
import numpy as np
def induced_drag_accent(y):
q = float(input("What is the dynamic pressure?"))
files = input("what is your file?")
data = reader.filereader(files)
y_array = data[0]
chord_array = da... |
#-*- coding: utf-8 -*-
# mecVovkeejMatsyas
import argparse
import getpass
import capture
import protocol_parser as pparser
import file_writer as fwriter
def parse_arguments():
parser = argparse.ArgumentParser(description="capture tool")
parser.add_argument("-u", "--user", type=str, help='ssh username (required... |
#
# class Marks:
#
# def __init__(self,m1,m2,m3):
# self.m1=m1
# self.m2=m2
# self.m3=m3
# def average(self):
# return sum([self.m1,self.m2,self.m3])//3
#
#
#
# class Smarks(Marks):
#
# def __init__(self,num,snum):
# super().__init__(10,20,30)
# self.num=num
#... |
class SubscriptionMgr(object):
def __init__(self):
self.__pendings = dict()
self.__doings = dict()
def add_subscription(self, topic, offset):
self.__pendings[topic] = offset
self.__doings.pop(topic, None)
def to_doing(self, topic, offset = None):
if offset == None:... |
import asyncio
import unittest
from decimal import Decimal
from test.hummingbot.connector.gateway.clob_spot.data_sources.injective.injective_mock_utils import InjectiveClientMock
from typing import Awaitable
from unittest.mock import MagicMock
from hummingbot.client.config.client_config_map import ClientConfigMap
from... |
from collections import deque
water_quantity = int(input())
q = deque()
while True:
command = input()
if command == 'Start':
break
q.append(command)
while True:
command = input().split()
if command[0] == 'End':
print(f'{water_quantity} liters left')
break
elif command... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.