text stringlengths 38 1.54M |
|---|
#%% [markdown]
# ### padding层就是给输入数据的边界做一定数量的扩充,以进行卷积和池化
# 有以下分类:
# - 镜像 padding
# - 复制 padding
# - 0 padding
# - 常数 padding
#%%
import numpy as np
import torch
import torch.nn as nn
import matplotlib.pyplot as plt
get_ipython().run_line_magic('matplotlib', 'inline')
#%%
#>一 镜像 padding
##>1.1 一维镜像padding
m1=nn.Refle... |
from direct.showbase.ShowBase import ShowBase
from gravbot.mainmenu import MainMenu
class App(ShowBase):
def __init__(self):
ShowBase.__init__(self)
self.screens = []
self.screens.append(MainMenu(self))
def run(self):
# start first screen
self.screens[-1].ente... |
import os
def get_filename_ext(filepath):
base_name = os.path.basename(filepath)
name, ext = os.path.splitext(base_name)
return name, ext
|
from flask import Flask
from flask_mysqldb import MySQL
from dotenv import load_dotenv
from flask_restful import Api
from controller.TripCategory import Trip_Category
app = Flask(__name__)
api = Api(app)
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = 'P@ssw0rd'... |
# importing libraries
from PyQt5.QtWidgets import *
from PyQt5 import QtCore, QtGui
from PyQt5.QtGui import *
from PyQt5.QtCore import *
import sys
from PyQt5 import QtWidgets,uic
from jayui_main import Ui_MainWindow
from astar import whole_astar
from binary import whole_binarysearch
from insertion import insertionsor... |
from time import sleep
from tamcolors.utils.path import abspath
from tamcolors.tam_basic.sound import Sound
def run():
with Sound(abspath("typing.wav")) as s:
s.play()
s2 = Sound(abspath("tally.wav"))
s2.play()
sleep(5)
s.play()
s2.play()
sleep(5)
s2... |
# -*- coding: utf-8 -*-
"""
@Time : 2018/9/18 16:26
@Author : Young
@QQ : 403353323
@File : auth_decorator.py
@Software: PyCharm
"""
import functools
from app.util.util import Util, Code
from app.models import User
from flask import g
def auth_decorator(request):
def decorator(func):
@functoo... |
import numpy as np
import cv2
import os
def rover_print(s):
print("ROVER: {}".format(s))
def mask(dists, dist_min, dist_max, angles, angle_min, angle_max):
normalized_angles = angles * 180/np.pi
return (normalized_angles > angle_min) & \
(normalized_angles < angle_max) & \
(dists >... |
# Generated by Django 2.1.7 on 2019-08-27 03:06
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('project', '0005_auto_20190827_1002'),
]
operations = [
migrations.AlterField(
model_name='task',
name='ID_task',
... |
#!/usr/bin/env python
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you ma... |
""" minimal SQL parser
By: Kevin Lundeen
For: CPSC 4300/5300, S17
Based on http://pyparsing.wikispaces.com/file/view/simpleSQL.py: Copyright (c) 2003,2016, Paul McGuire
Using grammar non-terminal names from sql2003 where possible.
"""
from pyparsing import CaselessLiteral, Dict, Word, delimitedList, Optional, \
... |
from datetime import datetime
from click.testing import CliRunner
from vigorish.cli.vig import cli
from vigorish.util.dt_format_strings import DATE_ONLY_2
def test_status_single_date_without_games_without_missing_pfx():
game_date = datetime(2019, 6, 17).strftime(DATE_ONLY_2)
runner = CliRunner()
result ... |
from django.urls import path
from correction_app import views
app_name = 'correction_app'
urlpatterns = [
path('', views.users, name='users'),
path('services-page/', views.services, name='services'),
path('post-detail/', views.post_detail, name='post_detail'),
path('contact-page/', views.contact, na... |
#Felix Bittmann, 2020
def primegenerator(n=2):
"""Creates consecutive prime numbers larger or equal to n"""
if n <= 2:
yield 2
n = 3
if n % 2 == 0:
n += 1
while True:
for divisor in range(3, int(n ** 0.5 + 1), 2):
if n % divisor == 0:
break
else: #break never reached
yield n
n += 2
... |
# import_export_batches/urls.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
from django.conf.urls import re_path
from . import views_admin, views_representatives
urlpatterns = [
re_path(r'^$', views_admin.batches_home_view, name='batches_home',),
re_path(r'^batch_action_list/$', views_admi... |
from user_ops_server import UserService
if __name__ == '__main__':
user_service = UserService()
user_service.serve()
|
# -*- coding: utf-8 -*-
from django import forms
from django.forms import inlineformset_factory
from django.utils.translation import ugettext_lazy as _
from djangosige.apps.cadastro.models import Pessoa, Endereco, Telefone, Email, Site, Banco, Documento
class EnderecoForm(forms.ModelForm):
class Meta:
... |
from django.contrib import admin
# Register your models here.
from .models import Application,ServerConfig,ndmDetails,Countries
#admin.site.register(Application)
admin.site.register(ServerConfig)
admin.site.register(ndmDetails)
admin.site.register(Countries)
class AppAdmin(admin.ModelAdmin):
list_display=('App... |
#!/usr/bin/env python
# encoding: utf-8
"""
__init__.py
Created by Kurtiss Hare on 2010-03-12.
"""
from version import VERSION
from base import Monque
from worker import MonqueWorker
from job import MonqueJob, job
__version__ = VERSION |
import torch
import torch.nn as nn
from graphgallery.nn.init.pytorch import uniform, zeros
from ..get_activation import get_activation
# TODO: change dtypes of trainable weights based on `floax`
class GraphConvolution(nn.Module):
def __init__(self,
in_channels,
out_channels,
... |
import cv2 as cv
import os
path = 'imq'
images = []
classes = []
imglist = os.listdir(path)
orb = cv.ORB_create()
for cls in imglist:
curimg = cv.imread(f'{path}/{cls}',0) # path is the image path and cl is img name
images.append(curimg)
classes.append(os.path.splitext(cls)[0]) # cl is image name ,cl [... |
import xlwings as xw
from Calibration.TermStructure import *
import pandas as pd
import numpy as np
@xw.func
@xw.arg('x', doc='swap years.')
@xw.arg('y', doc='swap rates in pencentage points.')
@xw.ret(index = False, header=False)
def Bootstrap_TS(x, y):
"""Returns the annual zero rates"""
ycrv_swap = ycrv_co... |
from rest_framework import serializers
from portfolio.app.common.serializers import PortfolioSerializer
from .models import Company
class CompanySerializer(PortfolioSerializer):
id = serializers.ReadOnlyField()
name = serializers.CharField()
city = serializers.CharField()
state = serializers.CharFiel... |
#!/usr/bin/env python
import CombineHarvester.CombineTools.ch as ch
import argparse
import os
parser = argparse.ArgumentParser()
parser.add_argument('--output', '-o', dest = 'output', required = True, help = 'Output directory')
parser.add_argument('--input', '-i', dest = 'input', required = True, hel... |
from django.shortcuts import render, redirect
from stocks.views import search_view
# Create your views here.
def home_view(request, *args, **kwargs):
if not request.user.is_authenticated:
return redirect('accounts/login', {})
return render(request, 'home.html', {}) |
people = 20
cars = 15
buses = 10
if cars < people:
print " people are more"
elif cars > people:
print " car are more"
if buses != cars:
print "car are more "
elif cars != buses:
print " equal"
if buses < people:
print " perfect fit"
elif buses > people:
print "not perfect "
buses = 10+5
i... |
from typing import *
from pydgraph import DgraphClient
from grapl_analyzerlib.nodes.comparators import (
Cmp,
IntCmp,
_int_cmps,
StrCmp,
_str_cmps,
PropertyFilter,
)
from grapl_analyzerlib.nodes.queryable import Queryable, NQ
from grapl_analyzerlib.nodes.types import PropertyT, Property
from g... |
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import pickle
dataset = pd.read_csv('student-data.csv')
X = dataset.iloc[:, :7]
#Converting words to integer values
def convert_to_int(word):
word_dict = {'female':1, 'male':0}
return word_di... |
import four
import unittest
class TestStringMethods(unittest.TestCase):
def setUp(self):
self.testcases = [
(['a','b','a','c','_'], 4, ['d', 'd', 'd', 'd', 'c']),
]
def execute_test(self, name, impl):
for arr_orig, size, arr_replace in self.testcases:
... |
import tkinter as tk
window = tk.Tk()
window.title('My Scale')
window.geometry('300x300')
l = tk.Label(window, bg = 'blue', width = 20, text = 'empty')
l.pack()
# 这里参数v是用来记录滚动条定位的数据(滑动到哪里了)
def job(v):
l.config(text = 'you have choosen ' + v)
# 参数解释:
# from_ = 1, to = 20:从1到20的意思,就是滚动条的起始刻度到终止刻度
# orient = tk.H... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def hasPathSum(self, root: TreeNode, sum: int) -> bool:
def dfs(node, value):
if node == None: return False
... |
#-*- coding:utf-8 -*-
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
np.random.seed(111)
'''
基础模型
data :输入训练数据
Dt :第t个基础模型对应的训练样本的权重
model :找到一个阈值,以该阈值为分类边界进行分类
'''
def base_model(data,Dt):
m = data.shape[0]
pred = []
pos = None
mark = None
min_err = np.inf
for ... |
#!/usr/bin/env python3
import re
import os
import sys
import json
import argparse
import statistics
from utils.colors import print_green, print_red, print_yellow
from os import listdir
from pathlib import Path
from os.path import isfile, join
from ccc.ccc import get_cc_from_callgrind_file
from utils.utils import conver... |
import config
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
def load_data():
"""
读取数据,按天重采样
"""
data = pd.read_csv(config.data_file)
data['date'] = pd.to_datetime(data['Timestamp'], unit = 's')
data.set_index('date', inplace = True)
data.sort_index(inplace = True)
da... |
truckNumber = '9999' # what is the truck this is on
urlServer = 'https://' # Server address to hit to process GPS data
UDP_IP = "0.0.0.0"
UDP_PORT = 65535 |
# -*- coding: utf-8 -*-
import os.path
DIR = '/media/zzh/HDD1/clueweb09_html'
def main():
file_count = sum(len(files) for _, _, files in os.walk(DIR))
print(file_count)
if __name__ == '__main__':
main()
|
#!/bin/env python3
import matplotlib as mpl
mpl.use('TkAgg')
import matplotlib.cm as cm
import matplotlib.pyplot as plt
from matplotlib.path import Path
from matplotlib.patches import PathPatch
import numpy as np
def clip_path():
delta = 0.025
x = y = np.arange(-3, 3, delta)
xx, yy = np.meshgrid(x, y)
... |
import threading
import socket
def newclient(client,addr):
s=threading.Thread(target=send1,args=(client,))
r=threading.Thread(target=receve,args=(client,))
s.start()
r.start()
s.join()
r.join()
client.close()
def send1(client):
while 1:
dat = input("我:")
client.send(dat.... |
# python3
from collections import deque
import glob
class Edge:
def __init__(self, u, v, capacity):
self.u = u
self.v = v
self.capacity = capacity
self.flow = 0
# This class implements a bit unusual scheme for storing edges of the graph,
# in order to retrieve the backward edge fo... |
# -*-coding:utf-8 -*-
"""
pytest运行时可以使用@pytest.mark.market装饰器来运行被标识的测试用例
使用命令行运行 pytest -m slow test_remarks_demo.py
如果要运行多个标识的话,可以使用以下表达式,如下:
pytest -m "slow or faster"
pytest -m "slow and faster"
pytest -m "slow and not faster"
"""
import pytest
class TestClass(object):
@p... |
# Import from itools
from itools.workflow import Workflow, WorkflowAware
# Workflow definition
workflow = Workflow()
# Specify the workflow states
workflow.add_state('private', title=u'Private')
workflow.add_state('pending', title=u'Pending')
workflow.add_state('public', title=u'Public')
# Specify the workflow trans... |
def sum_numbers(num1, num2):
return num1 + num2
def sub_numbers(num1, num2):
return num1 - num2
def multi_numbers(num1, num2):
return num1 * num2
def div_numbers(num1, num2):
try:
return num1 / num2
except ZeroDivisionError:
return "ERROR: No es pot dividir entre 0"
|
import pygame
from game_object import GameObject
from vector import Vector2
from constants import *
class Paddle(GameObject):
width = 100
height = 20
max_speed = 200
@staticmethod
def clamp_speed(vx):
return max(-Paddle.max_speed, min(Paddle.max_speed, vx))
def __init__(self, camer... |
import requests
import time
import threading
from queue import Queue
import random
import pandas as pd
from scrapy import Selector
import pymysql
import telnetlib # 测试方法2
# https://www.xicidaili.com/nn/ 西刺代理
# http://tool.chinaz.com/port/ 网站验证ip有效性
"""
从列表中随机获取请求头的方法
https://www.toolnb.com/tools/createuseragent.html 通... |
#@+leo-ver=5-thin
#@+node:ekr.20170217164004.1: * @file ../plugins/tables.py
"""
A plugin that inserts tables, inspired by org mode tables:
Written by Edward K. Ream, February 17, 2017.
"""
from leo.core import leoGlobals as g
#@+others
#@+node:ekr.20170217164709.1: ** top level
#@+node:ekr.20170217164759.1: *3* tabl... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'design.ui'
#
# Created by: PyQt5 UI code generator 5.13.0
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
... |
score = 0
program = True
while program:
print
question1 = raw_input("Who is the current president of the USA?\n "
"A: Marilyn Manson\nB: Donald Trump\nC: Hillary Clinton")
if question1 == "B" or "b":
score += 1
question2 = raw_input("The Earth is flat, (t)rue ... |
'''
Class 2 of package package2
'''
from myapp.package2.class1 import Class1
class Class2(Class1):
def __init__(self):
'''
init funtion of Class 2
'''
pass |
__author__ = 'Dario Hermida'
import main as calculate
import numpy as np
import matplotlib as plot
def testing_main(min_salary, max_salary, step):
regular_salary = []
ruling_salary = []
salary = list(range(min_salary, max_salary, step))
for input_bruto in salary:
regular_salary.append(calculate... |
from django.contrib import admin
from .models import Contact,Image
# Register your models here.
admin.site.register(Contact)
admin.site.register(Image) |
import time
import asyncio
from python3_anticaptcha import get_sync_result, get_async_result
class CustomResultHandler:
def __init__(self, anticaptcha_key: str, sleep_time: int = 5, **kwargs):
"""
The module is responsible for obtaining a captcha solution by task ID
:param anticaptcha_key... |
""" Script for cycling through reactions and testing Yuri's z-matrix code on
them
"""
import automol
import automol.sym_num
from autofile import fs
TMP_PFX = './TMP/'
COUNT2 = 0
COUNT3 = 0
MISSED2 = []
MISSED3 = []
for spc_locs, in fs.iterate_locators(TMP_PFX, ['SPECIES']):
ich, _, _ = spc_locs
geo = autom... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib.auth.models import User, AbstractUser
from django.db import models
# Create your models here.
class Appuser(models.Model):
uid = models.AutoField(
auto_created = True,
primary_key = True,
blank = True,
... |
import arcpy
# Data to be described
dElement = r"D:\EsriTraining_Past\SADistance\Otay.gdb"
# Print Element with number, key, value
descDict = arcpy.da.Describe(dElement)
for i, key in enumerate(descDict):
print(f"{i+1},{key},{descDict[key]}")
print("script finished") |
import django
django.setup()
from parsing_utilities.XML_to_JaggedArray import XML_to_JaggedArray
from sefaria.helper.schema import *
from sources.functions import *
from lxml import etree
import bleach
def preparser(root):
chs = [x for x in root if x.tag != "p"]
curr_book = etree.SubElement(root, "book")
c... |
import argparse
import xlwt
import os
import re
import shutil
def writeInSheet(sheet, n, data):
for i in range(len(data)):
sheet.write(n, i, data[i])
def main():
# parse inout arguments
parser = argparse.ArgumentParser(description='Test the job scheduler with all benchmark files.')
parser.add_... |
count = 1
for a in range(1,101):
include = str(a).find("7")
if a%7 != 0 and a%10 != 7 and a//10 != 7:#include == -1:
print(a,end=" ")
else:
print(end=" ")
if count == 6:
print("\n")
count =0
count +=1
|
def uniquePaths(r, c):
if(r==0 or c==0):
return
matrix = [[1]*c for i in range(r)]
for i in range(1,r):
for j in range(1,c):
matrix[i][j] = matrix[i-1][j] + matrix[i][j-1]
return matrix[r-1][c-1]
print(uniquePaths(6,8)) |
# def replaceSpace(str):
# newStr = ""
# for i in range(len(str)):
# if str[i] == " ":
# newStr += "%20"
# else:
# newStr += str[i]
# return newStr
# OR
def replaceSpace(str):
replacedStr = str.replace(" ", "%20")
return replacedStr
print(repl... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]:
if len(preorder)... |
from math import sqrt
def pandigital(n):
for i in range(1, len(str(n))+1):
if str(i) not in str(n):
return False
return True
def prime(n):
if n == 1:
return False
for i in range(2, int(sqrt(n))+1):
if n % i == 0:
return False
return True
n = 9999999
w... |
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium import webdriver
import math
browser = webdriver.Chrome()
browser.get("http://suninjuly.github.io/explicit_wait2.html")
text = WebDriverWa... |
import redis
r = redis.Redis()
r.flushall()
with open("female-names.txt", "r") as f:
for word in f:
letter = word[0]
if r.exists(letter):
r.incr(letter)
else:
r.set(letter, 1)
for key in r.keys():
print(str(key)+ ">>" + str(r.get(key))) |
from django.db import models
from django.utils import timezone
class Institution(models.Model):
name = models.CharField(max_length=200)
create_time = models.DateTimeField(default=timezone.now)
class InstitutionAdmin(models.Model):
institution = models.ForeignKey(Institution)
user = models.EmailField... |
"""Unit tests for the Event Dispatcher."""
import unittest
from tentacle.dispatcher import EventDispatcher
from kombu import Connection
class TestEventDispatcher(unittest.TestCase):
"""Tests for the EventDispatcher object."""
def setUp(self):
"""Initialize common objects."""
self.evdisp = Ev... |
# TODO: Create an empty dictionary, called inventory
inventory = {}
# TODO: Ask the user how many items they have in their inventory
item_count = int(input("How many items do you have in your inventory? "))
# TODO: Use `range` and `for` to loop over each number up to the inventory number
# TODO: Inside the loop, prom... |
from django.conf.urls import url
import views
app_name = 'cfam'
urlpatterns = [
url(r'^$',views.index,name='index'),
url(r'^molecules/?$',views.mols,name='mols'),
url(r'^molecules/(?P<mol_id>[^/]+)/?$',views.mol,name='mol'),
url(r'^families/?$',views.fams,name='fams'),
url(r'^families/(?P<fam_id>[... |
from django.contrib.auth.models import User
from django.db import models
from bs4 import BeautifulSoup
# Create your models here.
from django.template.defaultfilters import safe
from django.utils.html import strip_tags
from tktv.main.models import SubMenu, encode_con
class Board(models.Model):
submenu = models... |
from typing import List
from pymunk import Vec2d
from ..objects.physical import PhysicsInterface
from ..objects.base import EngineObject
from ..objects.body import Body
from ..objects.constraints import Constraint
from ..objects.container import ObjectContainer
class AgentBase(ObjectContainer):
def __init__(se... |
from .serializers import user_details_serializer, cart_products_serializer, order_serializer, LoginSerializer
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import details, deleted_accounts, cart, orders, login_log
from product.models import details as product_details... |
# 变态跳台阶
class Solution:
def jumpFloorII(self, number):
# write code here
if number == 1 or number == 2:
return number
ret = sum_ = 3
for i in range(number - 2):
ret = sum_ + 1
sum_ += ret
return ret
|
#!/usr/bin/python
# Import modules for CGI handling
import cgi, cgitb
import mysql.connector
from mysql.connector import errorcode
from mysql.connector.errors import Error
# Create instance of FieldStorage
form = cgi.FieldStorage()
# Get data from fields - drop down menu so type will always be valid
user_type = form... |
from django.test import TestCase
from django.urls import reverse
from webapp.models import Product, Category
from userapp.models import CustomUser
class AjaxSavedProductsPageTestCase(TestCase):
def test_ajax_saved_products_page_filters_nutriscore(self):
user = CustomUser.objects.create(
userna... |
my_list = [i ** 2 for i in range(1, 11)]
Generates a list of squares of the numbers 1 - 10
f = open("output.txt", "w")
for item in my_list:
f.write(str(item) + "\n")
f.close()
myfile = open("output.txt", "r+")
my_list = [i ** 2 for i in range(1, 11)]
my_file = open("output.txt", "w")
for value in my_list:
... |
def mostralinha():
print('-'*30)
mostralinha()
print('Sistema de Alunos')
mostralinha()
mostralinha()
print('Cadastro de Funcionários')
mostralinha()
mostralinha()
print('Erro de Sistema')
mostralinha()
mostralinha()
def soma(a, b):
s = a + b
print("A soma dos valores são: {}".format(s))
soma(40, 5)
mo... |
from sklearn import linear_model
import face_recognition
import cv2
import numpy as np
import os
import sys
import time
import datetime
import re
class FaceMatchingInWild(object):
def __init__(self, video_path, city_name, location_name = " "):
self.__video_path = video_path
self.__video_name = os.path.split... |
# -*- coding: utf-8 -*-
from flask import Flask, render_template,request
from popularity_checker import get_most_popular, check_popularity
import numpy as np
app = Flask(__name__)
@app.route('/',methods = ['GET'])
@app.route('/popularity', methods=['GET', 'POST'])
def popularity():
if request.method == 'POST':
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Evaluate baseline models train with a singly-connected layer inserted at certain position.
python evaluate_att_baseline_models --position 06
@author: yixiaowan
"""
import os
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
impo... |
# 单例模式方式
# 1、使用模块,将单例模式的类定义在一个模块中,初次导入模块时创建该类实例,再次导入时不再创建
# 2、使用__new__
# 3、使用装饰器
# 原理:
# common1 = Common('fwzhang')
# @singleton相当于Common = singleton(Common),在创建实例对象时会先将Common作为参数传入到singleton函数中,
# 函数在执行过程中不会执行_singleton函数(函数只有调用才会执行),直接返回_singleton函数名。
# 此时可以看作Common = _singleton,创建实例时相当于... |
"""
Public interface to the data
Contains accessor functions for getting probabilities of trips from workplaces to residential zones.
Further information is contained in each function description.
"""
import pandas as pd
import numpy as np
import pickle
from globals import *
import os
from analytics import graphProbab... |
"""Init module for importing the CLTK class."""
import pkg_resources
from .nlp import NLP
__version__ = curr_version = pkg_resources.get_distribution(
"cltk"
) # type: pkg_resources.EggInfoDistribution
|
import os
import json
# import numpy as np
origin_data_dir = os.path.join('origin_data', 'nyt')
test_result_dir = os.path.join('test_result', 'nyt')
def acc_diff():
# acc_total_fn = os.path.join(test_result_dir, 'nyt_pcnn_att_acc_total.json')
# acc_total = json.load(open(acc_total_fn, 'r'))
acc_not_na_fn... |
def Convert( fileName ):
#Takes a file (like an idle .py) written in windows and performs the linux flip -u command on it
#so that it can be uploaded to the server from home and not give an error.
file = open(fileName,"r").read()
fileHandle = open(fileName,"w", newline="\n")
fileHandle.write(... |
#Automatically created by SCRAM
import os
__path__.append(os.path.dirname(os.path.abspath(__file__).rsplit('/HarderAnalysis/DisplacedDileptons/',1)[0])+'/cfipython/slc5_amd64_gcc434/HarderAnalysis/DisplacedDileptons')
|
import fileinput
lines = list(fileinput.input("input.txt"))
def get_resulting_frequency():
start = 0
resulting_freq_list = {start}
while True:
for line in lines:
start += int(line)
if start in resulting_freq_list:
return start
resulting_freq_list... |
import pandas as pd
import scipy.io
from sklearn.datasets import fetch_20newsgroups
from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer, TfidfVectorizer
import numpy as np
from math import sqrt
import numpy.random as npr
import matplotlib.pyplot as plt
from sklearn.model_selection import trai... |
"""
AUTHOR: GAUTAM CHANDRA SAHA
DATE & TIME: 29/05/21 AT 3:33 PM
"""
friends = ["Gautam", "Rishabh"]
friends_copy = ["Gautam", "Rishabh"]
print(friends == friends_copy)
print(friends is friends_copy) # returns false as each list created in memory is assigned a different address
|
"""
John Choiniere's Baseball Simulator
---See LICENSE.txt for licensing/use information.
------Licensed under the Apache 2.0 license.
---Based on odds ratio calculations as explained by Tom Tango (aka Tangotiger)
here: http://www.insidethebook.com/ee/index.php/site/comments/the_odds_ratio_method/
---Last update: 30... |
def checkerboard():
for count in range(0,9):
if count%2 == 0:
print "* "*4
if count%2 == 1:
print " *"*4 |
import pytest
from puzzles.longest_increasing_subsequence import length_of_LIS
@pytest.mark.parametrize(
"nums, expected",
[
([], 0),
([10, 9, 2, 5, 3, 4], 3),
([10, 9, 2, 5, 3, 7, 101, 18], 4),
([7, 7, 7, 7, 7, 7, 7], 1),
],
)
def test_length_of_LIS(nums, expected):
a... |
#!/usr/bin/python
# -*- coding:utf-8 -*-
'''
Created on Dec 31, 2016
@author: weizhen
'''
import sys
print ('The command line arguments used are.')
for i in sys.argv:
print(i)
print ('\n\nThe PYTHONPATH is', sys.path, '\n')
|
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
class UserLoginForm(AuthenticationForm):
username = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control friendly-input', 'placeholder': 'Username'}))
... |
def hbal_tree(n):
E = 'E'
if n == 0:
return [None]
if n == 1:
return [[E, None, None]]
n_one_subtree = hbal_tree(n-1)
n_two_subtree = hbal_tree(n-2)
tree_a = [[E, left, right]
for left in n_one_subtree for right in n_one_subtree]
tree_b = [[E, left, right]
... |
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
from django.contrib.auth.views import PasswordResetView, PasswordResetDoneView, PasswordResetConfirmView, PasswordResetCompleteView
urlpatterns = [
path('admin/', admin.... |
from sys import argv
script, filename = argv # Scrip is the ex15.py file. Using argv to run the file name along with the script.
txt = open(filename) #using command open to open a filename.
print(f"Here's your file {filename}:")
print(txt.read()) #called function on txt named read. You give a file a command by using... |
##Numeric Comparison
age = 18
if age >= 18:
print ( "True" )
else:
print( "we aren't printing this" ) |
# http://setuptools.readthedocs.io/en/latest/setuptools.html
import setuptools
setuptools.setup(
name="setuptools-wheel-test",
version="0.1",
packages=setuptools.find_packages(),
)
|
# Generated by Django 3.0 on 2020-10-20 05:44
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('swk', '0004_auto_20201014_0745'),
]
operations = [
migrations.RenameField(
model_name='tracksheet',
old_name='attendan... |
class Santri:
def __init__(self,nama,hujroh,kelas,pangkat,nilai,penjara):
self.nama = nama
self.hujroh = hujroh
self.kelas = kelas
self.pangkat = pangkat
self.nilai = nilai
self.penjara = penjara
def hafal_quran(self):
if self.nilai == 100:
... |
class Solution(object):
def threeSumClosest(self, nums, target):
nums.sort()
result = abs((nums[0] + nums[1] + nums[2]) - target)
answer = nums[0] + nums[1] + nums[2]
for i in range(len(nums) - 2):
low = i + 1
high = len(nums) - 1
while low < high:... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.