text stringlengths 8 6.05M |
|---|
# -*- coding: utf-8 -*-
import os
import sys
import threading
import time
import itertools
from collections import namedtuple
import logging
import six
sys.argv = ["tensorboard"]
from tensorboard.backend import application # noqa
try:
# Tensorboard 0.4.x above series
from tensorboard im... |
def xor_sum(a, b):
result = []
total_sum = None
for i in a:
for j in b:
result.append(i+j)
total_sum = result[0]
for k in range(1, len(result)):
total_sum = total_sum ^ result[k]
print(total_sum)
xor_sum([4, 6, 0, 0, 3, 3], [0, 5, 6, 5, 0, 3])
x = 2
y = 3
print(x... |
from tables import Enum
from Util_new import Cardtype, split, Zone, Option, ThreatClasses
from Board import getEnemyCards, getMyCards,getCardByIngameId, isMyCard,\
getMyHandcardCount, getEnemyHandcardCount, getMyHero, getMyMana
raceDict = {1: 'minion', 2: 'beast', 3: 'mech', 4: 'dragon', 5: 'pirate', 6: 'demon', ... |
# Variable global para mantener activo el item en el navBar, sitios
def url(request):
value = {'url': request.path}
return value
|
from db import db
class ClosetModel(db.Model):
__tablename__ = 'closet'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80))
phone_number = db.Column(db.String(80))
carrier = db.Column(db.String(80))
items = db.relationship('ItemModel', lazy='dynamic')
user_id = d... |
"""
created by ldolin
"""
import scrapy
from learn.items import PaquItem
class PaquSpider(scrapy.Spider):
name = "paqu1"
start_urls = ["https://www.23us.so/list/1_1.html",
"https://www.23us.so/list/2_1.html",
"https://www.23us.so/list/3_1.html",
"https://... |
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the superDigit function below.
# recursive but fails for 3 testcases - might be stack overflow - python limit of 995 stacks
def superDigit(n, k=1):
sum = int(n[0:1])
if len(n) > 1:
sum += superDigit(n[1:])
sum *= k... |
'''This module implements the USB transport layer for PTP.
It exports the PTPUSB class. Both the transport layer and the basic PTP
implementation are Vendor agnostic. Vendor extensions should extend these to
support more operations.
'''
from __future__ import absolute_import
import atexit
import logging
import usb.cor... |
from typing import List, Any
from orun.views.generic.base import TemplateView
from .totals import Total
class Report(TemplateView):
def __init__(self):
super().__init__()
self.stream = []
def write(self, s: str):
pass
def write_line(self, s: str):
self.stream.append(s)
... |
"""SSVEP MAMEM1 dataset."""
import logging
import os.path as osp
import numpy as np
import pooch
from mne import create_info
from mne.channels import make_standard_montage
from mne.io import RawArray
from scipy.io import loadmat
from .base import BaseDataset
from .download import (
fs_get_file_hash,
fs_get_f... |
import json
import os
import subprocess
from loguru import logger
from django.conf import settings
from rest_framework import status
from rest_framework.response import Response
from agents.models import Agent
logger.configure(**settings.LOG_CONFIG)
notify_error = lambda msg: Response(msg, status=status.HTTP_400_BA... |
from operator import itemgetter
class Solution:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
intervals.sort(key=itemgetter(0))
interval_dict = {}
for start, end in intervals:
# Find closet
closest_start = None
for k in interval_dict:
... |
from peewee import *
from typing import List
from datetime import date
from dynaconf import settings
from investagram_data_loader.logger import logging
from investagram_data_loader.repository.base_dao import BaseDao
class Stock(Model):
stock_id = IntegerField(primary_key=True)
stock_code = CharField(max_lengt... |
import os
import subprocess
from process_handle import ProcessHandle, ProcessHandleParserBase
class ProcessHandlersPs(object):
@staticmethod
def handle_mem(_, value):
return value * 1024
@staticmethod
def handle_elapsed(_, value):
seconds = 0
unpack = value.split('-')
if len(unpack) == 2:
... |
import unittest
import calculate
def run_test(control_dist):
test = calculate.calc(control_dist)
if test == -1:
return -1
start = test[0].format("MM.DD.YYYY HH:mm")
finish = test[1].format("MM.DD.YYYY HH:mm")
return [start, finish]
class TestBrevetCalculator(unittest.TestCase):
## Thi... |
#一:使用Python中的urllib类中的urlretrieve()函数,直接从网上下载资源到本地
import os, stat
import urllib.request
img_url = "http://img1.bdstatic.com/img/image/shitu/feimg/uploading.gif"
file_path = 'D:/book/img'
file_name = "233"
try:
# 是否有这个路径
if not os.path.exists(file_path):
# 创建路径
os.makedirs(file_path)
#... |
"""
============
Moving Digit (Experimental - Hierarchical SFA)
============
An example of :class:`sksfa.HSFA` applied to a simple image time-series:
a one-digit version of the moving MNIST dataset. Each data point is 4096-dimensional.
.. image:: ../images/moving_mnist.gif
:align: center
If the change in x is not ... |
"""Advent of Code Day 9 - Marble Mania"""
import collections
def marble_game(num_players, num_marbles):
"""Play a game of marbles and return the winning score."""
circle = collections.deque([0])
scores = collections.defaultdict(int)
player = 1
for marble in range(1, num_marbles + 1):
if ... |
# Copyright 2011 OpenStack LLC.
# All Rights Reserved.
#
# 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 b... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import http.client
import urllib
import json
from constants import HOST, PORT
dest = ':'.join([HOST, PORT])
def getBotResponse(response):
'''
Parse Json response from server
response - JSON formated server response
return - actual string response fr... |
# -*- coding: utf-8 -*-
# for python3
#
# いろいろ学習する
# python training.py {m} {pcsv} {ncsv} {pdump}
# m : 'p'=パーセプトロン, 'a'=AdaBoost+パーセプトロン, 's'=SVM
# pcsv : 正例のCSVファイル名
# ncsv : 負例のCSVファイル名
# pdump : 学習後のパラメータ
#
# python chk_training.py {m} {pcsv} {ncsv} {pdump}
# として実行すると、学習後のパラメータを入力して検証する
import os
import sys
im... |
#!/usr/bin/python
#\file find_changept.py
#\brief Find a change point of a function.
#\author Akihiko Yamaguchi, info@akihikoy.net
#\version 0.1
#\date Mar.27, 2021
import scipy.optimize
'''
Find a change point of a function.
Assume a function func(x)={True,False} which has only one change point x0
where func... |
"""
תשע"ה מועד א' שאלה 1
"""
import numpy as np
from numpy import random as rn
import matplotlib.pyplot as plt
s=0.35
c=1
M=50000
T=2
N=200
dw1=rn.randn(M,N)
X0=-1+2*rn.rand(M)
h=T/N
X=np.ones((M,N+1))
X[:,0]=X0
for i in range(0,N):
X[:,i+1]=X[:,i]-c*X[:,i]*h*(X[:,i]**2-1)+s*dw1[:,i]*np.sqrt(h... |
"""
tests for {{cookiecutter.package_name}}
"""
|
import logging
from django.contrib.auth.models import AnonymousUser
from django.utils.deprecation import MiddlewareMixin
from rest_framework.request import Request
from rest_framework_simplejwt.authentication import JWTAuthentication
from project_management.models import ProjectUser
from site_manage.models import Sit... |
from .compile import CompileCodeResource
|
import pytest
import requests
import transaction
from datetime import datetime, timedelta
from onegov.core.utils import module_path
from onegov.directory import DirectoryCollection
from onegov.file import FileCollection
from onegov.people import Person
from tests.shared.utils import create_image
from pytz import UTC
f... |
a = float(input('请输入华氏温度:'))
b = (a - 32) / 1.8
print('华氏温度%.1f = 摄氏温度为%.1f' % (a, b)) |
from flask import render_template
import re
import json
from .. import db
from ..work import views
from ..models import Comment
def add_comment(json, comment):
if 'user_id' in json:
comment.user_id = json['user_id']
if 'parent_id' in json:
parent_comment = Comment.query.filter_by(id = json['parent_id']).first()... |
from ...config import params
from collections import deque
import random
import numpy as np
from ..update_strategy.normalDQN import normalStrategy
class NormalStrategy:
def __init__(self, ):
self.memory = deque()
self.noram = normalStrategy()
def getLength(self):
return len(self.memory)
def getHeldoutSet(se... |
#输入1970以来的一年及月份,从而打印日历的一个程序
def is_bissextile(year):
if year%400==0 or year%4==0 and year%100!=0:
return True
else:
return False
def days_of_month(year,month):
if month in [1,3,5,7,8,10,12]:
days=31
elif month in [4,6,9,11]:
days=30
else:
if is_bissextile(year):
da... |
import os
import yaml
from click.testing import CliRunner
from datetime import datetime
from onegov.chat import MessageCollection
from onegov.core.cli.commands import cli as core_cli
from onegov.event import Event, EventCollection
from onegov.org.cli import cli
from onegov.ticket import TicketCollection
from onegov.us... |
import streamlit as st
import plotly.express as px
import numpy as np
import pickle
import load_data
import time
# make a timer on the page
# with st.spinner(text='In progress'):
# time.sleep(5)
# st.success('Done')
# input images / video -- link to the file you want
# could upload file to the specific df
fil... |
import fullname
import unittest
class TestFullname(unittest.TestCase):
#Tests that invalid input (containing non-alphabetical characters, spaces, etc) raises a TypeValue error. Should return true
def test_fullname_input(self):
self.assertRaises(TypeError, fullname.fullname, 'first124', 'last ')
... |
import os, requests, zipfile
download_url = 'https://storage.googleapis.com/download.tensorflow.org/models/inception5h.zip'
model_file = 'tensorflow_inception_graph.pb'
def download_model(data_dir):
download_path = get_zip_file_name(data_dir)
response = requests.get(download_url)
with open(download_path... |
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from notification.models import Notification
from twitter_user.models import Profile
@login_required
def notifications_view(request, handle):
html = 'notification.html'
notifcation_count = Notification.objects.filter... |
# -*- coding: utf-8 -*-
import numpy as np
from torch import Tensor
from framework.modules import Module
class ReLU(Module):
"""Implements the Rectified Linear Unit activation layer"""
def forward(self, x):
"""Carries out the forward pass for backpropagation.
INPUT
x: input
... |
__author__="Sara Farazi"
# Defines a cell on the map with its four corner points
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
class Coordinates:
def __init__(self, upper_right, upper_left, lower_right, lower_left):
self.upper_right = upper_right
self.upper_l... |
import sedate
from datetime import datetime, timedelta
from onegov.core.security import Public
from onegov.core.security.permissions import Intent
from onegov.user import User
from onegov.user import UserCollection
from onegov.wtfs import WtfsApp
from onegov.wtfs.collections import ScanJobCollection
from onegov.wtfs.m... |
import logging
import time
import re
from proxmoxer import ProxmoxAPI
from subcontractor.credentials import getCredentials
# https://pve.proxmox.com/pve-docs/api-viewer/
POLL_INTERVAL = 4
BOOT_ORDER_MAP = { 'hdd': 'c', 'net': 'n', 'cd': 'd' }
vlaned_network = re.compile( r'^[a-zA-Z0-9][a-zA-Z0-9_\-]*\.[0-9]{1,4}$'... |
from flask import Flask
from flask import render_template
from flask import jsonify
import json
import sqlalchemy
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine
from config import username, password
# Postgresql Database info
database_name = ... |
n=int(input())%1440
y=n%60
x=(n-y)//60
print(x,y) |
from game.items import NormalLog
from game.models.model import Tree
from game.skills import SkillTypes
class CommonTree(Tree):
name = 'Common Tree'
health = 1
xp = {SkillTypes.woodcutting: 25}
skill_requirement = {SkillTypes.woodcutting: 1, SkillTypes.firemaking: 1}
resource = NormalLog
|
#coding:utf-8
from django.db import models
from django.contrib.auth.models import User,AnonymousUser
# Create your models here.
# class Application(models.Model):
# user = models.ForeignKey(User)
# name = models.CharField( max_length=100 ,null=True)
# description = models.CharField( max_length= 1000,null=True)
#... |
"""
This is a setup.py script generated by py2applet
Usage:
python setup.py py2app
"""
from setuptools import setup
APP = ['../main.py']
DATA_FILES = ['../Resources/SolarFarmDiagram.bmp','../Resources/currencyList.txt','../Resources/help.html']
OPTIONS = {'argv_emulation': False}
setup(
name="Solar Farm Calcul... |
from dotenv import dotenv_values
from aws_cdk import (
core,
)
from collections import OrderedDict
from .common_resources import CommonResourceStack
from .stage_resources import StageResourceStack
from .app_pipeline import AppPipelineStack
class BackstageStack(core.Stack):
def __init__(self, scope: core.Con... |
import requests
import os
import time
import json
#TODO json 解析
file = "D:/locked.csv"
file_line = open(file)
all_lines = file_line.readlines()
i=0
for num in all_lines:
# 判断是否是数字
#
if((num!="\r\n")&num.isdigit()):
print("开始解锁ID = "+num)
i+=1
url ="https://utc.365sale.com/wenzhou/con... |
class Value:
pass
class Integer(Value):
def __init__(self, value):
self.value = value
def __repr__(self):
return '<Integer %d>' % self.value
class String(Value):
def __init__(self, value):
self.value = value
def __repr__(self):
return '<String %r>' % self.value
class Application(Value):... |
import numpy as np
import ot
import matplotlib.pyplot as plt
import scipy
# 2D
n = 100 # nb bins
# bin positions
x = np.arange(n, dtype=np.float64)
# a1 = np.ones((n,20)) * 0.001 # m= mean, s= std
# a2 = np.ones((n,20)) * 0.001
# a1[10:20] = 1
# a2[60:70] = 1
# arti = np.vstack((a1.reshape(1,2000), a2.reshape(1,200... |
#!/usr/bin/env python
"""
The documentation for the framework
"""
import cherrypy
from cherrypy import expose
from WMCore.WebTools.Page import TemplatedPage
from os import path
from cherrypy import HTTPError
from cherrypy.lib.static import serve_file
def serveFile(contentType, prefix, *args):
"""Return a workfl... |
# Komputer nastrojów
# Demonstruje klauzulę elif w instrukcji if
import random
print("Wyczuwam Twoją energię użytkowniku. Twoje prawdziwe emocje znajdują odbiie na moim ekranie.")
print("Jesteś...")
mood = random.randint(1,3)
if mood == 1:
# szczęśliwy
print(
"""
-----------
... |
from typing import *
import numpy as np
import pandas as pd
import scipy.stats as stats
from scipy import sparse as sp
import torch
class Graph(object):
def __init__(self, num_nodes: int, edges: np.ndarray, flow: np.ndarray = None):
self._verify(num_nodes, edges, flow)
self._num_nodes = num_node... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('proyectos', '0020_auto_20150813_1815'),
]
operations = [
migrations.AlterField(
model_name='detalleproductoestim... |
from onegov.core.orm.abstract import AdjacencyList
from onegov.core.orm.abstract import MoveDirection
from onegov.core.orm.mixins import ContentMixin
from onegov.core.orm.mixins import meta_property
from onegov.core.orm.mixins import TimestampMixin
from sqlalchemy import Boolean
from sqlalchemy import Column
from sqlal... |
import io
import copy
import random
import asyncio
import textwrap
import traceback
from typing import Union, Sequence
from contextlib import redirect_stdout
import discord
import aiosqlite
from discord.ext import commands
from potato_bot.bot import Bot
from potato_bot.cog import Cog
from potato_bot.utils import ru... |
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(style="ticks")
from sklearn.datasets import make_blobs
X, y = make_blobs(n_samples=600, centers=4, n_features=3, random_state=42, cluster_std = 2)
df = pd.DataFrame(X)
df.columns = ["col_1", "col_2", "col_3"]
df["Label"] = y
df.to_csv... |
#! usr/bin/python3
from treenode import TreeNode
def levelOrder(root: TreeNode) -> List[List[int]]:
arr = []
def prtnext(root: TreeNode) -> list:
pass
|
import sys
from abc import ABC, abstractmethod
from typing import Callable, Dict
from colosseum.ipc import FileNoComs
pipeout_fileno = sys.stdout.fileno()
pipein_fileno = sys.stdin.fileno()
_coms = FileNoComs(
True,
read_fileno=pipein_fileno,
write_fileno=pipeout_fileno
)
def log(*args, **kwargs):
"""
Logs a m... |
from django.shortcuts import render, redirect
from django.views.generic.edit import CreateView
from django.views.generic import ListView, DetailView
from django.views.generic.base import View
from movie.models import Movie
from movie.forms import ReviewForm
class MovieView(ListView):
"""Вывод всех фильмов"""
... |
import os
from dotenv import load_dotenv
from slack_sdk import WebClient
from slack_sdk.errors import SlackApiError
from src.Config import Config
class Slack(Config):
token = None
client = None
def __init__(self):
super().__init__()
self.set_token()
def set_token(self):
if o... |
# -*- coding: utf-8 -*-
# flake8: noqa
# Generated by Django 1.11 on 2017-05-06 15:43
from __future__ import unicode_literals
import ckeditor_uploader.fields
from django.db import migrations, models
import django.db.models.deletion
import image_cropping.fields
import snippets.utils.datetime
class Migration(migration... |
import pytest
from onegov.ticket import Handler
from onegov.ticket.errors import DuplicateHandlerError
def test_invalid_handler_code(handlers):
# it's possible for the registry to not be empty due to other tests
count = len(handlers.registry)
with pytest.raises(AssertionError):
handlers.registe... |
N, K = map( int, input().split())
T = [(0,0)]*N
for i in range(N):
t, d = map( int, input().split())
T[i] = (d,t)
T.sort( key= None, reverse = True)
C = T[:K]
AC = T[K:]
kiso = 0
s = 0
S = [0]*(N+1)
for i in range(K):
d, t = T[i]
kiso += d
if S[t] == 0:
S[t] = 1
s += 1
else:
... |
from atm_card import ATMCard
class Customer:
def __init__(self, id, cust_pin = 1234, cust_balance = 10000):
self.__id = id
self.__atm = ATMCard(cust_pin, cust_balance)
@property
def id(self):
pass
@id.getter
def id(self):
return self.__id
@property
def cus... |
"""
------------------------------------
@Time : 2020/9/15 14:46
@Auth : chai
@File : test_2_homePageCase.py
@IDE : PyCharm
@Motto:
------------------------------------
"""
import time
import random
import pytest
from Page import BasePage
from data.login_data import LoginData
from Page.BasePage import BasePage
from co... |
from unittest import TestCase
import unittest
import sys
sys.path.append('../')
from leetCodeUtil import TreeNode
from convert_sorted_array_binarytree import Solution
class TestSolution(TestCase):
def test_convertCase1(self):
## Test case 1
sol = Solution()
node = sol.sortedArrayToBST([1, ... |
import os
import time
import datetime
import pandas as pd
import requests
from key import fcs_key
# TODO: dividend tracker pulling newest update from database
# TODO: appending newest update to GSheets (online database)
def check_make_dir() -> str:
""" Checks if dir exists and creates it.
To hold csv_file
... |
# %% Import Libraries
from utils import edges, show_graph, Graph, get_input, sort_edge, is_connected
from copy import deepcopy
# %% Algorithm
def kruskal(graph):
"""
Apply Kruskal algorithm to find minimum spanning tree of a graph
:param graph: A list of nodes (a graph)
:return: Spanning tree of a gr... |
def flip_num(my_nu):
return '1' if(my_nu == '0') else '0';
def gray_to_binary(gray):
binary_code = ""
binary_code += gray[0]
for i in range(1, len(gray)):
if (gray[i] == '0'):
binary_code += binary_code[i - 1]
else:
binary_code += flip_num(binary_code[i - 1])
return binary_code... |
# coding: utf-8
# Copyright 2013 The Font Bakery Authors. All Rights Reserved.
#
# 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 re... |
# Create your views here.
from django.http import HttpResponse,HttpResponseRedirect
from django.shortcuts import render,get_object_or_404,render_to_response
from django.utils import timezone
from django.core.context_processors import csrf
from django import forms
from django.template import RequestContext
from core.mo... |
from os.path import join
from joblib import load
import os
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
from mvmm.multi_view.block_diag.graph.bipt_community import community_summary
from mvmm.multi_view.block_diag.graph.linalg import eigh_Lsym_bp
from mvmm.clustering_measures import MEASUR... |
# coding:utf-8
# This program is used to show the curves of Figure 2 in the paper
import numpy as np
import matplotlib.pyplot as plt
# The font size on the graph we will plot
size_font = 18
# The marker size on the graph we will plot
size_marker = 9
# Opening a txt file
f = open("../Data/SampleIncrease.txt")
sample... |
from django.conf.urls.defaults import *
from django.views.generic.simple import direct_to_template
from django.views.generic.list_detail import object_list
from stereoit.djangoapps.news.models import News
news_dict = {
'queryset' : News.objects.all()
}
urlpatterns = patterns('stereoit.djangoapps.news.views',
# ... |
#!env python3
# -*- coding: utf-8 -*-
from pymongo import MongoClient
nobel_winners = [{
'category': 'Physics',
'name': 'Albert Einstein',
'nationality': 'Swiss',
'sex': 'male',
'year': 1921
}, {
'category': 'Physics',
'name': 'Paul Dirac',
'nationality': 'British',
'sex': 'male',
... |
import torch
from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.init as init
from torch.utils import data
import torch.utils.model_zoo as model_zoo
from torchvision import models
class Refine(nn.Module):
def __init__(self, inplanes, planes, scale_factor=2):
... |
from SingleLinkList import SingleLinkList
def find_common_node1(singlelinklistA, singlelinklistB):
"""
思路一:两个单链中的元素依次分别放入两个栈中,然后依次弾栈找到第一个不相同的元素,
最后一个相同的元素就是第一个公共的节点.
"""
stack_A = []
stack_B = []
same_item = []
while not singlelinklistA.isEmpty():
stack_A.append(sin... |
from django.contrib import admin
from .models import Region, Country
admin.site.register(Region)
admin.site.register(Country) |
from django.db import models
from django.utils.translation import ugettext as _
from django.core.validators import MaxValueValidator, MinValueValidator
class ThomCurrency(models.Model):
currency = models.CharField(max_length=5, primary_key=True, verbose_name=_("Currency"))
currency_name = models.CharField(max_length... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.Create... |
a = [1,2,3,4,5,6] #creating a list using [] bracket
print(a) # printing the list
print(a[0]) # printing the element of the list
a[0] = 19 #changing the element of the list
print(a)
# we can create a list with items of different type
b = [19,"sarthak","python developer",False,6.8]
print(b)
#list slicing
print(... |
#!/usr/bin/env python
# coding: utf-8
# In[2]:
import cv2
# In[3]:
def nothing(x):
pass
cv2.namedWindow('threshold')
cv2.namedWindow('canny')
# add ON/OFF switch to "canny"
switch_c = '0 : OFF \n1 : ON'
switch_t = '0 : OFF \n1 : ON'
cv2.createTrackbar(switch_c, 'canny', 0, 1, nothing)
cv2.createTrackbar(swit... |
if __name__ == "__main__":
n, m = map(int, input().split())
sneezes = 0
while m > 0:
if m & 1:
sneezes += 1
m = m // 2
print(sneezes)
|
import subprocess
import os
import time
import recent.markup.markup
from recent.notifier.base import Notifier
class X11Notifier(Notifier):
id = 'x11notify'
deps = ['x11']
config_keys = ['display']
def notify(self, item):
if self.config['display'].startswith(':'):
os.putenv('DISPLAY... |
import unittest
def unique_0(s):
dic = {}
for c in s:
if c in dic:
return False
dic[c] = True
return True
def unique_1(s):
return len(s) == len(set(s))
class Test(unittest.TestCase):
def test_unique(self):
data = [
('', True),
('abc', ... |
#!/usr/bin/env python
'''
This program is used to simulate the basic Paxos algorithm.
The Proposer is also the Learner who finally learns which proposal is chosen. The Acceptor receives proposal and make desision.
We simulate the case that network is broken so the message can not reach to a target. But we do not simul... |
import re
textstr = "http://220.181.154.15/youku/777/6973A2989B932823EEF40247DA/0300020100563ABD71FD2B0230E416F0CBC1F3-EE10-EB22-744F-6010E6849F8C.flv?nk=314613209945_24111796410&ns=2880720_2720180&special=true"
#textstr = "http://220.181.154.15/youku/777/6973A2989B932823EEF40247DA/0300020100563ABD71FD2B0230E416F0CBC1... |
# Given a string, find the first non-repeating character in it and return
# it's index. If it doesn't exist, return -1.
#
# Examples:
#
# s = "leetcode"
# return 0.
#
# s = "loveleetcode",
# return 2.
# Note: You may assume the string contain only lowercase letters.
def first_unique_char(s):
low = {}
seen = ... |
# Download Pycrypto for Windows - pycrypto 2.6 for win32 py 2.7
# http://www.voidspace.org.uk/python/modules.shtml#pycrypto
# Download Pycrypto source
# https://pypi.python.org/pypi/pycrypto
# For Kali, after extract the tar file, invoke "python setup.py install"
import socket
import subpr... |
from pyral import Rally, rallySettings, rallyWorkset
import sys
import csv
"""
"""
gAttribs = [
"FormattedID", #"Name",
"ScheduleState",
"Project.Name",
"Project.Parent.Name",
"PlanEstimate",
"Iteration.Name",
"PortfolioItem.FormattedID", #"Portf... |
# -*- coding: utf-8 -*-
# This file as well as the whole tsfresh package are licenced under the MIT licence (see the LICENCE.txt)
# Maximilian Christ (maximilianchrist.com), Blue Yonder Gmbh, 2016
"""
Contains methods to start and stop the profiler that checks the runtime of the different feature calculators
"""
impor... |
from constants import DEFAULT_LOCATION_DESCRIPTION
class Environment:
"""Represent the game's environment; physical and historical."""
_shared_state = {"items": []}
def __init__(self):
self.__dict__ = self._shared_state
def best_match(self, itemname):
"""
Return the best matc... |
import requests
class BadRequest(requests.exceptions.HTTPError):
"""
Represents a detailed error message from a web server.
"""
def __str__(self) -> str:
message = super().__str__()
return f'{message} (status: {self.response.status_code})'
|
# coding: utf-8
import matplotlib.pyplot as plt
import seaborn as sns
class HistgramCreator():
def __init__(self, parent, figure_num):
self.fig, self.axes = plt.subplots()
self.parent = parent
self.data_list = []
self.data_name_list = []
self.color_list = [... |
import sqlite3
db=sqlite3.connect('college.db')
db.execute("DROP TABLE IF EXISTS stud")
db.execute("DROP TABLE IF EXISTS dept")
db.execute("DROP TABLE IF EXISTS courses")
db.execute("DROP TABLE IF EXISTS fac")
db.execute("DROP TABLE IF EXISTS res")
db.execute("CREATE TABLE stud(id INTEGER PRIMARY KEY AUTOINCREMENT,depa... |
"""
Time Complexity = O(N)
Space Coomplexity = O(W)
"""
from collections import deque
class Solution:
def getTargetCopy(self, original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode:
if not original or not cloned:
return None
queue = deque()
queue.... |
from unittest import TestCase
import unittest
from ugly_number import Solution
class TestSolution(TestCase):
def test_uglyNumberCase1(self):
sol = Solution()
self.assertEqual(sol.isUgly(8), True)
def test_uglyNumberCase2(self):
sol = Solution()
self.assertEqual(sol.isUgly(7),... |
# pylint: disable = C0103, C0111, C0301, R0913, R0903, R0914, E1101
from __future__ import division
import os
import shutil
# import cPickle as pickle
import tensorflow as tf
def get_trainable_vars(scope_name):
train_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope=scope_name)
return train_v... |
#!env python3
# -*- coding: utf-8 -*-
import threading
from socketserver import ThreadingMixIn
from http.server import BaseHTTPRequestHandler, HTTPServer
class TestServer(BaseHTTPRequestHandler):
def handle_headers(self):
for k, v in self.headers.items():
print(k , ":" ,v)
self.rfil... |
import numpy as np
import librosa
from tensorflow.keras.models import load_model
import warnings
warnings.filterwarnings('ignore')
test_music = './project/mini/data/country.6.mp3'
y, sr = librosa.load(test_music)
mel_spect = librosa.feature.melspectrogram(y=y, sr=sr, n_fft=2048, hop_length=1024)
mel_spect = librosa.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.