text stringlengths 8 6.05M |
|---|
import profile
def fib(n):
# from http://en.literateprograms.org/Fibonacci_numbers_(Python)
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib(n-1) + fib(n-2)
def fib_seq(n):
seq = [ ]
if n > 0:
seq.extend(fib_seq(n-1))
seq.append(fib(n))
return ... |
import numpy as np
from dps.train import training_loop
from dps.config import DEFAULT_CONFIG
from dps.rl.algorithms import qlearning
from dps.env import cliff_walk
from dps.rl.policy import BuildLinearController
config = DEFAULT_CONFIG.copy()
config.update(qlearning.config)
config.update(cliff_walk.config)
config.up... |
#!/usr/bin/python
# Copyright (c) 2016 University of Utah Student Computing Labs. ################
# All Rights Reserved.
#
# Permission to use, copy, modify, and distribute this software and
# its documentation for any purpose and without fee is hereby granted,
# provided that the above copyright notice appears in al... |
new_text = "winner winner chicken dinner"
print(new_text[0],new_text[1],new_text[2], new_text[3])
print(new_text[0:6])
cs_all_in_one = "파이썬, 자료구조, C, C++"
cs_all_in_one.split("+")
print(cs_all_in_one)
python = "파이썬"
before = "cs all in one %s" % python
after = "cs 올인원 {}".format(python)
print(before)
prin... |
# By: Jared Donnelly
# CS 110 - Prof. Kevin Ryan
# I pledge my Honor that I have abided by the Stevens Honor System
def main():
print("The following program accepts numerical inputs and sums them")
print("Please list all the numbers you would like to enter in a list separated by spaces")
sumables = input("... |
const { HeroType } = require('./model/hero');
const { AbilityType } = require('./model/abilites');
const { State } = require('./model/state');
const { Map } = require('./model/map');
const { Parameters } = require('./model/parameters');
const { Teams } = require('./model/teams');
let game_map = null;
let game_params =... |
from bs4 import BeautifulSoup
from requests import get
from flask import Flask
app = Flask(__name__)
@app.route('/')
def helloWorld():
print('Hello, Scrapers!')
@app.route('/scrape')
def scrape():
url = 'https://www.basketball-reference.com/players/w/wadedw01.html'
response = get(url)
soup = Beautiful... |
s,v=map(int,input().split())
print(pow(s,v))
|
from typing import List
from pydantic import BaseModel
class Prediction(BaseModel):
filename: str
predicted: str
extracted_features: List
|
from modules import cell as c,\
explosive as exive,\
explosion as ex,\
wall_mutable as wm
class Bomb(c.Cell, exive.Explosive):
def __init__(self, position, timer, user):
self.timer = timer
self.ex_type = user.ex_type
self._position = position
self.user = us... |
#!/usr/bin/python3
"""Square Module"""
class Square():
"""Square.
Private instance attribute: size:
property def size(self).
property setter def size(self, value).
Instantiation with optional size.
Public instance method: def area(self).
"""
def __init__(self, size=0):
... |
class Point:
def __init__(self, x=0, y=0):
self.a = x
self.b = y
def __pow__(self, otherObj):
obj = Point()
obj.a = self.a ** otherObj.a
obj.b = self.b ** otherObj.b
return obj
def main():
object1 = Point(12, 13)
object2 = Point(2, 2)
object3 = ... |
'''
Created on Jul 19, 2012
@author: Michele Sama (m.sama@puzzledev.com)
'''
import datetime
from django.template.defaultfilters import safe
from django.db.models.base import Model
from jom import factory as jom_factory
from django.template.loader import render_to_string
from types import NoneType
class JomField(obje... |
n=int(input())
l=list(map(int,input().split()))
v=[]
for i in range(n):
if i%2==0:
if l[i]%2!=0:
v.append(l[i])
elif i%2!=0:
if l[i]%2==0:
v.append(l[i])
for i in v:
print(i,end=" ")
|
from discord.ext import commands
import re
class Maths():
"""Some mathematical commands"""
def __init__(self, bot):
self.bot = bot
@commands.command(description="Add two numbers together",
brief="Addition")
async def add(self, left : float, right : float):
await... |
""" Geometry with automated choice of used format. """
from .base import SeismicGeometry
from .blosc import BloscFile
|
# -*- coding: utf-8 -*-
import statistics
import scipy.stats as sts
from scipy.stats import norm
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.mlab as mlab
print("Homework 1: Hailey Kryszewski 124001456")
print("Question 1:\n")
print("Mean Median and Mode for FE_H")
astroValuesFE=[-.60,-.63,-.57,... |
draws_bounding_box = False
|
import calendar
year = 2021
for month in range(1, 13):
print(calendar.month(year, month))
|
def df1(max):
n,a,b = 0, 0, 1
while n < max:
print(b)
b,a = a + b, b
n = n + 1
return 'done'
|
class Solution:
def longestValidParentheses(self, s):
"""
:type s: str
:rtype: int
来自LeetCode的答案 写的非常的好
https://leetcode.com/problems/longest-valid-parentheses/discuss/14126/My-O(n)-solution-using-a-stack
"""
stack, res, s = [0], 0, ')'+s
for i in rang... |
import math
from new.rules import *
class Point(object):
x = 0
y = 0
def __init__(self, x, y):
self.x = x
self.y = y
class Branch(object):
color = Color(0, 0, 0)
def __init__(self, angle, start_point, end_point):
self.length = 10
self.angle = angle
self... |
#!/proj/sot/ska3/flight/bin/python
#####################################################################################
# #
# create_interactive_page.py: create interactive html page for a given msid #
# ... |
from itertools import permutations
print list(permutations([0,1,2,3,4,5,6,7,8,9]))[999999]
|
import random
import my_module
print("Module Implementation:")
print("My name is:", my_module.name)
print(my_module.age)
print("Print a random whole number between 1 and 10 (inclusive):")
# randint generates a random number in a given range (inclusive of the lower and upper limit)
random_integer = random.ran... |
import re
import os
def is_loc(line):
raise NotImplementedError()
def loc_in_file(filename):
raise NotImplementedError()
def loc_in_directory():
raise NotImplementedError()
|
from collections import Counter
def sherlockValidSting(s):
freq = Counter(s)
# same frequency
if len(set(freq.values()) == 1):
return 'Yes'
# more than 2 unique frequencies
elif len(freq.values() > 2):
return 'No'
# two unit freq
else:
for key in freq:
freq[key] -=1
temp = list(f... |
"""
作者:Wanghao
日期:2020年11月19日
"""
import matlab.engine
import numpy as np
from tkinter import *
root = Tk()
root.title("图像重建")
root.geometry("600x230")
eng1 = matlab.engine.start_matlab()
eng2 = matlab.engine.start_matlab()
eng3 = matlab.engine.start_matlab()
def Import():
a=np.loadtxt("tr... |
import tek.test
tek.test.setup(__file__)
|
from random import shuffle
from scratch.linear_algebra import sum_of_squares
from s1 import quantile
import math
num_friends = list(range(101))
shuffle(num_friends)
def mean(xs: List[float]) -> float:
return sum(xs)/len(xs)
def data_range(xs: List[float]) -> float:
return max(xs) - min(xs)
def de_mean(xs: L... |
import numpy as np
import nibabel as nib
# Define Paths
confounds_path = '/mnt/project1/home1/varunk/fMRI/Autism-Connectome-Analysis/confounds/calc_residuals/'
mean_csf = confounds_path + 'mean_csf.txt'
mean_wm = confounds_path + 'mean_wm.txt'
mean_global = confounds_path + 'mean_global.txt'
residual_file = confoun... |
import fcntl, termios, struct
def get_console_size():
h, w, hp, wp = struct.unpack("HHHH",
fcntl.ioctl(0, termios.TIOCGWINSZ,
struct.pack("HHHH", 0, 0, 0, 0)
)
)
return {"height": h, "width": w}
|
limits, lines = [], []
with open('/var/lib/dpkg/status') as fp:
lines = fp.read().splitlines()
begin, end = 0, 0
for line in lines:
if len(line.rstrip()) == 0:
limits.append((begin, end))
begin = end + 1
end += 1
# uqnique dependencies
unique_dependenc... |
# Copyright 2020 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
from pathlib import PurePath
from textwrap import dedent
import pytest
from packaging.utils import canonicalize_name as canonicalize_project_name
from... |
"""
================================
Digits Classification Exercise
================================
A tutorial exercise regarding the use of classification techniques on
the Digits dataset.
This exercise is used in the :ref:`clf_tut` part of the
:ref:`supervised_learning_tut` section of the
:ref:`stat_learn_tut_inde... |
from rest_framework import serializers
from .models import Event
class EventSerializer(serializers.ModelSerializer):
id = serializers.IntegerField(read_only=True)
title = serializers.CharField()
description = serializers.CharField()
start = serializers.CharField()
end = serializers.CharField()
... |
from DPjudge import Power
class XtalballPower(Power):
# ----------------------------------------------------------------------
def __init__(self, game, name, type = None):
Power.__init__(self, game, name, type)
# ----------------------------------------------------------------------
def __repr__(self):
text = ... |
from django.db import models
from django_countries.fields import CountryField
from phone_field import PhoneField
from django.conf import settings
gender_choices = (
('M', 'Male'),
('F', 'Female'),
('O', 'Other'),
)
class_choices = (
('6', 'Class 6'),
('7', 'Class 7'),
('8', 'Class 8'),
('9... |
from django.urls import path
from . import views
urlpatterns = [
#main paig
path("", views.index, name="index"),
#groupe list page
path("groups",views.groups_list, name="list"),
path('group/<str:slug>/',views.detail_group, name="detail_group_url"),
#user page , list post... |
"""
Python types on which database engine operates using public interfaces.
"""
from typing import Union
__all__ = [
'DB_TYPE',
'BYTEORDER',
'SIGNED',
'ENCODING',
'INVALID_ID',
'DFS_CONFIG_PATH',
'WORKER_PATH',
'REPLICA_PATH',
'NODE_STORAGE',
'RELATIONSHIP_STORAGE',
'PROPERT... |
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
journeys_df = pd.read_csv('data/clean_journeys.csv', parse_dates=[14, 15])
clean_df = pd.read_csv('data/clean_pred.csv')
station_df = pd.read_csv('data/stations.csv')
# create time colu... |
__author__ = 'toby'
|
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import json
data = pd.read_csv("D:\\Documents\\GitHub\\pyqt_groundstation\\logs\\07-24-2022_09-29-13\\PROP_DATA_0.txt")
other = open("D:\\Documents\\GitHub\\pyqt_groundstation\\logs\\07-24-2022_09-29-13\\PROP_OTHER_MSGS.txt").readlines()
transitio... |
import wx
import re
from mcp21.package import MCPPackageBase
class MCPPackage(MCPPackageBase):
def __init__(self, mcp):
MCPPackageBase.__init__(self, mcp)
self.package = 'dns-com-vmoo-smartcomplete'
self.min = '1.0'
self.max = '1.0'
self.callbacks = {}
... |
import glob
import re
from pprint import pprint
import tensorflow as tf
import tensorflow_hub as hub
import matplotlib.pyplot as plt
from sklearn.model_selection import KFold
import time
import numpy as np
import pandas as pd
import seaborn as sns
best_roc_aucs = {
'accuracy': [],
'accuracy_baseline': [],
... |
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the jumpingOnClouds function below.
def jumpingOnClouds(c):
pos = 0
jump_count = 0
while pos < len(c)-1:
pos = pos+2 if len(c) - pos -1 >= 2 else pos+1
if c[pos] == 1:
pos -= 1
jump_count... |
__author__ = 'maguowei'
|
# Copyright (c) 2017-2020, University of Tennessee. All rights reserved.
# SPDX-License-Identifier: BSD-3-Clause
# This program is free software: you can redistribute it and/or modify it under
# the terms of the BSD 3-Clause license. See the accompanying LICENSE file.
'''
Tags project with version based on current dat... |
from re import compile, match
REGEX = compile(r'^(?:([a-zA-Z]+) ?(\d+)|(\d+) ?([a-zA-Z]+))$')
VALUES = {
'USD': [1, 2, 5, 10, 20, 50, 100], 'CUP': [1, 3, 5, 10, 20, 50, 100],
'RUB': [10, 50, 100, 500, 1000, 5000], 'UAH': [1, 2, 5, 10, 50, 100, 500],
'SOS': [1000], 'EUR': [5, 10, 20, 50, 100, 200, 500]}
d... |
"""
<Function 2: Duplication Check>
Author: Osiel Ramirez
Authored on: 12/22/2020
1. Receive the dictionary from the 1st function.
2. Check if the dictionary value [Mac address] exists more than once.
3. If a duplication is found, print that machine is being ARP spoofed
4. Exit elegantly without fail.
"""
import ext... |
from Node import Node
class BST:
def __init__(self):
self.__root = None
def isEmpty(self):
return self.__root == None
def insertNodes(self,other):
new_node = Node()
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (C) 2009-2012:
# Hynes Stephen, sthynes8@gmail.com
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation... |
import os
from os.path import dirname, basename, join, abspath, relpath
import platform
from datetime import date, datetime
from .json_uploader import json_uploader
DEBUG = os.environ['DEBUG'] == 'True' if 'DEBUG' in os.environ else False
EMULATE_UCONTROLLERS = DEBUG
VERSION = '1.0.3.6'
PROJECT_PATH = dirname(dirna... |
import numpy as np
import math
import matplotlib.pyplot as plt
#plt.switch_backend('Qt4Agg')
# read in and plot
rg = np.loadtxt("langevin/rg.txt", skiprows=2)
rg2 = np.loadtxt("dpd/rg.txt", skiprows=2)
fig, ax = plt.subplots()
ax.plot(rg[:,0], rg[:,1], "r-", label="Rg, Langevin")
ax.plot(rg2[:,0], rg2[:,1], "b-", l... |
from fractions import gcd
def nbr_of_laps(x, y):
lcm = (x * y) / gcd(x, y)
return [lcm / x, lcm / y]
|
# Import all libraries and classes
import os
from random import randint
import pygame
from pygame.locals import *
from Collision import GameCheck
from Fish import Fish
from Fruit import Fruit
from Slither import Slither
# Position of game screen
x_pos = 300
y_pos = 120
cmd = 'wmic desktopmonitor get s... |
#Time Complexity: O(n)
#Space Complexity: O(1)
#Did this code successfully run on Leetcode : Yes
#Any problem you faced while coding this : No
class Solution:
def rob(self, nums: List[int]) -> int:
total=0
n=len(nums)
n = len(nums)
if n == 0:
return 0
i... |
from django.contrib import admin
from .models import Profile, FollowList
admin.site.register(Profile)
admin.site.register(FollowList)
|
from fabric.api import env
env.shell = '/bin/sh -c '
DEBUG = 1
import setup
import deploy
import rollback
import hostinfo
#TODO: shuold make some install/register mechanism
T = [setup.setup,
deploy.deploy,
deploy.ideploy,
deploy.check,
rollback.rollback,
hostinfo.hostinfo,
]
if DEBUG:
... |
#-*- coding: utf-8 -*-
"""referrence:
1. https://blog.csdn.net/zhupenghui176/article/details/109097737
2. https://www.jb51.net/LINUXjishu/457748.html ##如何解决僵尸进程及其原理
"""
import os
import time
import signal
print("main main pid")
print(os.getppid())
print("main pid:%d" % os.getpid())
def fork(cmd, times=3):
r, w = ... |
from flaskbox.helpers import create_init_file
def test_init_file(tmpdir):
"""Check if flaskbox.yml file is created correct
"""
file = tmpdir.join('flaskbox.yml')
create_init_file()
assert file
|
# Find the number of composite integers, n < 10^8, that have precisely two,
# not necessarily distinct, prime factors.
from math import floor, sqrt
LIMIT = 100000000
# A semiprime is a composite number that has precisely two, not necessarily
# distinct prime factors.
def countSemiPrime():
numPrimeFactorSieve = f... |
t=int(raw_input())
s=0
while t:
ip=int(raw_input())
if ip>0:
s+=ip
t-=1
print s
|
Python 3.6.2 |Anaconda custom (64-bit)| (default, Sep 19 2017, 08:03:39) [MSC v.1900 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> obj={'day':1,'date':1,'week':7,'fortnight':14,'month':1,'year':1,'decade':10,'century':100}
multi={'before':-1,'after':1,'later':1,'next... |
#!/usr/bin/env python
"""
ox.py : quick checks on photons
===================================
::
In [36]: ox.view(np.int32)[:,3] ... |
from rest_framework import serializers
from . import models
from artuium_server.artwork import serializers as artwork_serializers
from artuium_server.statics import models as statics_models
class RegionSerializer(serializers.ModelSerializer):
class Meta:
model = models.Region
fields = ['name']
c... |
if __name__ == '__main__':
num = [int(x) for x in raw_input().split(" ")]
count = 0
num.sort()
for i in xrange(0, 3):
if num[i] == num[i+1]:
count += 1
print count
|
import copy
from unittest import mock, skipIf
import pandas as pd
from django.conf import settings
from django.test import TestCase, RequestFactory, Client as Browser, override_settings
from django.contrib.sessions.middleware import SessionMiddleware
from django.core.exceptions import ObjectDoesNotExist, ValidationEr... |
import boto3
import json
def get_key_information():
conn = boto3.client('ec2')
regions = [region['RegionName'] for region in conn.describe_regions()['Regions']]
key_info = []
for region in regions:
client = boto3.client('kms', region_name=region)
response = client.list_keys()['Keys']
... |
import json
from django.http import HttpResponse
from django.views import View
from django.contrib.contenttypes.models import ContentType
from django.views.generic import TemplateView
from home.forms import HomeForm, CommentForm
from django.shortcuts import redirect, render
from home.models import Post, Comment, Like,... |
from selenium.webdriver import Chrome
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
def test_KeyBoard():
path = "C:\\chromedriver\\chromedriver.exe"
driver = Chrome(executable_path=path)
driver.get("https://www.theTestingWorld.com/testings"... |
from board2 import *
class Minmax():
def __init__(self, eval):
self._eval = eval
def minmax(self, board, depth=2):
if depth == 0 or board.get_winner() != 0:
return (self._eval(board) * board.playerTurn, None)
children = ((move, board.apply_move(move[0], *move[1])) for move in board.moves())
return max(
... |
# -*- coding: UTF-8 -*-
from __future__ import unicode_literals # Python提供了__future__模块,把下一个新版本的特性导入到当前版本,于是我们就可以在当前版本中测试一些新版本的特性
import datetime #导入时间模块
import requests
import feedparser #此模块可以方便的获取RSS订阅源的信息
from flask import Flask, render_template, request, make_response
#render_template模块根据用户模板返回信息给templat... |
#!/usr/bin/python
# -*- coding: cp936 -*-
import sqlite3
import pandas as pd
def importNewregToSQLite():
"""excel"""
with sqlite3.connect('C:\sqlite\db\hxdata.db') as db:
#ExcelDocument('..\input\营销人员和营业部列表.xlsx') as src:
insert_template_4 = "INSERT INTO newreg " \
... |
#-*- coding: utf-8 -*-
from models import *
from django.contrib.auth import authenticate, login
from django.contrib.auth.models import User
from django.http import HttpResponse, HttpResponseBadRequest
from django.http.response import HttpResponseNotAllowed
from django.utils import simplejson
from django.core import se... |
from flask import request
from kernel.signal import http_request_signal, http_response_signal
def init_event(core):
app = core.app
app.before_request(_before_each_request)
app.after_request(_after_each_request)
def _before_each_request():
http_request_signal.send(request=request)
def _after_each_r... |
from __future__ import print_function # Python 2/3 compatibility
import boto3
import time
import csv
import sys
from lab_config import boto_args
def import_csv(tableName, fileName):
dynamodb = boto3.resource(**boto_args)
dynamodb_table = dynamodb.Table(tableName)
count = 0
time1 = time.time()
with... |
from django.db import models
from django.contrib.auth.models import AbstractUser
# Create your models here.
class Meeting(models.Model):
meeting_title = models.CharField(max_length = 50, blank = True, default = 'Title is not given')
meeting_estimated_time = models.DurationField(blank = False, null = False)
... |
from flask import Flask
from flask_restful import Api
from flaskext.mysql import MySQL |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Created on 2018-11-06 11:52:31
# Project: PySpider_MaFengWo
from pyspider.libs.base_handler import *
import json
from pyspider.libs.utils import md5string
import re
from fake_useragent import UserAgent
default_headers = {
'Accept':'application/json, text/ja... |
from PyML import *
from PyML import ker
from PyML.classifiers import multi
from PyML.demo import demo2d
import csv
from PyML.datagen import sample
import matplotlib.pyplot as plt
def read_data(file_name):
if file_name== 'train':
data = vectorDatasets.VectorDataSet("train_new_train.data")
data.attachL... |
'''
Arduino
requirement:
pip3 install pymata-aio --user
'''
import zmq
import subprocess
import pathlib
import platform
import time
import threading
from codelab_adapter import settings
from codelab_adapter.core_extension import Extension
def get_python3_path():
# If it is not working, Please replace pytho... |
def reverse(st):
return ' '.join(reversed(st.split(' ')))
|
#!/usr/bin/python
#from pylab import plot,show,norm
#from pylab import plot,show,norm
#import numpy
import sys
from csv import reader, writer
#from sklearn import preprocessing
from decimal import *
betas = []
betas.append(0.0)
betas.append(0.0)
betas.append(0.0)
def load_csv(filename):
samples = list()
wit... |
from __future__ import print_function
import os,imp
import pprint as pp
import socket
import sys
import datetime as dt
import errno
import traceback
from socket import error as socket_error
e=sys.exit
#builtins: init, config
def formatExceptionInfo(maxTBlevel=5):
cla, exc, trbk = sys.exc_info()
excName = cla.__name... |
#!/usr/bin/python3
# Written by Michael Gillett, 2020
# github.com/gillettmi
# A simple morse code conversion program
import time
import os
from playsound import playsound as ps
from cipher import *
morse = {
'a': '.-', 'b': '-...', 'c': '-.-.',
'd': '-..', 'e': '.', 'f': '..-.',
'g': ... |
from tour import Tour
class Population(object):
def __init__(self, size, initialize, tour_manager):
self._tours = []
self.tour_manager = tour_manager
if initialize:
for i in range(0, size):
tour = Tour(tour_manager)
tour.generate_individu... |
from django.apps import AppConfig
class PioperateConfig(AppConfig):
name = 'PiOperate'
|
import scipy
from numpy import *
import scipy.integrate
from fractions import Fraction
# finding the volume integral of divergence
def Dv(x,y,z):
return 2*(x+y)
D1, errt = scipy.integrate.tplquad(Dv, 0, 1, lambda z: 0, lambda z: 1, lambda z,y: 0, lambda z,y: 1)
# finding the surface integral of 6 surfaces of a cub... |
from argparse import ArgumentParser
from types import SimpleNamespace
import os
import yaml
def convert_dict_namespace(dict_convert):
"""
Convert params from dictionary to SimpleNamespace type (in order to use dotted notation)
:param dict_convert: dictionary to convert
:return: SimpleNamespace
"""... |
# Copyright (c) 2021 kamyu. All rights reserved.
#
# Google Code Jam 2021 Round 3 - Problem B. Square Free
# https://codingcompetitions.withgoogle.com/codejam/round/0000000000436142/0000000000813e1a
#
# Time: O(R^2 * C^2)
# Space: O(R + C)
#
def inplace_counting_sort(nums, reverse=False): # Time: O(len(nums)+max(num... |
import json
import csv
import requests
from requests.auth import HTTPBasicAuth
import DiscoveryDetails as dt
from ibm_cloud_sdk_core.api_exception import ApiException
def delete_and_add_example(query_id, document_id, relevance):
deleteResult = dt.discovery.delete_training_example(dt.environment_id, dt.collection_i... |
import urllib.request
from bs4 import BeautifulSoup
def getDOBBoilerData( boroNum, houseNum, houseStreet ):
url = requestToDOBUrl( boroNum, houseNum, houseStreet )
soup = urlToSoup( url )
if hasDOBData( soup ):
return extractDOBDataFromSoup( soup )
else:
return "Invalid Query"
def requ... |
def binarySearch(array, start, end, needle):
if start > end:
return -1
mid = (start + end)/2;
if array[mid] == needle:
return mid
if needle < array[mid]:
end = mid-1
else:
start = mid+1
return binarySearch(array, start, end, needle)
array = [2, 3, 14, 25, 36, 47];
start = 0
end = len(array) - 1
needle... |
import numpy as np
import matplotlib.pyplot as plt
t = np.arange(0.0,5.0,0.01)
y = np.cos(2*np.pi*t)
plt.plot(t,y,'r--')
#注释函数
#xy 注释坐标
#xytext 注释文字坐标
plt.annotate('local max',xy = (2,1), xytext = (3,1.5),arrowprops=dict(facecolor='black', shrink=0.05),)
#y范围
plt.ylim(-2,2)
plt.show()
|
import os
os.system("rm ks_cpp.so")
import numpy as np
from KS_Sampling import ks_sampling, ks_sampling_mem
np.set_printoptions(precision=6, linewidth=120, suppress=True)
np.random.seed(0)
if __name__ == '__main__':
# -- Example 1 -- 5000 data points, feature vector length 100
n_sample = 5000
n_feature... |
import collections
import os
import urllib
import pytest
import torch
import torchvision
from pytest import approx
from torchvision.datasets.utils import download_url
from torchvision.io import _HAS_VIDEO_OPT, VideoReader
# WARNING: these tests have been skipped forever on the CI because the video ops
# are never pr... |
import re
from pathlib import Path
from bs4 import BeautifulSoup
from django.core.management import BaseCommand
from psqlextra.query import ConflictAction
from psqlextra.util import postgres_manager
# https://www.goodreads.com/work/quotes/1494157
from web.models import GoodreadsQuote
class Command(BaseCommand):
... |
# Copyright (c) Members of the EGEE Collaboration. 2004.
# See http://www.eu-egee.org/partners/ for details on the copyright
# holders.
#
# 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
#... |
packList = ['a', 'a', 'b', 'c', 'd', 'e', 'e', 'f', 'a', 'a', 'a', 'q', 'q', 'r']
bufferList = []
runList = []
element = 0
sameChar = 0
bounds = len(packList) - 1
while sameChar <= bounds:
bufferList.append(packList[element])
sameChar = element + 1
while sameChar <= bounds:
if packList[ele... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.