text stringlengths 8 6.05M |
|---|
"""Management command tests."""
import os
import shutil
import tempfile
from django.core.management import call_command
from django.urls import reverse
from modoboa.core.tests.test_views import SETTINGS_SAMPLE
from modoboa.lib.tests import ModoTestCase
from .. import factories
class NeedDovecotUpdateTestCase(Modo... |
"""
Label classifier
"""
# Internal libraries
from big_picture.pre_processor import pre_process
from big_picture.vectorizers import embedding_strings, tf_idf
from big_picture.label import Label
# General libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import pickl... |
from page.page_address import PageAddress
from page.page_login import PageLogin
from tools.read_data import read_data
class PageIn:
# 获取登录page页面对象
@classmethod
def get_page_login(cls):
return PageLogin()
@classmethod
def read_data(cls):
return read_data("data.yaml")
@classmet... |
#Format Strings
my_name='Kalyan Ghosh'
my_age=27
my_height=5.7
my_weight=60
my_eyes='Black'
my_teeth='White'
my_hair='Brown'
print "Let's talk about %s." %my_name
print "He's %f feet tall." %my_height
print "He's %d pounds heavy." %my_weight
print "He's got %s eyes and %s hair."%(my_eyes,my_hair)
print "If I add %d %... |
import numpy as np
import sys
import os
import yaml
def read_yaml(path):
return yaml.load(open(path, 'r'), Loader=yaml.FullLoader)
def get_correct_path(relative_path):
'''
Used when packaged app with PyInstaller
To find external paths outside of the packaged app
'''
try:
base_path = sy... |
import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import interp1d
import scipy.integrate as integrate
plt.close('all')
# ------ defining constants ----- #
# -- using mks for convenience -- #
c = 2.998e8 # m / s
h = 6.626e-34 # m^s * kg / s
k = 1.31e-23 # J / K
b = 2.898e-3 # m * K
# ------ FU... |
#Q.1- Print anything you want on screen.
print("anything you want on screen")
#Q.2- Join two strings using '+'. E.g.-"Acad"+"View”
a=input(" enter ur first string ")
b=input("enter ur second string ")
print(a+b)
#Q.3- Take the input of 3 variables x, y and z . Print their values on screen.
a=input(" enter ur first str... |
import mysql.connector
mydb = mysql.connector.connect(
host="",
user="",
password="",
database=""
)
print("please enter your email:")
email = input()
print("please enter your password:")
password = input()
mycursor = mydb.cursor()
sql = "INSERT INTO info (Emails, PASSWORDS) VALUES (%s, %s)"
val = (... |
"""
Functions for projecting between pushbroom sensors (with known orientation/position from IMU data) and a 3D point cloud.
"""
import hylite
from hylite.project import rasterize, PMap, push_to_cloud
from scipy import spatial
import numpy as np
import matplotlib.pyplot as plt
from tqdm import tqdm
import scipy as sp
f... |
n1 = int (input ('Digite um nº:'))
n2 = int (input ('Digite outro nº:'))
soma = n1+n2
print ('A soma é: {}'.format(soma))
|
n = 1000
ans = 0
prod = 2**n
for n in str(prod):
ans += int(n)
print(ans)
|
Ceci est un script parce que simon a tout merger
|
# 5-10
current_users = ['markfromjoberg', 'ncmbartlett', 'nakedcranium', 'naomiche', 'therealekevin']
new_user = input('Please enter your desired username: ')
new_user = new_user.lower()
while new_user in current_users:
print('Sorry that username is taken.')
new_user = input('Please enter another username: ')
new_... |
import random
from center import Center
from tract import Tract
class Model:
def __init__(self, census_tracts, number_of_districts):
self.census_tracts = [Tract(tract) for tract in census_tracts]
self.number_of_districts = number_of_districts
self.target_district_population = su... |
from PyQt5.QtCore import QAbstractListModel, Qt, pyqtSignal, pyqtSlot, QModelIndex
class BestellModel(QAbstractListModel):
NameRole = Qt.UserRole + 1
PreisRole = Qt.UserRole + 2
bestellungChanged = pyqtSignal()
def __init__(self, parent=None):
super().__init__(parent)
self.bestel... |
from bibpdf import normalizer
from bibpdf.formatters import simple_format
__author__ = 'Keji Li'
def order_str(order: int) -> str:
if order % 10 == 1 and order % 100 != 11:
return "{0}st".format(order)
elif order % 10 == 2 and order % 100 != 12:
return "{0}nd".format(order)
elif order % ... |
a="pikachu"
print(a[0])
print(a[5])
print(a[-1])
print(a[-2])
print(a[-3])
print(a[0:3])
print(a[0:7])
print(a[0:9])
print(a[1:5]) |
from marshmallow import Schema, fields, ValidationError
import os
# Custom validators
def must_not_be_blank(data):
if not data:
raise ValidationError("Data not provided.")
def must_be_in_allowed_extension(extension: str):
return extension in os.environ.get('ALLOWED_EXTENSIONS')
def validate_quant... |
from copy import deepcopy
from indigox.config import BALL_DATA_FILE, INFINITY, MAX_SOLUTIONS
from indigox.misc import BondOrderAssignment, graph_to_dist_graph, node_energy
try:
import BALLCore as BALL
BALL_AVAILABLE = True
BALL_ELEMENTS = dict(
H=BALL.PTE['H'], He=BALL.PTE['HE'], Li=BALL.PTE['LI'],... |
#!/usr/bin/env python
#Bao Dang
#Assignment 1
class arraylist:
def __init__(self):
self.maxlength = 10000
self.elements = [None]*self.maxlength
self.last = 0
#Print the first position
def first(self):
return 0
#Print the last position
def end(self):
... |
from django.shortcuts import render
def index_planner(request):
return render(request, 'planner/index.html')
def login_planner(request):
pass |
from repositories.DataRepository import DataRepository
from flask import Flask, request, jsonify
from flask_socketio import SocketIO
from flask_cors import CORS
import os
import json
import time
#from datetime import datetime
import datetime
from datetime import timedelta
import threading
from subprocess import chec... |
import itertools
from collections import deque
from heapq import heappush, heappop, heapify
from Heuristic import Heuristic
from Node import Node
from Puzzle import Puzzle
class Solver:
def __init__(self):
self.expanded_nodes: int = 0
self.max_search_depth: int = 0
self.max_frontier_size... |
from unittest import TestCase
import newMain as mn
__author__ = 'bartek'
def TestCountCenters(self, TestCase):
nodes = [mn.Node([3,3],1),mn.Node([1,1],1),mn.Node([-1,-1],1)]
allgroups = [nodes, nodes]
centers = mn.countCenters(allgroups)
for i in centers:
assert isinstance(i, mn.Node)
assert is... |
# -*- coding: utf-8 -*-
from importlib import import_module
from distutils.core import setup
from distutils.extension import Extension
from Cython.Build import cythonize
from Cython.Distutils import build_ext
import numpy as np
extensions = []
EXT_FILES = ['c_formula_int64', 'cpp_formula_int64', 'cpp_polynomial_int... |
import turtle # 导入模块
zhufu = turtle.Turtle() # 创建Turtle对象,命名为zhufu
chuangkou = turtle.Screen # 创建窗口
turtle.screensize(400,300,"green") # 设置窗口长宽,背景色
zhufu.pencolor("green") # 设置画笔颜色
zhufu.hideturtle() # 隐藏箭头
zhufu.setpos(-150,50) # 移动画笔至坐标 处
zhufu.pencolor("red") # 设置画笔颜色
if True: # 输入5
zhufu.pensi... |
# Estimtate the Lyapunov spectrum of the QG model,
# using a limited (rank-N) ensemble.
# Inspired by EmblAUS/Lor95_Lyap.py
from common import *
from mods.QG.core import shape, step, sample_filename, dt
import mods.QG.core as mod
# NB: "Sometimes" multiprocessing does not work here.
# This may be nn ipython bug (stack... |
import gtk
try :
import hildon
except :
hildon = None
class FuelpadAbstractCombo :
def __init__ ( self ) :
raise Exception( "Instantiating abstract class %s" % self.__class__ )
def fill_combo( self , items , active=None ) :
raise Exception( "Calling uninmplemented method 'fill_combo... |
import numpy as np
import math
import matplotlib.pyplot as plt
from .baseKernel import baseKernel
from ..tools.utils import sigmoid
from ..tools.utils import timeit
# Weighted Kernel Ridge Regression
class WKRR():
def __init__(self):
self.alpha_ = None
def fit(self,K_train,y_train,w,lambda_reg=... |
import re
origin = open('idf_sample/demo.idf', 'r')
for line in origin:
if "U-Factor" in line:
print re.search(r'[-+]?\d*\.\d+|\d+', line).group()
origin.close()
|
import sys
import os
f = open("C://Users/OZ/Documents/python/atcoder/import.txt","r")
sys.stdin = f
# -*- coding: utf-8 -*-
n=int(input())
l=list(map(int,input().split()))
sl=l[:]
sl.sort()
a=sl[n//2-1]
b=sl[n//2]
for i in l:
if i<=a:
print(b)
else:
print(a)
|
"""
Various helper utilities for the HTCondor-ES integration
"""
import os
import pwd
import sys
import time
import errno
import socket
import logging
import smtplib
import email.mime.text
import logging.handlers
TIMEOUT_MINS = 11
def send_email_alert(recipients, subject, message):
"""
Send a simple email ... |
#!/usr/bin/python3
n = 100
sum = 0
counter = 1
while counter <= n:
sum = sum + counter
counter += 1
print("1 ~ %d sum is: %d" % (n,sum)) |
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)
import tensorflow as tf
import numpy as
import scipy.ndimage
import scipy.misc
sess = tf.Session()
saver = tf.train.import_meta_graph('model.meta')
saver.restore(sess, tf.train.latest_checkpoint('./... |
from django.contrib.auth.models import User
from rest_framework import mixins, status
from rest_framework.permissions import AllowAny
from rest_framework.response import Response
from rest_framework.viewsets import GenericViewSet
from account.serializers import UserSerializer
from .permissions import IsStaffOrTargetUs... |
def chiffre (c):
n = str(c)
arr = []
for i in range(0,len(n)):
arr.append(int(n[i]))
return arr
print(chiffre(1234))
def liste (arr):
c=0
n=len(arr)
for i in range(n):
c += arr[i]*10**(n-1-i)
return c
print(liste([1, 2, 3, 4]))
def decroissant (c):
arr = chiffre... |
import unittest
from btree import BTree
class BTreeTest(unittest.TestCase):
def setUp(self):
self.btree = BTree()
self.btree.add(10)
self.btree.add(20)
self.btree.add(40)
self.btree.add(50)
def test_contains(self):
assert 10 in self.btree
assert 20 in... |
import kivy
import socket, os
import time
import download_dhaga
from kivy.uix.textinput import TextInput
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.gridlayout import GridLayout
from kivy.uix.button import Button
from kivy.clock import Clock
from kivy.app import App
from kivy.lang import Builder
from kivy.ui... |
from .data_augment import *
from .averageMeter import AverageMeter |
from contextlib import redirect_stdout
from io import StringIO
stream = StringIO()
write_to_stream = redirect_stdout(stream)
with write_to_stream:
print("This is written to the stream rather than stdout")
with write_to_stream:
print("This is also written to the stream") |
import math
from datetime import datetime
import numpy as np
from flask import Flask, request
from matplotlib.figure import Figure
import base64
from io import BytesIO
import matplotlib.dates as mdates
import matplotlib.ticker as tick
import yfinance as yf
app = Flask(__name__)
def smav2(data, window):
res = []
... |
from drone_model import Drone
from math import pi,cos,sin
import numpy as np
import time
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from trajectory_planner import Trajectories
def simulate():
def init_plot():
fig = plt.figure()
ax = fig.add_subplot(111, projection='3... |
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 13 21:55:58 2017
@author: XuGang
"""
import numpy as np
import DQN
import random
#给Card排序
class SortCards(object):
def __init__(self, cards_combination,cards_type):
self.cards_combination = cards_combination
self.rank = 0
self.cards = []
... |
import argparse
import json
import time
from annotation_pipeline.pipeline import Pipeline
from annotation_pipeline.utils import get_pywren_stats
import logging
logging.basicConfig(level=logging.INFO)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Run annotation pipeline', usage='')
... |
# Copyright 2017 The TensorFlow 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 applica... |
# coding: utf-8
# In[1]:
import cv2
import numpy as np
import imutils
# In[2]:
img = cv2.imread('./datasets/flower3.jpg')
# In[9]:
#Resizing image by width
(h,w) = img.shape[:2]
new_width = 800.0
r = new_width/w
calc_height = h*r
dim = (int(new_width), int(calc_height))
resized_image1 = cv2.resize(img, dim, cv... |
from django.db import models
class NbaNews(models.Model):
created = models.DateTimeField(blank = True, default = '')
title = models.CharField(max_length = 100, blank = True, default='')
author = models.CharField(max_length = 100, blank = True, default = '')
context = models.CharField(max_length = 1000,... |
def generateShape(int):
return "".join("{}\n".format("+"*int) for x in range(int))[:-1]
'''
I will give you an integer. Give me back a shape that is as long and wide
as the integer. The integer will be a whole number between 0 and 50.
Example
n = 3, so I expect a 3x3 square back just like below as a string:
+++... |
import logging
from six.moves import input
from django.core.management import BaseCommand, CommandError, call_command
from elasticsearch_dsl import connections
from stretch import stretch_app
class Command(BaseCommand):
"""
List the Stretch Indices in a Project (not in Elasticsearch)
"""
can_import_... |
import difflib
import random
import re
import string
import subprocess
import sys
import time
from os import path
import requests
class Nginx:
command_config_test = ["nginx", "-t"]
command_reload = ["nginx", "-s", "reload"]
command_start = ["nginx"]
def __init__(self, config_file_path):
self... |
from user.models import Client
from django.contrib.auth.backends import ModelBackend
def jwt_response_payload_handler(token, user=None, request=None):
return {'token': token, 'user_id': user.id, 'username': user.name}
|
from collections.abc import Iterable
from networkx.classes.graph import Graph, _Node
def enumerate_all_cliques(G: Graph[_Node]) -> Iterable[list[_Node]]: ...
def find_cliques(
G: Graph[_Node], nodes: list[_Node] | None = ...
) -> Iterable[list[_Node]]: ...
def find_cliques_recursive(
G: Graph[_Node], nodes: l... |
import socket
import select
import errno
import threading
import patterns
import re
class SocketClient(threading.Thread, patterns.Publisher):
def __init__(self, HOST, PORT):
super().__init__(daemon=True)
self.HOST = HOST
self.PORT = PORT
self.s = socket.socket(socket.AF_INET, sock... |
import numpy as np
class ExtractedFeatures:
def __init__(self, num_items, dim):
self.patches6 = np.zeros( (num_items, dim), dtype='float32' )
self.patches7 = np.zeros( (num_items, dim), dtype='float32' )
self.pos = np.zeros( (num_items, 2), dtype='uint16' )
self.cursor = 0
def ... |
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
from textwrap import dedent
import pytest
from pants.backend.docker.subsystems.dockerfile_parser import DockerfileInfo, DockerfileInfoRequest
from pant... |
def solution(s):
if len(s) % 2 == 1:
center = len(s) // 2
result = s[center]
else:
center = len(s) // 2
result = s[center-1:center+1]
return result
solution("ABCDEFG")
|
from django.apps import AppConfig
class AggsConfig(AppConfig):
name = 'aggs'
|
import sqlite3 as lite
import pandas as pd
con = lite.connect('getting_started.db')
cities = (
('New York City', 'NY'),
('Boston', 'MA'),
('Chicago', 'IL'),
('Miami', 'FL'),
('Dallas', 'TX'),
('Seattle', 'WA'),
('Portland', 'OR'),
... |
#!/usr/bin/env python
#+
# Name:
# download_era_interim_sfc_pl_v2
# Purpose:
# An IDL procedure to download the majority of ERA-Interim variables on
# model levels and at the surface.
# Inputs:
# None.
# Outputs:
# netCDF files with both the pressure level and surface data
# Keywords:
# VERBOSE : Set to in... |
class Optimizer(object):
def __init__(self, loss_var, lr, lr_schedualer=None):
self._prog = None
self._lr_schedualer = lr_schedualer
def _build(self, grad_clip=None):
raise NotImplementedError()
def _set_prog(self, prog, init_prog):
self._prog = prog
self._init_pr... |
#!/usr/bin/env python3
from threading import Thread, Condition
from time import sleep
'''
1115. Print FooBar Alternately
https://leetcode.com/problems/print-foobar-alternately/
'''
class FooBar(object):
def __init__(self, n):
self.n = n
self.cond = Condition()
self.order = 0
self.f... |
#!/usr/bin/env python3
import csv
from enum import Enum
import openpyxl
import utm
# Enum to differentiate between the two file formats
class Version(Enum):
V1 = 1
V2 = 2
# Reads an xlsx file with harbour porpoise observations and copies it to a csv. If multiple harbour porpoises are
# spotted the row is ... |
# Generated by Django 3.0.8 on 2020-07-15 11:29
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('photos', '0003_auto_20200715_1105'),
]
operations = [
migrations.RenameField(
model_name='comment',
old_name='photo',
... |
from gym.envs.registration import register
register(
id='VizdoomBasic-v0',
entry_point='vizdoomgym.envs:VizdoomBasic',
max_episode_steps=10000,
reward_threshold=10.0
)
register(
id='VizdoomCorridor-v0',
entry_point='vizdoomgym.envs:VizdoomCorridor',
max_episode_steps=10000,
reward_thr... |
# coding: utf-8
# シーザー暗号解くためのスクリプト
MAPPING = [
'a', 'b', 'c', 'd', 'e', 'f', 'g',
'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u',
'v', 'w', 'x', 'y', 'z'
]
TARGET_STRING = 'EBG KVVV vf n fvzcyr yrggre fhofgvghgvba pvcure gung ercynprf n yrggre jvgu gur yrggre KVVV yrggref nsgre v... |
# Generated by Django 2.0.5 on 2018-06-05 10:51
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('calculation', '0015_auto_20180605_1046'),
]
operations = [
migrations.AlterField(
model_name='regprice',
name='creat... |
"""Limits serializers for API v2."""
import os
from django.utils.translation import gettext_lazy as _
from rest_framework import serializers, status
from rest_framework.exceptions import PermissionDenied, APIException
from modoboa.core.models import User
from modoboa.parameters import tools as param_tools
from ...... |
from time import sleep
from appium.webdriver.webdriver import WebDriver
from appium import webdriver
from pageobject.page import Page
class MockMethodsLocator(object):
""" Class contains locator for behaviour mocking methods. """
getting_started_id = "com.flickr.android:id/activity_welcome_sign_button"
l... |
#-*—coding:utf8-*-
import numpy as np
import gc
import re
import csv
import codecs
from decimal import *
try:
fil_winsize = codecs.open("r.txt", "r", 'utf_8_sig')
# fil6 = codecs.open("channel_ssid_time.csv", "w", 'utf_8_sig')
winsize = csv.reader(fil_winsize)
# write_ssid = csv.writer(fil6)
except Exce... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
if __name__ =="__main__":
eat = pd.read_csv('EatingDataUnFiltered.csv')
write = pd.read_csv('WriteData.csv')
columns = eat.columns.tolist()[1:]
#create this path manually
path = "plot/comparision"
for column in col... |
from flask import render_template, redirect, url_for, request
from app import app, db
from app.forms import LoginForm, RegistrationForm
from app.models import User, Post
from flask_login import current_user, login_user, logout_user, login_required
from werkzeug.urls import url_parse
from datetime import datetime
... |
def read_the_file(file):
"""
Returns the data of the file file
:param file: the file to read (str)
:return: the data (dictionnary)
"""
fh = open(file, 'r')
lines = fh.readlines()
dico = {}
for line in lines:
elements = line.split(';')
dico[elements[0].strip()] = (ele... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 14 11:59:22 2017
@author: ares
"""
import sys
sys.path.append('~/home/ares/Code/PredyNet/predynet')
from helpers import *
import torch
from torch.autograd import Variable
import numpy as np
M = 20 # Size of Patch Array
ySize = 120
timelength = 1... |
import boto3
import os
import csv
import time
os.system("aws configure set aws_access_key_id XXXX(you access key)")
os.system("aws configure set aws_secret_access_key XXXX(you secret key)")
os.system("aws configure set default.region eu-west-2")
shell = """#!/bin/bash
sudo python /home/ec2-user/1.py
"""
shell2 = """#!... |
import numpy as np
def main():
sampl = np.random.uniform(low=-49.0, high=49.0, size=(100,))
sampl2 = np.random.uniform(low=-49.0, high=49.0, size=(100,))
for i in range(1, len(sampl)):
print("treeLocations.push_back(make_pair(%ff, %ff));" %
(sampl[i], sampl2[i]))
main()
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Create report for Apache logfiles. You can use
--consolidate or --regex keys for creating report
"""
from optparse import OptionParser
def open_files(files):
for f in files:
yield (f, open(f))
def combine_lines(files):
for f, f_obj in files:
... |
import gym
import baxter_env
import pybullet as p
import pybullet_data
import numpy as np
import cv2
import time
import matplotlib.pyplot as plt
class ObsWrapper(gym.ObservationWrapper):
def __init__(self, env):
super(ObsWrapper, self).__init__(env)
self.observation_space = gym.spaces.Box(low = -1... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.http import HttpResponseRedirect
from django.shortcuts import render, redirect
from django.core.urlresolvers import reverse
from django.contrib.auth import authenticate, login, logout, update_session_auth_hash
from azure.storage.blob import Bl... |
#!/usr/bin/env python3
from flask import Flask, send_from_directory
app = Flask(__name__)
@app.route("/video", methods=["GET"])
def get_movie():
return send_from_directory(
"/",
"video.mp4",
conditional=True,
)
if __name__ == '__main__':
app.run(hos... |
from appuser.models import Post
from django.db import models
from django.shortcuts import render
from django.views.generic import ListView, DetailView, CreateView, UpdateView
from .models import Post
from .forms import PostForm , EditForm
# Create your views here.
#def home(request):
#return render(request, 'home.... |
#MenuTitle: Batch Generate Fonts
# -*- coding: utf-8 -*-
__doc__="""
Batch Generate Fonts.
"""
from GlyphsApp import OTF, TTF, WOFF, WOFF2, EOT, UFO
fileFolder = "~/Desktop/files"
otf_path = "~/Desktop/export"
ttf_path = "~/Desktop/export"
ufo_path = "~/Desktop/export"
web_path = "~/Desktop/export"
OTF_AutoHint = T... |
#!/usr/local/bin/python
import json
import os
import sys
import traceback
import urllib2
import Config
def makeOpener():
manager = urllib2.HTTPPasswordMgrWithDefaultRealm()
manager.add_password(None, *Config.ADMIN)
handler = urllib2.HTTPBasicAuthHandler(manager)
return urllib2.build_opener(handler)
_index =... |
""" Given the root node of a binary search tree,
return the sum of values of all nodes with value between L and R (inclusive).
The binary search tree is guaranteed to have unique values.
Input: root = [10,5,15,3,7,null,18], L = 7, R = 15
Output: 32
"""
# Definition for a binary tree node.
# class TreeNode:
# de... |
import tkinter as tk
import pyglet
window = tk.Tk()
window.title('卷积实现过程')
window.geometry('900x600')
txt = tk.StringVar()
txt.set('请选择连续信号或者是离散信号')
Bar = tk.Label(window, textvariable=txt, width=50, height=2)
Bar.place(x=300, y=10)
Barflag = True
def d_app(): # 离散信号
global d_app1
global d_app2
globa... |
def example_sort(arr, example_arr):
keys = {k: i for i, k in enumerate(example_arr)}
return sorted(arr, key=lambda a: keys[a])
|
def main():
vDict = {}
with open('test.txt') as f:
for line in f:
tempList = line.split('\t')
vDict[int(tempList[0])] = []
for v in tempList[1:]: # use [1:-1] for actual graph, [1:] for test
tempstr = v.split(',')
vDict[int(tempList[0])].append((int(tempstr[0]), int(tempstr[1])))
start = ... |
#!/usr/bin/python
import sys
import time
import struct
import re
import numpy as np
import katcp_wrapper
import katadc
import pyqtgraph as pg
# boffile='katadc_zdok0_snap_2016_Mar_10_2010.bof.gz'
boffile='katadc_zdok0_snap_2017_Oct_23_1613.bof.gz'
# boffile='katadc_zdok1_snap_2016_Aug_18_1351.bof.gz'
# boffile='katad... |
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from pants.backend.debian import rules as debian_rules
from pants.backend.debian.target_types import DebianPackage
def target_types():
return [DebianPackage]
def rules():
retur... |
# -*- coding: utf-8 -*-
import itertools
class Solution:
def checkZeroOnes(self, s: str) -> bool:
zero_group_max_length, one_group_max_length = float("-inf"), float("-inf")
for digit, group in itertools.groupby(s):
if digit == "0":
zero_group_max_length = max(zero_grou... |
__author__ = 'pandazxx'
from utilities import trace
class DummyObject(object):
@trace
def __init__(self, *args, **kwargs):
self.__args = args
self.__kwargs = kwargs
class DecoratorExample(object):
@trace
def __init__(self, name, defval):
self.__name = name
self.__val ... |
#I think this is slower than solve.py, actually
import socket
import time
def cubeEnding(sequence, ending):
i = 0
count = 0
answer = 0
while(count != sequence):
i += 1
cube = int(str(i) + str(ending))
answer = root3rd(cube)
if(answer != -1):
count += 1
print "i= " + str(i)
print "cube= " + str(c... |
from django.urls import path, include, re_path
from api.endpoint import history_view
urlpatterns = [
re_path(r'entity', history_view.HistoryView.as_view()),
re_path(r'list', history_view.HistoryListView.as_view()),
]
|
BROKER_URL = "sqla+sqlite:///vpt_tasks.db"
CELERY_ACCEPT_CONTENT = ["pickle"]
CELERY_IGNORE_RESULT = True
CELERY_IMPORTS = ("app.notifications.handlers", ) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import json
class Database:
__location__ = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))
__DATA_FILEPATH = os.path.join(__location__, 'data', 'database.json')
def __init__(self):
self._filepath = Da... |
#Tamishia Ayala
#Date: 01/27/2019
#This program will prompt the user to enter miles and then convert the user input (miles)to kilometers
sMiles = input ('Enter miles: ')
float_KMs = float (sMiles)
def sMilestoKilometers (x):
c = 1.609 * x
return c
Kilom = sMilestoKilometers(float_KMs)
print ('Kilometers ar... |
from Bio import SeqIO
import pandas as pd
dictseq = {}
n = 0
for seq_record in SeqIO.parse("TIR.fasta", "fasta"):
n = n + 1
xid = seq_record.id.split("|")
yid = xid[1]
z = str(seq_record.seq)
m = {yid:z}
dictseq.update(m)
print('运行至第',n,'次,蛋白质ID为',yid)
|
"""
Dieses Programm trainiert das neuronale Netz.
Dafür werden die Daten aus dem "dataset"-Verzeichnis verwendet.
Verwendung: 'python3 train-netzwerk.py'
(am besten zusamen mit 'nice' ausführen, da das Training lange
dauert und sehr rechenintensiv ist)
"""
import sys
import os
import numpy as np
from keras.models im... |
from pycaret.classification import * # Preprocessing, modelling, interpretation, deployment...
import pandas as pd # Basic data manipulation
import dabl as db # Summary plot
from sklearn.model_selection import train_test_split # Data split
from sdv.tabular import CopulaGAN # Synthetic data
from sdv.evaluation import ev... |
# Generated by Django 3.1.5 on 2021-01-28 13:55
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('pages', '0002_auto_20210128_1355'),
]
operations = [
migrations.AddField(
model_name='diary',
name='title',
... |
from tkinter import *
from tkinter.messagebox import showinfo
import echec.classe
from echec.classe import Pieces
from PIL import ImageTk, Image
import pickle
from tkinter.messagebox import *
from tkinter.simpledialog import *
class Plateau:
def __init__(self, window, couleur, netConn, username, room):
s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.