text stringlengths 38 1.54M |
|---|
'''
39. Combination Sum [Medium]
Given a set of candidate numbers (candidates) (without duplicates) and
a target number (target), find all unique combinations in candidates
where the candidate numbers sums to target.
The same repeated number may be chosen from candidates unlimited number of times.
Note:
... |
import gzip
from datetime import datetime
from collections import defaultdict
from multicorn import ForeignDataWrapper
from multicorn.utils import log_to_postgres
def get_rows(path):
"""Iterates through compressed access log and yields dicts that
contain ip, time, and error code info.
"""
with gz... |
#!/usr/bin/env python
import unittest
from acme import Product
from acme_report import generate_products, ADJECTIVES, NOUNS
class AcmeProductTests(unittest.TestCase):
"""Making sure Acme products are the tops!"""
def test_default_product_price(self):
"""Test default product price being 10."""
... |
# Find out whether a list is a palindrome.
def rev(lst):
reversed = []
for i in lst:
reversed.insert(0, i)
return reversed
def isPalindrome(lst):
if lst == rev(lst):
return True
return False |
f = [41, 32, 212]
v = list(map(lambda x: (x - 32) * 5 / 9, f))
print(v)
rev = [item ** 2 for item in reversed(f)]
print(rev) |
#This problem computes the largest 1 to 9 pandigital 9-digit number that can be formed as the concatenated product of an integer with (1,2,...,n) where n>1.
max = 0
for i in range(2,10):
listfac = range(1,i)
for j in range(1,10000):
n = ''
for k in listfac:
n = n + str(k*j)
if len(n) == 9 and set(n) == {'1'... |
import sys
import time
import datetime
from awsglue.transforms import *
from awsglue.utils import getResolvedOptions
from pyspark.context import SparkContext
from awsglue.context import GlueContext
from awsglue.job import Job
## @params: [JOB_NAME]
args = getResolvedOptions(sys.argv, ['JOB_NAME'])
print "Starting the ... |
"""Terminal management for exposing terminals to a web interface using Tornado.
"""
from __future__ import absolute_import, print_function, with_statement
import sys
if sys.version_info[0] < 3:
byte_code = ord
else:
byte_code = lambda x: x
unicode = str
import itertools
import logging
import os
import si... |
#!C:\python38\python
#coding=utf-8
import os
import time
# 获取当前路径
currDir = os.getcwd()
print(currDir)
# 修改当前路径
os.chdir(r"c:")
print(os.getcwd())
os.chdir(currDir)
print(os.getcwd())
# 获得绝对路径
fileA = os.path.join(os.getcwd(), 'a')
print(fileA)
print(os.path.abspath(fileA))
print("------------------------------------... |
# coding: utf8
#
# Project: Time-Resolved EXAFS
# http://www.edna-site.org
#
# Copyright (C) 2013 European Synchrotron Radiation Facility
# Grenoble, France
#
# Principal authors: Olof Svensson (svensson@esrf.fr)
#
# This program is free software: you can re... |
arr1 = input()
A = input()
arr1 = list(map(int,arr1.split()))
M = arr1[1]
A = list(map(int,A.split()))
x = 0
y = max(A)
h = (x + y) // 2
def calS(a, h):
s = 0
for i in A:
if i > h:
s += i - h
return s
k = calS(A, h)
while k != M and y-x > 1:
if k > M:
x = h
elif k < M... |
class Poly:
def __init__(self,mylist = 0):
self.alist = [mylist[0]]
for i in mylist[1:]:
self.alist += [i]
def __str__(self):
return str(self.alist)
def degree(self):
return len(self.alist) - 1
def addTerm(self,exp,coeff):
self.alist +=
|
import cv2
# import and show image
img = cv2.imread("v2_train/image1.jpg") # read image file
cv2.imshow("Output", img) # display image file (but continue execution)
cv2.waitKey() # pause execution for arg ms (0 or none = infinite)
# import and show video
video_cap = cv2.VideoCapture("video_test.mp4") # read vid... |
#!/usr/bin/env python
import sys
import pandas
import datetime
from pathlib import Path
csv_file = sys.argv[1]
output_dir = Path(csv_file.replace('.csv', '') + '-segments')
if not output_dir.is_dir():
output_dir.mkdir()
df = pandas.read_csv(csv_file, parse_dates=['created'])
df = df.sort_values('created', asce... |
#! /usr/bin/env python
import numpy as num
from pdb import set_trace as stop
def rot180numpy(image,center):
"""Rotates an image 180 degrees respect to a center, using numpy."""
# IMPORT STUFF
from algorithms_II import shrotate
from time import time
# END IMPORT
#print time()
#shap... |
#En este punto de inicio __init__ se harà la configuraciòn de las apis
#desde aquì podremos configurar el inicio por default de las apis
#por lo que pondrémos la documentación de cada una de ellas
from flask_restplus import Api
# Importamos los Namespaces que creamos en cada metodo
from src.methods.items import serv... |
# noinspection DuplicatedCode
class BinMinHeap:
def __init__(self):
self.heap = [0]
self.length = 0
def __len__(self):
return self.length
# Easiest and most efficient way to add an element? Append it!
# Good news about appending: guarantees that we will maintain the complete tr... |
import os
import pty
import select
import shlex
import shutil
import pyte
from cobra_py import rl
from cobra_py.kbd_layout import read_xmodmap
# TODO:
# * mouse support
# * generalize keyboard support for screens/layers
# Codes for ctrl+keys
def ctrl_key(char: bytes):
if 96 < char[0] < 123:
return chr... |
from flask_apscheduler import APScheduler
from flask import Blueprint, request, jsonify, session
import requests
import socket
import json
import os
manifest = Blueprint('manifest', 'manifest' ,url_prefix='/manifest')
scheduler = APScheduler()
def set_manifest():
f = open("manifest_cpu.json", "r")
manifest... |
import hanlp
import json
import torch
from torchtext import data
import argparse
def parse_args():
args = argparse.ArgumentParser()
# network arguments
args.add_argument("-data", "--data",
default="project3_train.csv", help="data directory(默认在data文件夹下)")
args.add_argument("-j_s",... |
# coding=utf-8
import time
import abc
from collections import OrderedDict
from ruamel.yaml import dump as ydump, load as yload, RoundTripDumper, resolver, add_constructor, add_representer
from src.meta.abstract import AbstractMeta
from utils.custom_logging import make_logger
from utils.custom_path import Path
logger... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
counter = 100 # 赋值整型变量
miles = 1000.0 # 浮点型
name = "John" # 字符串
if counter == 100:
print counter;
else:
print miles;
print name;
# 运行结果
"""
100
John
"""
|
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 6 11:00:28 2018
@author: 鑫鑫玉川
"""
"""
名字:Mod(a,b,n),a,b表示列表,长度都为n
功能:返回a模b的列表
"""
def Mod(a,b,n):
result=a[:] #c拷贝a
d=b[:]
a_len=n
b_len=n
for i in range(n):
if(a[i]!=0):
break
a... |
#_*_coding:utf-8_*_
print 打飞机游戏
加载背景音乐
播放背景音乐(设置单曲循环)
加载我方飞机
interval=0
while True:
if 用户点击关闭按钮
退出程序
interval+=1
if interval=50
加载敌方飞机
interval=0
敌方飞机移动
屏幕刷新
if 用户鼠标发生移动
鼠标位置==我方飞机的位置
屏幕刷新
elseif 我方飞机的位置==敌方飞机的位置
播放撞机音乐
加载飞机爆炸的图片
print 游戏结束
关闭背景音乐(设置淡出)
|
# -*- coding: utf-8 -*-
studentsSet = {"ahmet" , "ali" , "Erkan"}
print(studentsSet)
for students in studentsSet:
print(students)
print("erkan" in studentsSet)
if "ali" in studentsSet:
print("listede var")
studentsSet.add("melis")
print(studentsSet)
studentsSet.update(["mer... |
'''
Created on 6 Aug 2014
@author: michael
'''
from mjb.dev.game_utility.shapes.shape import Shape
from mjb.dev.game_utility.shapes.handlers.drawable_shape_handler import DrawableShapeHandler
from mjb.dev.game_utility.capabilities.drawable import Drawable
class DrawableRectangleHandler(DrawableShapeHandler):
'''... |
# Generated by Django 2.2.3 on 2019-08-28 22:18
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('sarklo', '0004_auto_20190828_1838'),
]
operations = [
migrations.AddField(
model_name='oglas',
... |
#!/usr/bin/python
import happybase
import struct
import re
import getopt
import sys
from DB.Registry import Registry
def usage():
print "index-stats.py [-h] [-H hbhostname]\n"
def HBConnection(host):
c = happybase.Connection(host)
return c
def load_primary_index_map(reg):
km = {}
for reg_key in ... |
#
# MansOS web server - server-side configuration settings
#
from __future__ import print_function
import configfile
import os
HTTP_SERVER_PORT = 30000
SERIAL_BAUDRATE = 38400
# global variable
c = configfile.ConfigFile("server.cfg", automaticSections = True)
# default values
c.setCfgValue("port", HTTP_SERVER_PORT)... |
from .scenes import Scenes
from src.scenes import SceneBase
from src.utils import load_image
import pygame
from pygame.locals import *
class StartMenu(SceneBase):
def __init__(self):
super().__init__()
btns_path = './tresenraya/assets/buttons/'
start_btn, rect = load_image(f'{btns_path}/s... |
# -*- coding: utf-8 -*-
import unittest
from pg_requests.exceptions import TokenError
from pg_requests.operators import And, JOIN
from pg_requests.tokens import Token, TupleValue, CommaValue, StringValue, \
NullValue, FilterValue, DictValue, CommaDictValue
class TokensTest(unittest.TestCase):
def test_token_w... |
"""from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
from flask_bcrypt import Bcrypt
def create_app():
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:d00m3r456@localhost:3307/llantera'
app.config['SQLALCHEMY_TRACK_MODIFI... |
for letter in "Python":
if letter == 'h':
break
print letter
index = 10
while index > 0:
print index
index = index - 1
if index == 5 :
break
|
import ast
import os
from collections import defaultdict
THRESHOLD1 = 0.27
THRESHOLD2 = 0.54
FRACTION = 8 # If there are more than 1/FRACTION of the total variants, use thr1 for that family for that app
TRUSTED_NUM_REPRESENTATIVES = 8 # If there are less variants, without looking to neighbours, the higher threshold ... |
# this lets me just use Square() instead of Square.Square()
# from is the Module name ( file name ), import is the class name
from Square import Square
def print_square_stats( square ):
print("a square with length of", square.length_of_side,
"has an area of", square.calculate_area(),
"and a per... |
import pymongo
from pymongo import MongoClient
import json
import os
# 開啟json檔
def open_json_file(CACHE_FNAME):
try:
cache_file = open('./data/'+CACHE_FNAME, 'r')
cache_contents = cache_file.read()
# print(type(cache_contents))
CACHE_DICTION = json.loads(cache_conte... |
from django.contrib import admin
from .models import Impacto
from import_export.admin import ImportExportModelAdmin
from .resources import ImpactoResource
#@admin.register(Impacto)
#class ImpactoAdmin(admin.ModelAdmin):
# pass
@admin.register(Impacto)
class ImpactoAdmin(ImportExportModelAdmin):
resource_class... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@author Zhett
@email stratos33290@gmail.com
@version 0.1
@copyright 2013 Zhett
"""
from django.contrib.auth.models import User
from django.db import models
from website.models import *
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.contrib.auth.models imp... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
#
# Copyright (c) 2022 Baidu, Inc. 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/LICEN... |
from __future__ import print_function
import sys
import os
import requests
import datetime
import pandas as pd
from bokeh.io import curdoc
from bokeh.layouts import row, widgetbox
from bokeh.models import ColumnDataSource
from bokeh.models.widgets import TextInput, RadioButtonGroup
from bokeh.models.tools import HoverT... |
from flask import Flask
from Crypto.Cipher import AES
from os import urandom as rand
from binascii import unhexlify
app = Flask(__name__)
flag = 'flag{' + rand(32).hex() + '}'
key = rand(32) # AES key
# Creates an AES cipher object
def aes(iv):
return AES.new(key, AES.MODE_CBC, iv)
# apply PKCS#7 padding to m... |
# TODO: Write docstring here
"""A program to hype you up on a dreary day."""
__author__: str = "730247598"
# TODO: Initialize __author__ variable here
name: str = input("What is your name? " + "\n")
# TODO: Implement your program logic here
print(name + ", you got this!" + "\n")
print("Hang in there a little longer "... |
def matrix_for_traces(l,theta1,theta2):
solutions = []
if len(l) <= 1:
return "More than one trace needed!"
for i in range(len(l)+1):
others = []
others.append(l[0:i])
others.append(l[i:len(l)+1])
basetrace = l[i][0:i]
for x in basetrace:
for y in ... |
def decor(fun):
def inner():
result =fun()
return result*2
return inner
def num():
return 5
newresult =decor(num)
print(newresult())
|
def fullcode():
# code word zo vaak uitgevoerd totdat er (input) geldige BSN's zijn
try:
BSNcounter = int(input("Hoeveel BSN's?: "))
except:
print("Geef een getal op!")
return()
while BSNcounter > 0:
import random
y = 0
h = 0
BSN =... |
from django.shortcuts import render
from .models import Post
from .forms import PostForm, WishForm
from django.views.generic import ListView, CreateView, TemplateView
# Create your views here.
class PostListView(ListView):
allow_empty = True
model = Post
template_name = 'blog/post-list.html'
def... |
"""
Takes revision event data file. Keeps just anonymous user data.
Usage:
anonymous_edits (-h|--help)
anonymous_edits <input> <output>
[--debug]
[--verbose]
Options:
-h, --help This help message is printed
<input> Path to input file to process. ... |
from django.contrib import admin
from homepage.models import Roast_Boast
# Register your models here.
admin.site.register(Roast_Boast) |
def markDigits(number, digits):
while number:
digit = number % 10
digits[digit] = True
number //= 10
def isTimeToSleep(digits):
for marked in digits:
if not marked:
return False
return True
numbers = []
with open("input.txt", "r") as inputFile:
inputFile.readline()
for line in inputFi... |
from .provider import TicketProvider
import gitlab
import os
GITLAB_URL = os.getenv('GITLAB_URL', 'https://gitlab.fabcloud.org')
GITLAB_TOKEN = os.getenv('GITLAB_TOKEN')
def gitClient(sudo=None):
git = gitlab.Gitlab(GITLAB_URL, GITLAB_TOKEN, api_version=4)
if sudo:
git.headers['Sudo'] = str(sudo)
... |
#!/usr/bin/python3
import datetime
import inquirer
import requests
import re
import csv
import os
import json
repositories = [
"beagle",
"beagle-web-react",
"beagle-web-core",
"beagle-web-angular",
"charlescd",
"charlescd-docs",
"horusec",
"horusec-engine-docs",
"ritchie-cli",
"... |
"""
This service monitors
"""
import asyncio
import json
import logging
import time
from asyncio_redis import Connection as RedisConnection
from collections import namedtuple
from importlib import import_module
from .utils import (
DEFAULT_REDIS_KEY,
extract_package,
)
LOG = logging.getLogger(__name__)
Que... |
# Recaman Object:
# Returns a Recaman object with solved sequence up to n,
# where n is the single constructor input argument.
#
# Tested with python version 3.6.6
class Recaman(object):
''' ATTRIBUTES '''
sequence = {}
''' METHODS '''
# constructor
def __init__(self,n):
super(Recaman... |
from django.contrib.auth.decorators import login_required
from django.shortcuts import render, get_object_or_404, redirect
from django.utils import timezone
from .models import *
from .forms import *
from django.contrib import messages
# Create your views here.
def project_list(request):
projects = Project.objects.f... |
# Libreria para generar datos aleatorios
import random
# Libreria para generar graficas
import matplotlib.pyplot as plt
# Generar un numero aleatorio -> randint, randrange
print(random.randrange(10,100,2))
# Reacomodar una lista al azar
lista=[1,2,3,4,5,6,7,8,9,10]
print('Lista original', lista)
random.shuffle(list... |
import random
def contains(listx, x):
flag=False
for y in listx:
if(x==y):
flag=True
break
return flag
def deal_cards():
listx=[]
while True:
x = random.randint(0, 51)
while contains(listx,x):
x = random.randint(0, 51)
... |
# -*- coding:utf-8 -*-
from django.shortcuts import redirect, render
from automechanic.client.forms import ClientForm, DeleteForm
from automechanic.client.models import Client
from django.contrib import messages
from automechanic.messages import success_messages, error_messages
from django.views.decorators.http import ... |
import re
from django.core.exceptions import ValidationError
def NotesValidator(input):
# TODO : make this validator 'stronger' (should try to convert input into
# a NoteSeq and see if it works)
try:
str(input)
except Exception:
raise ValidationError("Wrong datatype")
if ... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-02-07 13:15
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('voa', '0002_adjustment'),
]
operations = [
migrations.CreateModel(
... |
"""
Tests CQGI functionality
Currently, this includes:
Parsing a script, and detecting its available variables
Altering the values at runtime
defining a build_object function to return results
"""
from cadquery import cqgi
from tests import BaseTest
import textwrap
TESTSCRIPT = textwrap.... |
""" Super class for the model objects """
import numpy as np
class ModelLoader(object):
""" Super class for all ModelLoader objects.
Holds the model information for converting trajectories into data. Also
constructs methods for computing the energy from epsilon model parameters.
The attribute model (... |
import os
# 현재 디렉토리
# print(os.getcwd)
# print(os.path.curdir)
# print(os.path.realpath('.'))
# print(os.path.exists()) # 해당 파일이 존재하는지 체크
# print('|'.join(['a.png','b.png','c.png']))
print('abc.png'.split('.')[1]) |
class animal:
def sleep(self):
print("睡")
def __eat(self): # 私有成员不会被子类继承
print("吃")
class dog(animal): # 在dog类里面,没有__eat方法
pass
d = dog()
d.sleep()
# d.__eat() # 这里的代码会出错 |
from random import randint
class Player:
hp = 5 # здоровье
mana = 5 # мана
max_hp = 5 # максимальное здоровье
max_mana = 5 # максимальная мана
pw = 2 # сила(урон с руки)
lvl = 0 # уровень
sp = 5 # скилл поинт
xp = 0 # опыт
max_xp = 10 # максималный опыт
if hp > max_hp:
hp = max_hp
if mana > max_mana:
m... |
# yukicoder No.436 ccw 2020/01/30
s=list(input())
n=len(s)
for i in range(n-1):
if s[i]+s[i+1]=='cw':
ans=min(n-(i+1),i)
print(ans) |
import random
mass = [ random.randrange(1, 1000) for _ in range(20) ]
enter_number = 500
max_numbers =[]
for number in mass:
if number > enter_number:
max_numbers.append(number)
if len(max_numbers) == 3: break
print(max_numbers) |
import cs50
height = int(input("Height: "))
if height > 0 and height < 23:
x = " "
spaces = height
hashes = 2
print(hashes)
for i in range(0,height):
for s in range(1,spaces):
print(x,end="")
for h in range(0,hashes):
print("#",end=""... |
"""Storage-related exceptions."""
from ..core.error import BaseError
class StorageError(BaseError):
"""Base class for Storage errors."""
class StorageNotFoundError(StorageError):
"""Record not found in storage."""
class StorageDuplicateError(StorageError):
"""Duplicate record found in storage."""
c... |
def contribs(x):
links = x[1][0].split()
out_d = len(links)
for link in links:
yield link, x[1][1]/out_d
rank_raw = [('a',.25), ('b', .25), ('c', .25), ('d', .25)] # initial ranks
link_raw = [('a', 'b c d'), ('b', 'a c'), ('c', 'd'), ('d', 'a b')]
ranks = sc.parallelize(rank_raw)
links = sc.paralle... |
import labs.day9.lsystem as lsys
import labs.day9.draw as draw
lsys_rule = lsys.Rule({
"1": [
["11",0.8],
["1",0.08],
["111",0.008],
["",-1]
],
"0": "1[0]0"
})
#
draw_rule = {
"1": draw.one_rule,
"0": draw.zero_rule,
"[": draw.left_bracket_rule,
"]": draw.rig... |
#!/usr/bin/python3
import csv
import json
import os
IN_FILENAME_FOR_SNIPPETS = 'source.txt'
OUT_FILENAME_FOR_VSCODE = os.path.join('out', 'vscode', 'git-commit.json')
def to_vscode_snippet(body: str, prefix: str = None, description: str = None):
if not prefix:
prefix = body.split(' ')[0].split('/')[0]
... |
from src.HistData.Candle.Candle import Candle
class FileParser:
timeIndex = 0
openIndex = 1
highIndex = 2
lowIndex = 3
closeIndex = 4
cellSeparator = ';'
fileOperation = 'rU'
def __init__(self, filename):
self.filename = filename
# Get all rows from file
# File format... |
# one 3
# two 3
# three 5
# four 4
# five 4
# six 3
# seven 5
# eight 5
# nine 4
# ten 3
# eleven 6
# twelve 6
# thirteen 8
# fourteen 8
# fifteen 7
# sixteen 7
# seventeen 9
# eighteen 8
# nineteen 8
# twenty 6
# thirty 6
# forty 5
# fifty 5
# sixty 5
# seventy 7
# eighty 6
# ni... |
import sys
sys.setrecursionlimit(2**20)
DEBUG = 0
def testRemove(string, target, remove, until):
copy = string.copy()
for i in remove[:until]:
copy[i - 1] = 0
if (DEBUG):
print(copy, string)
j = 0
for i in copy:
if (i == target[j]):
j += 1
if (j == len(target... |
# Generated by Django 3.0.5 on 2020-04-22 00:40
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [("data", "0003_auto_20200422_0031")]
operations = [
migrations.RemoveField(model_name="membership", name="on_behalf_of"),
migrations.RemoveField(model_name... |
import pygame
from .base import BaseEffect
from ...arrays.point import Point
class Shadow(BaseEffect):
def __init__(self, parent, color, offset_point, trail=False, step=1, alpha=None):
self.offset = Point(offset_point)
self.trail = trail
self.step = step
BaseEffect.__init__(self, pa... |
# -*- coding: utf-8 -*-
from __future__ import print_function
import six
import time
from datetime import datetime, tzinfo
import requests
from copy import deepcopy
API_V1_0 = 'https://emp.mos.ru/v1.0'
API_V1_1 = 'https://emp.mos.ru/v1.1'
class AuthException(Exception):
pass
class EmpServerException(Exception... |
from petl import *
# Call extract script and get a file.
# Load it as a petl table
# Extract the columns needed
# Save it in data directory as a compressed HDF5 file for later use in Pandas
|
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, Http404
from django.template import RequestContext, loader
from .models import Post, Page
def index(request):
latest_post_list = Post.objects.order_by('-pub_date')[::-1]
latest_page_list = Page.objects.order_by('-ppub_... |
import numpy as np
def pretty(mat, label):
print('Covariance Matrix {}'.format(label))
print(mat)
matinv = np.linalg.inv(mat)
print('Inverse Covariance Matrix {}'.format(label))
print(matinv)
A = np.array([[9, 3, 1], [3, 9, 3], [1, 3, 9]])
B = np.array([[8, -3, 1], [-3, 9, -3], [1, -3, 8]])
C = np... |
import tensorflow as tf
class Optimizer(object):
def __init__(self, parameters):
self.parameters = parameters
def get_optimizer(self):
self.optimizer_object = tf.train.AdamOptimizer(learning_rate=self.parameters.learning_rate)
return self.optimizer_object
|
from sets import Set
from nevow import inevow, tags as T, flat, loaders, rend
from tub.public.web import common as tubcommon
from crux import web, icrux, skin
from navigation import NestedListNavigationFragment
from pollen.nevow import renderers
from basiccms.paging import ListPagingData, PagingControlsFragment
from ... |
from fbs_runtime.application_context.PyQt5 import ApplicationContext
from core.amazon_scraper.scraper import Scraper
from ui.keetext import KeetextGui
import sys
def main():
appctxt = ApplicationContext() # 1. Instantiate ApplicationContext
window = KeetextGui()
window.show()
exit_code = appctxt... |
from django import forms
from Crud.models import King,Dummy
class king(forms.ModelForm):
class Meta:
model = King
fields = '__all__'
class dummy(forms.ModelForm):
class Meta:
model = Dummy
fields = '__all__'
|
# This server will be run on the jupyter notebook, where it will call down to jupyter nbconvert
# to execute the notebook from airflow.
import subprocess
from flask import Flask
from flask_restful import reqparse, Resource, Api
parser = reqparse.RequestParser()
parser.add_argument('input_nb', required=True, type=str)
... |
#Youtube video downlaod√√
from pytube import YouTube
link = input('Enter the link :')
yt = YouTube(link)
videos = yt.streams.all()
# videos= videos.index(res)
# print(videos)
# https://www.youtube.com/watch?v=Yqur47HdKd8
i = 1
for stream in videos:
print(stream)
print(str(i)+' '+ str(stream))
i+=1
stre... |
from datetime import date, timedelta
import pymysql
from baseObject import baseObject
import re
from contract import contractList
class userList(baseObject):
# list object for User table
def __init__(self):
self.setupObject('Users')
def verifyNew(self,n=0):
# check data for errors,... |
import json
import urllib2
import urllib
import urlparse
import re
import helperfunctions
import base64
import datetime
import hashlib
class lribhelper(object):
def __init__(self, config, logging):
self.config = config
self.logging = logging
self.entityCache = {}
# List of propert... |
from prediction.classes import Meeting, Course, Section
from prediction import schedule_generator
import datetime
#Meeting 1, Section 1, Course 1
meetingType = "Lecture"
campus = "Newark"
startTime = datetime.time(7,0)
endTime = datetime.time(8,5)
professorName = "Suporn Chenhansa"
room = "NC2308"
recurrence = ["MO","... |
from optparse import make_option
from six.moves.urllib.request import urlopen
import xml.etree.ElementTree as etree
from django.core.management.base import BaseCommand, CommandError
from speeches.models import Section, Speech, Speaker
from instances.models import Instance
PLAYS = {
"all_well.xml": "All's Well Th... |
#! /usr/bin/env python
# -*- coding:utf-8 -*-
# __author__ = "LJ"
# Date: 2019/3/6
filepath = "D:\\test.txt"
#1.读取D盘根目录下文件test.txt的内容
with open(filepath,'r',encoding='utf-8') as rf:
filedata=rf.read()
print(filedata)
# 2.遍历所有行,得到邮箱格式的每一行
with open(filepath,'r',encoding='utf-8') as rf:
emaillist = [] # 保... |
import numpy as np
import numpy.linalg as la
file = open("data.txt")
data = np.genfromtxt(file, delimiter=",")
file.close()
print "data ="
print data
M = []
b = []
for x_prime, y_prime, x, y in data:
M.append([x,y,1,0,0,0])
M.append([0,0,0,x,y,1])
b.append([x_prime])
b.append([y_prime])
M = np.matrix(M)
print ... |
import requests
from bs4 import BeautifulSoup
from csv import writer
import time
API_KEY='15d2ea6d0dc1d476efbca3eba2b9bbfb'
BASE_URL = 'https://api.themoviedb.org/3/search/movie?api_key=15d2ea6d0dc1d476efbca3eba2b9bbfb&query='
def fetch_movies_data():
url = 'http://www.imdb.com/chart/top?pf_rd_m=A2FGELUUNOQJNL&pf_r... |
# First we'll import the os module
# This will allow us to create file paths across operating systems
import os
# Module for reading CSV files
import csv
# csvpath = os.path.join('Resources', 'Netflix.csv')
mainpath = os.path.join('Resources', 'election_data.csv')
output_path = os.path.join('Resources', 'Polling_Resu... |
#created a list of non-random numbers
names = ['*']
names2 = []
for i in names:
names2 = i + ('*' * 2)
print (names2)
|
from tmcl.dynamics.tmcl import MCLMultiHeadedCaDMDynamicsModel
from tmcl.trainers.mb_trainer import Trainer
from tmcl.policies.mpc_controller import MPCController
from tmcl.samplers.sampler import Sampler
from tmcl.logger import logger
from tmcl.envs.normalized_env import normalize
from tmcl.utils.utils import ClassEnc... |
# Python Cryptography Toolkit (pycrypto)
from Crypto.Cipher import AES
from .utils import grouper, xor
PAD_CHAR = b'\x04'
IV = b'\x00' * AES.block_size
def encrypt_ecb(plaintext, password):
crypter = AES.new(password, AES.MODE_ECB)
return crypter.encrypt(plaintext)
def decrypt_ecb(ciphertext, password):
... |
import json
import os
import logging
import tornado.httpserver
import tornado.websocket
import tornado.ioloop
import tornado.web
import socket
import redis
import threading
class IndexHandler(tornado.web.RequestHandler):
@tornado.web.asynchronous
def get(self):
items = ["Item 1", "Item 2", "Item 3"]... |
import sys, random
print("Welcome to the NFL 'What If Name Picker.'\n")
print("Imagine If the New York Giants were the New York Rams:\n\n")
first = ('New York', 'Arizona', 'Green Bay', "Jacksonville'",
"Charlotte'", 'Buffalo', 'Tampa Bay', "Cincinnati' ",
'Baltimore', 'Phoenix', 'Kansas City', 'Inid... |
# Generated by Django 3.2 on 2021-04-15 19:34
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('Social_Media', '0002_alter_socialmedia_app_img'),
]
operations = [
migrations.AlterField(
model_name='socialmedia',
na... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.