text stringlengths 8 6.05M |
|---|
# encoding: utf-8
from web.session.mongo import MongoSessionStorage, MongoSession
MongoSessionStorage, MongoSession
|
import numpy as np
import multiprocessing as mp
import gym
def _child(id, pipe):
"""
Event loop run by the child processes
"""
env = gym.make(id)
try:
while True:
command = pipe.recv()
# command is a tuple like ("call" | "get", "name.of.attr", extra args...)
... |
from KasaskiTest import KasaskiTest
from AdditiveCipher import AdditiveCipher
class VigenereCipher:
def __init__(self, keyString, base=ord("a")):
self.base = base
self.SecretKey = [ord(ch)-base for ch in keyString]
def encrypt(self, plainText):
m = len(self.SecretKey)
plainTex... |
import sys
from SudokuSolve.extractor import Extractor
from SudokuSolve import sudoku_solver
def output(a):
sys.stdout.write(str(a))
def display_sudoku(sudoku):
for i in range(9):
for j in range(9):
cell = sudoku[i][j]
if cell == 0 or isinstance(cell, set):
ou... |
from django.shortcuts import render, redirect
from django.urls import reverse
from django.http import HttpResponseRedirect, JsonResponse
from django.contrib.auth.models import User
from django.contrib import messages
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import ... |
#-*- coding:utf8 -*-
from django.contrib import admin
from django.db import models
from django.forms import TextInput, Textarea
from shopapp.smsmgr.models import SMSPlatform,SMSRecord,SMSActivity
class SMSPlatformAdmin(admin.ModelAdmin):
list_display = ('code','name','user_id','account','remainums','sendnums','is... |
# https://abc002.contest.atcoder.jp/tasks/abc002_4
# ref https://abc002.contest.atcoder.jp/submissions/110949
# O(2^|V|*|V|^2)
def dfs(v, k):
if k == N:
for i in range(len(v)):
for j in range(i + 1, len(v)):
if G[v[i]][v[j]] == 0:
return
cand.append(le... |
import pygame
from pygame.sprite import Sprite
class ship(Sprite):
def __init__(self, AI_game):
super().__init__()
# recting the screen and setting a variable for settings
self.screen = AI_game.screen
self.setting = AI_game.setting
self.screen_rect = AI_game... |
from pandas import read_csv
import sqlite3
con = sqlite3.connect('eq.db')
data = read_csv('all_month.csv')
data.to_sql('earthquake',con, if_exists='append', index=False )
cur=con.cursor()
cur.execute('SELECT * FROM \'all\'')
d = cur.fetchall()
for d_ in d:
print(d_) |
class Users:
def __init__(self, users_id=0, first_name="", last_name="", login_id="", password="", role_id=0):
self.users_id = users_id
self.first_name = first_name
self.last_name = last_name
self.login_id = login_id
self.password = password
self.role_id = role_id
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import subprocess
import time
import json
import os
import requests
timestamp = int(time.time())
mlist = ["we.node.cpu","we.node.mem"]
data = []
def create_record(pid,cvalue,mvalue):
record = {}
record['endpoint'] = os.uname()[1]
record['metric'] = "we.node.... |
"""Author Arianna Delgado
Created on June 20, 2020
"""
"A decorator function is a function that return another function"
"""Doubles the number returned """
#Function that returns another function
def decor(fun):
#Inner function
def inner():
#Invokes fun()
result = fun()
return result... |
#!/usr/bin/env python
import os
import csv
class CSVDataWrite:
""" For logging CSV files to disk for further analysis
"""
def __init__(self):
self.file_ref = None
self.csvwriter = None
def open_output(self, file_name='testoutput.csv', path='', reset_file=True):
""" Opens a f... |
import cv2
face_cascade=cv2.CascadeClassifier("C:\\Users\\agup0013\\PycharmProjects\\ImageProcessing\\haarcascade_frontalface_default.xml")
img=cv2.imread("C:\\Users\\agup0013\\Desktop\\pp.jpg")
#Reading image as grey scale image
gray_img=cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
#Search the coordinates of ima... |
from .pgbm_nb import PGBM |
from django.contrib import admin
from .models import *
admin.site.register(Formation)
admin.site.register(Session)
admin.site.register(Catalogue)
admin.site.register(Entreprise)
admin.site.register(Client)
admin.site.register(Profile)
admin.site.register(Localisation)
admin.site.register(Cours)
admin.site.register(In... |
#!/usr/bin/python
import json
import urllib2
import sys
from jinja2 import Template
try:
data = json.load(urllib2.urlopen('http://169.254.169.254/latest/user-data'))
ip = urllib2.urlopen('http://169.254.169.254/latest/meta-data/local-ipv4').read()
except:
print >> sys.stderr, 'Was not able to connect to ... |
#!/usr/bin/evn python
import pyscreenshot as ImageGrab
if __name__ == "__main__":
# part of the screen
#im=ImageGrab.grab(bbox=(10,10,510,510)) # X1,Y1,X2,Y2
im = ImageGrab.grab()
im.save('screenshot.png')
im.show()
|
"""
"""
import ast
import operator
from collections import deque
from . import ASTOptimization
class ConstantFolding(ASTOptimization):
"""
"""
@property
def name(self) -> str:
return 'Constant folding'
@property
def description(self) -> str:
return ''
@property
d... |
import pygame
import time
from random import choice
pygame.mixer.init()
pygame.mixer.music.load("\windows\media\chimes.wav")
sm = 30
sise = int((470-sm)/(sm+2))
spd = 0.05
Hi = We = sise* sm+ 2*sise+ sm
BLACK = (0,0,0)
GREY = (220,220,220)
sc = pygame.display.set_mode((We,Hi))
def rnd_lst(ln):
x = lis... |
#!/usr/bin/env python
"""This scripts automatically checks for updates on the used tools."""
import os
import json
import re
import requests
from bs4 import BeautifulSoup
class color:
GREEN = '\033[0;32m'
RED = '\033[0;31m'
ORANGE = '\033[0;33m'
BOLD = '\033[1m'
NORMAL = '\033[0m'
# Load the curr... |
num_list = []
for i in range(2,101):
for j in range(2,101):
num_list.append(i**j)
print len(list(set(num_list)))
|
N, K = map( int, input().split())
A = list( map( int, input().split()))
RA = sorted(A)
RA = RA[::-1]
s = 0
ans = 0
for i in range(N):
a = RA[i]
if s+a < K:
s += a
ans += 1
else:
ans = 0
print(ans)
#反例
#5 12
#6 4 3 2 1
#通るらしいけどなんでかわからない
#https://beta.atcoder.jp/contests/abc056/submiss... |
# -*- coding: utf-8 -*-
from snippets.template_backends.jinja2 import jinjaglobal
from training import models
@jinjaglobal
def get_training_categories():
return models.TrainingCategory.objects.published().order_by('ordering')
|
#Ryan Ulsbegrer
#October 24, 2014
#Challenge question 2 Exercise 6
import arcpy
from arcpy import env
env.overwriteOutput = True
env.workspace = "C:\MS_GST\TGIS_501\lab4\Exercise06\Challenge\challenge.gdb"
arcpy.management.CreateFileGDB("C:\MS_GST\TGIS_501\lab4\Exercise06\Challenge", "new_challenge.gdb")
fclist = arcp... |
import torch
import torch.nn as nn
from utils import RD_fn
cfgs = {
'A': [64, 'M', 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'],
'B': [[64, 64, 'M'], [128, 128, 'M'], [256, 256, 'M'], [512, 512, 'M']],
'D': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'M', 512, 512, 512, 'M', 512, 512, 512,... |
class Solution(object):
def lengthOfLongestSubstring(self, s):
words, last, longestSubstr = {}, 0, 0
for i, ch in enumerate(s):
if ch in words:
last = max(last, words[ch] + 1)
words[ch] = i
longestSubstr = max(longestSubstr, i - last + 1)
r... |
import json
import re
import textwrap
from datetime import date, timedelta, datetime
import os
import transaction
from webtest import Upload
from onegov.form import FormCollection
from onegov.reservation import ResourceCollection
def test_tickets(client):
assert client.get(
'/tickets/ALL/open', expect_... |
import smtplib
# from email import encoders
from email.mime.text import MIMEText
# from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
class Mailer:
def __init__(self, url, port):
self.server = smtplib.SMTP_SSL(url, port)
self.server.ehlo()
def authenticate(se... |
N, K = map( int, input().split())
A = list( map( int, input().split()))
# 1の個数をそれぞれの桁でカウントしたい
V = [0]*41
for a in A:
for i in range(40,-1,-1):
if a%2 == 0:
pass
else:
V[i] += 1
a //= 2
if a == 0:
break
W = [0]*41
for i in range(40,-1,-1):
if K%... |
class Animal(object):
# For initializing our member variables
is_alive = True
health = "good"
# Constructor
def __init__(self, name, age, is_hungry):
self.name = name
self.age = age
self.is_hungry = is_hungry
def description(self):
print (self.name)
prin... |
import random
import sqlite3
class Banking:
def __init__(self, con, cursor):
self.card = cursor.execute("""CREATE TABLE IF NOT EXISTS card
(id INTEGER,
number TEXT,
pin TEXT,
... |
#coding=utf-8
# 通过socket建立网络连接的步骤:
# 至少需要2个套接字, server和client
# 需要建立socket之间的连接, 通过连接来进行收发data
# client 和 server连接的过程:
# 1. 建立server的套接字,绑定主机和端口,并监听client的连接请求
# 2. client套接字根据server的地址发出连接请求, 连接到server的socket上; client socket需要提供自己的 socket fd,以便server socket回应
# 3. 当server监听到client连接请求时, 响应请求, 建立一个新的线程, 把server ... |
from django.urls import reverse
from rest_framework import status
from rest_framework.test import APITestCase
from .models import (Customer, CustomerInfo, Order,
Pizza, PizzaDetail, PizzaOrder)
CUSTOMER1 = {'name': 'Customer1', 'address': 'Address1', 'phone': '1234'}
CUSTOMER2 = {'name': 'Custom... |
player = 1
playerOne = 'X'
playerTwo = 'O'
def display_gameboard(gameBoard):
'''
Literally just a print statement that displays the gameBoard
'''
print(f'Here is the current game board:\n{gameBoard[0]}|{gameBoard[1]}|{gameBoard[2]}\n{gameBoard[3]}|{gameBoard[4]}|{gameBoard[5]}\n{gameBoard[6]}|{gameBoard... |
import discord
import asyncio
from discord.ext.commands import Bot
from discord.ext import commands
import platform
client = Bot(description="responds no u", command_prefix="", pm_help = False)
@client.event
async def on_ready():
print('Logged in as '+client.user.name+' (ID:'+client.user.id+') | Connected ... |
#!/usr/bin/env python
from __future__ import print_function
import os
import sys
import itertools
HEADER = """#!/bin/bash -l
#SBATCH
#SBATCH --partition=shared
#SBATCH --nodes=1
#SBATCH --mem=%s
#SBATCH --time=4:00:00
#SBATCH --ntasks-per-node=8
"""
# aws --profile jhu-langmead s3 ls s3://recount-reads/human_sim/ |... |
# reverse words in a string
def reverse_words(s):
words = s.split(' ')
result = []
for i in words:
result.append(i[::-1])
return ' '.join(result)
if __name__ == '__main__':
print(reverse_words("Let's take LeetCode contest")) |
#!env python3
# -*- coding: utf-8 -*-
import pandas as pd
import numpy as np
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
import json
import seaborn as sns
df = pd.read_json('../data/nobel_winners_biopic_cleaned.json')
fig = df['award_age'].hist(bins=20).get_figure()
sns.distplot(df['award_... |
# -*- coding:utf-8 -*-
#
import os, sys
import cmd
import subprocess
import shlex
class Shell(cmd.Cmd):
def __init__(self):
cmd.Cmd.__init__(self)
self.prompt = '(hadoop) '
def do_help(self, args):
"pirnt help message"
'List available commands with "help" or detailed help with "help cmd".'
if args:
... |
from datetime import date
import pytz
from django.contrib.postgres.fields import ArrayField
from django.db import models
from django.db.models.enums import Choices
from django.utils.translation import gettext as _
from apps.users.models import CustomUser
from apps.mailaccounts.models import EmailAccount
# Create you... |
#!/usr/bin/python
#############################################################################
# #
# Module : HomeConnect Event Receiver #
# #
# Purpose: Receive Events and write to DB #
# #
# Author : Andreas D. Kull ... |
from typing import Union
import sys
import commons.errors as errors
"""
Change type String to Bool.
String型からBool型への変更.
"""
def str_to_bool(string: str) -> bool:
return str(string).lower() in ["true", "1", "yes"]
"""
Change type String to Int.
String型からInt型への変更.
"""
def str_to_int(string: str) -> Union[int, bool... |
import setuptools
from setuptools import setup
setup(name='automl_pn',
version='0.1.3',
description='Automated binary classification',
packages=['automl_pn', 'automl_pn.utils'],
author_email='maximponomarev92@gmail.com',
zip_safe=False,
python_requires='>= 3.7',
install_requi... |
# as in tambura
from pippi import dsp
from pippi import tune
midi = {'lpd': 3}
def play(ctl):
param = ctl.get('param')
lpd = ctl.get('midi').get('lpd')
pw = lpd.get(7, low=0.001, high=1, default=1)
modr = dsp.rand(0, 0.005)
modf = dsp.rand(0.01, 0.05)
amp = lpd.get(8, low=0, high=2, default=0... |
import os
import pytest
from simexpal import util
file_dir = os.path.abspath(os.path.dirname(__file__))
valid_experiments_ymls = ['../../examples/sorting/experiments.yml',
'../../examples/sorting_cpp/experiments.yml',
'../../examples/download_instances/experiments... |
#!/usr/bin/env python
"""Copyright 2010 Phidgets Inc.
This work is licensed under the Creative Commons Attribution 2.5 Canada License.
To view a copy of this license, visit http://creativecommons.org/licenses/by/2.5/ca/
"""
__author__ = 'Adam Stelmack'
__version__ = '2.1.8'
__date__ = 'May 17 2010'
#Basic imports
f... |
import numpy as np
from collections import Counter
from sklearn.feature_extraction import DictVectorizer
from nltk.corpus import wordnet as wn
################################################################################
################################################################################
class English_... |
import argparse
from datetime import datetime
import tensorflow as tf
from experiments import build_model, options
from tensorflow.keras.datasets import cifar10
from tensorflow.keras.models import Sequential
from tensorflow.keras.utils import plot_model, to_categorical
# Argument Parsing
parser = argparse.ArgumentPar... |
from rest_framework.routers import DefaultRouter
from .views import UserRegistrationView
router = DefaultRouter()
router.register(r'', UserRegistrationViewleViewSet, basename='articles')
urlpatterns = router.urls |
# coding: utf-8
# In[1]:
import time
import urllib.response
import urllib.request
from bs4 import BeautifulSoup
import datetime
import logging
from urllib.request import urlopen
import re
from io import BytesIO
from zipfile import ZipFile
import os
import sys
import pandas as pd
import numpy as np
import zipfile
imp... |
######find largest number
# a=[22,34,55,78,90,54,55,12,100,32,67,89]
# largest=a[0]
# i=0
# while i<len(a):
# if a[i]>largest:
# largest=a[i]
# i=i+1
# print(largest) |
a=int(input('digite um numero '))
b=int(input('digite outro numero '))
print(f'a soma de {a} + {b} é {a+b}') |
class RPNParser(object):
OPERATORS = ["+", "-", "*", "/"]
class Stack(list):
def push(self, obj):
self.append(obj)
def __init__(self):
self.queue = []
self.stack = self.Stack()
def validate(self, rpn_string):
rpn_list = rpn_string.split(" ")
op_cou... |
#!/usr/bin/env python2.7
import queue, tempfile, subprocess, contextlib, datetime
from contextlib import closing, contextmanager
@contextmanager
def r_subprocess():
""" Context manager; use as
with r_subprocess() as r:
# Here, a R subprocess is running and awaiting commands on the file object 'r'
# R's ... |
# 카드 구매하기
'''
1. 정의
f(i) = i가의 카드를 구입할 때 지불하는 금액의 최댓값
2. 구하는 답
f(n)
3. 초깃값
f(1) = P(1)
4. 점화식
f(i) = max(
P(i),
f(1) + f(i - 1),
f(2) + f(i - 2),
...
f(j) + f(i - j)
)
'''
# 다리 놓기
'''
1. 정의
f(i, j) = 서쪽에 i개, 동쪽에 j개의 사이트가 있을 때 지울 수 있는 다리의 경우의 수
2. 구하는 답
... |
import numpy as np
import matplotlib.pyplot as plt
import cPickle as pickle
import gzip
import heapq
ribocov = np.array([5, 4, 3, 6, 4, 1, 5, 2, 0, 8, 3, 1, 6, 2, 0])
nts = np.array(range(0, len(ribocov)))
ft_ribocov = np.fft.fft(ribocov, axis=0)
amplitudes = abs(ft_ribocov)
frequencies = np.fft.fftfreq(len(ribocov),... |
class Arbol:
def __init__(self,valor):
self.valor = valor
self.izquierda = None
self.derecha = None
#Metodo para agregar nodos a la izquierda del arbol, no importando que nodo
#del arbol queremos como padre de este
def AgregaIzquierda(self,padre,dato):
if self.valor != padre:
if self.izquierda != None:
... |
a, b = map( int, input().split())
if b%a == 0:
print( a+b)
else:
print( b-a)
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
from webpages import *
@pytest.fixture
def page(browser, server_url, access_token):
return NoticesPage(browser, server_url, access_token)
class TestNoticesPage(object):
def test_should_find_page_div(s... |
import os
from setuptools.command.develop import develop
from setuptools.command.install import install
import subprocess
JAVA_PROJ_PATH = "java/javaparser-util/"
def install_java_module():
# print("Installing maven module")
subprocess.run(["mvn", "clean", "install"], cwd=JAVA_PROJ_PATH)
class Develop(dev... |
from tkinter import *
root = Tk()
# Labels
l1 = Label(root, text="Name")
l2 = Label(root, text="Password")
# Entries
e1 = Entry(root)
e2 = Entry(root)
# Checkbox
c = Checkbutton(root, text="Don't keep me logged in")
# Grid
# sticky= N,E,S,W
l1.grid(row=0, sticky=E)
l2.grid(row=1)
e1.grid(row=0, column=1)
e2.grid... |
import sys
import glob
import os
try:
sys.path.append(glob.glob('/opt/carla-simulator/PythonAPI/carla/dist/carla-*%d.%d-%s.egg' % (
sys.version_info.major,
sys.version_info.minor,
'win-amd64' if os.name == 'nt' else 'linux-x86_64'))[0])
except IndexError:
pass
import carla
import cv2
... |
#!/usr/bin/env python
import rospy
import sys
from sensor_msgs.msg import Image
from std_msgs.msg import Int32 ## 0 = success; 1 = failure
import os
import cv2
from cv_bridge import CvBridge, CvBridgeError
class PhotoHandler:
def __init__(self):
self.feedback_pub = rospy.Publisher('camera/photo/feedback', Int32, q... |
from collections import OrderedDict
_Author_ = "Karthik Vaidhyanathan"
# Analyze the results generated from the simulation
import pandas as pd
import os
from Initalizer import Initialize
import json
import plotly.graph_objects as go
import statistics
import math
import numpy as np
from plotly.subplots import make_su... |
def lower(string):
return string.lower()
def strip_nextline_return(string):
string = string.replace('\n', ' ').replace('\r', ' ').strip()
return string
|
from django.contrib.auth import forms, get_user_model
from django.utils.translation import ugettext_lazy as _
from .models import Cocktail, Evaluation
from django import forms as forms_django
User = get_user_model()
class UserCreationForm(forms.UserCreationForm):
error_message = forms.UserCreationForm.error_mes... |
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Category(models.Model):
name = models.CharField(max_length=255)
def __str__(self):
return u"{}".format(self.name)
class Movie(models.Model):
"""Create movie model"""
image = models.Imag... |
from typing import List
from urllib.request import Request, urlopen
from bs4 import BeautifulSoup
import json
BASE_URL = 'https://replay.pokemonshowdown.com/'
REPLAY_FORMAT = '.json'
class ReplayFetcher:
def __init__(self):
pass
def get_replays(self) -> List[dict]:
replays = []
for r... |
from sklearn.preprocessing import MinMaxScaler as MMS, StandardScaler as SS, LabelEncoder, OrdinalEncoder, \
OneHotEncoder, Binarizer, KBinsDiscretizer
from sklearn.impute import SimpleImputer
import pandas as pd
import numpy as np
'''
无量纲化:归一化、标准化
主要思想:中心化(zero-centered or subtraction)和缩放(scale)
'''
# Normalizati... |
N, Q = map( int, input().split())
V = [ i for i in range(N)]
def find(x):
p = V[x]
if p == x:
return x
a = find(p)
V[x] = a
return a
for _ in range(Q):
P, A, B = map( int, input().split())
if P == 0:
A, B = A-1, B-1
pA, pB = find(A), find(B)
V[B] = pA
... |
from flask import Flask
from flask_mysqldb import MySQL
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
app = Flask(__name__)
app.config.from_object('lesara.settings')
db = SQLAlchemy(app)
migrate = Migrate(app, db)
import lesara.views
import lesara.models
import lesara.commands |
from zope.annotation.interfaces import IAttributeAnnotatable
from zope.interface import Interface
class IPotentiallyAddableToCart(Interface):
"""Marker interface to content type instance to make potentially addable to cart."""
class IAddableToCart(IPotentiallyAddableToCart, IAttributeAnnotatable):
"""Marker... |
from socket import *
import pickle
from threading import *
player = socket(AF_INET, SOCK_STREAM)
player.connect(("26.52.80.182", 9997))
lock = Lock()
print("\033[40m{}".format(""))
def mutar():
global lock
lock.acquire()
print("ESPERE A VEZ DO OUTRO JOGADOR E NÃO DIGITE NADA")
while True:
m... |
#!/usr/bin/env python
from sys import argv
import cv2
def interpolation_types(interpolationTypeIndex):
return {
0: cv2.INTER_NEAREST,
1: cv2.INTER_LINEAR,
2: cv2.INTER_CUBIC,
3: cv2.INTER_AREA,
4: cv2.INTER_LANCZOS4
}.get(interpolationTypeIndex, None)
#
path = argv[1]
imag... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import settings
start = {'mes':'start',
'text':'''
Тебя приветсвует Горшочек с золотом!
✔️ Приглашай друзей в "Горшочек с золотом" и получи:
✔️ 15% от заработка рефералов 1 уровня
✔️ 5% от заработка рефералов 2 уровня
✔️ Больше друзей - больше золота!
✔️ Минимальная вы... |
from kivy.clock import mainthread
from kivy.storage.dictstore import DictStore
from kivy.logger import Logger
from worker import WorkerThread
from sunfish.sunfish import (initial, parse, render, Position, Searcher, MATE_LOWER,MATE_UPPER)
import chess
import re
import time
##############################################... |
#!/usr/bin/python
DXL_ID= 1
#BAUDRATE= 57600
BAUDRATE= 2e6
#BAUDRATE= 3e6
#DXL_TYPE= 'XM430-W350' #Finger robot
DXL_TYPE= 'XH430-V350' #Dynamixel gripper
#DXL_TYPE= 'RH-P12-RN' #Thormang3 gripper
DEV='/dev/ttyUSB0'
#DEV='/dev/ttyUSB1'
##Gripper of Mikata arm:
#DXL_ID= 5
#BAUDRATE= 1e6
#DXL_TYPE= 'XM430-W350'
##SAK... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('competition', '0004_tournament_add_matches'),
]
operations = [
migrations.AlterModelOptions(
name='tournament',
... |
from settings import *
from shared import *
import pandas as pd
def combine(df):
# create 'active unsubs' and 'other' column by summing other columns
df['ActiveUnsubs'] = df['Feedback Loop - ACTIVE'] + df['Feedback - ACTIVE'] + df['Web Site - ACTIVE'] + df['Android - ACTIVE']
df['Other'] = df['Other'] + d... |
# the science lab was some functions for converting between temperatures
# 1. write the interface (Python does not have an interface keyword)
from abc import ABC, abstractmethod
# ABC is ABstract Class. An abstract Class is a class you cannot directly create
class TemperatureCalculator(ABC):
@abstractmethod
... |
#!/usr/bin/env python3
import os
import sys
import argparse
import urllib.parse
import logging
def main(url, file_format, length):
if not url:
url = open('url.txt').read().strip()
uri = urllib.parse.urlparse(url)
uri = uri._replace(path = uri.path[:uri.path.rfind('/') + 1])
url = urllib.pars... |
from irc3.testing import BotTestCase
from irc3.plugins import quakenet
class TestQuakenet(BotTestCase):
config = dict(
includes=['irc3.plugins.quakenet'],
quakenet=dict(user="bot", password="password", hidehost=True,
challenge_auth=False))
def test_challenge(self):
... |
"""
作为动态性的强类型脚本语言,Python中的变量在定义的时候并不会指明具体类型,Python解释器会在运行时自动进行类型检查并根据需要进行隐式类型转换。按照Python的理念,为了充分利用其动态性的特征是不推荐进行类型检查的。如下面的函数add(),在无需对参数进行任何约束的情况下便可以轻松地实现字符串的连接、数字的加法、列表的合并等多种功能,甚至处理复数都非常灵活。解释器能够根据变量类型的不同调用合适的内部方法进行处理,而当a、b类型不同而两者之间又不能进行隐式类型转换时便抛出TypeError异常。
"""
def add(a, b):
return a + b
"""
不刻意进行类型检查,而是在出错的情... |
from api.sklearn_func import evaluation
from api.sklearn_func import pre_processing
from api.sklearn_func import train_models
from api.sklearn_func import transform
|
import sys
import datetime
from mx import connector
from gui import *
from PyQt4.QtGui import *
from PyQt4.QtCore import *
import traceback
class TBrowser:
def __init__(self):
self.connector=False
self.settings=QSettings( QSettings.UserScope,"X1","jsonbrowser")
self.standardConnections=[]
self.readStandardCon... |
from django.contrib import admin
from msclassapp.models import Scripture, Trait, Question
admin.site.register(Scripture)
admin.site.register(Trait)
admin.site.register(Question) |
import concurrent
import time
from supporters import *
from concurrent import futures
# main program
if __name__ == "__main__":
# sources and their scrapping areas
# src 1
money_control = "https://www.moneycontrol.com/news/tags/cryptocurrency.html/news/"
money_news = "#cagetory"
money_indi_1 = ""
... |
# -*- coding: utf-8 -*-
import config
import mailController
import os
import csv
import pprint
def compareManifest():
#TODO: There seems to be a whole host of things that can go wrong here
list_msg_ids = mailController.getGmailMsgIds()
mailMsgs = []
manifestMsgs = []
output = []
for msg in list... |
from functools import cached_property
from onegov.form import Form, FormDefinition
from onegov.form.fields import MultiCheckboxField
from onegov.org import _
from wtforms.fields import BooleanField
from wtforms.fields import DateField
from wtforms.fields import IntegerField
from wtforms.fields import RadioField
from wt... |
from pysph.sph.equation import Group, Equation
class SurfaceForceAdami(Equation):
def initialize(self, d_au, d_av, d_idx):
d_au[d_idx] = 0.0
d_av[d_idx] = 0.0
def loop(self, d_au, d_av, d_idx, d_m, DWIJ, d_pi00, d_pi01, d_pi10, d_pi11, s_pi00, s_pi01, s_pi10, s_pi11, d_V, s_V, s_idx):
... |
import os
import asyncio
import discord
from discord.ext import commands
from cogs.utils.dataIO import dataIO
from .utils import checks
from discord.utils import find
from cogs.utils.chat_formatting import box, pagify
class AutoRooms:
"""
auto spawn rooms
"""
__author__ = "mikeshardmind"
__version... |
__author__ = "Komal Atul Sorte"
import collections
"""
There are a total of numCourses courses you have to take, labeled from 0 to numCourses-1.
Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]
Given the total number of courses an... |
from django.apps import AppConfig
class LyricvideoConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'lyricvideo'
|
import cv2
face_detector = cv2.CascadeClassifier('Face.xml')
smile_detector = cv2.CascadeClassifier('Smile.xml')
webcam = cv2.VideoCapture(0)
while True:
successful_frame_read,frame = webcam.read()
if not successful_frame_read:
break
frame_grayscale = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
faces = face_detec... |
from django.contrib.auth.views import LoginView,LogoutView
from django.urls import path
#从当前的urls.py模块所在的文件夹中导入视图
from . import views
#添加命名空间,必须设置命名空间
app_name='users'
urlpatterns=[
#登录页面
#这里与教程上不同,login变为了LoginView,且调用as_view方法
path('login/',LoginView.as_view(template_name='users/login.html'),... |
"""
Utility functions for search views
"""
def _get_price(price_range):
if price_range == "0-10":
gte = 0
lte = 10
if price_range == "10-20":
gte = 10
lte = 20
if price_range == "20-30":
gte = 20
lte = 30
if price_range == "30-40":
gte = 30
... |
from fst import FST
import string, sys
from fsmutils import composechars, trace
def letters_to_numbers():
"""
Returns an FST that converts letters to numbers as specified by
the soundex algorithm
"""
# Let's define our first FST
f1 = FST('soundex-generate')
# Indicate that '1' is the init... |
#! /usr/bin/python
# Test case to test multi-port functionality
# The configuration file for this test case specifies 2 different cores, each with a different
# data source. Three search terms are tested, each expected to be returned by one and only one
# of the cores. The usual syntax of the queriesAndResults.txt f... |
# -*- coding: utf-8 -*-
# Copyright (c) 2014 Plivo Team. See LICENSE.txt for details.
# A WSGI application driver to deploy Sharq Server using other
# application servers like uWSGI, etc.
import os
from sharq_server import setup_server
# read path from variable / default to current working directory
sharq_config_path... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.