text stringlengths 8 6.05M |
|---|
import sys, random, subprocess
proc = subprocess.Popen('python.exe', stdin=subprocess.PIPE, stdout=subprocess.PIPE)
def p(x):
proc.stdin.write(x+'\n')
proc.stdin.flush()
wordlist=[]
f=open('wordlist.txt', 'r')
for i in f:
wordlist.append(i[:-1] if i[-1]=='\n' else i)
# wordlist=[i[:-1] for i in f]
random.... |
import sys
input = sys.stdin.readline
def main():
N, C, K = map( int, input().split())
T = [ int( input()) for _ in range(N)]
T.sort()
deadline = -1
ans = 0
count = 0
for t in T:
if deadline < t or count >= C:
ans += 1
deadline = t+K
count = 1
... |
#-*- coding: utf-8 -*-
import os
import json
import requests
import tornado.web
import tornado.ioloop
import tornado.httpserver
from apiclient.discovery import build
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = "v3"
DEVELOPER_KEY = os.environ.get('DEVELOPER_KEY', '')
class MainHandler(tornado.web.R... |
#! /usr/bin/env python3
# Calculates and re-constructs the first line of a number pyramid given an outside diagonal
# Creates a list with binomials (n, k) for each integer k <= n
# Follows the formula: (n, k) = (n, k-1) * (n + 1 - k)/k
def calculate_coefficients(n):
coefficients = [1]
if n > 0:
for i ... |
# Overloading the addition Operator
class Square:
def __init__(self,side):
self.side = side
def __add__(squareOne, squareTwo):
return((4*squareOne.side + 4*squareTwo.side))
squareOne = Square(5) # 5*4 = 20
squareTwo = Square(10) # 10*4 = 40
print("Sum of sides of both squares = " , squareOn... |
from .build import make_optimizer, make_lr_scheduler |
import visdom
import time
import numpy as np
class Visulizer(object):
"""the object interface to store train trace to website"""
def __init__(self,host="http://hpc3.yud.io",port=8088,env='street'):
self.vis = visdom.Visdom(server=host,port=port,env=env)
self.host = host
self.port... |
import numpy as np
import matplotlib.pyplot as plt
x=np.arange(0,10,0.1)
y=2*x+5
plt.plot(x,y)
plt.show() |
from django.shortcuts import render, redirect, get_object_or_404
from django.core.exceptions import ObjectDoesNotExist
from django.contrib import messages
from django.conf import settings
from django.contrib.auth.models import User
from django.template.loader import get_template
from django.core.mail import EmailMessag... |
import requests
from bs4 import BeautifulSoup
import sqlite3 as sql
conn =sql.connect('data.db')
cur=conn.cursor()
cur.execute("create table if not exists mydata( s_title text ,s_answer text ,s_pages text)")
print("Table created")
url="https://www.udemy.com/topic/django/"
response=requests.get(url)
soup=Beaut... |
import pandas as pd
import matplotlib.pyplot as plt
plt.style.use('default')
df = pd.read_csv('../auto-mpg.csv', header=None)
df.columns = ['mpg','cylinders','displacement','horsepower','weight','acceleration','model year','origin','name']
df['count']=1
df_origin=df.groupby('origin').sum()
print(df_origin.head())
df... |
import re
sectors = open('input').read()
total = 0
for sector in sectors.split("\n"):
if not sector:
continue
letters = dict()
sector_id = re.search(r"\d+", sector).group(0)
checksum = re.search(r"\[(.*?)\]", sector).group(1)
codes = re.match(r"[a-z-]+", sector).group(0).replace("-", "")... |
import streamlit as st
import difflib
st.write("""
# Version control in 2 code snippets
**For experimentation purpose only | Indraneel Chakraborty**
""")
l1 = st.text_area("Enter the first code snippet")
l2 = st.text_area("Enter the modified code snippet")
l1.strip().splitlines()
l2.strip().splitlines()
l3 = list... |
def solution(n, computers) :
start = [0, 0]
visited = {}
answer = n
i = 0
j = 0
low = 0
column = 0
while low < n and column < n:
if column == n - 1 :
low += 1
column = 0
elif low == n - 1 and column == n - 1:
for i in range(n) :
... |
import tensorflow as tf
from tensorflow.keras.layers import Input, Layer, Conv1D, Dense, BatchNormalization, Activation, GlobalAveragePooling1D, MaxPool1D
from tensorflow.keras.layers import add
from tensorflow.keras.models import Sequential, Model
from tensorflow.keras import backend as K
class BasicBlock(Layer):
... |
"""
LRGAN
-----
Implements the latent regressor GAN well described in the BicycleGAN paper[1].
It introduces an encoder network which maps the generator output back to the latent
input space. This should help to prevent mode collapse and improve image variety.
Losses:
- Generator: Binary cross-entropy + L1-latent... |
from django.db import models
class Usuarios(models.Model):
nome = models.CharField(max_length=50)
telefone = models.CharField(max_length=12)
cargo = models.CharField(max_length=25)
def __str__(self):
return ("nome %s, cargo %s" %(self.nome, self.cargo))
|
#
# Kiwi - An open source application framework
# Copyright (C) 2012-Today Thibaut DIRLIK <thibaut.dirlik@gmail.com>
#
# This program 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, either version 3 of ... |
import os
from pathlib import Path
from fastapi import FastAPI
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
import brocolli
app = FastAPI()
app_path = Path(os.curdir, "build/sample_app.js").resolve()
app_node_modules = Path(os.curdir, "example_app/node_modules").resolve()
rea... |
import os, sys, logging, warnings, time
import osmnx
import networkx as nx
import pandas as pd
import geopandas as gpd
import numpy as np
from shapely.geometry import Point
import GOSTnet as gn
def calculateOD_gdf(G, origins, destinations, fail_value=-1, weight="time"):
''' Calculate Origin destination matrix f... |
"""
Given two integers L and R, find the count of numbers in the range [L, R] (inclusive) having a prime number of set bits in their binary representation.
(Recall that the number of set bits an integer has is the number of 1s present when written in binary. For example, 21 written in binary is 10101 which has 3 set b... |
from dataclasses import dataclass
from typing import Optional, List, Union
from rdflib import Graph
from rdflib.namespace import NamespaceManager, OWL
from rdflib.term import URIRef
from funowl.base.cast_function import exclude
from funowl.base.fun_owl_base import FunOwlBase
from funowl.general_definitions import Pre... |
class Solution(object):
def countComponents(self, n, edges):
"""
:type n: int
:type edges: List[List[int]]
:rtype: int
"""
graph = [set() for _ in range(n)]
for x, y in edges:
graph[x].add(y)
graph[y].add(x)
def dfs(nid):
... |
# 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... |
from django.urls import path
from myapp import views
app_name="myapp"
urlpatterns=[
path('topics/',views.topic,name="topic"),
path('records/',views.records,name="records"),
] |
# Windows
# ArcPy
__version__ = "0.1.1"
import arcpy
import os
import sys
import csv
import time
import argsparse
from datetime import datetime
print sys.version
startTime = time.time()
parser = argparse.ArgumentParser(description='Remove duplicates of Agri Maps')
parser.add_argument('-i','--input_directory')
args ... |
import os
import unittest
from test_octree_conv import OctreeConvTest
from test_octree2col import Octree2ColTest
from test_octree_pool import OctreePoolTest
from test_octree_property import OctreePropertyTest
if __name__ == "__main__":
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
unittest.main()
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Получение цитаты из forismatic.com
import pycurl, io
def get_quote():
data = io.BytesIO()
c = pycurl.Curl()
c.setopt(pycurl.POST,1)
c.setopt(pycurl.WRITEFUNCTION, data.write)
c.setopt(pycurl.USERAGENT, 'Mozilla/4.0')
c.setopt(pycurl.POSTFIELDS, '... |
from django.contrib import admin
from .models import Tag
from Kursach.admin import AutoInsertUserAdmin
class TagAdmin(AutoInsertUserAdmin):
list_display = ('title', 'name', 'tag_wiki', 'get_quantity_articles', 'user')
fields = ('title', 'tag_wiki',)
search_fields = ('title', 'name',)
admin.site.registe... |
import collections
import syntax
#Flatten nested list to single list
def flatten(L):
if(type(L) != list):
return [L]
if len(L) == 1:
if type(L[0]) == list:
result = flatten(L[0])
else:
result = L
elif type(L[0]) == list:
result = flatten(L[1:])
... |
# -*- coding: utf-8 -*-
# Geo Technosoft Pvt Ltd.
{
'name': 'GTS Database Connection',
'version': '8.0.0.1',
'author': 'Geo Technosoft',
'sequence':'10',
'category': 'Tools',
'website': 'https://www.geotechnosoft.com',
'summary': 'Database Load Balancing',
'description': """
Th... |
students = [
{'first_name': 'Michael', 'last_name' : 'Jordan'},
{'first_name' : 'John', 'last_name' : 'Rosales'},
{'first_name' : 'Mark', 'last_name' : 'Guillen'},
{'first_name' : 'KB', 'last_name' : 'Tonel'}
]
for i in students:
itemnum =
print (itemnum, i['first_name'], i['last_name'], '-', ... |
# medikit (see github.com/python-edgy/medikit)
from medikit import require
require("git")
require("make")
require("pytest")
require("format")
with require("python") as python:
python.setup(
name="django_includes",
description="Include django views as a subparts of other django views, using eithe... |
def getDigitCount(n):
test = 9
count = 1
while test < n:
test *= 10
test += 9
count += 1
return count
def resolve(a, b):
digit_count_a = getDigitCount(a)
digit_count_b = getDigitCount(b)
diff = digit_count_a - digit_count_b
if diff > 0: b *= pow(10, diff)
... |
import marshmallow
from marshmallow import fields
class AuthRequestSchema(marshmallow.Schema):
dicom_uid = fields.Str(required=False, data_key='dicom-uid')
level = fields.Str(required=True)
method = fields.Str(required=True)
orthanc_id = fields.Str(required=False, data_key='orthanc-id')
token_key ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat May 16 02:33:49 2020
@author: altsai
"""
import os
import sys
import shutil
#import re
import subprocess
#import numpy as np
import pandas as pd
file_rest_Ip='rest/rest_NCU_Ip_35.txt'
file_rest_Ip2='rest/rest_NCU_Ip_35-2.txt'
file_NCU='pub_list_NCU.tx... |
VTABLE(_Main) {
<empty>
Main
_Main.create;
}
FUNCTION(_Main_New) {
memo ''
_Main_New:
_T2 = 8
parm _T2
_T3 = call _Alloc
_T4 = 0
*(_T3 + 4) = _T4
_T5 = VTBL <_Main>
*(_T3 + 0) = _T5
return _T3
}
FUNCTION(main) {
memo ''
main:
_T6 = call _Main_New
_T7 = 1
_T8 =... |
# -*- coding: utf-8 -*-
__author__ = 'Yuvv'
import json
import functools
rule_file = open('res/rules-v1.json')
rules = json.load(rule_file)
explanations = rules['explanations']
rules = rules['rules']
rule_file.close()
def param_splitter(params):
param_dict = {}
for i in range(len(params)):
... |
from rest_framework import viewsets
import bookapi
from bookapi import serializer
from bookapi.models import Book
from bookapi.serializer import BookSerializer
class BooksViewSet(viewsets.ModelViewSet):
queryset = Book.objects.all()
serializer_class = BookSerializer
|
import flask_security as security
from bestvods.database import db
from typing import List
class Base(db.Model):
__abstract__ = True
id = db.Column(db.Integer, primary_key=True)
timestamp_created = db.Column(db.DateTime, default=db.func.current_timestamp())
timestamp_modified = db.Column(db.DateTime... |
import os
import cv2
import json
FONT = cv2.FONT_HERSHEY_SIMPLEX
LABELS = {
'AV': 'AV',
'Amber': 'Amber Light',
'Break': 'Breaking',
'Bus': 'Bus',
'BusStop': 'Bus Stop',
'Car': 'Car',
'Cyc': 'Cyclist',
'EmVeh': 'Emergency Vehicle',
'Green': 'Green Light',
'HazLit': 'Hazard Lig... |
class Privileges():
def __init__(self, *privilege):
self.privileges = privilege[:]
def show_privileages(self):
print(self.privileages)
class Admin(Privileges):
def __init__(self, *privilege):
super().__init__(*privilege)
self.privileages = privilege[:]
privileages = ['ca... |
#Caleb Lewandowski
#February 21, 2021
#Module 9.2 Assignment
#Purpose: To inner join tables.
#Import classes.
import mysql.connector
from mysql.connector import errorcode
#Create dictionary config.
config = {
"user": "pysports_user",
"password": "12345678",
"host": "127.0.0.1",
"database": "pysports",... |
# SPDX-License-Identifier: GPL-2.0
#
# Copyright (c) NXP 2019
import gdb
import sys
from linux import utils, lists, constants
clk_core_type = utils.CachedType("struct clk_core")
def clk_core_for_each_child(hlist_head):
return lists.hlist_for_each_entry(hlist_head,
clk_core_type.get_type().pointer()... |
#Caleb Lewandowski
#January 31, 2021
#Module 5.2 Assignment
#Set up connection.
from pymongo import MongoClient
url="mongodb+srv://admin:admin@cluster0.lwbyv.mongodb.net/pytech"
client = MongoClient(url)
db = client.pytech
#List collections in database.
print("-- Pytech Collection List --")
print(db.list_collection_n... |
#!/usr/bin/env python3
import scapy.all as scapy
import time
def get_mac(ip):
arp_request = scapy.ARP(pdst=ip)
broadcast = scapy.Ether(dst="ff:ff:ff:ff:ff:ff")
arp_request_broadcast = broadcast/arp_request
answered_list = scapy.srp(arp_request_broadcast,
timeout=1, verbo... |
#!/usr/bin/env python
from os import system
import datetime
import curses
def pretty_time_delta(delta_time):
if delta_time == None:
return "-"
seconds = delta_time.total_seconds()
sign_string = '-' if seconds < 0 else ''
seconds = abs(int(seconds))
days, seconds = divmod(seconds, 86400)
... |
class Solution:
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums)<1:
return 0
pos = 0
for i in range(1, len(nums)):
if nums[i] > nums[pos]:
if pos+1 != i:
pos+=... |
from lotus.domino import *
from notesentry import NotesEntry
from notesview import NotesView
'''
This only works if Lotus Notes is running and for local database files.
As of 12/02/2014 I do not plan on supporting any other setup because I don't need any other setup.
Contributions are welcome of course.
Rui Covelo
''... |
# 2. Реализовать класс Road (дорога), в котором определить атрибуты: length (длина), width (ширина).
# Значения данных атрибутов должны передаваться при создании экземпляра класса.
# Атрибуты сделать защищенными. Определить метод расчета массы асфальта,
# необходимого для покрытия всего дорожного полотна. Использовать ... |
import time
def triangle(i=1):
return i * (i + 1) / 2
def pentagonal(i=1):
return i * (3 * i - 1) / 2
def is_pentagonal(n):
x = int((24 * n + 1) ** 0.5 + 1)/6
if x*(3*x-1)/2 == n:
return True
else:
return False
def hexagonal(i=1):
while True:
yield i * (2 * i -... |
print( input()+"s")
|
from django.contrib import admin
from . models import Wallet, MinimunCoin, ExchangeTaxRates, OrderBook, SGDWallet, Notification, CryptoCurrency, Fiat, ConfirmFiatTransaction, Transaction
# Register your models here.
admin.site.register(Wallet)
admin.site.register(MinimunCoin)
admin.site.register(ExchangeTaxRates)
adm... |
print('Este programa es capaz de operar con fracciones de este tipo ==> a/b y c/d.')
print('Las operaciones seguirán el siguiente orden a la hora de operar. 1º a/b y 2º c/d')
a = float(input('Introduce el valor de a:'))
b = float(input('Introduce el valor de b:'))
c = float(input('Introduce el valor de c:'))
d =... |
#!/usr/bin/python
# template for "Stopwatch: The Game"
import simplegui
# define global variables
COUNTER = "0:00.0"
NUMBER = 0
SUC_STOP = 0
TOL_STOP = 0
FLAG = False
# define helper function format that converts time
# in tenths of seconds into formatted string A:BC.D
def format(val):
minutes = str(int(val) / 60... |
import re
#region Exceptions
class AzurApiException(Exception):
pass
class UnknownShipException(AzurApiException):
pass
class UnknownLanguageException(AzurApiException):
pass
class UnknownChapterException(AzurApiException):
pass
class UnknownDifficultyException(AzurApiException):
pass
class Un... |
# ----------------------------------------------------------------------------
# Copyright 2014 Nervana Systems Inc.
# 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.o... |
# (c) 2012 Urban Airship and Contributors
from django.test import TestCase
from django.template.defaultfilters import slugify
from mithril.forms import WhitelistForm, RangeForm
from mithril.models import Whitelist
from mithril.tests.utils import fmt_ip
import random
class MithrilFormsTestCase(TestCase):
def tes... |
from flask import Flask, render_template, session, redirect, url_for, request
import verifier
app=Flask(__name__)
@app.route('/')
def index():
cu=''
if len(session.keys())!=0:
cu=session[session.keys()[0]]
else:
cu='guest'
return render_template("index.html", current_user=cu)
@app.rou... |
# -*- coding: utf-8 -*-
from odoo import models, fields, api, exceptions, _
import time
class Partner(models.Model):
_inherit = 'res.partner'
author = fields.Boolean('is an Author', default=False)
publisher = fields.Boolean('is a Publisher', default=False)
current_rental_ids = fields.One2many(
... |
from Bio import SeqIO
import sys
import os
import shutil
import numpy as np
import re
'''
Usage:
python binary_encoding.py input.fa output
'''
#Convert to sequence to binary
inputFASTA = sys.argv[1]
record = list(SeqIO.parse(inputFASTA, "fasta"))
trainMat = np.empty(shape = [1, 201, 4])
tt = 0
for fasta in record:
... |
###############################################################################
# Author: Wasi Ahmad
# Adapted by: Jonathan Hurwitz
# Project: Biattentive Classification Network for Sentence Classification
# Date Created: 01/06/2018
#
# File Description: This script is the entry point of the entire pipeline.
##########... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import os
import re
import pathlib
from collections import Counter
from python_graphql_client import GraphqlClient
root = pathlib.Path(__file__).parent.resolve()
client = GraphqlClient(endpoint="https://api.github.com/graphql")
TOKEN = os.environ.get("CONTRIBUTORS_TOKE... |
from bernoulli import BernoulliBayes
import numpy as np
from nose.tools import assert_equal
import nose
X = np.array([[1,0,1],
[1,0,0],
[0,1,0],
[1,1,0],
[0,1,1]])
y = np.array([0,0,1,1,1])
bb = BernoulliBayes()
bb.fit(X,y)
def test_priors():
assert_equal(bb.prior[0],2)
assert_equal(bb.prior... |
import Queue
import threading
import shutil
import glob
fileQ = Queue.Queue()
src = './src'
dest = './dest'
fcnt = 0
total = 0
def Copy():
while True:
filename = fileQ.get()
fileQ.task_done()
shutil.copy(filename, dest)
fcnt += 1
print 'copied: ', fcnt, ' of ', total
def m... |
# --------
# Note
# --------
#
car_stopped = True
while True:
user_input = input('> ').lower()
if user_input == 'help':
print('start - to start car')
print('stop - to stop car')
print('quit - to quit game')
elif user_input == 'start':
if car_stopped:
print('Ca... |
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 27 09:29:53 2021
@author: GIANG Cécile, KHALFAT Célina
"""
##################### IMPORTATION DES LIBRAIRIES UTILES ####################
import numpy as np
from IRModel import *
from Metrics import *
from EvalIRModel import *
from GridSearch import *
##... |
from datetime import datetime, timedelta
import psycopg2
def connect():
conn = psycopg2.connect(
host="database-1.ctjpvwq07ek9.us-east-2.rds.amazonaws.com",
port='5432',
database="avallon",
user="postgres",
password="postgres")
return conn
def get_books():
conn =... |
from summarkup.utils import detokenize, make_word_match_header
from summarkup.generators.conceptv2 import ConceptV2
from scripts_sum.summary_instructions import get_instructions
from scripts_sum.borda import merge_scores
import numpy as np
import re
from nltk.corpus import stopwords
en_stopwords = set(stopwords.words(... |
# -*- coding: utf-8 -*-
import time
from modules import cbpi
from modules.core.hardware import ActorBase
from modules.core.props import Property
try:
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
except Exception as e:
print e
pass
@cbpi.actor
class GPIODelay(ActorBase):
gpio = Property.Selec... |
/home/miaojian/miniconda3/lib/python3.7/ntpath.py |
# Kleinberg's method of finding probabilistic geographic distribution for terms (events)
import pdb
import json
import re
import sys
import math
from pymongo import MongoClient
from cell import Point, Coordinates, Cell
from scipy.optimize import minimize
from geopy.distance import great_circle
# Input file path:
fi... |
import random
from alien import Alien
class Enemy:
# TODO add a level later
def __init__(self, screen, settings):
self.aliens = []
self.settings = settings
self.screen = screen
self.alive_alien_count = 0;
def spawn_aliens(self):
alien_count = random.randrange(3, ... |
from sklearn.linear_model import LogisticRegression
import scipy.io, sys,pickle
from numpy import *
aspects = list()
aspects.append(sys.argv[1])
modelName=sys.argv[2]
#aspects = ['service','price','miscellaneous','food','ambience']
for aspect in aspects:
feature_file = scipy.io.loadmat('../data/features_'+modelName+'/... |
"""
MIT License
Copyright (c) 2018 Simon Raschke
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish,... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# @author: B17455
#作业1:对照 day9 sample-code 打一遍代码
#
#作业2: (选做)模拟下面的过程,用今天学到的知识
#【场景模拟】
#
# 老爸在看一本英文书,他旁边有一个词典,但是只有三个词的解释
# abandon “to give up to the control or influence of another person or agent”
# abase “to lower in rank, office, prestige, or esteem ”
# abash “to destroy ... |
#!/usr/bin/env python
"""
_ListForSubmitter_
MySQL function to list jobs for submission
"""
from WMCore.Database.DBFormatter import DBFormatter
class ListForSubmitter(DBFormatter):
sql = """SELECT wmbs_job.id AS id, wmbs_job.name AS name,
wmbs_job.cache_dir AS cache_dir,
... |
a,b=input().split()
c=[]
c=input().split()
d=c[-int(b):]
e=''
for i in range(len(d)):
e+=d[i]+" "
for i in range(len(c)-len(d)):
e+=c[i]+" "
print(e)
|
from paramspace.traits_model import ModelTraits, load
from hyperopt import hp, pyll
from traits.api import Float, Range, Instance, Any
class TestModel(ModelTraits):
x = Float(0.0)
y = Float(0.0, dist=hp.uniform("y", 0, 1))
z = Range(low=0.0, dist=hp.normal("z", 0, 1))
class TestModel2(ModelTraits):
a = Instan... |
from ED6ScenarioHelper import *
def main():
# 封印区域
CreateScenaFile(
FileName = 'C4304 ._SN',
MapName = 'Grancel',
Location = 'C4304.x',
MapIndex = 216,
MapDefaultBGM = "ed60035",
Flags = 0,
... |
import bus_times
import os
import define
#import analyze
import prepare
import feature_selection
import evaluate
import tools
from pyspark.ml.feature import StringIndexer
from pyspark import SparkContext, SparkConf
from pyspark.sql import SQLContext, Row, SparkSession
from pyspark.sql.types import *
#name = "datasets... |
"""Test suite for the LMS select function."""
from django.test import TestCase
from django.test.utils import override_settings
from richie.apps.courses.lms import LMSHandler
from richie.apps.courses.lms.base import BaseLMSBackend
from richie.apps.courses.lms.edx import TokenEdXLMSBackend
class LMSSelectTestCase(Test... |
import socket
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((socket.gethostname(), 5050))
while True:
msg = client.recv(9999)
final_msg = msg.decode('utf-8')
if final_msg == "exit" or final_msg == "break":
print(final_msg)
break
elif final_msg... |
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from numpy import array
from keras.layers import Flatten
from keras.layers import GlobalMaxPooling1D
from keras.layers.convolutional import Conv1D
from keras.layers.embeddings import Embedding
from sklearn.model_selection import train_test_split
fro... |
DEBUG = True
SERVE_MEDIA = DEBUG
TEMPLATE_DEBUG = DEBUG
EMAIL_DEBUG = DEBUG
THUMBNAIL_DEBUG = DEBUG
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
|
# Create your views here.
from django.shortcuts import render, redirect
from django.views import generic
from django.contrib.auth import logout as drchrono_logout
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.core.mail import send_mail,send_mass_mail
from .models import PatientMod... |
'''a program to print the pattern.'''
max=5
for i in range(1, max + 1):
for j in range(max , i-1 , -1):
print(" ",end="")
for k in range(1 , i + 1):
print(k,end="")
for l in range(k-1,0, -1):
print(l,end="")
print() |
from django.contrib import admin
from leads.models import *
admin.site.register(User)
admin.site.register(UserProfile)
admin.site.register(Agent)
admin.site.register(Lead)
|
# Generated by Django 3.0.4 on 2020-06-27 12:58
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('tour', '0008_auto_20200627_1253'),
('activity', '0004_auto_20200627_1253'),
]
operations = [
migrations.RemoveField(
mod... |
import __init__
from __init__ import *
import numpy as np
import statsmodels
from statsmodels.tsa.stattools import levinson_durbin
from ArrayTree import ArrayTree
""" matlab api """
import matlab
import matlab.engine
""" check format """
def _check_1d_ndarray(x):
assert(type(x) == np.ndarray)
assert(len(x.s... |
from django.urls import path,include
from .views import *
from django.contrib.auth import views as auth_views
from django.conf.urls import url
urlpatterns = [
path('', profile, name='profile'),
path('register/',register,name="register"),
path('login/',auth_views.LoginView.as_view(template_name='stu... |
__author__ = 'alex'
class Solution(object):
def lengthOfLongestSubstring(self, s):
if s == "":
return 0
posi_dict = dict()
start_position = 0
current_longest_length = 0
posi = 0
for index in range(len(s)):
if not s[index] in posi_dict:
... |
#!/usr/bin/python3
Rectangle = __import__('9-rectangle').Rectangle
r = Rectangle(3, 5)
print(r)
print(r.area())
|
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
class RelianceDigital :
def __init__(self):
webOptions = webdriver.ChromeOptions()
webOptions.ad... |
import json
import keys
def api_msg_render(headers, body, method, api_url):
#
# If rendering API message is enabled this takes a collection of variables and builds a dict containing API usage info.
# input:
# headers - dict of headers
# body - dict for body; supports --form, -F, group, user_policy, video, or N... |
from onegov.swissvotes.models.actor import Actor
from onegov.swissvotes.models.column_mapper import ColumnMapperDataset
from onegov.swissvotes.models.column_mapper import ColumnMapperMetadata
from onegov.swissvotes.models.file import SwissVoteFile
from onegov.swissvotes.models.file import TranslatablePageFile
from oneg... |
RULES_FILE = "rules.json"
|
# Yue Kuang
# May 13th 2020
import pandas as pd
import numpy as np
from scipy import stats
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.svm import LinearSVC
from sklearn.naive_bayes import GaussianN... |
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from method import *
class sphere:
def __init__(self, p):
#パラメータ
self.p = p
# 球の方程式: f(x,y,z) = r - √(x-a)^2 + (y-b)^2 + (z-c)^2
def f_rep(self, x, y, z):
return self.p[3] - np.sqrt((x-self... |
from django.shortcuts import render
def sign_up(request):
return render(request, 'users/form_user.html')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.