text stringlengths 38 1.54M |
|---|
'''
Created on Dec 21, 2017
@author: Alex
'''
import sqlite3
def main():
createDB()
insertDummyValues()
def createDB():
db = sqlite3.connect("login.sqlite")
cursor = db.cursor()
cursor.execute("DROP TABLE IF EXISTS LoginInfo")
cursor.execute("CREATE TABLE loginInfo(username VARCHAR(20) PRI... |
"""
A script that creates a configmap with all values from `terraform output`.
It skips output values that are marked as "sensitive"
"""
import sys
import tempfile
from ruamel import yaml
from typing import Dict
from argparse import ArgumentParser
import subprocess
import json
def get_terraform_outputs():
prin... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on 2017-02-27 17:32
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('mozartweb', '0008_auto_20170227_1732'),
]
operations = [
migrations.AlterUniqueToget... |
import numpy as np
import string, csv, os
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.feature_extraction.text import CountVectorizer
# from os.path import join
def sentlist(in_fname):
f = open(in_fname, mode='r', encoding = 'utf-8-sig', errors='ignore')
# each sentance
s = []... |
import os
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class book(db.Model):
__tablename__ = "books"
isbn = db.Column(db.String, primary_key = True)
title = db.Column(db.String, nullable = False)
author = db.Column(db.String, nullable = False)
year... |
# -*- coding: utf-8 -*-
# @Author: Denghui Zhao
# @Date: 2021-01-27 14:50:15
# @Last Modified by: Denghui Zhao
# @Last Modified time: 2021-01-27 16:26:07
class Solution:
def isPalindrome(self, s) -> bool:
s = s.lower()
i = 0
j = len(s)-1
while(i < j):
if not s[i].isalnum(): i+=1; c... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-07-16 12:51
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('home', '0001_initial'),
]
operations = [
migrations.AlterModelOptions(
... |
import keras
from preprocessor import load_vocabulary, preprocess, loadQuestionsFromDB
from keras.models import load_model
from google.cloud import bigquery
import json
if __name__ == '__main__':
# # step1, save results into csv file
# # read all questions
# data = loadQuestionsFromDB(-1)
# vocabulary ... |
import logging
from sagas.util.loader import class_from_module_path
logger = logging.getLogger(__name__)
class Startup(object):
def __init__(self):
self.mods=[]
def start(self):
import json
import glob
import os
import sys
from sagas.conf import resource_files... |
import struct
class Sources:
"""Klasa trzymajaca ENUM z typami zrodel.
DRIVER, APPLICATION, SERVER
"""
DRIVER, APPLICATION, SERVER = range(3)
class Communicates:
"""Klasa trzymajca ENUM z typami komunikatow.
SREQ, SACK, SDEN,CHECK, CONFIRM, UPDATE, CLOSE, OBJECT, OTHER, ERR... |
# Generated by Django 2.0.2 on 2018-02-17 20:53
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('course', '0006_auto_20180217_2026'),
]
operation... |
import numpy as np
import cv2
import tkinter as tk
from PIL import ImageTk, Image
from tkinter import PhotoImage
root = tk.Tk()
w = tk.Frame(root,height="400", width="900", bg="black")
w.pack()
w.pack_propagate(0)
foto = ImageTk.PhotoImage(Image.open("dados.jpg"))
pop = ImageTk.PhotoImage(Image.open("popup.jpg"))
lma... |
import mysql.connector
import paho.mqtt.client as mqtt
from datetime import datetime
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="",
database="mqtt-project"
)
def on_connect(client, userdata, flags, rc):
client.subscribe('/data')
topic = "/data"
print("subscribed to: " + topic)... |
import pprint
import re
from collections import defaultdict
from tqdm import trange
pp = pprint.PrettyPrinter(indent=4)
def process_input():
file = 'a.txt'
data = [_.strip() for _ in open(file).readlines()]
return data
def get_input():
data = process_input()
begin = data.pop(0)[-2]
steps =... |
#!/usr/bin/python
# no_minimizebox.py
import wx
app = wx.App()
frame = wx.Frame(None, style=wx.MAXIMIZE_BOX | wx.RESIZE_BORDER
| wx.SYSTEM_MENU | wx.CAPTION | wx.CLOSE_BOX)
frame.Show(True)
app.MainLoop()
|
import numpy as np
import math
class PARAMS:
def __init__(self, totwalkers=10000, initwalkers = 10, init_shift=0.0, shift_damp=0.1, timestep=1.e-3,
det_thresh=0.25, eqm_iters=50, max_iter=100000, stats_cycle=10, seed=7, init_thresh=None):
''' Class to set up fixed parameters for FCIQMC simulatio... |
# Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import errno
import os
import pickle
import threading
import zlib
from libs.cache import Cache
ROOT_DIR = os.path.join(os.path.dirname(__file__), os.path.p... |
# Program: cipres_data_parse
#
# Description: Standalone Python program to parse data files uploaded
# to CIPRES gateway. Currently configued to handle BEAST, BEAST2 and
# Migrate input files, but will be extended to other file formats
#
# Note that all files are opened with universal newlines support
# ('rU') so that... |
import pytest
import yaml
class TestDemo:
@pytest.mark.parametrize("env",yaml.safe_load(open("D:\mylearntest\datas\env.yml")))
def test_demo(self,env):
if "test" in env:
print("这是测试环境")
print(env)
print("测试环境的ip是:",env["test"]) #取字典中的test的value
elif "dev... |
# Generated by Django 3.1.1 on 2020-11-14 12:46
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('habit', '0003_auto_20201114_2145'),
]
operations = [
migrations.AlterField(
model_name='habit',
name='habit_type',
... |
# coding=UTF-8
import numpy as np
import jieba
import re
import os
import _pickle as cPickle
import sys
import importlib
importlib.reload(sys)
import jieba.posseg as pseg
import copy
from py2neo import Graph,Node,Relationship,Path,NodeSelector
import datetime
from neo4j.v1 import GraphDatabase, basic_auth
import gl... |
import requests
from bs4 import BeautifulSoup
from message import message
import util as ut
from webscraping.tag import CTag
DEFAULT_HEADERS = {'User-Agent':'Mozilla/5.0'}
DEFAULT_LINK_ATTR_NAME = "href"
class CWebsite():
def __init__(self, url, home_url, headers=DEFAULT_HEADERS, name="Website"):
if not ... |
import sys
import random
def mergeSort(alist,otherid,creation):
#print("Splitting ",alist)
if len(alist)>1:
mid = len(alist)//2
lefthalf = alist[:mid]
righthalf = alist[mid:]
leftotherid=otherid[:mid]
rightotherid=otherid[mid:]
leftcreation=creation[:mid]
... |
import numpy as np
from scipy.special import erf
otherwise = lambda x: np.full_like(x, True, dtype=bool)
def constant(c):
return lambda x: np.ones_like(x) * c
def smaller_of(val1):
return lambda x: x <= val1
def bigger_of(val1):
return lambda x: x >= val1
def between(val1, val2):
return lambda ... |
import json
from bokeh.client import push_session
from bokeh.driving import repeat
from bokeh.io import curdoc
from bokeh.models import GeoJSONDataSource
from bokeh.plotting import figure
from bokeh.sampledata.sample_geojson import geojson as original
updated = json.dumps({
'type': 'FeatureCollection',
'featu... |
"""
在编写程序的时候,千万不要把实例属性和类属性使用相同的名字,
因为相同名称的实例属性将屏蔽掉类属性,但是当你删除实例属性后,
再使用相同的名称,访问到的将是类属性。
"""
|
"""
给定一个机票的字符串二维数组 [from, to],子数组中的两个成员分别表示飞机出发和降落的机场地点,对该行程进行重新规划排序。
所有这些机票都属于一个从JFK(肯尼迪国际机场)出发的先生,所以该行程必须从 JFK 出发。
说明:
如果存在多种有效的行程,你可以按字符自然排序返回最小的行程组合。例如,行程 ["JFK", "LGA"] 与 ["JFK", "LGB"] 相比就更小,排序更靠前
所有的机场都用三个大写字母表示(机场代码)。
假定所有机票至少存在一种合理的行程。
示例 1:
输入: [["MUC", "LHR"], ["JFK", "MUC"], ["SFO", "SJC"], ["LHR", "SFO"... |
#!/usr/bin/env pypy3
import angr
import logging
import re
from claripy.ast.bool import true
current_log_file = "../log/run_util.log"
angr_log_file = "../log/angr_run_util.log"
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
fh = logging.FileHandler("../log/logging.log", mode='w', encoding="utf-8"... |
# 布尔值为空值的情况 --->> 值都是False
s1 = "" # 空字符串
print(bool(s1))
i = 0 # 数字等于0
print(bool(i))
t = () # 空元组
print(bool(t))
li = [] # 空列表
print(bool(li))
dic = {} # 空字典
print(bool(dic))
# Nono
person = None
print(bool(person)) |
#arr = [64, 34, 25, 12, 22, 11, 90]
def bubble_sort(arr):
for i in range(0,len(arr)):
for n in range(i+1,len(arr)):
if arr[i] > arr[n]:
arr[i],arr[n] = arr[n],arr[i]
print(arr)
return arr
print(bubble_sort([64, 34, 25, 12, 22, 11, 90]))
|
from flask_sqlalchemy import SQLAlchemy
from flask import Flask
import pandas as pd
import logging
import psycopg2
from os import listdir
from sqlalchemy import create_engine
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db_test.sqlite3'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = Fals... |
input_arr = []
number = input()
for i in range(len(number)):
input_arr.append(int(number[i]))
print(input_arr)
|
# -*- coding: UTF-8 -*-
from django.shortcuts import (
render,
get_object_or_404
)
from shop.models import (
Category,
Product
)
from cart.forms import CartAddProductForm
def homepage(request):
categories = Category.objects.all()
return render(
request,
'shop/homepage.html',
... |
from __future__ import print_function
# Standard Library Imports
from typing import List, Iterator, NamedTuple, NoReturn
from functools import partial
from copy import deepcopy
import binascii
import argparse
import pickle
import json
import abc
import re
# Package imports
from kodi_addon_dev.repo import LocalRepo
fr... |
import json
import os
import unittest
import onedrivesdk
import requests_mock
from onedrive_client import get_resource, od_task, od_webhook
from onedrive_client.od_tasks.base import TaskBase
from onedrive_client.od_tasks.start_repo import StartRepositoryTask
from onedrive_client.od_tasks.update_subscriptions import U... |
# -*- coding: utf-8 -*-
"""
Autorun directives with default directories for:
* myproject
* super
* super/subproject
"""
from autorun import RunBlock, RunCommit
from workrun import OBJECTS_INC
class ProjectRun(RunBlock):
default_cwd = '/working/myproject'
default_home = '/working'
class ProjectOut(Project... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
import os
import shutil
from distutils.version import StrictVersion
from pathlib import Path
from typing import Literal
import json
import sys
from appdirs import user_data_dir
from box import Box, BoxError
from pydantic import BaseModel, Field
from reusable... |
import base64
import time
import requests
from eth_account.messages import encode_defunct
from web3 import Web3
from web3.auto import w3
# From https://github.com/AudiusProject/sig/blob/main/python/index.py
def sign(input, private_key):
to_sign_hash = Web3.keccak(text=input).hex()
encoded_to_sign = encode_de... |
from django.urls import path
from . import views
urlpatterns = [
path('',views.products,name="products"),
path('products/<slug:slug>',views.product_detail,name="product-details")
]
|
# 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, software
# distrib... |
#!/usr/bin/env python3
import argparse
import logging
import os
import subprocess
from metallum import album_search
logger = logging.getLogger(__name__)
DEFAULT_CONFIG_FILE_PATH = os.path.expanduser('~/.config/lastfm_wallpaper.ini')
def run(*cmd):
with subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subpr... |
# -*- coding:utf-8 -*-
# @Author: zhu733756
# @Time: 2020/4/13
# @Description:
from datetime import datetime
import json
import os
import sys
import pathlib
import numpy as np
import scrapy
from scrapy.crawler import CrawlerProcess
from scrapy.http import Request, HtmlResponse
from scrapy.spiders import Rule
from .bas... |
实现 int sqrt(int x) 函数。
计算并返回 x 的平方根,其中 x 是非负整数。
由于返回类型是整数,结果只保留整数的部分,小数部分将被舍去。
示例 1:
输入: 4
输出: 2
示例 2:
输入: 8
输出: 2
说明: 8 的平方根是 2.82842...,
由于返回类型是整数,小数部分将被舍去。
class Solution(object):
def my_sqrt(self, x):
# # 第一种解法,二分查找法
# # 为了照顾到0,把左边界设置为0
# left = 0
# # 为了照顾到1,把左边界设置为... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from jieba import cut
from argparse import ArgumentParser
def main():
parser = ArgumentParser()
parser.add_argument("source_file", help = "source file")
parser.add_argument("target_file", help = "target file")
args = parser.parse_args()
source_file =... |
import sys
import random
sys.argv
ran_num=random.randint(1,10)
user_num = int(input("Enter a number between 1 and 10: "))
count=1
if user_num>10 or user_num<1:
int(input("Out of boundaries. Enter a valid number between 1 and 10: "))
count +=1
while ran_num!=user_num:
try:
user_num_new = int(inp... |
from numpy import *
import matplotlib.pyplot as plt
def kernelTrans(X,A,kTup):
m,n=shape(X)
K=mat(zeros((m,1)))
if kTup[0]=='lin':
K=X*A.T
elif kTup[0]=='rbf':
for j in range(m):
deltaRow=X[j,:]-A
K[j]=deltaRow*deltaRow.T
K=exp(K/(-1*kTup[1]**... |
"""
Django settings for restful project.
Generated by 'django-admin startproject' using Django 3.0.3.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""
import os
#... |
#!/usr/bin/env python
from __future__ import division
import sys, os, argparse
import numpy as np, scipy as sp, pandas as pd
from scipy import stats
import matplotlib.pyplot as plt
import mdtraj as md
import MDToolBox as mdt
import MDToolBox.util
from MDToolBox import pygro
parser = argparse.ArgumentParser(descriptio... |
"""
Exercise 1
The code below creates the CelestialBody class as well as the function compared_to_earth.
Transform the compared_to_earth function so that it becomes an instance method of the CelestialBody class.
Expected Output
Printing the compared_to_earth instance method should return 11.208892860782516.
"""
class... |
import sys
sys.path.append('../utils')
sys.path.append('../model')
from skimage import io
import os
import numpy as np
import time
import torch.optim as optim
from torch.autograd import Variable
import torchvision.transforms as transforms
import torch
from tensorboardX import SummaryWriter
from setDataPath import *
... |
def djkstra(indexcity):
while (indexcity != endcity):
for i in range(number_citys):
if (distance_of_two_roads[indexcity][i] != 999999 and visit[i] == 0):
if (mindis[i] > mindis[indexcity] + distance_of_two_roads[indexcity][i]):
mindis[i] = mindis[indexcity] + ... |
from typing import List
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
step = [[0,1], [1,0], [0,-1], [-1,0]]
res = []
curr = [0,0]
vlim = [0, len(matrix)]
hlim = [0, len(matrix[0])]
step_count = 0
while vlim[0] < vlim[1] and hlim... |
class csstudent():
stream = "cse"
def __init__(self,rollno):
self.rollno = rollno
def setaddr(self,addr):
self.addr = addr
def getaddr(self):
return self.addr
a = csstudent(101)
b = csstudent(102)
a.setaddr("delhi")
b.setaddr("noida")
print(a.stream)
print(a.roll... |
import pandas as pd
import csv
import plotly.express as px
import statistics
df = pd.read_csv('marks.csv')
studentPerf = df.groupby(["student_id","level"],as_index=False)["attempt"].mean()
fig = px.scatter(studentPerf, x="student_id",y="level",size="attempt",color ="attempt")
fig.show()
print(studentPerf) |
import numpy as np
import matplotlib.pyplot as plt
import random
plt.figure(10)
plt.ion()
state=np.array([[1.0,1.0]])
up=np.array([0.0,1.0])
down=np.array([0.0,-1.0])
left=np.array([-1.0,0.0])
right=np.array([1.0,0.0])
actions=np.array([up,left,right,down])
goal=np.array([[1.0, 10.0]])
xBar = np.append([np.linspac... |
import sys
import aiohttp
from exceptions import InvalidCustomConf
import re
from mattermost.notify import NOTIFICATION_ERROR
from monitors.utils import monitor_register
from monitors.monitor import Monitor
from bs4 import BeautifulSoup
from aioresponses import aioresponses
@monitor_register(name="fnac")
class FnacM... |
import numpy as np
# 21. Create a checkerboard 8x8 matrix using the tile function (★☆☆)
Z = np.array([[1,0],[0,1]])
print(np.tile(Z, (4,4))) |
from econtext.util.falcon.route import Route
from jose import jwt
import datetime
import json
from econtext.util.log import log
from ...util import compare_passwords, hash_secret
class Authenticate(Route):
"""
Authenticate
Authenticate against the Auth user store
"""
def on_post(self, r... |
from django.forms import widgets
from rest_framework import serializers
from webms.models import Webm
from webms.models import Tag
class TagSerializer(serializers.ModelSerializer):
class Meta:
model = Tag
def to_representation(self, value):
return value.name
class WebmSerializer(serializers.ModelSerialize... |
# 3. 算出100~999之间的水仙花数(Narcissistic Number)
# 水仙花数是指百位的3次方 + 十位的3次方 + 个位的3次方等于原数的整数
# 例如:
# 153 = 1**3 + 5**3 + 3 ** 3
# 答案:
# 153 370 ...
# # 方法1
# for x in range(100, 1000):
# bai = x // 100 # 百位
# shi = x % 100 // 10 # 十位
# ge = x % 10
# if x == bai ** 3 + shi ** 3 + ge ** 3:
# ... |
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def index(request):
return HttpResponse("<h1>Finally did it! :P</h1>"); |
'''
PICK'S THEOREM!!!!!!!!
'''
from helpers import gcd, memoize
gcd = memoize(gcd)
def number_of_lattice_points(a, b, c, d):
twice_area = (b + d) * (a + c)
num_boundary = gcd(a, b) + gcd(b, c) + gcd(c, d) + gcd(d, a)
interior_lattice_points = (twice_area - num_boundary) / 2 + 1
return interior_lattice_poin... |
#Function to withraw money from the individual's bank
#and then deposit in the central Onu Bank
#will then subtract from the Onu bank
#Also keeps track how much
import requests
import json
import random
import datetime
from getBalance import getBalance
from getMembers import getMembers
names = {"tester1":"5927271dc... |
#!/usr/bin/env python3
def not_using_tuple_unpacking():
mytuple = 1, 2
x = mytuple[0]
y = mytuple[1]
print(f"x equals {x} and y equals {y}.")
def using_tuple_unpacking():
mytuple = 3, 4
x, y = mytuple
print(f"x equals {x} and y equals {y}.")
def main():
not_using_tuple_unpacking()
... |
import sys
import random
import time
import optparse
import csv
import urllib.request as urequest
from urllib.error import HTTPError
import openpyxl
class NationalAustralianBank:
def __init__(self, infile, atmsfile, brcfile):
self.postcodes_file = infile
self.URL = "https://api.nab.com.au/info/nab... |
#te : 2014-11-05 17:34:57
# @Author : yml_bright@163.com
import base64
from sqlalchemy.orm.exc import NoResultFound
from config import *
from tornado.httpclient import HTTPRequest, AsyncHTTPClient
from BeautifulSoup import BeautifulSoup
import tornado.web
import tornado.gen
import urllib
import json, re
from ..mod... |
# -*- coding: utf-8 -*-
"""
Package Open Source functionality of Moler.
"""
__author__ = 'Grzegorz Latuszek, Marcin Usielski, Michal Ernst'
__copyright__ = 'Copyright (C) 2018, Nokia'
__email__ = 'grzegorz.latuszek@nokia.com, marcin.usielski@nokia.com, michal.ernst@nokia.com'
from moler.config import devices as device... |
import argparse
import os
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
import torchvision.datasets as datasets
import tensorflow as tf
from utils import preprocess_for_eval
from pnasnet import build_pnasnet_large, pnasnet_large_arg_scope
slim = tf.contrib.slim
parser = argparse.ArgumentParser()
parser.add_argument('--va... |
## Construct model
## Label: rate_spread
##
import pandas as pd
from sklearn import preprocessing
import sklearn.model_selection as ms
from sklearn import linear_model
import sklearn.metrics as sklm
import numpy as np
import numpy.random as nr
import matplotlib.pyplot as plt
import seaborn as sns
import scipy.stats as... |
# Copyright 2021 Hathor Labs
#
# 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, s... |
# Generated by Django 3.2.9 on 2021-11-16 05:20
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('typescards', '0002_alter_typecards_category'),
]
operations = [
migrations.AlterField(
model_name='typecards',
name=... |
#!/usr/bin/python
"""
linuxrouter.py: Example network with Linux IP router
This example converts a Node into a router using IP forwarding
already built into Linux.
The topology contains a router with IP subnets:
- 192.168.1.0/24 (interface IP: 192.168.1.1)
- 10.0.0.0/8 (interface IP: 10.0.0.1)
It also contains h... |
# Piotr Bogun
# Merge Sort
# mergeSort('10_Random.txt') <-- Copy/Pase call
numOps = 0
numComp = 0
def mergeSort(file):
# Reset globals for each run
global numOps
global numComp
numOps = 0
numComp = 0
# Opens file and outputs into int(list(nums))
nums = []
infile = open(file, 'r')... |
import os
import numpy
import pandas as pd
import ml_utils
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
def reorder_select_cols(orderdic, matchdic, datacols, tkey):
# define input layer for each subscale
# get input names from dic
key = [key for key in list(orderdic.k... |
import numpy as np
import mne
import pickle
from pathlib import Path
# sample_data_raw_file=('imagery)
data=mne.io.read_raw_persyst('./imageryruns/imageryS001R03.dat')
# with open('./imageryruns/imageryS001R03.dat', 'rb',0) as f:
# y = pickle.load(f, encoding='latin1')
# path = Path('./imageryruns/imageryS001R03... |
from lab04 import *
# Q12
def flatten(lst):
"""Returns a flattened version of lst.
>>> flatten([1, 2, 3]) # normal list
[1, 2, 3]
>>> x = [1, [2, 3], 4] # deep list
>>> flatten(x)
[1, 2, 3, 4]
>>> x = [[1, [1, 1]], 1, [1, 1]] # deep list
>>> flatten(x)
[1, 1, 1, 1, 1, 1]
... |
import random
class MaxSizeList(object):
def __init__(self, max_length):
self.max_length = max_length
self.ls = []
def push(self, st):
if len(self.ls) == self.max_length:
self.ls.pop(0)
self.ls.append(st)
def get_list(self):
return self.ls
def get... |
# Copyright (c) 2013 Paul Tagliamonte <paultag@debian.org>
#
# 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, modif... |
# -*- coding: utf-8 -*-
import datetime
import pytz
import collections
import itertools as it
from healthtracker.app import create_app
from healthtracker.database import User, ScheduledQuestion, Answer
from healthtracker.extensions import db
import healthtracker.mailer as mailer
def to_utc(timestamp):
return da... |
import maya.cmds as cmds
import maya.mel as mel
import glTools.utils.mesh
import glTools.utils.stringUtils
def meshToNurbs(mesh, rebuild=False, spansU=0, spansV=0, prefix=''):
"""
@param mesh:
@param rebuild:
@param spansU:
@param spansV:
@param prefix:
"""
# Check prefix
if not pr... |
def timeConversion(s):
hour = s[:2]
isNoon = s[len(s) - 2:] == 'PM'
if isNoon and hour != '12':
hour = str(int(hour) + 12)
elif not isNoon and hour == '12':
hour = '00'
return hour+s[2:len(s)-2]
print(timeConversion('12:05:45PM'))
print(timeConversion('02:05:45PM'))
print(timeConv... |
# imports
import os
import csv
import cv2
import numpy as np
import matplotlib.pyplot as plt
import sklearn
from sklearn.model_selection import train_test_split
from keras.models import Sequential
from keras.layers import Flatten, Dense, Cropping2D, Conv2D, Lambda
# extract csv data
print("Loading data...")
lines = []... |
import numpy as np
# 28. What are the result of the following expressions?
print(np.array(0))
print(np.array(0) / np.array(0))
# NaN
print(np.array(0) // np.array(0))
# 0
print(np.array([np.nan]).astype(int).astype(float))
|
from gird_state import gird_info
import copy
class IDS:
goal0 = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
goal1 = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,0]
sol_flag = False
depth = 9999999
goalState = []
girdToSolve = []
gird_flag = True
updateGird = []
previous = {}
def __init__(self,gird):
self.girdToSolv... |
from util import *
import csv
if SS_FILE_TYPE == EXCEL_FORMAT:
from openpyxl import Workbook
class SSWriter:
def __init__(self, filename, type, log):
self.type = type
self.log = log
self.filename = filename
if self.type == CSV_FORMAT:
try:
self.file =... |
import os
import random
import discord
import datetime
from datetime import timedelta
from dotenv import load_dotenv
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
client = discord.Client()
@client.event
async def on_ready():
print(f'{client.user.name} has connected to Discord!')
@client.event
async de... |
'''
Created on Aug 11, 2014
@author: noob
'''
from django.http import HttpResponseNotAllowed, HttpResponseRedirect, HttpResponse
from django.shortcuts import render_to_response
from django.template import RequestContext
from models import Country
import json
import logging
def home(request):
loggin... |
class Solution:
def sortArray(self, nums):
"""
:type nums:List[int]
:rtype: List[int]
"""
if len(nums) <= 1:
return nums
mid_point = int(len(nums) / 2)
left, right = self.sortArray(
nums[:mid_point]), self.sortArray(nums[mid_point:])
... |
from mrbuilder.layer_registry import register_layer_wrapper
registered_layers = {}
def register_layer(name: str, *aliases):
return register_layer_wrapper(registered_layers, name, *aliases)
|
#!/usr/bin/env python3
import cv2
import numpy
import json
import math
from genericfinder import GenericFinder, main
import hough_fit
class HopperFinder2020(GenericFinder):
'''Find hopper target for Infinite Recharge 2020'''
# real world dimensions of the hopper target
TARGET_WIDTH = 7.0 # inches... |
# -*- coding: utf-8 -*-
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.loader import ItemLoader
import string
from network54.items import ThreadItem, PostItem
from bs4 import BeautifulSoup, Comment, NavigableString
import json
def clean_text(text):
if text is None:
return ""
text = text.... |
from tools.mt19937 import mt19937_32
from tools.rngattacks import mtClone
from random import randint
num_test_vals = 1000
seed = randint(0, 2**32)
twister = mt19937_32(seed)
clone = mtClone(twister)
print("Testing that the first %d outputs of cloned RNG match those of the original..." % num_test_vals)
for k in range(... |
from app import dynamoDB, cache
from app.genius.client import get_artist_songs, get_artist_data
def get_songs_by_artist_id(artist_id: int, caching=True) -> dict:
if caching is True:
cache_data = cache.get(str(artist_id))
else:
cache_data = None
if not cache_data:
artist_data = get... |
#!/usr/bin/env python
import sys
import re
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
from selenium.webd... |
from .curation_tools import find_duplicated_spikes
from .remove_redundant import remove_redundant_units, find_redundant_units
from .remove_duplicated_spikes import remove_duplicated_spikes
from .remove_excess_spikes import remove_excess_spikes
from .auto_merge import get_potential_auto_merge
# manual sorting,
from .... |
from tools.data import DataImport
import ast
import json
import logging
import sys
_logger = logging.getLogger(__name__)
channel_ket_list = ['robot_id', 'run_out_before_look', 'backup_channel_id', 'only_meme_speak_channel']
channel_data_path = 'addons/team_fight/data/channel.json'
channel_file = DataImport(channel_dat... |
##=======================================================
## Nicholas Richardson (20660084)
## CS 116 Winter 2017
## Assignment 09 Question 1
##=======================================================
## find_winner(filename) Takes a filename and returns the
## total score of the winning team in the file
## fi... |
# +
"""
This module tests that we can use a unique key instead of a primary key for upserting.
Thanks to LawrentChen on GitHub for pointing out this is possible and providing me
with an example.
See https://github.com/ThibTrip/pangres/issues/12
"""
import pandas as pd
from sqlalchemy import INTEGER, VARCHAR, Column, U... |
import boto3
import json
# AWS credentials
AWS_SECRET_ACCESS_KEY = 'BJCYwL5zAEIt3hPGZnfkt3RBU1SAYgjQRlKqGzfX'
AWS_ACCESS_KEY_ID = 'AKIAIUXWPXCNXXZQKZQA'
AWS_REGION_NAME = 'us-east-1'
AWS_STREAM_NAME = 'DIC_MRT'
TOTAL_SHARDS = 0
kinesis = boto3.client('kinesis', region_name=AWS_REGION_NAME, \
... |
import argparse
import numpy as np
import os
import torch
from torch import nn
from torch.autograd import Variable
from torch.backends import cudnn
from torch.utils import data
from utils.plan_class import plan_dataset
from utils.pnet import PNet
def main(args):
cudnn.benchmark = True
# Parameters
train... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.