text stringlengths 8 6.05M |
|---|
import torch
import rlkit.torch.pytorch_util as ptu
import numpy as np
def fetch_preprocessing(obs,
actions=None,
normalizer=None,
robot_dim=10,
object_dim=15,
goal_dim=3,
ze... |
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
def cost(x, y, w):
c = 0
for i in np.arange(len(x)):
hx = w * x[i]
c = c + (hx - y[i]) ** 2
return c / len(x)
x = [1, 2, 3]
y = [1, 2, 3]
print(cost(x, y, -1))
print(cost(x, y, 0))
print(cost(x, y, 1))
print(cos... |
import unittest
import numpy as np
from pathlib import Path
from pdb2sql import many2sql
from pdb2sql import pdb2sql
from .utils import CaptureOutErr
from . import pdb_folder
class TestMany2SQL(unittest.TestCase):
def setUp(self):
pdb1 = Path(pdb_folder, '1AK4', '1AK4_5w.pdb')
pdb2 = Path(pdb_fo... |
import numpy as np
import torch
from torch.utils.data import TensorDataset, DataLoader
import time
import matplotlib.pyplot as plt
import sys
import itertools
import numpy as np
import torch
from torch.utils.data import TensorDataset, DataLoader
import anfis
from membership import TrapezoidalMembFunc, ... |
from __future__ import absolute_import
import os
import sys
from celery import Celery
# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings.base')
# go from /src/apps/workers to /src
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.... |
#coding: utf-8
from __future__ import print_function, absolute_import
import logging
import re
import json
import requests
import uuid
import time
import os
import argparse
import uuid
import datetime
import socket
import apache_beam as beam
from apache_beam.io import ReadFromText
from apache_beam.io import WriteToT... |
# Generated by Django 3.0.5 on 2020-05-27 21:03
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('catalog', '0006_auto_20200527_1543'),
]
operations = [
migrations.AlterField(
model_name='bookinstance',
name='due_b... |
import re
from six.moves.urllib.parse import urljoin
import requests
class RobotsTxt(object):
def __init__(self, base_url, verify_ssl=True):
self._url = urljoin(base_url, 'robots.txt')
self._verify_ssl = verify_ssl
self._response = None
@property
def url(self):
return se... |
#the immutable tuple list of simple foods:
def main():
simple_foods = ('raw fish', 'nuts', 'berries', 'tree bark')
for food in simple_foods:
print(food)
if __name__ == '__main__':
main() |
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def removeElements(self, head: ListNode, val: int) -> ListNode:
node = None
ret = None
while head:
if head.val != val:
if node:
... |
from django.contrib import admin
from flatblocks.models import FlatBlock
from flatblocks.settings import ADMIN_SHOW_ALL_SITES_BLOCKS
if ADMIN_SHOW_ALL_SITES_BLOCKS:
list_filter = ['site', ]
else:
list_filter = []
class FlatBlockAdmin(admin.ModelAdmin):
ordering = ['slug', ]
list_display = ('slug', '... |
__author__ = 'Alberto Nieto'
__version__ = "0.1.0"
# from gis_utils import *
# from general_utils import *
# from geoalloc_utils import *
# from tradearea_utils import *
import gis_utils
import general_utils
import data_utils |
class Solution:
def eraseOverlapIntervals(self, intervals):
intervals.sort(key = lambda x: x[1])
n, count = len(intervals), 1
if n == 0: return 0
curr = intervals[0]
for i in range(n):
if curr[1] <= intervals[i][0]:
count += 1
... |
import re
# Finding Patterns in Text
patterns = ['this', 'that']
text = 'Does this text match the patterns'
for pattern in patterns:
print 'Looking for "%s" in "%s" ->' % (pattern, text),
if re.search(pattern, text):
print 'found a match'
else:
print 'no match'
'''
Looking for "this" in ... |
from flask import url_for, render_template, flash
from flask_login import login_user, current_user
from werkzeug.security import check_password_hash
from werkzeug.utils import redirect
import logging
import app.forms
from util.logutils import loghelpers
from app.models import User
# from main import app, logger
log... |
import unittest
from test.test_float import NAN
class ConditionalTests(unittest.TestCase):
def test_if_else(self):
a = input("please input a number")
a = (a.isdigit() and int(a)) or 0
if (a == 4):
print("a is 4")
else:
print("a:%d isn't 4" % a)
... |
'''
Manage the pipeline : reading the logs, parsing them and generating stats.
'''
import os
import time
from monilog.parser import Parser
from monilog.statistics import Statistics
from monilog.utils import init_logger
HIGH_TRAFFIC_DUR = 2*60
STAT_DUR = 10
MAX_IDLE_TIME = 5*60
class MonilogPipeline:
'''
Re... |
import requests
import feedparser
from typing import List
from readability import Document
from .story import Story
from .util import PlacementPreference
from .storyprovider import StoryProvider
class RSSFeedStoryProvider(StoryProvider):
def __init__(self, rss_path: str, limit: int = 5) -> None:
self.lim... |
from django.shortcuts import render
from .forms import BlogDetail
from .models import Blog
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.views.generic import CreateView, DeleteView, UpdateView, ListView, DetailView
@method_decorator(login_r... |
n=int(input("enter upper range"))
m=int(input("enter lower range"))
for x in range(m,n+1):
if x>=0:
print("positives are:",x)
else:
print("negatives are:",x) |
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 18 10:07:06 2019
@author: HP
"""
import math
def Det(x,n):
if len(x[0])==1:
return x[0][0]
else:
sum=0
for i in range(n):
sum+=math.pow(1,i)*x[0][i]*Det(x[1:n,[j for j in range(n) if j!=i]],n-1)
return sum
x=[[1,2,... |
from util.subprocess import register
reg = register()
f = open('code.txt', 'w') #清空文件内容再写
f.write(reg.getCombinNumber()) #只能写字符串
f.close()
#F4:8E:38:99:38:28BFEBFBFF000306C3WD-WCC6Z6DFR1S6/5257GD2/CN70163654032M/ |
from distutils.core import setup, Extension
module1 = Extension('_system',
sources=['_system.c'])
setup(name='_system',
version='0.1',
description='Basic system commands',
ext_modules=[module1])
|
# -*- coding: utf-8 -*-
# @Author: Fallen
# @Date: 2020-04-19 14:36:33
# @Last Modified by: Fallen
# @Last Modified time: 2020-04-19 15:37:29
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2020-04-18 16:59:44
# @Author : Fallen (xdd043@qq.com)
# @Link : https://github.com/fallencrasher/python-learni... |
year,month,day = int(input("년 : ")), int(input("월 : ")), int(input("일 : "))
#2008 % 10 => 8
# if str(year - month + day)[-1] == '0':
if (year - month + day) % 10 == 0:
print("올해 대박")
else:
print("그럭저럭")
|
'''Write the above solution in a function which takes take numbers and return the bigger number
[topic covered: function]'''
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
num3 = float(input("Enter third number: "))
def largest(n1,n2,n3):
if (n1 >= n2 and n1 >= n3):
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf.urls import url,include
from .views import inicio,contato
urlpatterns = [
url(r'^$', inicio,name='inicio'),
url(r'^contato/$', contato,name='contato'),
]
|
# Usage: $ python3 get_comment_ratio.py /home/kevin/Desktop/sac-data/stats output.csv
# python3 get_comment_ratio.py <merged_files> <output_path>
#
# Merges all the extracted contribution per tag data into one single file.
__author__ = 'kevin'
import sys
import csv
import os
# RQ 1: Generate a csv file for ... |
"""
This is a game of BlackJack.
"""
from random import randint
# Here we should make some Objects(classes) and Functions for the BJ game
# First define the class Account with all its attributes
class Account:
def __init__(self, balance = 0):
self.balance = balance
def add_funds(self, funds_amt = 0)... |
import cv2 as cv
src = cv.imread("D:/python_file/Opencv3_study_file/images/PT_Picture.jpg",-1)
cv.namedWindow("NO.1 image",cv.WINDOW_AUTOSIZE)
cv.imshow("NO.1 image",src)
cv.waitKey(0)
cv.destroyAllWindows()
print("Hi,Python!") |
# Python Coroutines and Tasks.
# Coroutines declared with async/await syntax is the preferred way of writing asyncio applications.
#
# To actually run a coroutine, asyncio provides three main mechanisms:
#
# > The asyncio.run() function to run the top-level entry point “main()” function.
# > Awaiting on a corout... |
import argparse
import datetime
import logging
import platform
import aq.aq_external as aq
import loading.data_loading as dl
from aq.aq_description import Fact
from jsm.jsm_analysis import FactBase, search_norris
from gui.graph_gen import generate_graph
log_levels = ['debug', 'info', 'warning', 'error']
def parse_a... |
# -*- coding: utf-8 -*-
from app.models.meta import metadata, Base
from app.utils import Enum
from sqlalchemy import Table, Column, Integer, String
from sqlalchemy.orm import mapper
from sqlalchemy.orm.exc import NoResultFound
from web import config
import collections
import web
users_table = Table("USERS"... |
'''
Created on May 18th, 2018
author: Julian Weisbord
sources:
description: Create a data set by overlaying Time magazine covers onto random images.
'''
import os
import sys
import random
import glob
import cv2
import numpy as np
BACKGROUND_WIDTH = 600
BACKGROUND_HEIGHT = 600
OVERLAY_WIDTH = 150
OVERLAY_HEIGHT = 150
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import mysql.connector
from sgmllib import SGMLParser
from HTMLParser import HTMLParser
import urllib2
import os
from Site import *
from Card import *
from Edition import *
from Price import *
url="http://www.magiccorporation.com/gathering-cartes-edition-170-tenebres-su... |
#!/usr/bin/env python2.7
import math
import numpy as np
#pylint: disable=C0301,C0111,W0603,W0613
ARTICLE_FEATURES = {}
USER_FEATURES_DIM = 6
LAST_RECOMMENDATION = None
LAST_USER = None
ALPHA = 3
# Evaluator will call this function and pass the article features.
# Check evaluator.py description for details.
def set_a... |
#!/bin/python
import logging
import os
import time
from typing import List, Dict
import boto3
import botocore
from botocore.config import Config
logger = logging.getLogger()
logger.setLevel(logging.INFO)
def get_enabled_standard_subscriptions(standards, account_id, security_hub_client):
""" return enabled stan... |
import modules.peripherals.heap as heap
import tests.peripheral_tests.myio_testing as myio
#tests heap made of churches
def test_heap_church():
buildingList = myio.input('documentation/TN7_Test.xlsx')[1]
building_heap = heap.heap()
building_heap.heapify(buildingList)
a = []
while not building_heap... |
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
# from sklearn import preprocessing
# 값차이가 상당히 크기 때문에 정규화가 필수
# 정규화된 데이터
data = np.loadtxt("../../../data/diabetes1.csv", skiprows=1, delimiter=",", dtype=np.float32)
print(data)
x_data = data[:, :-1]
y_data = data[:, -1:]
print(x_data.shape... |
# 最多只有两个节点作为根(反证法证明)
# 叶子节点作为根得到的高度比非叶子节点得到的要大 => 遍历叶子节点
# 从叶子节点向上到根节点,每次对其进行剪枝,最后留下的就是高度最小的根节点
class Solution:
def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]:
in_degree, connect = [0] * n, defaultdict(list)
for a, b in edges:
in_degree[a] += 1
in_d... |
from sklearn.feature_extraction.text import TfidfVectorizer
# list of text documents
text = ["The quick brown fox jumped over the lazy dog.",
"The dog.",
"The fox"]
# create the transform
vectorizer = TfidfVectorizer()
# tokenize and build vocab
vectorizer.fit(text)
# summarize
print(vectorizer.vocabulary... |
"""Module that allows Redis to be used as cache. Useful when running on Heroku or such platforms without persistent
file storage.
"""
from redis import Redis
from config import CACHE_URL, CACHE_TTL
from util.caching.caching import CacheAPI
from util.logger import logger
__author__ = 'MePsyDuck'
class RedisCache(Ca... |
# -*- coding: utf-8 -*-
"""
LeetCode 34.
Given an array of integers sorted in ascending order, find the starting and ending position of a given target value.
Your algorithm's runtime complexity must be in the order of O(log n).
If the target is not found in the array, return [-1, -1].
For example,
Given [5, 7, 7, ... |
import napalm
from pprint import pprint as pp
from time import sleep
driver = napalm.get_network_driver('ios')
list_of_devices = ['ios-xe-mgmt-latest.cisco.com']
for device in list_of_devices:
connection = driver(hostname=device, username='developer', password='C1sco12345', optional_args={'port': 8181})
conn... |
from typing import List
from leetcode import TreeNode, test, new_tree, sorted_list
def path_sum(root: TreeNode, target: int) -> List[List[int]]:
if not root:
return []
stack, result, = (
[],
[],
)
def dfs(node: TreeNode, remaining: int) -> None:
stack.append(node)
... |
import numpy as np
import pandas as pd
import warnings
warnings.filterwarnings("ignore")
from wordcloud import WordCloud
import matplotlib.pyplot as plt
import pandas
import seaborn as sns
import matplotlib.pyplot as plt
# # content_polluters_tweets
# # Loading datasets
data = pd.read_excel (r'datasets/content_pol... |
class parentclass():
def send_message(self):
print("bu alan içerisnde mesaj verilecektir")
class basedclass(parentclass):
def send_message(self):
print("base class üzerinden glen mesaj")
parent = parentclass()
parent.send_message()
base = basedclass()
base.send_message()
|
import random
import time
import decimal
def test_sort(lista):
for i in range(len(lista)-1):
if lista[i] > lista[i+1]:
return False
return True
def interclasre(lista1,lista2):
i = j = 0
sol = []
while i != len(lista1) and j!= len(lista2):
if lista1[i] ... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import sys
import re
import os
try:
from PySide.QtCore import *
from PySide.QtGui import *
except:
print ("Error: This program needs PySide module.", file=sys.stderr)
sys.exit(1)
class InfoWindows(QMessageBox):
""" Simple informative modal message """
... |
from iranlowo import adr
|
import os # run os commands
import subprocess # capture os output
class MetaData:
def __init__(self, file):
self.file = file
# Read codecs
cmd = 'mdls -name kMDItemCodecs ' + file
result = self.run_cmd(cmd)
self.codecs = result
# Read height
cmd = 'mdls -name kMDItemPixelHeight ' + file
result = sel... |
# Generated from Wordlify.g4 by ANTLR 4.9.2
from antlr4 import *
if __name__ is not None and "." in __name__:
from .WordlifyParser import WordlifyParser
else:
from WordlifyParser import WordlifyParser
# This class defines a complete listener for a parse tree produced by WordlifyParser.
class WordlifyListener(P... |
#!/usr/bin/env python
#
# Copyright (c) 2019 Opticks Team. All Rights Reserved.
#
# This file is part of Opticks
# (see https://bitbucket.org/simoncblyth/opticks).
#
# 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... |
"""
Created by Alex Wang on 2018-03-14
"""
import numpy as np
def test_numpy_array():
"""
获取部分数组只是引用,不是真的复制
复制需要使用copy函数
:return:
"""
ones_arr = np.ones((5, 5), dtype=np.uint8)
part = ones_arr[2:4, 2:4]
print(ones_arr)
part[0, 0] = 0
print(ones_arr)
def test_broadcast():
... |
#!/usr/bin/env python
import boto3
import requests
from sys import exit
from os import path, remove
from subprocess import call
from datetime import datetime, timedelta
TIMESTAMP_FILE = 'shutdown.timestamp'
NOW = datetime.now()
def get_instance_id():
return requests.get('http://instance-data/latest/meta-data/ins... |
#!/usr/bin/python3
import hidden_4
if __name__ == "__main__":
names = dir(hidden_4)
for i in range(0, len(names)):
if names[i].find("__") == -1:
print("{:s}".format(names[i]))
|
import cv2
image = cv2.imread("red_panda.jpg")
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
cv2.imwrite("Gray_panda.jpg", gray_image)
|
import os
import sys
import subprocess
import shutil
sys.path.insert(0, 'scripts')
import experiments as exp
import rf_distance
def get_rf_pair(tree1, tree2):
command = []
command.append(exp.raxml_nompi_exec)
command.append("--rf")
command.append(tree1 + "," + tree2)
out = subprocess.check_output(command... |
TO_KELVIN = {
'C': (1, 273.15),
'F': (5.0 / 9, 459.67 * 5.0 / 9),
'R': (5.0 / 9, 0),
'De': (-2.0 / 3, 373.15),
'N': (100.0 / 33, 273.15),
'Re': (5.0 / 4, 273.15),
'Ro': (40.0 / 21, -7.5 * 40 / 21 + 273.15),
}
def convert_temp(temp, from_scale, to_scale):
""" Thanks to 'jolaf' on CodeWa... |
import csv
from multiprocessing import Pool
import xmltodict
from api.fill import fill_match_info
from api.headers import headers
from api.send_request import futblot24
from scripts.utils import parse_leagues
from tables.countries import countries
import os
from api.utils import get_time
_FIELD_NAMES = headers
if not... |
from pocket import Pocket, PocketException
p = Pocket(
consumer_key="92912-704c4cd2fa6f2871d28faebb",
access_token="cb3b7b6d-f8c5-e0e9-02ae-21ff42"
)
|
def conference_picker(visited, offered):
visited = set(visited)
return next((city for city in offered if city not in visited),
'No worthwhile conferences this year!')
|
def fib(n, list):
if n == 0:
return 1, 0
elif n == 1:
return 0, 1
else:
return list[n-1][0] + list[n-2][0], list[n-1][1] + list[n-2][1]
from sys import stdin
n = int(stdin.readline())
value = []
for _ in range(n):
tn = int(stdin.readline())
value.append(tn)
for n in value... |
import argparse
import config
import os
import json
if __name__ == '__main__':
parse = argparse.ArgumentParser()
parse.add_argument("corpus", choices=["en", "fr", "de", "ru", "pt", "zh", "pl", "uk", "ta"])
args = parse.parse_args()
inputdir = config.CORPUS_NAME_TO_PATH[args.corpus]
outdir = os.path.join(in... |
import json
from datetime import datetime
import os
from subprocess import Popen, PIPE
import sys
#import psutil
import re
import time
class main():
def __init__(self):
#Verifica o Sistema Operacional
self.verify_system_host()
#Verifica se o ADB está instalado
self.verify_in... |
mac = ['aabb:cc80:7000', 'aabb:dd80:7340', 'aabb:ee80:7000', 'aabb:ff80:7000']
mac_cisco = []
for mac_address in mac:
temp = mac_address.split(':')
mac_cisco.append('.'.join(temp))
print(mac)
print(mac_cisco) |
###Find cos-sim and rating estimations
import numpy
from scipy import spatial
import operator
import os.path
my_path = os.path.abspath(os.path.dirname(__file__))
prePath = os.path.join(my_path,"checkins/")
cityName = "London/"
expertListFileName = "experts"
fileSuffix = ".csv"
delimiter = ","
expertsFilePath = prePa... |
import logging
from decimal import Decimal
from django.db import transaction
from furskru_tools.numbers import round_int, round_down_int
from loyalty.bonuses.const import CEILING, DEFAULT_DISCOUNT_PERCENT
from loyalty.program.models import Discount, PointsRange, RatingGroup
logger = logging.getLogger('points_discoun... |
class Solution:
def maximumTop(self, nums: List[int], k: int) -> int:
n = len(nums)
# n = 0
# n=1, k为奇数个时会拿空
if n == 0 or (n==1 and k % 2 == 1):
return -1
# sb
if k == 0:
return nums[0]
# 只能是第二个
if n > 1 and k == 1:
... |
from django.db import models
def upload_partner_icon(instance, filename):
return f'image/partner/{filename}'
class Partner(models.Model):
name = models.CharField(
max_length=50
)
image = models.FileField(
upload_to=upload_partner_icon
)
url = models.URLField()
def __str_... |
#start_dir = os.getcwd()
cmd.set("cartoon_fancy_helices", 1)
cmd.set("ignore_case", 1)
cmd.set("ignore_case_chain", 1)
#Dropbox scripts
#cd E:
#run \Users\Brahm\Documents\Dropbox\pymol\seq_diff.py
#run \Users\Brahm\Documents\Dropbox\pymol\goto.py
#run \Users\Brahm\Documents\Dropbox\pymol\modevectors.py
#run \Users\Bra... |
# Copyright 2017 The Forseti Security 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 ap... |
# Generated by Django 2.0.9 on 2018-11-06 00:11
import cloudinary.models
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Perros',
fields=[
... |
import datetime
import os
import os.path
import numpy as np
import pandas as pd
datadir = "./data/" # data dorectory path
input_column_names = ["unit","date","rawtime","wind_speed_avg_mps","wind_direction_avg_deg",
"wind_direction_stddev_deg","wind_speed_peak_mps","temperature_C",
"relative_humidity","pre... |
import unittest
import numpy as np
import numpy.testing as npt
from sigpy.mri import samp
if __name__ == '__main__':
unittest.main()
class TestPoisson(unittest.TestCase):
"""Test poisson undersampling defined in `sigpy.mri.samp.poisson`."""
def test_numpy_random_state(self):
"""Verify that rand... |
# Filename: QuadSplitter.py
# Created by: Brian Lach (June 4, 2020)
# Purpose: Resizable quad-viewport widget for PyQt. Ported to Python.
from direct.directnotify.DirectNotifyGlobal import directNotify
from PyQt5 import QtWidgets, QtCore
import math
class AdvSplitter(QtWidgets.QWidget):
def __init__(self, par... |
#!/bin/python
#-*- coding: utf-8 -*-
import requests, os, sys, time, re
from bs4 import BeautifulSoup as bs
token = 'TOKENBOT'
api = f"https://api.telegram.org/bot{token}/"
def res(method, data):
global api
api_res = api+method
if requests.get(api_res,params=data):
return True
def send_Msg(id, text):
data = {
... |
#properties: hunger/thirst level, happiness, anger, energy, name, age, size
#methods(function)(method is a part of a class while function is not): run, bark,eat, sleep, play, bite
import random
class Leo:
#constructor
#scale out of 100
def __init__(self):#homework here is a variable that holds a value
self.ful... |
from tabela_espalhamento import tabela_espalhamento
class Conjunto:
def __init__(self, categorias=10):
self.__elementos = tabela_espalhamento.Tabela_espelhamento(categorias)
def inserir(self, elemento):
self.__elementos.inserir(elemento)
#def inserir_pos(self, elemento, pos):
# if self.contem(elemento):
# ... |
import threading
import time
def fun1(tread_name,delay):
print('线程{0}开始运行'.format(tread_name))
time.sleep(delay)
print('线程{0}结束运行'.format(tread_name))
def fun2(tread_name, delay):
print('线程{0}开始运行'.format(tread_name))
time.sleep(delay)
print('线程{0}结束运行'.format(tread_name))
if __name__=='__main_... |
#variável de texto(string), exemplo de case-sensitive
TEXTO = "teste 1"
texto = "teste 2"
#variável com número inteiro(integer)
numero_inteiro = 100
#variável com número real (float)
numero_real = 2.5
#não existe variável vazia no Python
soma = 0
#função print para mostrar um texto na tela
print("soma... |
from django.contrib import admin
from .models import Attempted
class AttemptedAdmin(admin.ModelAdmin):
list_display = ('student', 'quiz_name', 'got',)
search_fields = ('user__username', 'quiz__name', 'got')
def quiz_name(self, instance):
return instance.quiz.name
def student(self, instance)... |
""" script to do pulse shape analysis of the fast neutron background:
Neutron hittimes from script hittime_distribution_fastneutron.py, that are saved in folder
/home/astro/blum/PhD/work/MeVDM_JUNO/fast_neutrons/hittimes/, are analyzed with this script.
As input for the different values defining the pulse... |
from random import randrange
print("A random number from 1 to 100")
n = randrange(1,100)
print(n)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__version__ = '1.0.1'
import ujson
from sanic import Blueprint
from sanic import response
from sanic.log import logger
from sanic.request import Request
from sanic_jwt import inject_user, scoped
from web_backend.nvlserver.helper.request_wrapper import populate_respo... |
import concurrent.futures
import config
import time
import pandas as pd
import requests
import os
def worker_process(d):
search_results = requests.get("https://api.spotify.com/v1/search",
{"q": d[0] + " " + d[1], "type": "track", "limit":50},
headers=config.spotify_headers).json()["tracks"]["items"]
filt... |
import sys
import itertools
if len(sys.argv) == 1 or sys.argv[1] == '-v':
print('Input filename:')
f=str(sys.stdin.readline()).strip()
else: f = sys.argv[1]
verbose = sys.argv[-1] == '-v'
for l in open(f):
mreset = [int(x) for x in l.strip().split(',')]
class Machine:
def __init__(self, m):
self.memo... |
try:
import smtplib
import sys
import pandas as pd
import numpy as np
import sqlite3
import os
import random
from datetime import datetime
from pm4py.objects.log.importer.xes import factory as xes_import_factory
from pm4py.objects.log.exporter.csv import factory as csv_exporter
... |
from flask_wtf import FlaskForm
from flask_wtf.file import FileRequired, FileAllowed
from wtforms import SubmitField, MultipleFileField
class UploadForm(FlaskForm):
"""
Data form of upload mask.
"""
file = MultipleFileField('File',
validators=[FileRequired(),
... |
#!/usr/bin/env/python
"""
Goal: from the input csv files, calculate the following variables:
PlusCount, AvgScore, MedianFeedbackLength, EntriesRead, EntriesWritten, MedianSubjectLength, MedianTextLength
for each user in each kursXX/semesterXX pair
where
PlusCount = count(plus) per user in a course
AvgSc... |
from typing import Optional, Tuple
import requests
import microstrategy_api
from microstrategy_api.task_proc.exceptions import MstrDocumentException
from microstrategy_api.task_proc.executable_base import ExecutableBase
from microstrategy_api.task_proc.object_type import ObjectType
class Document(ExecutableBase):
... |
__author__ = "Narwhale"
class Single_instance(object):
"""单例模式"""
__instance = None
def __init__(self):
pass
def __new__(cls, *args, **kwargs):
if cls.__instance == None:
cls._instance = object.__new__(cls, *args, **kwargs)
return cls.__instance
s = Single_instanc... |
from django.contrib import admin
# Register your models here.
from LaF.models import Lost,Find
# Register your models here.
admin.site.register(Lost)
admin.site.register(Find) |
# -*- encoding:utf-8 -*-
# __author__=='Gan'
# Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
# Definition for a binar... |
import curses
import time
from brewtroller import *
from mash import *
class CursesTun(Tun):
# window size
height=13
width=11
# temperature display position in the window
tempx=3
tempy=3
def __init__(self,bt,myid,title,x,y):
Tun.__init__(self,bt,myid,title)
self.win = curs... |
# coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import itertools
fro... |
# -*- coding: utf-8 -*-
' a test module '
from com.drcuiyutao.py.find import find_file_by_key
__author__ = 'Declan'
import sys
import os
import pickle
import json
import time
from io import BytesIO
def test():
args = sys.argv
argLength = len(args)
if argLength == 1:
print('Hello World!')
el... |
# sharepoint.py
from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait # available since 2.4.0
import time
browser = webdriver.Firefox()
browser.get('http://cmcallister:Zephyr2014@portal.catalystitservices.com/')
alert = browser.s... |
#-*- coding: utf-8 -*-
from django import forms
from django.core.mail import send_mail
from captcha.fields import CaptchaField
class FaleConoscoForm(forms.Form):
assunto = forms.CharField(max_length=50, widget=forms.TextInput(attrs={'placeholder': 'O assunto'}))
nome = forms.CharField(max_length=50, widget=f... |
import requests
API_URL = 'https://api.scryfall.com/cards/arena/'
def get_card_info(mtga_id: int):
"""
Parameters
mtga_id: Must be a valid mtg arena id and
Returns
A dictionary object containing full info of the card that has the specified MTGA id
Example output can be found here:... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.