text stringlengths 8 6.05M |
|---|
import os
import itertools
class NumberBase:
base_digits = '0123456789abcdefghijklmnopqrstuvwxyz'
@staticmethod
def get_minimum_non_repeating_number(base):
min_number_digits = ['1', '0'] + [NumberBase.base_digits[x] for x in range(2, base)]
min_number = int(''.join(min_number_digits), bas... |
"""empty message
Revision ID: 76d81c37d676
Revises: 21d138d4483a
Create Date: 2021-09-20 19:51:31.102664
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql
# revision identifiers, used by Alembic.
revision = '76d81c37d676'
down_revision = '21d138d4483a'
branch_labels = None
depe... |
from ED6ScenarioHelper import *
def main():
# 卢安
CreateScenaFile(
FileName = 'T2104 ._SN',
MapName = 'Ruan',
Location = 'T2104.x',
MapIndex = 1,
MapDefaultBGM = "ed60010",
Flags = 0,
Ent... |
# Exemplo de polimorfismo usando python
# Autor ~ Dilson
class Ponto:
def __init__(self, x, y):
self.x = x
self.y = y
def print_info (self):
print ("Centro = (", self.x, ",", self.y, ")")
class Circ(Ponto): #herança
def __init__(self, x, y, r):
Ponto.__init__(self,... |
print("--Gestor de Promedios--")
nota1 = int(input("Digite la primera nota: "))
nota2 = int(input("Digite la segunda nota: "))
nota3 = int(input("Digite la tercera nota: "))
promedio = (nota1 + nota2 + nota3)/3
if promedio >= 70:
print("El promedio obtenido en base a las notas ingresadas es :",promedio)
print(... |
#coding:utf-8
from exception.exceptions import ProjectNotFoundError
from dao.database import Database
from dao.project.project import ProjectDao
from dao.project.find import ProjectFindDao
from dao.project.sql import ProjectSQL
from model.project import Project
"""
"""
class ProjectRepository(object):
def __init__... |
#首先生成随机数,并写人文本文件中;
#接着打开文本文件,将里面的数字输出
#导入随机数生成的包
from random import randint
def main():
#打开一个存放随机的文件
randtxt=open('yjy_file_txt_writeread_random_teach.txt','w')
for i in range(20):
randtxt.write(str(randint(0,9))+",")
randtxt.close()
#将存储在文本文件中的数字提取出来并显示
randtxtread=open('yjy_file_txt... |
from ED6ScenarioHelper import *
def main():
# 蔡斯飞艇坪
CreateScenaFile(
FileName = 'T3101 ._SN',
MapName = 'Zeiss',
Location = 'T3101.x',
MapIndex = 1,
MapDefaultBGM = "ed60013",
Flags = 0,
... |
x, y = map( int, input().split())
print( y//x)
|
import math
def sqrt(n,MAX):
float_max=10**16
n_float=float((n*float_max)//MAX)/float_max
curr=(int(float_max*math.sqrt(n_float))*MAX)//float_max
n_MAX=n*MAX
while True:
prev=curr
curr=(curr+n_MAX//curr)//2
if curr==prev:
break
return curr
def power(n):
if... |
from gramps.version import major_version
register(GRAMPLET,
id = "PropertyEditor",
name = _("PropertyEditor"),
description = _("Gramplet to edit attributes of multiple objects"),
status = STABLE,
version = '1.1.1',
gramps_target_version = major_version,
fn... |
import thesaurus
# global lists
articles = ["the", "a", "an", "this", "that", "it", "its", "all", "thing"]
marker_words = ["before", "after", "because", "since", "in order to", "although", "though", "whenever", "wherever", "whether", "while", "even though", "even if", "at one point"]
prepositions = [
"aboard",
... |
# Generated by Django 2.2.11 on 2020-04-13 12:12
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('wishlist', '0009_auto_20200413_0008'),
]
operations = [
migrations.RemoveField(
model_name='wishlistmodel',
name='p... |
import fenics as fa
import math
import numpy as np
import matplotlib.pyplot as plt
import os.path
import pickle
from sklearn.neural_network import MLPRegressor
from sklearn.metrics import mean_squared_error
from .. import arguments
from ..collector.driver_sobol import solver_fluctuation
def RVE(args, parameters_list)... |
"""
inversion a list using stack
"""
from example_stack import ArrayStack
def reverse_list(data):
# modify the list in place
if len(data) <= 1:
return
S = ArrayStack()
for each in data:
S.push(each)
for i in range(len(data)):
data[i] = S.pop()
if __name_... |
#from esp32ap import Esp32Ap
#from ads1299 import Ads1299
#import utime
#from machine import SPI,Pin
#import utime
#import struct
#from ads1299 import *
#from spitest import *
from amplifier import *
if __name__ == '__main__':
main()
|
import unittest
import sys
from pathlib import Path
from typing import Tuple, Optional, Dict, Callable
import os
import requests
class ValidationTestCase(unittest.TestCase):
repo_base: str = None # Base URI or directory name
file_suffix: str = None # file suffix (e.g. ".shex")
start_at:... |
# 567. Permutation in String
#
# Given two strings s1 and s2, write a function to return true if s2 contains the permutation of s1.
# In other words, one of the first string's permutations is the substring of the second string.
# Example 1:
# Input:s1 = "ab" s2 = "eidbaooo"
# Output:True
# Explanation: s2 contains on... |
from functools import wraps, partial
def debug(func):
@wraps(func)
def wrapper(*args, **kwargs):
print(func.__qualname__)
return func(*args, **kwargs)
return wrapper
def debug_v(func):
print(func.__name__)
return func
# basically just patch
def debugmethods(cls):
for key, val... |
from django.contrib import admin
from .models import Rock, Material, RockComposition
admin.site.register(Rock)
admin.site.register(Material)
admin.site.register(RockComposition)
|
import pandas as pd
import numpy as np
# coding=utf8
if __name__=='__main__':
input_file=r'/home/leon/db/BOB投注属性表.txt'
with open(input_file,'r',newline='',encoding='utf8') as filereader:
for row in filereader:
print("{}".format(row.strip()))
|
import os
import cv2
import numpy as np
from util import BBox
def flip(img, bbox, landmark):
"""
Flip image horizontally as well as the bbox and landmark.
param:
-img, the original image
-landmark, using absolute coordinates
"""
# horizontally flip the image
img_flipped = cv2.flip(... |
import os
def model(num_subjects,dir):
mat_txt = ['/NumWaves 1',
'/NumPoints %d' % num_subjects,
'/PPheights %e' % 1,
'',
'/Matrix']
for i in range(num_subjects):
mat_txt += ['%e' % 1]
mat_txt = '\n'.join(mat_txt)
con_txt = ['/C... |
iModNone = 0
iModLCtrl = 1 << 0
iModLShift = 1 << 1
iModLAlt = 1 << 2
iModLWin = 1 << 3
iModRCtrl = 1 << 4
iModRShift = 1 << 5
iModRAlt = 1 << 6
iModRSuper = 1 << 7
bModCtrl = "0x%x" % iModLCtrl
bModShift = "0x%x" % iModLShift
bModAlt = "0x%x" % iModLAlt
bModWin = "0x%x" % iModLWin
bNull = "0x00"
bReleaseAll = bytes(in... |
"""config URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.1/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 ... |
try:
from private import *
except:
import getpass
uri = 'ldap://localhost'
dc = 'dc=domain,dc=com'
user_dn = 'cn=admin,' + dc
user_pw = getpass.getpass("Password for %s:" % user_dn)
|
n = 0
while n**3 <12000:
n += 1
print(n-1) |
project_path = '/home/parkhi/Desktop/DIP_project'
video_resource = project_path+'/data/'
frame_resource = project_path+'/data/' # Any resource/pickles can be stored here.
model_resource = project_path+"/data/models/"
|
#!/usr/bin/python
import ConfigParser
from morsegenerator import MorseGenerator
from voicesynthetizer import Synthetizer
nato = {'A': 'alfa', 'B': 'bravo', 'C': 'charli',
'D': 'delta', 'E': 'eco', 'F': 'foxtrot',
'G': 'golf', 'H': 'hotel', 'I': 'india',
'J': 'yuliet', 'K': 'kilo', 'L': 'lima',
'M': 'm... |
from Products.CMFPlone.CatalogTool import CatalogTool
from collective.rooter.navroot import getNavigationRoot
# Make portal_catalog's search function use a navigation root if no path
# parameter is given
CatalogTool._oldSearchResults = CatalogTool.searchResults
def searchResults(self, REQUEST=None, **kw):
if 'U... |
# import library that allows us to pull data from websites
import requests
# source 1
# requests data from url below
request = requests.get('https://www.adl.org/hate-symbols')
content = request.content
# imports library that allows for us to pick what parts of the content to pull
from bs4 import BeautifulSoup
# st... |
import sys
sys.setrecursionlimit(100000)
n, m, root = map(int, sys.stdin.readline().split(' '))
children = [[] for ix in range(n)]
cs = []
for ix in range(n - 1):
h, t = map(lambda x: int(x) - 1, sys.stdin.readline().split(' '))
children[h].append(t)
children[t].append(h)
for ix in range(n):
c = in... |
import argparse
import tensorflow as tf
import tensorflow.keras as keras
import mnist
import special
import tensorflow.keras.backend as K
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib.animation import FuncAnimation
import os
from os.path import join as pjoi... |
from bs4 import BeautifulSoup
import urlparse
import requests
class Extract_links(object):
unvisited_for_current_link=[] #this list is used to store all the unvisited links in this class then will be merged with main unvisited list
def __init__(self,get_soup, visited, old_unvisited_links, url):
self.ge... |
# Imports
import os
import numpy as np
import argparse
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from cosmo_utils.helpers import yyyymmddhhmmss_strtotime, make_timelist, \
yyyymmddhhmmss
from datetime import timedelta
# Arguments
parser = argparse.ArgumentParser(description = 'Proces... |
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BOARD)
GPIO.setup(11,GPIO.OUT) #set pin 11 as out
GPIO.setup(13,GPIO.IN, pull_up_down=GPIO.PUD_UP) #set pin 13 as input
def Button (channel): #this function will be called when the button is pressed
GPIO.output(11,1) #Turn ON the LED
GPIO.add_event_detect(1... |
try:
i=int(input())
except Exception as e:
print(e)
else:
print("every thing is good")
finally:
print("the entered number is") |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('polls', '0002_auto_20150314_0215'),
]
operations = [
migrations.DeleteModel(
name='Accolades',
),
... |
import sys
from numpy import *
from matplotlib import pyplot as plt
#xvar = array([1,2,3,4,5])
#yvar = xvar*2
xvar, yvar = loadtxt("../data/data.csv", unpack=True, delimiter=',')
plt.clf()
plt.plot(xvar,yvar,'rx')
plt.plot(xvar,yvar,'b')
plt.xlim((0,6))
plt.ylim((0,12))
plt.xlabel("My X Variable")
plt.ylabel("My Y... |
def urai(word):
huruf = '' #list kosong untuk menampung hasil looping 1
char_2 = '' #list kosong untuk menampung hasil looping 2
for i in range(1,len(word)+1): #untuk looping pertama
huruf = huruf + word[0:i]
for j in range(len(word)-1): #untuk looping kedua
char_2 = char_2 + word... |
import time
import pytest
from .pages.product_page import BookOrderPage
from .pages.basket_page import BasketPage
from .pages.login_page import LoginPage
links = ["http://selenium1py.pythonanywhere.com/catalogue/coders-at-work_207/?promo=offer0"]
@pytest.mark.need_review
@pytest.mark.parametrize('link', links)
de... |
import asyncio
from django.core.management import BaseCommand
from backend.user_service.user.infra.adapter.user_create_command_handler \
import UserCreateCommandHandler
from backend.user_service.user.infra.adapter.user_point_update_command_handler \
import UserPointUpdateCommandHandler
from backend.user_servi... |
# -*- coding:UTF-8 -*-
u'''
******************************************************************************
* 文 件:GDC03849.py
* 概 述:ht1621x芯片驱动GDC03849段式液晶的程序,显示范围-99.99-999.99
* 版 本:V0.10
* 作 者:Robin Chen
* 日 期:2018年5月9日
* 历 史: 日期 编辑 版本 记录
2018年5月9日 Robin Chen V0.10 ... |
import time
from ops import *
#from utils import *
def network( x,training,res_n=10, reuse=False):
"""
Args:
x: the input of the network,a tensor of size [batch_size, height,width,channel]
training: if training
res_n: the number of the blocks to use for each layer
Returns:
the output of eac... |
import pyqrcode
import png
from datetime import date
def barcodeGenerator(order_id, event_name, ref_code, order_uuid, user_order):
today_date = date.today()
order_details = "AFRIVENT \
\n ORDER {0} CONFIRMED For {1}, \
\n Payment ID: {2} \
\n Uniq... |
# username = input('Your username ')
# Email = input('your email ')
# password = input('choose a suitable password ')
# fullname = input('what is your fullname? ')
f = open("staff.txt",'w')
staffDetails = str("1." )+str("Tara, Taradebby@gmail.com, Taradee, Omotara Kuds \n")
f.write(staffDetails)
f = open("staff.txt",... |
#coding=utf-8
import sys
sys.path.append("../")
from src import verbalGraphGenerator
import random
from src import logger
import logging
import uuid
from src import utils
from src import constants
import argparse
import codecs
import os
import time
import pdb
import json
import regular_test
sentences = regular_test.... |
#Relational / Comparison Operators
a=3
b=3
print(a==b)
a=4
b=5
print(a!=b)
a=2
b=6
print(a>b)
a=5
b=6
print(a<b)
a=6
b=7
print(a>b)
a=8
b=7
print(a>b)
a=3
b=4
print(a<=b)
a=9
b=4
print(a<=b)
a=5
b=9
print(a>b)
a=5
b=9
print(a>=b)
a=8
b=4
print(a>b)
a=1... |
# -*- encoding: utf-8 -*-
from odoo.addons.account.tests.account_test_savepoint import AccountTestInvoicingCommon
from odoo import fields
from odoo.tests import tagged
from odoo.tests.common import Form
@tagged('post_install', '-at_install')
class TestBillsPrediction(AccountTestInvoicingCommon):
@classmethod
... |
# @Time : 2018/3/7 16:15
# @Author : Jing Xu
import threading
import requests
from bs4 import BeautifulSoup
def gettitle(page):
url = "https://movie.douban.com/top250?start={}&filter=".format(page * 25)
r = requests.get(url)
soup = BeautifulSoup(r.content, "html.parser")
lis = soup.find("ol", class_="grid_view")... |
import numpy as np
import pandas as pd # pip install pandas
from sklearn.naive_bayes import GaussianNB # pip install sklearn
from sklearn.neighbors import KNeighborsClassifier
from sklearn import svm
from sklearn import tree
# from sklearn.model_selection.cross_validation import cross_val_predict
from sklearn.model_s... |
import argparse
import os
from model_temp import Temp_RFRNetModel
from dataset_temp import Tem_Dataset
from torch.utils.data import DataLoader
def run():
parser = argparse.ArgumentParser()
#训练数据的位置
parser.add_argument('--data_root', type=str, default='/home/yaoziqiang/py_project/train&test_data/train_mavg'... |
class NumMatrix(object):
def __init__(self, matrix):
row_num = len(matrix)
col_num = len(matrix[0]) if row_num > 0 else 0
m = [[0 for i in range(col_num + 1)] for j in range(row_num + 1)]
for i in range(1, row_num + 1):
for j in range(1, col_num + 1):
... |
"""
자연수 A, B가 주어지면 A+B를 구하는 프로그램을 작성하시오.
입력
자연수 A, B (0 < A, B ≤ 10)가 첫 번째 줄에 주어진다. 단, 두 수의 사이에는 공백이 주어지지 않는다. 두 수의 앞에 불필요한 0이 붙는 경우는 없다.
출력
첫 번째 줄에 A+B의 값을 출력한다.
예제 입력 1
37
예제 출력 1
10
"""
s=input()
r=0
for i in range(0, len(s)):
if int(s[i]) == 0:
r += 9
r += int(s[i])
print(r) |
#is 练习:判断二个变量是否为同一个对象, 是否指向同一个内存地址
stu_list=['王利利',24,88888.88]
print(id(stu_list))
#地址传递
stu2_list=stu_list
print(id(stu2_list))
#is 运算
if stu_list is stu2_list:
print('A is B')
else :
print('A is not B')
#值传递,再开辟一个空间存放数据
c=stu_list[:] #切片 没头没尾就是全部复制
print(id(c)) #查看内存地址
if c is stu_list:
print( 'C i... |
'''
author: juzicode
address: www.juzicode.com
公众号: 桔子code/juzicode
date: 2020.8.1
'''
print('\n')
print('-----欢迎来到www.juzicode.com')
print('-----公众号: 桔子code/juzicode \n')
from ctypes import *
class TuTest(Union): #定义ctypes类型的“结构体”
_fields_ = [('a', c_char),
('b', c_int),
(... |
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import ListView, CreateView, UpdateView, TemplateView
from django.contrib.auth import login, authenticate
from django.shortcuts import render, redirect
from django.urls import reverse_lazy
from functools import wraps
from chartjs.views.... |
# Generated by Django 2.1.2 on 2019-05-02 14:56
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('scheduler', '0027_request_path'),
]
operations = [
migrations.AlterField(
model_name='request',
name='date_time',
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('course_selection', '0006_auto_20141124_1441'),
]
operations = [
migrations.AlterField(
model_name='semester',
... |
from django.contrib import admin
from detectdata.models import *
# Register your models here.
admin.site.register(Detect) |
from flask import Flask, jsonify
import time
from stats_helper import StatsHelper
from flask_cors import CORS
import simplejson as json # instead of import json
app = Flask(__name__)
CORS(app)
stats_helper = StatsHelper()
#Used to bring in employee table information
# @app.route('/')
# def home():
# ... |
#!/usr/bin/env python
"""
_LoadForErrHandler_
MySQL implementation of Jobs.LoadForErrorHandler.
"""
from WMCore.Database.DBFormatter import DBFormatter
from WMCore.WMBS.File import File
from WMCore.DataStructs.Run import Run
class LoadForErrorHandler(DBFormatter):
"""
_LoadForErrorHandler_
Retrie... |
import random
import string
# randCharList = list(string.ascii_lowercase) + (list(string.ascii_uppercase))
randCharList = list("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!#$%&'()*+,-./:;<=>?@[\]^_`{|}~")
def encode(msg):
# randCharList = list(string.ascii_lowercase) + (list(string.ascii_upperc... |
"""
@author:ming
@file:梨视频下载.py
@time:2021/10/26
"""
import requests
# https://www.pearvideo.com/video_1744464 页面链接
# https://video.pearvideo.com/mp4/adshort/20211025/cont-1744464-15787050_adpkg-ad_hd.mp4 播放链接
# https://video.pearvideo.com/mp4/adshort/20211025/1635257300512-15787050_adpkg-ad_hd.mp4 后端返回链接,加密处理过
# 页面
... |
f = open('rosalind_ini3.txt', 'r')
strings = f.readlines()
f.close()
marker = strings[1]
a,b,c,d = [int(i) for i in marker.split(' ')]
sequence = strings[0]
print '{0} {1}'.format(sequence[a:b+1], sequence[c:d+1])
|
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
plt.figure(figsize=[6,3])
# plt.rcParams['figure.dpi'] = 200 #分辨率
# the histogram of the data
plt.hist(df['Normalized Score'],bins=50,color='lightgray',edgecolor='black',alpha=0.75)
plt.ylabel('Requests')
plt.axis([-3, 3, 0, 300])
plt.grid(True,linestyle... |
'''
Created on Dec 22, 2014
@author: desposito
'''
from Ingredient import Ingredient
class Malt(Ingredient):
'''
classdocs
'''
def __init__(self, name, quantity, ppg, srm):
'''
Constructor
'''
Ingredient.__init__(self, name, quantity, "lbs", ppg=ppg, srm=srm)
... |
import re
import pandas as pd
from os.path import dirname,abspath
import sys
sys.path.append(dirname(dirname(abspath(__file__))))
from os.path import join as pjoin
from sklearn.utils import shuffle
import cv2
import numpy as np
import torch
from torch.utils.data import Dataset, DataLoader
import xml.etree.El... |
kimport model_training
import predict
import Data_importer
from datetime import datetime as dt
def main():
tstart = dt.now()
print('\nStarting with program\n')
model_training.main()
print('Finished training model in:\n', dt.now()-tstart)
print('predicting outcome of test set:\n')
bool_ = inpu... |
from bs4 import BeautifulSoup
from speaker import Speaker
from topic import Topic
from speech import Speech
import urllib
import re
class Scraper(object):
"""Docstring for Scraper."""
def __init__(self):
"""Docstring for init."""
super(Scraper, self).__init__()
def scrape(self, p):
... |
"""
re-write the initialization part in the CaesarCipher
"""
from example_cipher import CaesarCipher
class CaesarCipher2(CaesarCipher):
def __init__(self, shift):
"""this part replaces the original initialization"""
self._forward_key = "".join( chr( (k+shift)%26 + ord('A') ) for k in range(26) ) ... |
from random import randrange
get_zero_or_one = lambda: randrange(2)
def get_random(max_number):
# Please implement this method # using only `get_zero_or_one`
k = 0
while max_number > 2 ** k:
k = k + 1
num = max_number
while num >= max_number:
num = 0
for i in range(0, k):... |
import io
import cmd
import platform
import sys
import signal
if platform.system() in ('Linux', 'Darwin'):
import readline
else:
import pyreadline as readline
import shlex
import traceback
import importlib.util
from argparse import _SubParsersAction
from argparse import _HelpAction, Action
from contextlib im... |
# -*- coding: utf-8 -*-
"""
Created on Sat Nov 28 09:39:40 2020
@author: lakhan
"""
#importing libraries
import numpy as np
import pandas as pd
import re
import nltk
import matplotlib.pyplot as plt
#importing the data
airline = pd.read_csv('airline_sentiment_analysis.csv')
airline.airline_sentiment.value_counts()... |
from .stage import PipelineStage
import numpy as np
import blind2pt
class Blinding(PipelineStage):
name = "blind"
# fixed cosmological parameter sets input.
# cosmosis parameter file and values file
# string seed from the parameter
inputs = {
"2pt_extended" : ("2pt", "2pt_extended_... |
A = input ().split ()
B = input ().split ()
for i in range (len (A)):
A [i] = int(A [i])
for j in range (len (B)):
B [j] = int(B [j])
C = []
for k in range (len (A)):
s = B.count (A [k])
if s > 0:
C.append(A [k])
for x in range (len (C)):
print(C [x], end = ' ') |
class NamedObjectList(list):
def __getitem__(self, key):
if isinstance(key, str):
for item in self:
if item.name == key:
return item
raise IndexError('no object named {!r}'.format(key))
return list.__getitem__(self, key) |
#
# Copyright (C) 2018 Satoru SATOH <ssato @ redhat.com>
# License: MIT
#
# pylint: disable=missing-docstring, invalid-name
import os.path
import os
import unittest
import anyconfig.compat
import anyconfig.ioinfo as TT
import anyconfig.utils
from anyconfig.globals import (
IOI_PATH_STR, IOI_PATH_OBJ, IOI_STREAM,
... |
from elasticsearch import Elasticsearch
mappingJson = {
"behave": {
"_timestamp": {
"enabled": True,
"path": "date"
},
"properties": {
"date": {
"type": "date"
},
"duration": {
"type": "string"
... |
#!/usr/bin/env python3.4
# encoding: utf-8
import os
import sys
from pymzid.pymzid import Mzid
def main():
'''
Simple parser for Mzid files based on pymzl_integrator module
© Johannes Leufken 2017
'''
reader = Mzid(
sys.argv[1],
verbose = False
)
data_frame = reader.pept... |
# -*- coding: utf-8 -*-
"""Classes for interactions between the TXM class and the real TXM.
TxmPV
A descriptor for the process variables used by the microscopes.
"""
import logging
import datetime as dt
import os
import epics
import numpy as np
__author__ = 'Mark Wolfman'
__copyright__ = 'Copyright (c) 2017, UC... |
import os
import docker
import constants
from flask import redirect, url_for, session, request, jsonify
from git import Repo
from app import app, github
from config import Config
from parser import parse
from helpers import (
id_generator,
find_free_port,
get_pull_request_info,
execute_testfile
)
@a... |
from django.conf.urls import patterns, url
from planner import views
urlpatterns = patterns(
'',
url(r'^$',
views.PlannerHomeView.as_view(),
name='planner'
),
url(r'^(?P<year>[\d]+)/(?P<month>[\d]+)/(?P<day>[\d]+)/$',
views.PlannerDayView.as_view(),
name='planner-da... |
"""
Adapted from: https://wiki.python.org/moin/Powerful%20Python%20One-Liners
"""
import sys
pattern = sys.argv[1]
substitution = sys.argv[2]
line = 'My cat looks weirdly. The neighbours cat too...'
print(line.replace(pattern, substitution))
|
# 单例设计模式:某个类或者模型在整个程序运行期间最多只能有一个对象被创建
# 我们可以判断,如果User这个类没有创建过对象,那么就创建一个对象保存在某个地方
# 以后如果要再创建对象,我会去判断,如果之前已经创建了一个对象,那么就不再创建
# 而是直接把之前那个对象返回回去
class User(object):
__instance = None
def __new__(cls, *args, **kwargs):
if not cls.__instance:
# 以下写法和python2不同
cls.__instance = super(Use... |
times = 0
PATH = ''
import sys
import subprocess
import ctypes
import os
import random
if ctypes.windll.shell32.IsUserAnAdmin():
pass
else:
ctypes.windll.shell32.ShellExecuteW(
None, "runas", sys.executable, __file__, None, 1)
sys.exit()
times = times+1
this = __file__
def random_path():
d... |
import argparse
import json
from sklearn.datasets import load_wine
from typing import Text
import yaml
def data_load(config_path: Text) -> None:
"""Load raw data
Args:
config_path {Text}: path to config
"""
config = yaml.safe_load(open(config_path))
raw_data_path = config['data_load']['r... |
import syllabifier, sys
from textgrid import TextGrid
import numpy as np
from phn_info import vowels, consonants
import argparse
def gop_feat(gop_vals, textgrid_file):
"""
Calculate gop statistics on vowels, consonants and syllables
:param gop_vals: gop values of one utterance extracted from gop files
... |
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 25 09:14:14 2018
@author: JHodges
"""
import time
import pickle
import numpy as np
import xml.etree.ElementTree as ET
import matplotlib.pyplot as plt
import scipy.interpolate as scpi
from matplotlib.colors import LinearSegmentedColormap
import imageio
import glob
import ... |
#!/bin/python3
from lexer import lexer_qsl
from parserqsl import parser_qsl
from process.link import link
from process.types import types
from process.execute import execute
from process.load import load
from process.print import printkb
from process.slink import slink
import argparse
p = argparse.ArgumentParser(prog=... |
"""Blogly application."""
from flask import Flask, request, redirect, render_template, url_for
from models import db, connect_db, User, Post, Tag, PostTag
from flask_debugtoolbar import DebugToolbarExtension
app = Flask(__name__)
app.config["SECRET_KEY"] = "SECRET_GARFIELD"
app.config['DEBUG_TB_INTERCEPT_REDIRECTS'] ... |
from django.db import models
class Material(models.Model):
name = models.CharField(max_length=50, unique=True)
def __str__(self):
return self.name
class Meta:
db_table='material'
class Rock(models.Model):
name = models.CharField(max_length=50, unique=True)
description = models.... |
# Copyright (c) 2020 Dell Inc. or its subsidiaries.
# 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 requi... |
import os
from setuptools import setup, Command, find_packages
def readme():
with open('README.rst') as f:
return f.read()
class CleanCommand(Command):
"""Custom clean command to tidy up the project root."""
user_options = []
def initialize_options(self):
pass
def finalize_options(... |
import requests
from bs4 import BeautifulSoup as bs
url2 = "https://artsandculture.google.com/asset/anne-in-a-striped-dress-fairfield-porter/TAHUTWNOPxdkYA"
req2 = requests.get(url2)
soup2 = bs(req2.text, "lxml")
im = "https:" + soup2.find_all("img", class_="pmK5Xc")[0]["src"] # img_link
td1 = soup2.find("sect... |
import os
def main():
os.chdir(os.path.dirname(os.path.abspath(__file__)))
input = open("day15_input.txt").read().splitlines()
print(solve(input))
class Generator:
def __init__(self, starting_value, factor, multiple=1):
self.previous_value = starting_value
self.factor = factor
... |
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 16 10:26:16 2017
@author: Peter Wilson
"""
import numpy as np
import sympy as sp
print("sympy version: ",sp.__version__)
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.colors import Normalize
import matplotlib.pyplot as plt
from matplotlib import cm
from matplot... |
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 27 05:55:29 2020
@author: cupertino_user
"""
import torch
import gc
#del variables
#gc.collect()
#torch.cuda.memory_summary(device="cuda:1", abbreviated=False)
def pretty_size(size):
"""Pretty prints a torch.Size object"""
assert(isinstance(size, torch.Size))
return ... |
# Copyright 2016 Jochen Kursawe. See the LICENSE file at the top-level directory
# of this distribution and at https://github.com/kursawe/MCSTracker/blob/master/LICENSE.
import tracking
import networkx as nx
import matplotlib as mpl
import matplotlib.pyplot as plt
from os import path
from os.path import dirname
impor... |
import sys
import platform
# https://stackoverflow.com/a/22820100
def is_windows():
return any(platform.win32_ver())
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.