text stringlengths 8 6.05M |
|---|
import pandas as pd
import pickle
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score
from sklearn.preprocessing import MinMaxScaler
from sklearn import... |
from TikTokAPI import TikTokAPI
import json
import datetime
api = TikTokAPI()
def get_all_video_stats_by_username(username):
user = api.getUserByName(username)
video_list = []
videos = api.getVideosByUserName(username, count=user['userInfo']['stats']['videoCount'])['items']
for item in videos:
... |
def getPic():
""" prompts a user to pick a file to be converted to a jython picture """
return makePicture(pickAFile())
def amazify():
pic = getPic()
increaseContrast(pic)
addBorder(pic)
droste(pic)
writePictureTo(pic, 'C:\\Users\\J.McGhee\\Documents\\Jake\\CST205\\m... |
"""
LeetCode - Easy
"""
"""
Given an array of integers A sorted in non-decreasing order, return an array of the squares of each number, also in sorted non-decreasing order.
Example 1:
Input: [-4,-1,0,3,10]
Output: [0,1,9,16,100]
Example 2:
Input: [-7,-3,2,3,11]
Output: [4,9,9,49,121]
Note:
1 <= A.length <= 10... |
from django.conf.urls import url
from . import views
urlpatterns = [
#/orders/places/
url(r'^places/$',views.PlaceOrderAPIView.as_view(),name='placeorder'),
url(r'^$',views.OrderAPIView.as_view(),name='order'),
] |
from bitutils import test_bit as tb, set_bit, reset_bit
def next_(x):
""" Find the smallest number larger than `x` and has the same number of 1 bits as `x`
Idea: For a positive number `x`, we always can find the suffix `s` of the
style "0b011...100...0", where the number of "0" in the tail >= 0, and the
... |
#!/usr/bin/env python
from flask import Blueprint, request, current_app
from .util import log
api_bp = Blueprint("api", __name__)
@api_bp.after_request
def log_response(response):
"""Log any requests/responses with an error code"""
if current_app.debug: # pragma: no cover, debugging only
log.debu... |
# Generated by Django 3.0.1 on 2020-11-28 13:18
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
]
|
from ulugugu import BBox
from ulugugu.drawings import Drawing
class Empty(Drawing):
def __init__(self):
super().__init__(BBox((0, 0, 0, 0)))
def draw(self, ctx):
pass
class Rectangle(Drawing):
def __init__(self, size, color, fill='fill'):
super().__init__(BBox((0, 0, size[0], size[1])))
self.... |
import greenlet
def eat(name):
print("%s eat 1" % name)
# 第二步
g2.switch("egon")
print("%s eat 2" % name)
# 第四步
g2.switch()
def play(name):
print("%s play 1" % name)
# 第三步
g1.switch()
print("%s play 2" % name)
g1 = greenlet.greenlet(eat)
g2 = greenlet.greenlet(play)
# 第一步
g1... |
# 1.Given two integer numbers return their product.
# If the product is greater than 1000, then return their sum.
def summation(a, b):
sum = a + b
if(sum > 1000):
return sum
else:
return "Sumation is below 1000"
print(summation(100, 1000))
print(summation(100, 100))
|
posicion1 = input("Posición inicial canguro 1:")
longitud1 = input("Longitud de salto canguro 1:")
posicion2 = input("Posición inicial canguro 2:")
longitud2 = input("Longitud de salto canguro 2:")
if (posicion1 > posicion2 and longitud1 > longitud2) or (posicion1 < posicion2 and longitud1 < longitud2):
respuesta =... |
"""
CEASIOMpy: Conceptual Aircraft Design Software
Developed for CFS ENGINEERING, 1015 Lausanne, Switzerland
The scrpt will analyse the fuselage geometry from cpacs file for an
unconventional aircraft.
Python version: >=3.6
| Author : Stefano Piccini
| Date of creation: 2018-09-27
| Last modifiction: 2020-01-21 (AJ... |
#linux_handler
from Xlib.display import Display
from Xlib import X
from Xlib.ext import record
from Xlib.protocol import rq
import time
from linux_map import keysym_map
disp = None
class KeyListener(object):
def __init__(self):
"""Really simple implementation of a keylistener
Simply define your ... |
import time
from urllib.parse import urlparse
homeurl = "https://www.sunlifeglobalinvestments.com/"
class Advisor_tools_and_calculator():
def __init__(self, driver):
self.driver = driver
locators = {
"header_text": "//div[@class='title-bar']//h1[contains(text(),'Advisor tools and calculators... |
from django.shortcuts import render,HttpResponse,redirect
from django.contrib.auth.models import User
from .models import ContactUs
from django.contrib.auth import authenticate,login,logout
from django.contrib import messages
import re
from django.db import IntegrityError
from django.core.mail import send_mail
from dj... |
"""
Author: Sidhin S Thomas (sidhin@trymake.com)
Copyright (c) 2017 Sibibia Technologies Pvt Ltd
All Rights Reserved
Unauthorized copying of this file, via any medium is strictly prohibited
Proprietary and confidential
"""
from django.conf.urls import url, include
from trymake.website.core import views
# NAMESPA... |
#!/bin/python3
import sys
S = input().strip()
# Attempt to print the given input. If the input is not valid as an integer,
# handle the exception by priting "Bad String"
try:
print(int(S))
# Use type ValueError for conversion failures
except ValueError:
print("Bad String")
|
# https://old.reddit.com/r/dailyprogrammer/comments/8jcffg/20180514_challenge_361_easy_tally_program/
def tally(scoreTrack):
scoreTrack = list(scoreTrack)
print(scoreTrack)
scoreBoard = dict()
for char in scoreTrack:
if (char not in scoreBoard) and (char.islower() is True):
scoreBo... |
import numpy as np
a = np.array(range(1,11))
size = 5
# 모델을 구성하시오
def split_x(seq, size):
aaa = []
for i in range(len(seq) - size + 1):
subset = seq[i : (i+size)]
aaa.append(subset)
return np.array(aaa)
dataset = split_x(a,size)
x = dataset[:,:4] # (6, 4)
y = dataset[:,4] # (6,)
print(d... |
import pytest
import pdb
from pytest_bdd import scenarios, given, when, then, parsers
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
localhost = 'http://127.0.0.1:8000/'
# Scenarios
scenarios('../features/login.feature')
#Fixtures
@pytest.mark.usefixtures('chromeBrowser')
# Given St... |
import tensorflow as tf
import numpy as np
def norm_boxes(boxes, shape):
'''
Converts boxes from pixel coordinates to normalized coordinates.
Note: In pixel coordinates (y2, x2) is outside the box. But in normalized
coordinates it's inside the box.
:param boxes: [N, (y1, x1, y2, x2)] in pixel coo... |
import os
import shutil
from unittest import TestCase
from tempfile import TemporaryDirectory
import pandas as pd
__all__ = [
"test_base",
"test_empiric",
"test_enrich",
"test_enrich2",
"test_fasta",
"test_utilities",
"test_filters",
"test_validators",
"ProgramTestCase",
]
# TOD... |
import autograd.numpy as np
from CelestePy.util.data import mags2nanomaggies, df_from_fits
from CelestePy.util.dists.mog import MixtureOfGaussians
from CelestePy.util.dists.flux_prior import FluxColorMoG, GalShapeMoG, GalRadiusMoG, GalAbMoG
import cPickle as pickle
import pandas as pd
import pyprind
import fitsio
# cr... |
import sys
sys.stdin=open("input.txt", "r")
'''
# 사용해야 하는 자료 구조 = stack
: String을 그대로 사용하거나 Array를 사용하면 수정/삭제가 잦아서 시간복잡도 문제가 생긴다.
: 커서를 기준으로 좌우로 나누어서 stack 2개에 저장하면 될 것 같다.
: dequeue가 아니라 stack을 사용하는 이유는 문자열을 컨트롤할 때는
: 한번에 커서 전후의 data 하나씩만 조작가능하기 때문에 data가 들어오고 나가는 출입구는 하나면 된다.
# 문제 풀이 아이디어
: ... |
from Heap import MaxHeap
# Binary max heap percolate down
def max_heap_percolate_down(node_index, heap_list, list_size):
child_index = 2 * node_index + 1
value = heap_list[node_index]
while child_index < list_size:
# Find the max among the node and all the node's children
max_value = valu... |
from __future__ import division
try:
from collections.abc import Iterable
except:
from collections import Iterable
import warnings
from itertools import product
import numpy as np
# TODO: Incorporate @pablodecm's cover API.
__all__ = ["Cover", "CubicalCover"]
class Cover:
"""Helper class that defines ... |
from selenium import webdriver
import time
driver = webdriver.Chrome()
driver.implicitly_wait(10)
driver.get("https://www.baidu.com")
sreach_windows = driver.current_window_handle #获得当前窗口的句柄
driver.find_element_by_link_text("登录").click()
driver.find_element_by_link_text("立即注册").click()
all_handles = driver.window_... |
#Johnathan Hinebrook 9-24-14 -- 10-14-14
#mainprog.py
#This program calls all created mdels and plays the in order
################################################
##Imports
################################################
import time #for timeing
import stry #holds story and most text
import mov2 ... |
import numpy as np
import random as random
from math import *
from point import Point
class EESTOPlanner():
def __init__(self):
pass
def get_path(self, costMap, startPoint, endPoint):
num_paths = 20
max_num_its = 100
decay_factor = .99
cur_decay = decay_factor
N = 30 |
{
"uidPageCalendar": {
W3Const.w3PropType: W3Const.w3TypePanel,
W3Const.w3PropSubUI: [
"uidCalendarPanel",
"uidCalendarAddPanel"
]
},
# Calendar
"uidCalendarPanel": {
W3Const.w3PropType: W3Const.w3TypePanel,
W3Const.w3PropSubUI: [
... |
from flask import Flask, request, redirect, render_template, flash, session
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['DEBUG'] = True
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://blogz:locker@localhost:8889/blogz'
app.config['SQLALCHEMY_ECHO'] = True
db = SQLAlchemy(app)
app... |
from django.urls import path
from . import views
urlpatterns = [
path('ajouter_table', views.ajouter_table, name = 'ajouter_table'),
] |
"""
CSC131 - Computational Thinking
Missouri State University, Spring 2018
This module contains solutions to the problems found at the end of Chapter 5.
File: projects.py
"""
from functools import reduce
def is_sorted(my_list: list) -> bool:
"""
Project 6.5 - Defining a predicate.
:param my_list:
:r... |
import pandas as pd
student1 = pd. Series({'국어':100,"영어":80,'수학':90})
student2 = pd.Series({'수학':80,'국어':90})
print(student1,student2, sep='\n')
print()
print("# 두 학생의 과목별 점수로 사칙연산 수행 (시리즈 vs. 시리즈)")
addition = student1 + student2
subtraction = student1 - student2
multipication = student1 * student2
division = stude... |
# class sports:
# game = "cricket"
# def __init__(self, name, game, value):
# self.name=name
# self.game=game
# self.value=value
# def details(self):
# print(f"name of the player is {self.name}")
# print(f"game of the player is {self.game}")
# print(f"valu... |
import pygame, sys
from player import Player
from bullet import Bullet
class Game:
def __init__(self):
pygame.init()
self.screen = pygame.display.set_mode((1500, 800))
pygame.display.set_caption('Runner!')
self.clock = pygame.time.Clock()
self.fps = 60
self.player ... |
'''
Complete the function that accepts a string parameter, and reverses each word in the string. All spaces in the string should be retained.
Examples:
"This is an example!" ==> "sihT si na !elpmaxe"
"double spaces" ==> "elbuod secaps"
'''
def reverse_words(text):
textSplit = text.split(" ")
reverse = ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import time
buzpin = 23
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(buzpin,GPIO.OUT)
def beep(cnt):
for i in range(cnt):
GPIO.output(buzpin,True)
time.sleep(0.2)
GPIO.output(buzpin,False)
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from naoqi import ALProxy
from naoconfig import *
proxyMo = ALProxy('ALMotion',robot_IP,robot_port)
proxyMo.stiffnessInterpolation('Body', 1.0, 1.0)
proxyMo.angleInterpolation('HeadYaw', 1.2, 1.0, True)
|
import random
from numpy import array
from scipy.cluster.vq import kmeans
import numpy as np
#author name as key , and index as value
def read_authors_dict():
infile = open("data/authors.txt","r")
infile.readline()
authors_dict = {}
for line in infile:
fields = line.strip().split('|')
i... |
import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets, linear_model
from sklearn.metrics import mean_squared_error, r2_score
diabetes = datasets.load_diabetes()
type(diabetes)
type(diabetes.data)
diabetes.data.shape
x = diabetes.data[:, np.newaxis, 2]
y = diabetes.target
modelo = linear_mode... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import requests
import json
import os
import getpass
from bs4 import BeautifulSoup
import sys
import getopt
import subprocess
api_key_path = os.getcwd() + "/api.txt"
# 1。获得app路径
# 2。生成ipa包
# 3。登录蒲公英得到 key (保存key到文件)
# 4。上传ipa到蒲公英 (添加进度条)
# 5。通知测试用户
def get_app_path():
t... |
# Copyright 2016 Husky Team
#
# 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 law or agreed to in writing, softw... |
vowels='aeiou'
string=input('enter the string')
count=0
for i in vowels:
if i in string:
count+=1
print(count)
|
import os
from pyspark.sql import SparkSession
import pyspark.sql.functions as pssf
import pyspark.sql.types as psst
import pytest
import sparklib
@pytest.fixture(scope='session')
def spark():
os.environ['SPARK_LOCAL_IP'] = "127.0.0.1"
spark = SparkSession\
.builder\
.getOrCreate()
... |
#! /usr/bin/env python
import sys
import ddlib # Load the ddlib Python library for NLP functions
# For each input row
for row in sys.stdin:
# Parse tab-separated values
column1, column2, column3, ... = row.strip().split('\t')
# Output rows
print '\t'.join(map(str, [
column1,
column2,
colum... |
"""
the config info. in pre process.
"""
import os
# project path
PROJECT_PATH = os.path.abspath(os.path.dirname(os.getcwd()))
DATA_PATH = os.path.join(PROJECT_PATH, 'text_detector/data/train_data/')
IMG_PATH = os.path.join(DATA_PATH, 'sorted_image_9000/')
LABEL_PATH = os.path.join(DATA_PATH, 'sorted_txt_9000/')
# ra... |
from django.conf.urls import url
from eduprocess.views import GroupListView
urlpatterns = [
url(r'^list/$', GroupListView.as_view(), name='group_list'),
# url(r'^detail/$', GroupDetailView.as_view(), name='group_add'),
# url(r'^detail/(?P<pk>\d+)/$', GroupDetailView.as_view(), name='group_detail'),
] |
#!/usr/bin/env python
#-*- coding: utf-8 -*-
# author: hao 2019/7/17-21:44
from django.urls import path
from apps.news import views
app_name = 'news'
urlpatterns = [
path('', views.index, name='index'),
path('search/', views.search, name='search'),
]
|
# -*- coding: utf-8 -*-
"""
Created on Tue May 31 16:32:44 2016
@author: nmvenuti
Modeling grid search
"""
#Import packages
import pandas as pd
import numpy as np
import glob
from sklearn.preprocessing import StandardScaler
from sklearn import svm
from sklearn.ensemble import RandomForestRegressor
import time
#from... |
PORT = 80
HTTPS_PORT = 443
SERIAL = "/dev/ttyAMA0"
DOMAIN = "door.flipdot.space"
EMAIL = "my@invalid.email"
DEBUG=False
STAGING=True
fake_door = True |
# Generated by Django 2.2 on 2019-04-15 04:27
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('onlclass', '0008_auto_20190415_1319'),
]
operations = [
migrations.CreateModel(
name='Lesson',
... |
from django.contrib import admin
from django.urls import include, path
from django.conf import settings
from django.conf.urls.static import static
from profiles.views import home
from django.contrib.auth import views as auth_views
from django.views.generic.base import TemplateView
from profiles.views import home
urlpa... |
import numpy as np
import soundfile as sf
import pyworld as pw
WAV_FILE = ("./data/vaiueo2d")
data, fs = sf.read(WAV_FILE+".wav")
f0, t = pw.harvest(data, fs, 71.0, 800.0, 1.0)
option_cheaptrick_fft_size = 8192
sp = pw.cheaptrick(data, f0, t, fs, -0.15, 71.0, option_cheaptrick_fft_size)
option_d4c_fftsize = optio... |
# -*- coding: utf-8 -*-
#
# 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
#... |
from onegov.core.utils import module_path
from onegov.org.theme import OrgTheme
NEWSGOT = '"NewsGot", Verdana, Arial, sans-serif;'
# options editable by the user
user_options = {
'primary-color': '#e33521',
'font-family-sans-serif': NEWSGOT
}
class WinterthurTheme(OrgTheme):
name = 'onegov.winterthur.fo... |
import logging
from datetime import datetime
from typing import List, Optional
from dbcat.catalog import Catalog
from dbcat.catalog.models import JobExecution, JobExecutionStatus
from pglast.parser import ParseError
from data_lineage.parser.dml_visitor import (
CopyFromVisitor,
DmlVisitor,
SelectIntoVisit... |
a = [1, 2, 3]
b = [4, 5, 6]
c = [1]
d = [8, 8, 10]
list1 = c + b + a + d
list2 = a + b
list3 = c + d
list4 = a + a
print(list1)
print(list2)
print(list3)
print(list4) |
from manimlib.imports import *
def align_with(mob1, mob2):
'''
Will align the y component of the center of mob1 with mob2 by moving mob1 or mob2 horizontally
'''
mob1_center = mob1.get_center()
mob2_center = mob2.get_center()
mob1.shift((mob2_center[0] - mob1_center[0]) * RIGHT)
class IntroSce... |
#import sys
#input = sys.stdin.readline
from copy import deepcopy
def solve(N,Q):
Z = [0]*(N+1)
P = deepcopy(Q)
for i, p in enumerate(P):
Z[p] = i
permuted = [False]*N
for n in range(1,N+1):
if Z[n] == n-1:
continue
K = Z[n]
for i in range(K-1,n-2,-1):
... |
r,c=3,3
mainArray = [[0 for x in range(r)] for y in range(c)]
def printGrid():
for i in range(len(mainArray)):
for j in range(len(mainArray[i])):
if(mainArray[i][j]== 0):
print("|" + str(i) + str(j)+ "|" ,end="")
else:
print("|" + str(mainArray[i][j]) ... |
import gi, os
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
from gi.repository import Gdk
import threading
class Ventana(Gtk.Window):
def __init__(self):
#Creamos la ventana
Gtk.Window.__init__(self, title="rfid_gtk.py")
self.connect("destroy", Gtk.main_quit)
... |
import numpy as np
import os.path
import matplotlib.pyplot as plt
def writemr(filename):
path2mrfn='/kroot/rel/ao/qfix/data/ControlParms/Recon/'
file = np.fromfile(path2mrfn+filename, dtype='f', offset=1)
plt.plot(file)
np.savetxt('new_'+filename, file)
print('File '+ 'new_'+filename +' written')
|
import unittest
from pymongo import ReadPreference
from mongoengine.python_support import IS_PYMONGO_3
if IS_PYMONGO_3:
from pymongo import MongoClient
CONN_CLASS = MongoClient
READ_PREF = ReadPreference.SECONDARY
else:
from pymongo import ReplicaSetConnection
CONN_CLASS = ReplicaSetConnection
... |
import socket
HEADER_SIZE = 10
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((socket.gethostname(), 8086))
full_msg = ""
new_msg = True
while True:
msg = s.recv(16)
if new_msg:
print(f"new message length: {msg[:HEADER_SIZE]}")
msglen = int(msg[:HEADER_SIZE])
new_msg =... |
# Variables and Names
# defining cars variable and assigning value of 100
cars = 100
# defining space_in_a_car variable and assigning value of 4.0
space_in_a_car = 4.0
# defining drivers variable and assigning value of 30
drivers = 30
# defining passangers variable and assigning value of 90
passangers = 90
# calculati... |
from random import randint
"""
Rock Paper Scissors Game Implementation
Rock smashes scissors
Scissors cuts paper
Paper covers rock
"""
"""
improvement suggestions
get rid of the numbers, just use the strings directly and keep score of wins
"""
def name_to_number(name):
"""
Takes string name and converts ... |
from spider_lib import log_print
import threading
import spider_lib
class DownloadThread(threading.Thread):
'''下载线程
属性:
thread_name: 线程名字,用于区分
download_manager: 下载管理器
task: 下载任务
'''
def __init__(self, thread_name, download_manager, task):
threading.Thread.__init__(se... |
#Ejercicio 03
def parEimpar(array):
#Itera todo el array separando en dos arrays los pares e impares, devolviendo una dupla de arrays
par = []
impar = []
for n in array:
if n % 2 == 0:
par.append(n)
else:
impar.append(n)
return (par, impar)
array = [1, 2, 3,... |
# chat/views.py
from django.contrib.auth.decorators import login_required
from django.shortcuts import render
from django.utils.safestring import mark_safe
import json
from django.shortcuts import get_object_or_404
from django.contrib.auth import get_user_model
User = get_user_model()
@login_required
def room(reques... |
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 4 22:02:20 2017
@author: cvpr
Sort and save weighted patches
"""
import cv2
import numpy as np
import os
prewitt_img_path = '../data/Imageset/prewitt_images/' #path to gradient image
saliency_img_path = '../data/Imageset/saliency_images/' #path to salien... |
class Solution():
def k_largest_v1(self, numbers, k):
"""
Sort the array and return the kth largest element in the array
Naive solution
"""
numbers.sort(reverse=True)
return numbers[:k]
def k_largest_v2(self, numbers, k):
numbers = [7, 9, 10, 2, 35, 90, ... |
from django.contrib import admin
from .models import *
class Messageadmin(admin.ModelAdmin):
""" enable Chart Group admin """
list_display = ('author','timestamp')
list_filter = ('author', 'timestamp')
list_display_links = ('author', 'timestamp')
admin.site.register(Message,Messageadmin)
class ChatGr... |
import random as rn
nums=[ rn.randint(100,500) for i in range(100,500) if i%7 == 0 ]
print(nums) |
from collections import OrderedDict
from itertools import islice
from uuid import uuid4
from django.utils.functional import cached_property
from six import iteritems
from .exceptions import ValidationError
__all__ = [
'cached_property',
'cached_property_ignore_set',
'class_property',
'short_guid',
... |
import os, sys
from pkgutil import iter_modules, importlib
from inspect import getmembers
# sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))
import sys
sys.path.append(".")
from CoreLib.AbsHandler import AbsHandler
from importlib.util import spec_from_file_location, module_from_spec
def ... |
import asyncio
import functools
import re
from .authentication import authenticate, initialize as initialize_authentication
from .configuration import settings
from .logging import getlogger
from .queuemanager import getqueue, dispatcher, AlreadySubscribedError, NotSubscribedError, \
unsubscribe_all, subscribe, un... |
'''
Setup for 2l/3l/4l ttV selections.
Can use different lepton IDs, cuts etc for different channels.
Still missing:
- most of the 2l channel cuts/selections
- additional cuts for 4l channel (dl mass etc)
'''
#Standard import
import copy
# RootTools
from RootTools.core.standard import *
# Logging
import logging
logg... |
# coding: utf-8
def integer_partition(n):
return _integer_partition(n, n)
def _integer_partition(n, m):
"""n的分割中,最大值为m的分割总数"""
if n < 0:
return 0
if n == 0 or m == 1:
return 1
return _integer_partition(n - m, m) + _integer_partition(n, m - 1)
if __name__ == "__main__":
for i... |
import os
from setuptools import setup, find_packages
from packageinfo import VERSION, NAME
with open('README.rst', 'r') as readme:
README_TEXT = readme.read()
def write_version_py(filename=None):
if filename is None:
filename = os.path.join(
os.path.dirname(__file__), 'simlammps', 'ver... |
# -*- coding: utf-8 -*-
import pytest
@pytest.mark.asyncio
async def test_whois_fail(irc3_bot_factory):
bot = irc3_bot_factory(includes=['irc3.plugins.asynchronious'])
assert len(bot.registry.events_re['in']) == 0
task = bot.async_cmds.whois(nick='gawel')
assert len(bot.registry.events_re['in']) > 2
... |
import os
import sys
# Path hacks to make the code available for testing
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '../src')))
# Import the required classes and functions
from src.land_cover_classificat... |
import json
build = None # command for running a user's program
email = None
error = None
test_dict = {} # (key, val) where key is the name of the test case and val is its entire json object
output_list = [] # output value for every test case in json file
assert_list = [] # assert value for every test case in josn f... |
#VBO/IBO/DSC Model Writing from Blender
#Custom Properties:
#scene.hzg_file_name - name of zip file to write
#object.hzg_type - type of object to be populated by the reading program
# - Defaults to "ENTITY"
# - GEO_MIPMAP - Used for terrain geometry
#object.hzg_export_mode - how to export the data for this object... |
'''
Created on 14/04/2013
@author: carlos
'''
import unittest
from models import Content, Piece
class TestContent(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def testCreate (self):
content1 = Content (1, 'Title1')
content1.append_piece(Piece('p... |
# -*- coding: utf-8 -*-
#Copyright (C) 2011 Seán Hayes
import researchhub.settings as dj_settings
from fabric.api import local, run, sudo, env, prompt, settings, cd
from fabric.contrib.files import exists
from fabric.decorators import roles, runs_once
from fabric.tasks import execute
import json
import logging
import ... |
list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
list2 = list1
# Add 16 to the second list:
list2.append(16)
#
# Both lists are updated because when the second list is created
# its actually just a pointer to the first list in memory
#
print (list1)
print (list2) |
'''QLabel控件
setAlignment():设置文本的对齐方式
setIndent():设置文本缩进
text():获取文本内容
setBuddy():设置伙伴关系
setText():设置文本内容
selectedText():返回所选择的字符
setWordWrap():设置是否允许换行
QLabel常用的信号(事件)
1. 当鼠标滑过QLabel控件时触发:linkHovered
2. 当鼠标单击QLabel控件时触发:linkActivated
'''
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtC... |
# 530. Minimum Absolute Difference in BST
#
# refer to 783. Minimum Distance Between BST Nodes
# Given a binary search tree with non-negative values, find the minimum absolute difference between values of any two nodes.
#
# Example:
#
# Input:
#
# 1
# \
# 3
# /
# 2
#
# Output:
# 1
#
# Explanati... |
#!/bin/env python
# -*- coding: utf-8 -*-
import sys
import os
import copy
import configparser
import pandas as pd
# Type of printing.
OK = 'ok' # [*]
NOTE = 'note' # [+]
FAIL = 'fail' # [-]
WARNING = 'warn' # [!]
NONE = 'none' # No label.
# Create report.
class CreateReport:
... |
import datetime
import os
import random
import string
from typing import List, Dict
import json
from api.models import Citizen
from school import settings
def generate_correct_birth_date():
day = random.randint(1, 28)
month = random.randint(1, 12)
year = random.randint(1990, 2010)
return datetime.dat... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 15 17:48:38 2019
@author: 2020shatgiskessell
"""
import cv2
import numpy as np
import timeit
from matplotlib import pyplot as plt
template = cv2.imread("/Users/2020shatgiskessell/Desktop/Wheres_Waldo/template.png")
img = cv2.imread("/Users/2020sha... |
# Test Case 1:
# The following variables contain values as described below:
# balance - the outstanding balance on the credit card
# annualInterestRate - annual interest rate as a decimal+
import math
balance = 999999
annualInterestRate = 0.18
# aprxmonthlypay = int(round(totalpay/12, 0)) #increased divi... |
s=input();
if(s.isalpha()==True):
print("Al[phabet")
else:
print("No")
|
import numpy as np
import pandas as pd
import re
from bs4 import BeautifulSoup
import os
os.environ['KERAS_BACKEND']='theano' # Why theano why not
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
from keras.utils.np_utils import to_categorical
from keras.layers impo... |
# coding=utf-8
import urllib
import urllib2
import cookielib
import sys
from StringIO import StringIO
import login
#print resp.read()
def zhuangtai(sss):
html=login.login()
xn2={}
xn2['status']=sss
xn2['update']="发布"
zhuangtai=urllib.urlencode(xn2)
req2=urllib2.Request('http://3g.renren.com/status/wUpdateStatus.d... |
import sys
from config import load_config
from peewee import MySQLDatabase
from models import Order
config = load_config()
db = MySQLDatabase(**config["DB_CONFIG"])
try:
db.create_tables([Order])
except Exception as e:
pass
|
'''
Script used to experiment with random vs. stratified sampling schemes
to build random forest model for age mapping.
'''
import sys, os
import numpy as np
def main(args):
stratPath = args[1] #csv path
randPath = args[2] #csv path
# pctRand_str = args[3] #0-100
pcts = np.arange(5,80... |
EMPTY_RESULTS = {
'count': 0,
'items': []
}
ALL_INCOMPLETE_TODOS = {
'count': 7,
'items': [
{
'end_date': None,
'file_path': '/bugs.note',
'line_number': '7',
'start_date': None,
'status': 'incomplete',
'todo_text': 'Read t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.