text stringlengths 38 1.54M |
|---|
#Node of a Singly Linked List
class Node:
#constructor
def __init__ (self):
self.data = None
self.next = None
self.length=0
self.head=None
#method for setting the data field of the node
def setData(self,data):
self.data = data
#method for getting t... |
"""
A :class:`~allennlp.training.MultiTaskTrainer.MultiTaskTrainer` is responsible
for training a :class:`~allennlp.models.model.Model`.
Typically you might create a configuration file specifying the model and
training parameters and then use :mod:`~allennlp.commands.train`
rather than instantiating a ``MultiTaskTrain... |
from modules.calculator import Calculator
# Global variable shared by all methods
valid_choice = ("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11")
def number_validator(operand, count):
""" Validates our users input for value 1 and 2 """
number = ""
while True:
if count == 1 and operand no... |
import os, socket, sys, threading, time
class Output(threading.Thread):
def __init__(self, sock):
threading.Thread.__init__(self)
self.sock = sock
def run(self):
return_msg = self.sock.recv(1024)
while return_msg:
sys.stdout.write(return_msg.decode()... |
import glob
data = '/home/ubuntu/courses/ass2_multilingual/assign2/data/ted_raw/'
langmap = {'aze': 'azc', 'bel': 'bec'}
folders = ['azc_eng', 'bec_eng']
if __name__ == '__main__':
for lang in ['aze', 'bel']:
print (lang)
for dtype in ['train', 'test', 'dev']:
print (dtype)
for ftype in ['orig', 'mtok']:
... |
#!/bin/python3
import sys
n = int(input().strip())
def max(a,b):
return a if a>b else b
maxN = 0
count = 0
while n:
while n&1:
count+=1
n>>=1
maxN = max(count,maxN)
if not n&1:
count = 0
n>>=1
print(maxN)
|
print("hi russum")
print("concept of input output ")
no=10
print("value of no is",no)
print(1,2,3,4)
print("Enter First Number")
x=int(input())
print("Enter second number")
y=int(input())
z=x+y
print(z) |
from weltcharity import welt_charity
import unittest
import os
import mongomock
class BaseTestCase(unittest.TestCase):
def setUp(self):
welt_charity.app.config['TESTING'] = True
self.tester_app = welt_charity.app.test_client(self)
self.tester_db = mongomock.Connection().db.collection
if... |
from cv2 import imshow, waitKey, threshold, findContours
import cv2
import datetime
def detect(img,feed):
motiondetect=False
temp=img.copy()
contours,hierarchy=findContours(temp,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
if(len(contours)>0):
motiondetect=True
else:
motiondetect=Fals... |
from mesa import Agent, Model
from mesa.time import RandomActivation
from mesa.space import MultiGrid
from mesa.datacollection import DataCollector
from mesa.batchrunner import BatchRunner
from itertools import cycle
import random
stages = ['S','E','I','R']
def infection_rates(model):
agent_state = [ agent.state... |
#!/usr/bin/env python
import pysftp
import os
import sys
# make sure if paramiko throws an error it will get mentioned in log files
import logging
logging.basicConfig()
def transcript_pull(interview_type, data_root, study, ptID, username, password, transcription_language, pipeline=False, lab_email_path=None):
# tra... |
from flask_wtf import Form
from wtforms import TextField
from wtforms import Form, BooleanField, StringField, PasswordField, SubmitField, validators
class UserSignUpForm(Form):
username = StringField('Username', [validators.Length(min=4, max=25)])
email = StringField('Email Address', [validators.Length(min=6, ... |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def sumOfLeftLeaves(self, root: TreeNode) -> int:
total = 0
if root:
node_list = [root]
while node_list:
... |
import sys
end = False
while end == False:
primes = []
n = int(sys.stdin.readline().rstrip())
a = [False, False]+[True]*((2*n)-1)
for i in range(2,(2*n)+1):
if a[i]:
primes.append(i)
for j in range(i+i,(2*n)+1,i):
a[j]=False
primes = [i for i in primes... |
def hi() -> object:
print("hello from function")
def hiByName(name):
print("Hi Mr " + name)
def innerFunc(name):
print("starting inner function")
name = "Mr. " + name
def helloByName():
print("Hello from inner function: " + name)
helloByName()
hi()
hiByName("Zakir")
innerFunc("Za... |
# encoding: utf-8
# author: BrikerMan
# contact: eliyar917@gmail.com
# blog: https://eliyar.biz
# file: test_class_processor.py
# time: 12:04 下午
import unittest
from tests.test_macros import TestMacros
from kashgari.utils import load_data_object
from kashgari.generators import CorpusGenerator
from kashgari.process... |
# michaelpeterswa
# rocket.py
# 02.21.21
# sudo apt-get update
# sudo apt-get install python-smbus python3-smbus python-dev python3-dev i2c-tools
# sudo i2cdetect -y 1
# from mpu6050 import mpu6050
# sensor = mpu6050(0x68)
# accelerometer_data = sensor.get_accel_data()
# import Raspberry Pi GPIO module
import RPi.GP... |
# coding=utf-8
import os
import datetime
import re
from django.shortcuts import render
from django.conf import settings
import jieba
from jieba.analyse.analyzer import ChineseTokenizer
from whoosh.index import open_dir
from whoosh.qparser import MultifieldParser, QueryParser
# jieba.add_word(u'机器学习')
# jieba.add_word... |
# +--------------------------------------------------+
# | |
# | Project Folder Creator |
# | January 7th, 2014 |
# | Daniel Linge |
# | ... |
import requests
import time
#1. here is the api's url
url = 'https://api.coindesk.com/v1/bpi/currentprice.json'
def getLatestBitcoinPrice():
response = requests.get(url).json()
return response['bpi']['USD']['rate_float']*3.75
def CryptoCurrencyTracker():
#2. here, the while loop will loop forever
while True:
... |
"""
Implementation of Method Overriding in Python
"""
class A:
def show(self):
print("Displaying Value from Class A")
class B(A):
def show(self):
print("Displaying Value from Class B")
obj_test = B()
obj_test.show() |
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.image import Image
from kivy.clock import Clock
from kivy.properties import NumericProperty, ReferenceListProperty, ObjectProperty
from kivy.config import Config
import RPi.GPIO as GPIO
from Hole import *
from Kicker import *
from Switch import *... |
import matplotlib.pyplot as plt
from matplotlib.patches import Circle
from itertools import combinations
def visualize(title, particles):
""" Visualizes the particles in the circle. """
plt.figure(figsize=(10,10))
plt.title("Best configuration for " + str(len(particles)) + " particles", size=25)
plt.x... |
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
path("closed-listings", views.closed_listings, name="closed_listings"),
path("login/", views.login_view, name="login"),
path("logout/", views.logout_view, name="logout"),
path("register/", views.r... |
from __future__ import annotations
from pybind11_stubgen.structs import Identifier, QualifiedName
class ParserError(Exception):
pass
class InvalidIdentifierError(ParserError):
def __init__(self, name: Identifier, found_at: QualifiedName):
super().__init__()
self.name = name
self.at ... |
import panjangData as pd
import F01
def best_wahana():
rank = [[0 for i in range(4)] for j in range(3)]
arr = [[0 for i in range(2)] for i in range(F01.panjang_wahana)]
# Menghitung total penjualan tiket tiap wahana
for i in range(F01.panjang_wahana-1):
counter = 0
for j in r... |
# Copyright (c) 2015 Davide Gessa
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
import time
import cvmutils
if __name__ == "__main__":
cvmutils.spawn (3)
while True:
time.sleep (5)
sys.exit ()
|
__author__ = 'diego'
import logging
logger = logging.getLogger(__name__)
import ceil_bokeh
logger.debug('debug %.f',4)
logger.debug('asdf') |
#!/usr/bin/env python
"""
Script to export Vault-derived temporary AWS creds in the environment.
Canonical source of latest version:
<https://github.com/jantman/vault-aws-creds/blob/master/vault-aws-creds.py>
Installation
------------
Add a wrapper to your ``~/.bashrc`` to allow this script to set env vars in
the cu... |
#!/usr/bin/env python
#
# scene3dcanvas.py - The Scene3DCanvas class.
#
# Author: Paul McCarthy <pauldmccarthy@gmail.com>
#
"""This module provides the :class:`.Scene3DCanvas` class, which is used by
FSLeyes for its 3D view.
"""
import logging
import numpy as np
import OpenGL.GL as gl
import fsl.data.mesh ... |
from networkn import NdexGraph
import align_util as util
def align_test_helper(noi, rn, output_name):
noi_node_id_to_gene_map = util.create_node_id_to_gene_map(noi)
rn_node_id_to_gene_map = util.create_node_id_to_gene_map(rn)
noi.show_stats()
rn.show_stats()
for node_id, merge_id in noi_node_id_t... |
"""mytest URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from app import auth, nslxc, nslwp
from .views import *
# Auth routes
auth.add_resource(Auth, '/auth')
auth.add_resource(AuthRefresh, '/auth/refresh')
auth.add_resource(AuthCheck, '/auth/check')
# Users routes
nslwp.add_resource(UsersList, '/users')
nslwp.add_resource(Use... |
# Initialize plot objects for anim or save
# Assume that hte field is 2-dimensional
import numpy as np
import matplotlib.pyplot as plt
from update_anim_2D import update_anim_2D
from update_save_2D import update_save_2D
def initialize_plots_animsave_2D(sim):
figs = []
Qs = []
ttls = []
# Loop thro... |
class Solution:
def orangesRotting(self, grid: List[List[int]]) -> int:
row = len(grid)
col = len(grid[0])
rotten = {(i, j) for i in range(row) for j in range(col) if grid[i][j] == 2}
fresh = {(i, j) for i in range(row) for j in range(col) if grid[i][j] == 1}
t = 0
wh... |
# Generated by Django 2.1.5 on 2019-01-20 10:42
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('jobs', '0007_auto_20190120_1216'),
]
operations = [
migrations.AlterField(
model_name='companyp... |
def func(functionName):
print("---func---1----")
def func_in():
print("---func_in---1---")
ret = functionName() # 保存返回来的haha
print("---func_in---2---")
return ret # 把haha返回到19行处的调用
print("---func---2---")
return func_in
@func
def dtest():
print("---dtest---")
... |
# Generated by Django 2.0 on 2018-02-12 00:58
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('cloudlaunch', '0003_deploy... |
import requests
from pages.book_page import BookPage
page_content = requests.get('http://books.toscrape.com').content
page = BookPage(page_content)
books = page.books
for page_num in range(1, page.page_count):
url = f'http://books.toscrape.com/catalogue/page-{page_num+1}.html'
page_content = requests.get(url... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from math import factorial
from gmpy import bincoef
def prob(people):
return 1.0 - float(factorial(people)*bincoef(365, people))/(365**people)
if __name__ == '__main__':
with open('data.csv', 'w') as f:
f.write('People\tprobability\n')
for people in... |
import random
greeting_list = ['Ciao', 'Hei', 'Salut', 'Hola', 'Nihao']
print random.choice(greeting_list)
|
"""
Download RCONCAT and VLN Transformer checkpoints.
"""
import os
import texar.torch as tx
models = ['rconcat', 'vlntrans', 'ga']
experiments = ['vanilla', 'finetuned_manh50', 'finetuned_mask']
model_name = {'rconcat': 'RCONCAT', 'vlntrans': 'VLN Transformer', 'ga': 'GA'}
def check_dir(model):
if not os.path.i... |
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 5 13:04:11 2019
@author: Jason
"""
from utilities.Database import mongo
class RuleModel():
def __init__(self, ruleName, rules):
self.ruleName = ruleName
self.rules = rules
@classmethod
def apply_rules(cls, moviesPurchased, rules, playerBids... |
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QMessageBox
from PyQt5.QtCore import pyqtSignal
from threading import Thread
from max906 import Ui_Form
from utils import AutoScan
from PyQt5 import QtCore
from utils import WarnControl, WarmControl
import time
import socket
class MyMainWindow(QWidget, Ui_... |
'''
用关键字 class 去定义一个类,如果没有指定父类,默认继承 object
'''
class Human(object):
pass
'''
类属性
这个属性是和类绑定的,并不是和实例绑定的。
'''
class Human(object):
speak = True
'''
实例属性
'''
class Human(object):
def __init__(self, name):
self.name = name
human_a = Human('alan')
'''
类方法
可以看成是一种类属性,而传入的第一个参数是 self,表示调用这个类方法的实例。
'... |
#! /usr/bin/env python2
import logging
import string
logging.basicConfig(format='%(asctime)s %(levelname)s %(pathname)s:%(lineno)d %(msg).256s')
log = logging.getLogger()
log.setLevel(logging.DEBUG)
log.debug(string.letters * 100)
|
# LeetCode
# 56
# Medium
# Given a collection of intervals, merge all overlapping intervals.
# Example 1:
# Input: [[1,3],[2,6],[8,10],[15,18]]
# Output: [[1,6],[8,10],[15,18]]
# Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].
# Example 2:
# Input: [[1,4],[4,5]]
# Output: [[1,5]]
# E... |
import sys
import codecs
import os
import re
from utilites.num import replacenum
from utilites.skleika import skleika
from utilites.morph import morph
from utilites.morph_corrector import morph_corrector
path = os.path.dirname(os.path.abspath(__file__))
def print_on_screen(arr1):
arr1=list(arr1[0]... |
import os
import json
import time
import re
import csv
def solve(**kwargs):
"""
kwargs={
solver:{},
case_name:{},
case_dir:{},
kwargs:{pressure:,...}
}
"""
solver = kwargs["solver"]
case_name = kwargs["case_name"]
time_step = kwargs["... |
#
# Create by Hua on 5/13/22
#
"""
Given a positive integer n, find and return the longest distance between any two adjacent 1's in the binary representation of n. If there are no two adjacent 1's, return 0.
Two 1's are adjacent if there are only 0's separating them (possibly no 0's). The distance between two 1's is... |
from util import reverseRNA
if __name__ == '__main__':
s = raw_input()
r = 1
for c in s:
r *= len(reverseRNA[c])
print r |
# coding=utf-8
from __future__ import print_function
import numpy as np
import pandas as pd
from scipy import stats
from time import mktime
from datetime import datetime
import tensorflow as tf
import statsmodels.api as sm
from statsmodels.tsa.arima_model import ARIMA
from statsmodels.tsa.vector_ar.var_model import VAR... |
"""
Solve problem specified at : https://www.hackerrank.com/challenges/bfsshortreach
using Breadth First Search
"""
__author__ = "alye"
class Graph(object):
"""Represents a mathematical graph.
Attributes:
nodes({int : []}): Adjacency List style representation of the vertices
starting_node(in... |
#!/usr/bin/env python2
# encoding: utf8
import json
import os
import time
import urllib
import bottle
from bottle import route, run, template, request, static_file
from minidou.lib.crawl import DoubanCrawler
from minidou.lib.util import word_count
from minidou.lib.util import data_to_js
from minidou.config import ROO... |
from __future__ import annotations
from typing import Optional
from commonmodel.base import create_quick_schema
from dcp.storage.base import Storage
from dcp.storage.database.utils import get_tmp_sqlite_db_url
from dcp.utils.common import rand_str
from pandas import DataFrame
from snapflow.core.data_block import Data... |
"""
Copyright 2012 4Info
Helper Python functions for ADHaven UI
"""
import locale
import logging
import time
import filecmp
import re
import os
import sys
from decimal import Decimal
from datetime import datetime
from datetime import timedelta
import urllib2
import urllib
# Set up the logger
LOGGER ... |
from argparse import ArgumentParser
from pathlib import Path
from rkstr8.clients.container import pipeline_task
import os
import sys
def __dl_unpack_refs(task_context, tar_gz, unpack_dir):
'''
Download salmon index tarball and untar
'''
print('::UNPACKING REFS::')
sys.stdout.flush()
ref_tar_gz ... |
'''
Author: William Seagle
Date: 04/18/2019
Provides the Actions Tab contents for the Main Window
'''
import tkinter as tk
from tkinter import ttk
from tkinter import messagebox
from Postgres_Handler import DBConnection
import tkcalendar as tkc
class ActionFrame(tk.Frame):
def __init__(self, parent, ... |
"""Battleships package entry module."""
import sys
import params
from battleships import puzzle
def run() -> None:
"""Run the puzzle solver.
The results are written in the default output file whose path is
defined in the params module.
This function catches any previously uncaught exceptions (at l... |
#!/usr/bin/python
import pickle
import sys
import matplotlib.pyplot
sys.path.append("C:\\Users\\Victor\\Desktop\\Udacity\\introml\\ud421-projects\\tools")
from feature_format import featureFormat, targetFeatureSplit
### read in data dictionary, convert to numpy array
data_dict = pickle.load( open("C:\\Users\\Victor\... |
from functools import wraps
from datetime import datetime
import re
from flask import (render_template, request, Response, g, session, redirect,
url_for, flash, jsonify, json, send_from_directory, )
#from flask.ext.basicauth import BasicAuth
from flask.ext.login import login_required, login_user, lo... |
import socket
import numpy as np
class SocketCommunicator:
def __init__(self, **kwargs):
self.debug_mode = kwargs.get('debug_mode', True)
self.ip_address = kwargs.get('ip_address', 'localhost')
self.port = kwargs.get('port', 6006)
self.server = kwargs.get('server', True)
if... |
#Create a class RandomForest in ale called random_forest.py that takes in hyperparameters num_trees
#and max_depth andts num_trees random trees each with maximum depth max_depth. For prediction,
#have all trees predict and then take the mode.
from random_tree import RandomTree
import utils
import numpy as np
class R... |
from django.shortcuts import render
# Create your views here.
def portfolio(request):
return render(request, 'RealPortfolio/portfolio.html')
def projects(request):
return render(request, 'RealPortfolio/projects.html')
def me(request):
return render(request, 'RealPortfolio/me.html')
def testimonials(requ... |
#一个HTML文件,找出里面的链接
import requests
from bs4 import BeautifulSoup
if __name__ == "__main__":
url = "https://www.cnblogs.com/nancyzhu/p/8449545.html"
html = requests.get(url).text
soup = BeautifulSoup(html, "lxml")
aList = soup.find_all("a")
for a in aList:
print(a) |
from algorithm.atom import Atom
from collections import Counter
import algorithm.pattern_format as pf
from copy import deepcopy
import logging
class SubstitutionException(Exception):
def __init__(self, text):
self.txt = text
class ConstSubstitution:
"""Подстановка константного выражения в P"""
... |
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 19 18:03:00 2021
@author: 0014CR744
"""
class Brand():
def chooseBrand():
brandName = str(input("Enter Brand you wish to purchase : "))
return brandName
def selectBrand(brandName,searchList):
orderList = list(filter(lambda bran... |
# Copyright 2021 The NetKet 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 required by applicable ... |
# PyLite commands:
# CREATE tablename WITH col1 col2 col3
# ADD col1_val col2_val col3_val TO tablename
# CHANGE col TO val WHERE colname=val IN tablename
# GET colname1 colname2 WHERE colname=val FROM tablename
# REMOVE colname=val FROM tablename
# DISPLAY tablename
# DELETE tablename
# EXIT
# IMPOR... |
import random
#bowling first:-
def bowl():
score = 0
run = int(input("Choose between 1-6:"))
comp_move = random.randint(1,6)
while (comp_move != run):
score = score + comp_move
comp_move = random.randint(1,6)
run = int(input("Choose between 1-6:"))
else:
... |
#!/usr/bin/python3
import sys
import argparse
from extended_euclid import Extended_Euclid
from order_calc import Order_Calc
from ecc import *
# create top-level parser
parser = argparse.ArgumentParser(prog='crypto-wizard', description="crypto-wizard 0.0.4 ( https://github.com/alexanderbittner/crypto-tools )")
parser... |
"""
<Started>
June 2013
<Author>
Savvas Savvides <savvas@purdue.edu>
<Purpose>
Parse the definitions of all system calls from their man pages.
First read the manual page for syscalls (man 2 syscalls) and parse the names
of all system calls available in the system. Then for each system call read
its man p... |
from api import db
from api.utils import Mixin
from sqlalchemy.dialects.postgresql import JSON
from flask_sqlalchemy import SQLAlchemy
class User(Mixin, db.Model):
__tablename__ = 'user'
id = db.Column(db.Integer, unique=True, primary_key=True)
username = db.Column(db.String, unique=True, nullable=False)
... |
'''
Photometric Redshift to supplement fiber collision correction
Author(s): ChangHoon Hahn
'''
import numpy as np
import scipy as sp
import random
import os.path
# --- Local ----
import pyspherematch as pysph
from spec.data import Data
from defutility.fitstables import mrdfits
def match_zspec_zphoto_cmass():... |
import unittest
from selenium import webdriver
class BaseTestCase(unittest.TestCase):
def setUp(self, url=None):
self.driver = webdriver.Chrome(executable_path=r'./chromedriver.exe')
driver = self.driver
driver.implicitly_wait(30)
driver.maximize_window()
if url:
... |
import os
import webbrowser
BANNER = """
███████╗███╗ ██╗██╗ ██╗███╗ ███╗██╗
██╔════╝████╗ ██║██║ ██║████╗ ████║██║
█████╗ ██╔██╗ ██║██║ ██║██╔████╔██║██║
██╔══╝ ██║╚██╗██║██║ ██║██║╚██╔╝██║██║
███████╗██║ ╚████║╚██████╔╝██║ ╚═╝ ██║██║
╚══════╝╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═╝╚═╝
-------------------------... |
from django.contrib import admin
from .models import Country
from .models import Real_State
from .models import Property_Type
from .models import Neighborhood
from .models import Property
admin.site.register(Country)
admin.site.register(Real_State)
admin.site.register(Property_Type)
admin.site.register(Neighborhood)
... |
import unittest
import sys
sys.path.insert(1, "../code")
import main
class TestCalculator(unittest.TestCase):
def test_sum(self):
self.assertEqual(main.Operations.calculator(1, 5, 6), 11, "Should be 11")
self.assertEqual(main.Operations.calculator(1, -1, 1), 0, "Should be 0")
self.assertEqual(main.... |
#!/usr/bin/python3
"""
Install script for S3 cloud storage and related modules.
Must be run as sudo
"""
import os
os.system("fusermount -u /mnt/wasabi")
os.makedirs("/mnt/archive.allsky.tv")
os.system("chown ams:ams /mnt/archive.allsky.tv")
os.system("chmod 777 /mnt/archive.allsky.tv")
os.system("cd /home/ams... |
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 20 22:55:02 2016
% Purpose : Simple Recurrent Layer
@author: Sivanand Achanta
"""
import numpy as np
import actfn
class SimpleRecurrentLayer:
def get_params(self):
self.params = []
self.params.append(self.Wi)
self.params.append(self.Wfr)
... |
from __future__ import annotations
from abc import ABC, abstractmethod
from ctypes import sizeof, c_void_p,pointer
import pyglet
from random import random
import glm
from pyglet.gl import *
import tinyobjloader
vaos = []
vbos = []
def createVAO():
vao_id = GLuint()
glGenVertexArrays(1,vao_id)
glBind... |
import tkinter as tk
from tkinter import *
val=""
def click(number):
global val
val = val+str(number)
data.set(val)
def sum():
global val
val = str(eval(val))
data.set(val)
def clear():
global val
val=""
data.set(val)
cal = tk.Tk()
cal.title("Calculator"... |
from django.contrib.auth.models import AbstractUser
from django.db import models
class CustomUser(AbstractUser):
username = models.CharField(max_length=30, unique=False)
email = models.EmailField(max_length=255, unique=True)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']
def __int__(self)... |
import atexit
import json
import logging
import os
from datetime import datetime, timedelta
from apscheduler.schedulers.background import BackgroundScheduler
import imaplib
from flask import Flask, render_template, make_response
from config import *
app = Flask(__name__)
CACHE_FILE_PATH = "{}.data"
DAT... |
import json
import datetime
from collections import Counter
from bokeh.plotting import figure, show, output_file
def reading_json ():
with open("birthdayfile.json","r") as birthday: #birthdayfile.json is json file name
birthday_file = json.load(birthday)
getting_only_values = list(birthday_file.value... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
@author: ying
"""
import requests
# The selenium module
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
# The Beautifu... |
# -*- coding: utf-8 -*-
"""
Created on Sun Aug 2 22:52:51 2020
@author: hp
"""
import re
txt = "123-41412-41"
x = re.findall("[a-z]", txt)
print(x) |
"""读取文件"""
with open('learning_python.txt') as file_object:
lines = file_object.readlines()
print(lines)
|
import torch
from torchvision import datasets, transforms
def get_dataloader(args):
if args.dataset.lower()=='cifar10':
train_loader = torch.utils.data.DataLoader(
datasets.CIFAR10(args.data_root, train=True, download=True,
transform=transforms.Compose([
... |
"""
Pre-made Meshes for AER501 Assignment 2 Part B, Ported to Python 2.7 from MATLAB
Mesh1.m -> mesh.Mesh1
Mesh2.m -> mesh.Mesh2
Mesh3.m -> mesh.Mesh3
Mesh4.m -> mesh.Mesh4
"""
# Let K and M denote the global stiffness and mass matrices after assembly.
# The rows and columns corresponding to the zero displacement BCs ... |
import re
address = 'Tolebi 109A, 050040, 050040, Almaty, Kazakhstan, 045040, 050041'
# match = re.search('\d{6}', address) # только цифры из 6 знаков
# print(match.group(0)) # находит только первое совпадение
# print(re.findall('\d{6}', address)) # вернет список
pattern = '\d{3}[A-Z]'
match = re.search(patte... |
#!/usr/bin/env python
import irc.bot
import irc.strings
from irc.client import ip_numstr_to_quad, ip_quad_to_numstr
from conf import BotConfig
from rule import Rule
DEBUG = True
class MusselBot(irc.bot.SingleServerIRCBot):
def __init__(self, channel, nickname, server, port=6667, password=None, rules=[]):
... |
import csv
import glob
print "topic_num"
topic_num=raw_input()
print "LDA or LSI"
model=raw_input()
pas="C:/Users/masafumi/Desktop/Lresult/"+str(model)+"result/train_nNV/topic_"+str(topic_num)+"/business_"+str(model)
slist=glob.glob(pas+"/*")
wfile=open("hoge.csv","wb")
writer=csv.writer(wfile)
wlist=["rev_id","user_... |
# DO NOT EDIT THIS FILE!
#
# Python module gepetto.corbaserver generated by omniidl
import omniORB
omniORB.updateModule("gepetto.corbaserver.gepetto.corbaserver")
# ** 1. Stub files contributing to this module
import gepetto.corbaserver.graphical_interface_idl
# ** 2. Sub-modules
# ** 3. End
|
from django.shortcuts import render
from django.http import HttpResponse
from rest_framework.decorators import renderer_classes, api_view
from rest_framework.renderers import JSONRenderer
from rest_framework.response import Response
# Create your views here.
def showme(request):
return HttpResponse("Alright, thi... |
from flask import render_template, redirect, request, jsonify, json, url_for, session
from client import create_app
import requests
import os
import boto.sqs
from boto.sqs.message import Message
application = create_app()
ACCOUNTS_URL="https://i9p6a7vjqf.execute-api.us-west-2.amazonaws.com/prod/apps/accounts/"
# ACCO... |
import numpy as np
import random
from util import *
from classifier import *
import multiprocessing as mp
from itertools import repeat
import datetime
import csv
import pandas
def parallel_cross_validation(split_ID, passed_data):
#passed data from common main
split = passed_data[0]
train_inputs = passed_da... |
from django.http import HttpResponse
import datetime
from django.template import Template, Context
from django.template.loader import get_template
from django.shortcuts import render
#Proyecto
#class Persona(object):
# def __init__(self, nombre, apellido):
# self.nombre=nombre
#self.apellido=ap... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-11-02 21:41
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.Create... |
# -*- coding: utf-8 -*-
# !/usr/bin/env pytho
import time, re
import sys
from random import choice
from handlers.logHandler import Jcl_Logger
nowTime = time.strftime("%Y%m%d %H%M%S", time.localtime(time.time()))
'''
接口特殊返回码过滤规则
如果不在规则范围内,认为异常
如果在规则范围内,但规则码不包含实际Code码,认为异常
'''
# log记录:Jcl_Logger('jc... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.