text stringlengths 38 1.54M |
|---|
# Vincent Wong
# A01051004
import random
class Player:
def __init__(self, name: str, hp: int = 10, inventory: list = (), column_position: int = 0, row_position: int = 0):
"""initiate the player constructor,
PARAM:
name is a string,
hp is an integer and by default is 10,
i... |
# coding:utf-8
from flask import Blueprint,render_template, request
import requests
import os,sys
dirPath = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir,os.pardir))
sys.path.append(dirPath)
from service.wy import wy
from flask_cors import CORS
test = Blueprint('test',__name__)
CORS(test, resources=... |
import re
import urllib
def removeHTMLTags():
"""
Returns a regular expression for removing HTML tags
"""
return re.compile(r'<.*?>')
def removeNPSBs():
"""
Returns a regular expression for removing
"""
return re.compile(r' ')
def removeReferences():
"""
Returns a ... |
"""
(C) Copyright 2018-2023 Intel Corporation.
SPDX-License-Identifier: BSD-2-Clause-Patent
"""
import time
from mdtest_test_base import MdtestBase
# pylint: disable=too-few-public-methods
class RbldWidelyStriped(MdtestBase):
"""Rebuild test cases featuring mdtest.
This class contains tests for pool r... |
# importing required modules
from keras.applications import InceptionV3
from keras.models import Model
from keras.models import Sequential
from keras.layers import Activation, Dense
import keras
# creating bottleneck model
original_model = InceptionV3()
bottleneck_input = original_model.get_layer(index=0).input
bo... |
x = [1,2,3,4,5]
sum =0
for each in x:
sum += each
print(sum)
if(sum <= 15):
print("The answer is correct")
else:
print("Incorrect")
|
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 25 19:56:58 2018
@author: Dillon
"""
import numpy as np
import pandas as pd
import re
primary_dict = {2007:pd.to_datetime('8/28/08'),
2008:pd.to_datetime('8/28/08'),
2009:pd.to_datetime('9/02/10'),
2010:pd.to... |
import numpy as np
import numba
import collections
import sklearn as sk
from scipy.sparse import issparse, csr_matrix, coo_matrix
from sklearn.utils import check_array, check_random_state
import fuc
import math
@numba.njit(fastmath=True,nogil=True)#nogil:當進入這類編譯好的函數時,Numba將會釋放全局線程鎖,fastmath:減少運算時間
def SMM_e_step(a,X_r... |
import pandas as p
d={'NAME':['Tom','Jack','Steve','Ricky'],'AGE':[28,34,29,42]}
data=p.DataFrame(d)
print(data) |
from odoo import models, fields, api, _
from datetime import date
import datetime
class student_payment_report_wiz(models.TransientModel):
_name = 'student.payment.report.wiz'
student_id = fields.Many2one('res.partner', string="Student Name")
date_from = fields.Date(string="Date From")
date_to = f... |
#!/usr/bin/env python2
from collections import defaultdict
import logging
import json
import os
from os import path
import sys
d = sys.argv[1]
allocated = set()
builders = defaultdict(set)
machines = defaultdict(set)
allocated.update(json.load(open(path.join(d, "allocated", "all")))["machines"])
for m in os.listdi... |
import cv2 as cv
I = cv.VideoCapture(0)
nb_frames = 30 # number of frames used to initialize the background models
de_th = 0.9 # Threshold value, above which it is marked foreground, else background.
gmgSubtractor = cv.bgsegm.createBackgroundSubtractorGMG(nb_frames,de_th)
while(1):
ret, frame = I.read()
fram... |
# Generated by Django 3.2.3 on 2021-06-21 05:46
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('brand', '0001_initial'),
('category', '0001_initial'),
]
operations = [
migrati... |
while True:
girdi=input("Sayı girin (Çıkmak için 'q' ya basın.) : ")
if girdi=="q":
break
uzunluk=len(girdi)
toplam=0
for i in range(uzunluk):
toplam = toplam + int(girdi[i])**uzunluk
if(toplam==int(girdi)):
print("Girdiğiniz Sayı Bir Armstrong Sayıdır!")
... |
#print the last digit of a given number:
num=int(input("enter the number:"))
num2=int(input("enter the number:"))
if num%10== num2:
print(num2)
else:
print("wrong")
|
import math
n = 1000 #2부터 1000까지의 모든 수에 대하여 소수 판별
# 처음엔 모든 수가 소수인 것으로 초기화 (0과 1은 제외)
array = [True for _ in range(n+1)]
# 에라토스테네스의 체 알고리즘 수행
# 2부터 n의 제곱근까지의 모든 수를 확인하며
for i in range(2, int(math.sqrt(n)+1)):
if array[i] == True:
# i를 제외한 i의 모든 배수를 지우기
j = 2
while i * j <= n:
arra... |
# This code illustrates Closure example with help of a Nested Function. Print 9x5=45
#print "Hello, World!"
def multipier_of(n):
def multipler(number):
return number*n
return multipler
solpart= multipier_of(5)
print solpart (9)
|
#! /usr/bin/env python3
import sys, re
with open(sys.argv[1]) as f:
flines = f.readlines()
p = re.compile(r'"month".+?(\d+).+"day".+?(\d+).+"nocomment".+?(\d+).+"false".+?(\d+).+"confirmed".+?(\d+).+"total".+?(\d+).+"name".+?"(.+?)"')
print('customer month/day total confirmed%')
print('-------------------------... |
'''
Created on May 15, 2013
@author: ivano.ras@gmail.com
MIT License
'''
import sys
from time import sleep
from PyQt4.QtGui import qRgb, QVector3D
from PyQt4.QtCore import QThread, SIGNAL, QString
import MathTools
class REngineThread (QThread):
'''
(threaded) engine model class
'''
def __init__... |
# -*- coding: utf-8 -*-
"""
Created on Tue May 28 2019
@author: Stacy Bridges
This script does a few different things:
it uses country matcher on a long text
it analyzes the syntax
it updates doc entities with the matched countries
"""
import spacy
import json
from spacy.lang.en import English
from spacy... |
# coding: utf-8
# In[2]:
#taanilan git: valmistelu.ipynb
#https://github.com/taanila/tilastoapu/blob/master/valmistelu.ipynb
import pandas as pd
# In[3]:
df = pd.read_excel('http://taanila.fi/data1.xlsx')
df.head() #5 ensimmäistä riviä
# In[9]:
df.tail() #5 viimeistä riviä, id antaa rivimäärän
# In[24]:
... |
#!/usr/bin/env python3
import sys, argparse, matplotlib
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import root_scalar, root
from scipy.special import erf
from numpy import pi, sqrt, real, imag
from collections import defaultdict, namedtuple
from functools import partial
from termcolor impor... |
# coding=utf-8
__author__ = 'xyc'
import functools
# The Chain of Responsibility Pattern is designed to decouple the sender of a
# request from the recipient that processes the request.
# 将能处理请求的对象连成一条链,并沿着这条链传递该请求,直到有一个对象处理请求为止,避免请求的发送者和接收者之间的耦合关系。
def coroutine(function):
@functools.wraps(function)
def wra... |
from gol import GOL_DICTIONARY
def show_topic(question,options_dictionary):
"""Prints the question, and options"""
print question
for option in sorted(options_dictionary):
print option, options_dictionary[option]
def get_next_topic(topic, sub_topic):
user_input = raw_input(">> ").upper()
return GOL_DICTIONARY[... |
import pandas as pd
import numpy as np
import tldextract
import dateparser
from cleanco import prepare_terms, basename
import unidecode
import re
import string
class Preprocessing():
def __init__(self, df):
self.df_apps_match = df
self.google_play_df = self.df_apps_match[self.df_apps_match['store']... |
import numpy as np
import numpy.core.records as ncr
a= np.array([0,1,2,3,4,5,6,7,3,3])
print(a)
print(ncr.array([0,1,2,3,4,5]))
print(a.ndim)
print("Shape --",a.shape)
b = a.reshape((2,5))
print("Reshape ",b)
b[0][4]=77
print("After",b)
print(a*2)
print(a**2)
print([0,1,2,3,4,5,3,4,6,7,3,3]*2)
print(a>4)
c = np.array... |
#!/usr/bin/env python
###############################################################################
# $Id$
#
# Project: GDAL/OGR Test Suite
# Purpose: Test OGR VRT driver functionality.
# Author: Frank Warmerdam <warmerdam@pobox.com>
#
#############################################################################... |
import functools
import operator
import numpy
import six
import chainer
from chainer import backend
from chainer.backends import cuda
from chainer import function_node
from chainer.functions.pooling import average_pooling_nd_kernel
from chainer.functions.pooling import pooling_nd
from chainer.utils import conv
from c... |
numbers = [15, 32, 199, 22, 11]
while True:
answer = input("Guess a number:")
if answer == "q":
break
try:
answer = int(answer)
except ValueError:
print("Error! Please type a number!")
if answer in numbers:
print("Correct")
else:
print("Incorrect!") |
# -*- coding: utf-8 -*-
#####################################################################
########### Fields for WorkBook 'Capital Working' ##########
#####################################################################
from openerp import models, fields, api
class capital_working_sub(models.Model):
_name ... |
from django.views import generic
from books.models import Book
from django.core.paginator import Paginator
from django.core.paginator import EmptyPage
from django.core.paginator import PageNotAnInteger
from django.shortcuts import get_object_or_404
class BookListView(generic.ListView):
model = Book
context_o... |
# Rock-paper-scissors-lizard-Spock template
# The key idea of this program is to equate the strings
# "rock", "paper", "scissors", "lizard", "Spock" to numbers
# as follows:
#
# 0 - rock
# 1 - Spock
# 2 - paper
# 3 - lizard
# 4 - scissors
# helper functions
import random
def name_to_number(name):
# delete the fo... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/05/07 17:48
# @Author :
# @File : company.py
# @Software: PyCharm
# @Desc :
"""
"""
from typing import Optional
from fastapi import APIRouter
from app.core.quotations_fix.eastmoney_req import EastMoneyRequest
from app.utils import response_code
... |
#!/usr/bin/env python
#
# Pydget -
# Depositfiles Handler
#
import os, sys, time
import urllib, urllib2, urlparse
import BeautifulSoup
import form_grabber
def prepare_download(opener, page_url):
# Get web page
sys.stdout.write("[+] Grabbing web page, ")
sys.stdout.flush()
page = opener.open(page_url)
print "Don... |
from __future__ import absolute_import
import requests
from systemalib.utils.functional import dmerge
from systemalib.utils import json
def response_status(response):
return response.status_code
def response_json(response):
return json.loads(response.content)
def response_header(key, response):
return... |
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route("/mypage/me")
def hello():
return render_template("form.html")
@app.route("/message/contact", methods=["POST"])
def post_message():
return request.form.get("text")
app.run()
|
import urllib2
url = 'https://www.douban.com/accounts/login'
response = urllib2.urlopen(url)
content = urllib2.urlopen(url).read()
fi = open('begin.php','w')
fi.write(content)
fi.close()
|
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 9 15:24:22 2019
User Behavior Analysis and Commodity Recommendation for Point-Earning Apps
Yu-Ching Chen, Chia-Ching Yang, Yan-Jian Liau, Chia-Hui Chang
National Central University
Taoyuan, Taiwan
TAAI2016
Initial_Data_Process_Code
With Time Series Feature
... |
marks = int(input("enter your marks:"))
if 85 <= marks <= 100:
print('A')
elif 70 <= marks <= 85:
print('B')
elif 50 <= marks <= 69:
print('C')
elif 35 <= marks <= 49:
print('D')
elif marks < 35:
print('fail')
else:
print("enter valid marks below 100") |
import crypt
import hashlib
def testPass(cryptopass):
salt = cryptopass[0:2]
with open('dictionary.txt', 'r') as dictfile:
for word in dictfile:
word = word.strip('\n')
cryptword = crypt.crypt(word, salt)
if (cryptword == cryptopass or hashlib.sha512(word) == cryptword):
print('[+] Found password: ... |
# MENU FUNCTIONALITY
def menu():
print("Need to remember how i did all this")
print("Think i just stole it from dragon fire")
|
from __future__ import print_function
from ggplot import *
print(ggplot(diamonds, aes(x='price')) + geom_histogram())
print(ggplot(diamonds, aes(x='price')) + geom_histogram(bins=50))
|
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ovid_api.settings.base")
import django
django.setup()
import json
from api.models import Author, Work, Book, Poem, Line
json_data = open('corpus.json')
data = json.load(json_data)
author = data['author']
works = data['works']
# clear the decks so there are... |
# Generated by Django 2.2.2 on 2019-10-05 08:53
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('browser', '0020_auto_20191005_1418'),
]
operations = [
migrations.AlterField(
model_name='product',
... |
import keras
from keras.layers import Dense
from keras.models import Sequential
from keras.layers import Convolution2D
from keras.layers import MaxPool2D
from keras.layers import Flatten
import numpy as np
from numpy import genfromtxt # processing our csv files.
#Needed for unpacking the files
import shutil
import... |
class animals(object):
def __init__(self,name,health):
self.name =name
self.health =health
def walk(self):
self.health -= 1
return self
def run(self):
self.health -= 5
return self
def display_health(self):
print self.health
return self
class dog(animals):
def __init__(self,name,health):
s... |
__author__ = 'Gabrielle Martin-Fortier'
from interface.interface_logs import Nouveau_quart
if __name__ == '__main__':
# Point d'entrée principal du TP4. Vous n'avez pas à modifier ce fichier, il ne sert qu'à exécuter votre programme.
# Le fichier à éditer est interface/interface_dames.py.
f = Nouveau_qua... |
# Generated by Django 3.1.2 on 2020-10-10 16:16
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('main', '0005_auto_20201010_1550'),
]
operations = [
migrations.AlterField(
model_name='contact',
name='phone',
... |
from django.db import models
class ProjectInfo(models.Model):
name = models.CharField(max_length=30,null=False,blank=False)
description = models.TextField(null=False,blank=False)
start_date = models.DateTimeField(null=False,blank=False)
end_date = models.DateTimeField(null=False,blank=False)
is_del... |
from graphene_django import DjangoObjectType
from graphene_crud_maker.utils import CustomNode, CustomConnection
from Api.models import Users
class UsersType(DjangoObjectType):
class Meta:
model = Users
filter_fields = {
'id': ['exact',],
}
interfaces = (CustomNode,)
... |
#! /usr/bin/env python
# -*- coding UTF-8 -*-
# @ author: Yang Wu
# Email: wuyang.bnu@139.com
# import os
# import sys
# import time
# import gzip
# import tarfile
# import numpy as np
# import pandas as pd
# from functools import reduce
from os import listdir
class MyListDir():
def __init__(self, path, retain='... |
"""Remove unused models
Revision ID: 3f289637f530
Revises: 4ba1dd8c3080
Create Date: 2014-04-17 11:08:50.963964
"""
# revision identifiers, used by Alembic.
revision = '3f289637f530'
down_revision = '4ba1dd8c3080'
from alembic import op
def upgrade():
op.drop_table('aggtestgroup')
op.drop_table('testgroup... |
# -*- coding: utf-8 -*-
'''
Created on 6 de dez de 2018
@author: vgama
'''
from time import sleep
from lxml import etree as ET
class TelaUnica(object):
def __init__(self, context):
self.context = context
def abrir_soap(self):
self.context.asserts.verifica_tela(self.context.path+"dat... |
from traffic.models.PathEstimationModel import PathEstimationModel
from traffic.models.PathLengthModel import PathLengthModel
from traffic.queries.GoogleMapsRouteQuery import GoogleMapsRouteQuery
from traffic.shared.responses.GoogleResponseObject import GoogleResponseObject
from django.db.models import Avg
from traffic... |
import maya.cmds as cmds
import vectors ; from vectors import *
import math
class Obstacle:
def __init__(self, name, r = 1.0, h = 6.0, x = 0.0, y = 0.0, z = 0.0):
self._name = name
self.force = 4.0
self.direction = V(0.0, 1.0, 0.0)
if cmds.objExists(name):
self.position = V(cmds.getAttr("{0}.translate".for... |
# -*- coding: utf-8 -*-
import collections
import functools
import pymysql
from com.caeit.jn2xx.config.configParam import ConfigParameters
from com.caeit.jn2xx.utils.datatypeUtil import strWrappedQuota
"""
0. 提供数据库增、删、改、查基本功能
1. 安装pymysql模块 pip3 install pymysql
"""
__author__ = "Eugene Gao"
__date__ = "2018.08.10"
... |
# 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 -*-
"""Pub/Sub pull example on Google Kubernetes Engine.
This program pulls messages from a Cloud Pub/Sub topic and
prints to standard output.
"""
import datetime
import time
# [START gke_pubsub_pull]
# [START container_pubsub_pull]
from google import auth
from google.cloud import pubsub_v1
def... |
from django.contrib import admin
from .models import Cat
from .models import Breed
# Register your models here.
admin.site.register(Cat)
admin.site.register(Breed) |
'''
Train a CRF sequence tagging and global label prediction model on top of the eukarya AWD-LSTM model.
Reports a bunch of metrics to w&b. For hyperparameter search, we optimize the AUC of the global label and F1 of the cleavage site (no tolerance window)
Hyperparameters to be optimized:
- learning rate
- classifie... |
from framework.base_page import BasePage
class SportNewsHomePage(BasePage):
# NBA入口
nba_link = "xpath=>//div[@class='schedule clearfix']/ul/li/a"
def click_nba_link(self):
self.a_click_element(self.nba_link)
self.time_sleep(2) |
# Uso de condicionales para verificar si un numero es mayor a otro
print()
num_1 = int(input('Escriba un primer numero: '))
num_2 = int(input('Escriba un segundo numero: '))
print('==\n')
if num_1 > num_2:
print('El numero {} es mayor a {}.'.format(num_1, num_2))
elif num_1 < num_2:
print('El numero {} es ma... |
# What is the first term in the Fibonacci sequence to contain 1000 digits
ab = 1
ac = 1
count = 2
while True:
ab += ac
ac += ab
count += 2
if ac > 10**999:
if ab > 10**999:
print count - 1
else:
print count
break
|
# Dana jest posortowana rosnąco tablica A wielkości n zawierająca
# parami rozne liczby naturalne. Podaj algorytm, ktory sprawdzi, czy
# jest taki indeks i, ze A[i] == i.
# Co zmieni sie, jezeli liczby beda calkowite, niekoniecznie naturalne?
# 1. Gdy liczby sa naturalne wystarczy sprawdzic czy A[0] == 0 bo gdy A... |
# ______________________________________________________________________
#
# This module is part of the PyMINLP solver framework.
# ______________________________________________________________________
from pyminlp.solver import PyMINLP
from pyminlp.plugins.quad import *
def foo(filename):
# Create model i... |
import sys
import os
import argparse
import logging
import json
import time
import numpy as np
import torch
from torch.utils.data import DataLoader
from torch.optim import SGD
from torch.autograd import Variable
from torch.nn.utils import clip_grad_norm
from tensorboardX import SummaryWriter
sys.path.append(os.path.... |
#determinar si enviamos una alerta de sismo
#la alerta de sismo se enviara si y solo si, el valor de la actividad es mayor a 5
#num_habitantes > 1 -> si envio la alerta
valor_escala = float(input("Favor ingrese el valor en escala "))
num_habitantes = float(input("Favor ingrese el numero de habitantes en MM "))
'''
#... |
# Geschreven door Mark
import tkinter as tk
from GUI import Input
from Database import Database
from Billing import Billing
from tkinter import BOTH, END, LEFT
import uuid
from Email import Document
from Email import Email
class BillingEnglish(tk.Frame):
_emailInput = None
_nameInput = None... |
from seeltools.utilities.log import logger
from seeltools.utilities.parse import read_from_xml_node, xml_to_objfy
class Relationship(object):
def __init__(self):
self.pTolerance = 0
self.pDefaultTolerance = 0
self.defaultTolerance = 1
self.minID = 0
self.maxID = -... |
import pyspark
sc=pyspark.SparkContext()
file_text=sc.textFile('finalDataWithRepeats.txt')
def pairs(line):
fields=line.split('|')
hours=float(fields[0])
#to many decimals, so reduce it to 0.5 or to 0.0. Only to make it pretty
hours=int(hours*2)/2
calls=fields[1]
try: data=int(data[1])
exce... |
from datetime import date, datetime, timedelta
from coinapi_service import coin_api_get_exchange_rates
'''
date1 = date.today() # date du jour
#date2 = date1 + timedelta(10) # additionner / soustraire des jours
date3 = date(2021, 1, 30)
diff = date1-date3
# print(diff.days)
date3_str = date3.strftime("%d/%m/%Y") # Y... |
import sys
sys.path.append('..')
from intcode_computer import IntcodeComputer
from collections import defaultdict
class Node:
def __init__(self, position):
self.position = position
self.children = [None, None, None]
DIRECTION_MAP = {
1: [4, 3, 1, 2],
2: [3, 4, 2, 1],
3: [1, 2, 3, 4],
4: [2, 1, ... |
k = { 'EN':'English', 'FR':'French' }
#append Spanish
k.update({'ESP':'Spanish'})
k['DE'] = 'German'
print(k['ESP'])
|
from opengever.core.upgrade import SchemaMigration
from opengever.meeting.activity.watchers import add_watcher_on_proposal_created
from opengever.meeting.activity.watchers import add_watchers_on_submitted_proposal_created
class RegisterWatchersForProposals(SchemaMigration):
"""Register watchers for proposals.
... |
#Embedded file name: talecommon\const.py
"""
A common module to provide constants for the tale system
"""
import collections
import utillib as util
from dogma.const import attributeScanGravimetricStrength
from inventorycommon.const import ownerUnknown
from eve.common.lib.appConst import securityClassZeroSec, securityCl... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class ResourceUserDataVO(object):
def __init__(self):
self._profile_type = None
self._profile_value = None
self._report_date = None
self._user_cnt = None
self._u... |
# Web Scraper
# Imports
import os
import re
import csv
import pickle
import requests
from bs4 import BeautifulSoup
# Variável com o endereço da página
# Inicie o servidor web com o comando: python -m http.server
PAGE = "http://localhost:8000/index.html"
# Função para extrair os dados
def extrai_dados(cb):
# E... |
# emacs: -*- coding: utf-8; mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
"""
Dataset loading for ITK images and their respective labels within their metadata
header
"""
# Author: Nicolas Toussaint <nicolas.toussaint@gmail.com>
# King's College London, UK
import SimpleITK as sitk
import numpy as np... |
import os
from statsmodels.tsa.api import Holt
import pandas as pd
from sklearn import svm
from sklearn.svm import SVR
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from datetime import date, timedelta, datetime
import num... |
import httplib2
import random
def get_data():
return open("DATA.lst", 'r').readline()
def get_content_server(body):
return httplib2.Http().request(
"http://open-abbey.appspot.com/interactive/nim-game",
"POST",
body)[1].decode()
def get_body(*args):
if len(args) == 1:
re... |
import json
from gps import *
session = gps()
session.stream(WATCH_ENABLE)
for report in session:
if report['class']!='TPV' or report['mode'] not in [2, 3]:
continue
icarus = open('icarus_base.json', 'r')
point = json.load(icarus)
icarus.close()
point['features'][0]['geometry']['coordinates... |
def add(a,b):
return(a+b)
def subtract(a,b):
return(a-b)
def mult(a,b):
return(a*b)
def div(a,b):
return(a/b)
print(add(5,4))
print(subtract(5,4))
print(mult(5,4))
print(div(5,4))
|
import re
from typing import Dict
_short_tag_re = re.compile(r'^<([a-z0-9]+)(( [a-z0-9-]+="[^"]*")*)/>$')
_attribute_re = re.compile(r' ([a-z0-9-]+)="([^"]*)"')
def parse_short_tag(string):
matches = _short_tag_re.match(string)
assert matches is not None
tag = Tag(matches.group(1))
attribute_string =... |
num = input('Hányadik lettél a versenyen?')
if num <= 3:
print('dobogó')
if kerdes > 3:
print('nem baj szép volt!') |
# Generated by Django 3.1.6 on 2021-02-08 17:30
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
ope... |
class Employee:
def __init__(self , fname , lname):
self.fname = fname
self.lname = lname
# self.email = f"{fname}.{lname}@dw.net"
def explain(self):
return f"The employee name is {self.fname} {self.lname}."
@property
def email(self):
if self.fname==None or self... |
from config.configs import *
import pandas as pd
import argparse
import random
random.seed(1234)
parser = argparse.ArgumentParser(description="Run dataset splitting.")
parser.add_argument('--dataset', nargs='?', default='tradesy', help='dataset name')
parser.add_argument('--validation', type=bool, default=False, help... |
a = [3, 5, 6, 8, 10, 11, 45, 86, 95, 1826, 94648, 0, 3, 17]
minimum = 5000000000
for i in a:
if i < minimum and i % 10 == 5:
minimum = i
print(minimum)
|
def latest(scores):
last_added_score = len(scores) - 1
return scores[last_added_score]
def personal_best(scores):
scores.sort()
bigest_score = len(scores) - 1
return scores[bigest_score]
def personal_top_three(scores):
# scores.sort()
# scores[-1]
# scores[-2]
# scores[-3]
#... |
#!/usr/bin/env python
# coding=utf-8
import os
import sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import argparse
import time
import zmq
from utils import get_local_ip
context = zmq.Context()
socket = context.socket(zmq.DEALER)
parser = argparse.ArgumentParser()
parser.add_ar... |
from cas.rule import RuleList
from cas.operable import Operable, translate
from cas.symbol import Symbol
class Indexed(Operable):
@staticmethod
def add_order():
return Symbol.add_order()+.5
@staticmethod
def mul_order():
return Symbol.mul_order()+.5
rules = RuleList()
def __new... |
from flask import Flask, jsonify, request
import os
import database.db_connector as db
# Configuration
app = Flask(__name__, static_folder='./front/build', static_url_path='/')
'''
CONNECTS FOR EVERY ROUTE TO ALLOW MULTIPLE REQUESTS
'''
# Routes
@app.route('/')
def root():
# return render_template("main.j2")
... |
def Rotate_Value_Generate(AccuracyField):
AccuracyField = cmds.floatField(AccuracyField,q=1,v=1)
selList = cmds.ls(sl=1)
for sel in selList:
try:
cmds.addAttr("%s.RotateSpeed"%sel,q=1,ex=1)
except:
cmds.addAttr(sel,ln="RotateSpeed",sn="rs",at="double",dv=0,k=1)
... |
import tensorflow as tf
from tensorflow.keras import layers
import numpy as np
inputs1 = tf.keras.Input(shape=(32,), name="input_1")
inputs2 = tf.keras.Input(shape=(32,), name="input_2")
x1 = layers.Dense(64)(inputs1, name="dense_1")
x2 = layers.Dense(64)(inputs2, name="dense_2")
print(tf.shape(x1))
x = tf.concat([x1,... |
from copy import deepcopy
class Solution(object):
def __init__(self):
self.maxi = -1
self.visited = []
def getMaximumGold(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
def in_matrix(row, col):
return 0 <= row < len(grid) and... |
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def reorderList(self, head: ListNode) -> None:
"""
Do not return anything, modify head in-place instead.
"""
if not head or ... |
# -*- coding: utf-8 -*-
import codecs
import os
import sys
"""
Visit http://pyltp.readthedocs.io/zh_CN/latest/api.html
Download the model needed for pylty to run correctly
Remember to change the directories below to where you put the downloaded files
"""
LTP_DATA_DIR = '/Users/Herman/Documents/BOE/pyltp/ltp_data' # ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import struct
import sys
import os
import subprocess
import re
objdump_cmd="objdump"
objdump_param = ('-color', '-macho' ,'-source' ,'-mcpu=haswell' ,'-section=__const' ,'-section=__cstring' ,'-triple=x86_64-apple-darwin17.5.0')
rip_re = re.compile('(\d+)[(][%]rip[)]')
d... |
"""
Collect most recent data from SetTrade.com web site on all stocks.
Save to JSON file.
"""
import requests
from bs4 import BeautifulSoup
import os, os.path
from datetime import datetime
import json
ts = datetime.now()
dataFolder = os.path.join(os.path.abspath("."),"""market-data""")
baseURL = """http://www.settra... |
#!/bin/env python3
# -*- coding: utf-8 -*-
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.