content stringlengths 5 1.05M |
|---|
from django.shortcuts import render, get_object_or_404
from django.core.paginator import Paginator
from general_models.models import GeneralModel
def writing_home(request):
writing_posts = GeneralModel.objects.order_by('-publish_date').filter(is_published=True, category='writing')
paginator = Paginator(writ... |
from matplotlib import pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np
import scipy.stats as stats
import statsmodels.api as sm
import statsmodels.stats.api as sms
import statsmodels.formula.api as smf
import statsmodels.stats.multicomp as smm
import statsmodels.stats.outliers_influence as ss... |
import time
import sgeProto
data = {
'name': 'username1',
'id': [13245, 1,2,34,5],
'email': '1111112',
'phone': [
{ 'num': '1234', 'type': -1 },
{ 'num': '4321', 'type': -2 }
]
}
sgeProto.parseFile("../example.proto")
sgeProto.debug()
for i in range(10000000):
code = sgeProto.encode('Person', data)
pa... |
import copy
import decimal
import json
from django.contrib import messages
from django.core.exceptions import ValidationError
from django.db.utils import DataError
from django.http import Http404, HttpResponseBadRequest, HttpResponseRedirect
from django.urls import reverse
from django.utils.decorators import method_de... |
# Copyright 2010 Jacob Kaplan-Moss
# Copyright 2011 OpenStack Foundation
# Copyright 2013 OpenStack Foundation
# 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
... |
# [카카오] 추석 트래픽
"""
다음 시작 시간 - 1000이 현재 끝나는 시간보다 안쪽에 있거나 같다면 +1
"""
def solution(lines):
answer = 0
start_time = []
end_time = []
for t in lines:
time = t.split(" ")
start_time.append(get_start_time(time[1], time[2]))
end_time.append(get_time(time[1]))
for i in range(len(li... |
import unittest
import os
from polyglot.model import LanguageModel
from polyglot.classifier import Classifier
import cStringIO
from time import time
import logging
logging.basicConfig(format='%(asctime)s -- %(message)s', level=logging.INFO)
class TestShit(unittest.TestCase):
ngram = 3
corpus_dir = './corpus'
... |
# https://github.com/godbmw/various-codes/tree/master/DictEmotionAlgorithm
# https://github.com/AimeeLee77/senti_analysis/tree/master/data/ChnSentiCorp_htl_ba_2000
# https://github.com/godbmw/news-emotion/tree/master/data/trainset
import os
import io
DIR = os.path.join(os.path.dirname(__file__), "../unprepared_test_dat... |
from .p141_assigned import P141Assigned
from dataclasses import dataclass
@dataclass
class P35HasIdentified(P141Assigned):
"""
Scope note:
This property identifies the E3 Condition State that was observed in an E14 Condition Assessment activity.
Examples:
- 1997 condition assessment of silver cup 232 (E14) has ... |
import numpy as np
from quadruped_spring.env.tasks.task_base import TaskJumping
class JumpingOnPlaceHeight(TaskJumping):
"""
Robot has to perform one single jump in place. It has to fall the closest as possible
to the place it landed. Sparse reward based on maximizing the absolute reached height.
"""... |
#!/usr/bin/python
# Track target(s) for a specified time.
# Also set the data gains before and after the track
# The *with* keyword is standard in Python 2.6, but has to be explicitly imported in Python 2.5
from __future__ import with_statement
import time
from katcorelib.observe import standard_script_options, verif... |
from . import Globals
from .ReadMatrix import ReadMatrix
from .ReadComplexMatrix import ReadComplexMatrix
from .PlotMatrix import PlotMatrix
from .PlotMatrix3D import PlotMatrix3D
from .MatrixVariation import MatrixVariation
from . import Unwrapping
<<<<<<< HEAD
=======
from . import Smooth
from .GetComplex import GetC... |
from .packet_endpoints import (
Packet_EP,
Packet_Table_EP,
Packet_Table_Counts_EP,
Packet_Table_Views_EP,
)
|
# 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 law or agreed to in writing, software
# distributed under th... |
from sqlalchemy import Column, Integer, String, ForeignKey
from app.models.base import Base, db
from app.models.contest import Contest
from app.models.problem import Problem
class ProblemContestRel(Base):
__tablename__ = 'problem_contest_rel'
id = Column(Integer, primary_key=True, autoincrement=True)
pr... |
from matplotlib import rcParams
import numpy as np
# eternally grateful to http://blog.dmcdougall.co.uk/publication-ready-the-first-time-beautiful-reproducible-plots-with-matplotlib/
def default():
reference = 16
rcParams['axes.titlesize'] = 1 * reference
rcParams['axes.labelsize'] = 1 * reference
rcP... |
import tensorflow as tf
import tensorflow_addons as tfa
from vit_keras import vit, utils, visualize
from dataset import COVIDxCTDataset
from math import ceil
import os
import numpy as np
import pickle
import matplotlib.pyplot as plt
Training = True
DATA_DIR = '../2A_images/'
# TRAIN_LABEL_FILE = '../train_... |
import logging
import torch
import torch.nn as nn
import torch.nn.functional as F
from models.model_utils import ConvBlock, _ResNet, _ResnetBasicBlock
class BaseEncoder(nn.Module):
def __init__(
self,
n_input_channels: int = 1,
n_output_channels: int = 512,
p_dropout: float = 0.0... |
# This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
# for complete details.
from __future__ import absolute_import, division, print_function
import binascii
import pytest
from cryptography.exceptions import _Reas... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import json
class Settings:
SETTINGS_FILE_NAME = 'settings.json'
def __init__(self):
# 出力先ディレクトリーのパス
self.dst_dir_path = ''
# mdpiにおける幅
self.mdpi_image_width = 24
# フォアグラウンドカラー(空文字列だと塗らない)
self.fg_co... |
import json
import datetime
import peewee as pw
import pendulum
def patch_datetime_type():
pw.MySQLDatabase.field_types.update({'DATETIME': 'DATETIME(6)'})
pw.PostgresqlDatabase.field_types.update({'DATETIME': 'TIMESTAMPTZ'})
patch_datetime_type()
class DatetimeTZField(pw.Field):
field_type = 'DATETIM... |
import numpy as np
# Bezier Class representing a CUBIC bezier defined by four
# control points.
#
# at(t): gets a point on the curve at t
# distance2(pt) returns the closest distance^2 of
# pt and the curve
# closest(pt) returns the point on the curve
# which ... |
'''
Policies
========
Methods described in this section relate to the the files API.
These methods can be accessed at ``Nessus.policies``.
.. rst-class:: hide-signature
.. autoclass:: PoliciesAPI
:members:
'''
from io import BytesIO
from typing import Optional, Dict, List
from tenable.base.endpoint import APIEndp... |
"""
Utils for web frameworks request filters.
"""
from six.moves import urllib
from epsagon.trace import trace_factory
from epsagon.constants import IGNORED_ENDPOINTS
# Ignored content types for web frameworks.
IGNORED_CONTENT_TYPES = [
'image',
'audio',
'video',
'font',
'zip',
'css',
]
IGNORE... |
from flask import Flask, request, render_template, abort
from db import *
from random import choice
import string
import requests
app = Flask(__name__)
ALPHABET = string.ascii_uppercase + string.ascii_lowercase + string.digits
HEADERS = {
"User-Agent": "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; S... |
import graphene
from graphene_django import DjangoObjectType
from .models import Post
class PostType(DjangoObjectType):
class Meta:
model = Post
fields = ('id', 'title', 'description', 'image')
def resolve_image(self, info):
return self.image.thumbnails.large.url
class Query(graphen... |
from .kitti_dataset import KITTIRAWDataset, KITTIOdomDataset, KITTIDepthDataset
from .mc_dataset import MCDataset
|
# -*- coding: iso-8859-15 -*-
import ctypes
import json
import os
import pathlib
from . import ActiveClass, Bus, CapControls, Capacitors, Circuit, CktElement, CMathLib, CtrlQueue, DSSElement
from . import DSSExecutive, DSSInterface, DSSProgress, DSSProperties, ErrorOpenDSS, Fuses, Generators, ISources
from . import Li... |
n = int(input('Digite a quantidade de termos que você deseja saber da sequência de Fibonnaci: '))
n1 = 0
n2 = 1
c = 0
while c != n:
if c % 2 == 0:
print('{} -> '.format(n1), end='')
c += 1
n1 += n2
else:
print('{} -> '.format(n2), end='')
c += 1
n2 += n1
print('F... |
from libs.config import alias, set_namespace
from libs.myapp import clean_trace
# ? alias装饰器第一个参数为none_named_arg(true/FALSE),True即把没有参数名时传入的参数值顺序传入
@alias(func_alias="b", _type="COMMON")
def run():
"""
back
Back to main menu.
"""
clean_trace()
set_namespace("main")
|
import sys
import os.path
sys.path.append(os.path.curdir)
|
"""
A set of generic utilities used in bilby_pipe
"""
import re
import os
import sys
import logging
import ast
class BilbyPipeError(Exception):
def __init__(self, message):
super().__init__(message)
def get_command_line_arguments():
""" Helper function to return the list of command line arguments ""... |
''' Logic on how information is invalidated in cascade. It is used by
validation-type nodes and patch requests '''
from cacahuate.errors import EndOfProcess
def get_ref_index(state, node, actor, ref, index):
forms = state['state']['items'][node]['actors']['items'][actor]['forms']
ref_forms = [
i for ... |
__title__ = 'Website Colors'
|
from optparse import make_option
from django.core.management import BaseCommand, CommandError
from django.core.validators import URLValidator
from django.conf import settings
from django.utils.translation import ugettext as _
from apiclient.discovery import build
from apiclient.errors import HttpError
from psi.models ... |
import pandas as pd
import numpy as np
import random
## Hurst
def hurst_series(x, N):
def _hurst(x):
segs = 4.00 #5.0
N = len(x)
mlarge = np.floor(N/segs)
M = np.array([np.floor(np.logspace(0,np.log10(mlarge),50))])
M = np.unique(M[M>1])
n = len(M)
cut_min =... |
# The sender's email :
from_email = '' # 'example@gmail.com' - (must be a gmail account)
from_email_password = '' # 'password'
# The reciever's email :
to_email = '' # 'example@example.com'
|
#!/usr/bin/env python
"""Video eye tracking
Usage:
vid_track <vid.mov> <behave.csv> [--box <x,y,w,h>] [--dur <len_secs>] [--start <start_secs>] [--method <method>] [--fps <fps>]
vid_track methods
vid_track (-h | --help)
vid_track --version
Options:
--box POS initial pos of box containing pupil. csv like... |
import zipfile
from os import listdir
from os.path import isfile, join
import yaml
import asyncio
from flask import current_app
from .util import Loggers
async def get_plugins():
plugins = []
plugin_path = current_app.config['MINECRAFT_PLUGIN_FOLDER']
plugin_files = [f for f in listdir(
plugin_pa... |
#Copyright 2008 Erik Tollerud
#
# 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 law or agreed to i... |
def clean_dict(data):
"""
Delete keys with the value ``None`` in a dictionary, recursively.
This alters the input so you may wish to ``copy`` the dict first.
"""
for key, value in list(data.items()):
if value is None:
del data[key]
elif isinstance(value, dict):
... |
import urwid, time, threading
from tabulate import tabulate
from netaddr import EUI
from wifipumpkin3.core.utility.collection import SettingsINI
import wifipumpkin3.core.utility.constants as C
import fcntl, termios, struct, os
from wifipumpkin3.core.common.platforms import hexdump
from multiprocessing import Process
fr... |
# -*- coding: utf-8 -*-
"""Plugin to create a Quantum Espresso epw.x input file."""
import os
import numpy as np
from aiida import orm
from aiida.common import datastructures, exceptions
from aiida_quantumespresso.calculations import _lowercase_dict, _uppercase_dict
from aiida_quantumespresso.utils.convert import conv... |
# encoding: utf8
from collections import OrderedDict
from wtforms_alchemy import (ModelForm, QuerySelectField,
DataRequired)
from wtforms import TextField
from wtforms.validators import EqualTo, Required
from wtforms.fields import FormField, PasswordField, HiddenField
from wtforms.widgets i... |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: namespaces.proto
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.prot... |
# Given a positive integer n, generate a square matrix filled with elements from 1 to n^2 in spiral order.
# Example:
# Input: 3
# Output:
# [
# [ 1, 2, 3 ],
# [ 8, 9, 4 ],
# [ 7, 6, 5 ]
# ]
class Solution(object):
def generateMatrix(self, n):
"""
:type n: int
:rtype: List[List[int]]
... |
import torch
import pickle
import torch.utils.data
import time
import os
import numpy as np
import csv
import dgl
from dgl.data import CoraDataset
from dgl.data import CitationGraphDataset
import networkx as nx
import random
from data.ncdata import *
random.seed(42)
def self_loop(g):
"""
Utility functi... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Description: Development settings and globals.
"""
__author__ = "Ariel Gerardo Rios (ariel.gerardo.rios@gmail.com)"
from os.path import join, normpath
from base import *
########## DEBUG CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#debu... |
from . import stud
from . import cl_info |
print('-='*20)
print('Analisador de Triângulos')
print('-='*20)
a=float(input('Digite o primeiro lado de um triângulo: '))
b=float(input('Digite o segundo lado de um triângulo: '))
c=float(input('Digite o terceiro lado de um triângulo: '))
if a < b + c and b < a + c and c < a + b and a==b==c:
print('O seu triângulo... |
#!/usr/bin/env python3
import util
db = util.create_database()
root = "https://ss64.com/nt/"
for soup in util.soups_from_files("Documents/*.html"):
for tag in soup.select('.az a[href$=".html"]'):
name = tag.text
path = root + tag.attrs["href"]
util.insert(db, name, path)
|
# Generated by Django 3.0.2 on 2020-01-11 16:51
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('website', '0004_remove_comment_publication'),
]
operations = [
migrations.AddField(
model_name=... |
CIFAR_CONFIG = {
# Constants
"device": "cuda",
# Data parameters
"batch_size_train": 100, # E: Bugs want this to be 100 for cifar
"batch_size_test": 200,
"shuffle_train": True,
"image_min": 0,
"image_max": 1,
# Getter functions
"dataset": 'CIFAR10',
"model_name": 'ResNet18... |
import matplotlib
matplotlib.use('TkAgg') # This is needed for plotting through a CLI call
import matplotlib.pyplot as plt
import pandas as pd
import os
import numpy as np
import itertools
import seaborn as sns
from scipy.stats import ks_2samp
import argparse
import sys
# This function allows violinplots visualizati... |
# -- coding: utf-8 --
import json
import math
import urllib.request
from .lib.gethttp import *
class Upper:
__uid = 0
__caching = {'getUpperVideo': '', 'getUpperNavnum': '', 'getUpperStat': '',
'getUpperRelationstat': '', 'getUpperSpaceTop': '', 'getUpperInfo': ''}
def __init__(self, uid... |
# encoding = utf-8
import base64
import functools
import json
import os
import requests.exceptions
import sys
import time
'''
IMPORTANT
Edit only the validate_input and collect_events functions.
Do not edit any other part in this file.
This file is generated only once when creating the modular input... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-10-28 15:07
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('ecom_webapp', '0005_auto_20171028_1504'),
]
operations = [
migration... |
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from backend.config import DATABASE_URI
engine = create_engine(DATABASE_URI, convert_unicode=True, echo=True)
db_session = scoped_session(
sessionmaker(autocommit=Fa... |
# -*- coding: utf-8 -*-
import unittest
from .fixtures import (
fixture_data,
Chain,
SharedInstance,
shared_blockchain_instance,
set_shared_blockchain_instance,
set_shared_config,
)
class Testcases(unittest.TestCase):
def setUp(self):
fixture_data()
def test_shared_instance(se... |
import pygame
pygame.init()
import json
from datetime import datetime
from random import randrange
import math
from board import board
import sys
from pathlib import Path
sys.path.append(str(Path(__file__).parent) + '/players_script')
from ai import ai
from human import human
sys.path.append(str(Path(__file__).parent) ... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... |
from PyQt5.QtWidgets import QWidget
from .RemoteSpyUI import Ui_RemoteSpy
class RemoteSpyForm(QWidget):
parent = None
def __init__(self, parent=None):
super(RemoteSpyForm, self).__init__()
self.parent = parent
self.frame_proportion = 9 / 16
self.ui = Ui_RemoteSpy()
sel... |
import numpy as np
from pymks.bases import GSHBasis
def test_gsh_no_symmetry():
"""this test checks that a particular gsh basis function with no
symmetry is being evaluated properly"""
X = np.array([[0.1, 0.2, 0.3],
[6.5, 2.3, 3.4]])
gsh_basis = GSHBasis(n_states=[1])
assert(np... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
usage : tJOG.py [-h] [-ADL] <inputfile>
-h : (optional) display help
-ADL : (optional) set the origin to the city centre of Adelaide (Australia, South Australia)
The output file tJOG_<inputfile> is created, with origin removed/replaced
e.g. tJ... |
"""
File largely based on sample celery.py file from documentation
for working with Celery and Django here:
http://docs.celeryproject.org/en/latest/django/first-steps-with-django.html
"""
from __future__ import absolute_import
import os
from celery import Celery
from django.conf import settings
# Set the default Dj... |
__________________________________________________________________________________________________
sample 84 ms submission
class Solution:
def removeCoveredIntervals(self, intervals: List[List[int]]) -> int:
if not intervals: return 0
intervals.sort()
L, R = intervals[0]
for i in ran... |
from pyglet.graphics import Batch
class Scene():
def __init__(self, game=None, context=None):
self.game = game
self.batch = Batch()
self.context = context or {}
def load(self):
pass
def unload(self):
pass
def draw(self):
self.batch.draw()
def res... |
#!/usr/bin/env python3
import copy
from typing import List, Optional, Tuple
import i3ipc
from i3wsgroups import i3_proxy, icons, logger
from i3wsgroups import workspace_names as ws_names
# from i3wsgroups.ws_names import *
GroupToWorkspaces = ws_names.GroupToWorkspaces
OrderedWorkspaceGroups = List[Tuple[str, List... |
import math
from decimal import Decimal
from .probability import roll_chance, roll_success_range
from .action import max_actions
def max_shots(group):
"""
Returns the max number of shots a weapon can achieve in a turn.
Takes into consideration that the weapon may have to reload.
"""
return max_a... |
import explorerhat as eh
from time import sleep
while True:
v1 = eh.analog.one.read()
celsius = 100.0 * (v1 - 0.5)
fahrenheit = 32 + 9 * celsius / 5.0
print('Temperature is %4.1f degrees C or %4.1f degrees F'
% (celsius, fahrenheit))
v2 = eh.analog.two.read()
light_level = 'low' if v2... |
#!/usr/local/bin/python3
bloco_attrs = ('bloco_id', 'bloco_style')
ul_attrs = ('ul_id', 'ul_style')
def filtra_attrs(attrs, permitidos):
return ' '.join(f'{k.split("_")[-1]}="{v}"' for k, v in attrs.items()
if k in permitidos)
def tag_bloco(conteudo, *args, classe='success', inline=False, *... |
def pony_func(func):
"""Decorator to mark expose a method to a PonyDebugger caller."""
func.is_pony_func = True
return func
class BasePonyDomain(object):
STATIC_FUNCS = {}
def __init__(self, client):
self.client = client
self.enabled = False
@pony_func
def enable(self, pa... |
#OSBS mining
from src import predict
from src import data
from src import neon_paths
from glob import glob
import pandas as pd
import geopandas as gpd
from src.start_cluster import start
from distributed import wait
import os
import re
import traceback
def find_rgb_files(site, year, config):
tiles = glob(config["r... |
import cv2
import os
USERNAME = 'admin'
PASSWORD = 'admin'
IP = '192.168.1.107:8081'
PORT = '554'
os.environ["OPENCV_FFMPEG_CAPTURE_OPTIONS"] = "rtsp_transport;udp"
URL = 'https//{}:{}@{}/'.format(USERNAME, PASSWORD, IP, PORT)
print('Conectado com: ' + URL)
cap = cv2.VideoCapture(URL, cv2.CAP_FFMPEG)
faceCascade =... |
from torch import nn as nn
from .resnet import conv3x3x3, conv1x1x1
class MyronenkoConvolutionBlock(nn.Module):
def __init__(self, in_planes, planes, stride=1, norm_layer=None, norm_groups=8, kernel_size=3):
super(MyronenkoConvolutionBlock, self).__init__()
self.norm_groups = norm_groups
i... |
import pandas as pd
import numpy as np
from flask import (
Blueprint,
render_template,
abort, request,
make_response,
url_for,
redirect
)
from flask_login import login_required, current_user
from flask_api import status
# Bokeh imports.
from bokeh.embed import components
from bokeh.plotting impo... |
# coding: utf-8
"""The django_nose module."""
from __future__ import unicode_literals
VERSION = (1, 4, 1)
__version__ = '.'.join(map(str, VERSION))
from django_nose.runner import BasicNoseRunner, NoseTestSuiteRunner
from django_nose.testcases import FastFixtureTestCase
assert BasicNoseRunner
assert FastFixtureTestCas... |
import pytest
import fairing
import sys
import io
import tempfile
import random
import os
from google.cloud import storage
from fairing import TrainJob
from fairing.backends import KubernetesBackend, KubeflowBackend
from fairing.backends import KubeflowGKEBackend, GKEBackend, GCPManagedBackend
GCS_PROJECT_ID = fairin... |
txt = "Quick brown fox"
mlist = [1, 2, 3, 9]
# TODO move add to my utilities module
def add(a, b):
print(f"adding {a=} and {b=}")
return a+b
# best to keep Classes in separate module
# big class could have its own file with name such as klase.py
class Klase:
pass
class Garage:
def __init__(self,... |
'''
Created on Aug 27, 2017
@author: arnon
'''
import pickle
import sys
# need to import objects that would be passed with in
from concepts.sshtypes import RemoteWorker
workload = sys.stdin.buffer.read()
worker = pickle.loads(workload)
worker.run() |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Sambacry (CVE-2017-7494) exploit by opsxcq
github.com/opsxcq
twitter.com/opsxcq
Tested on samba 5.4.9
If you don't have a samba server, use the vulnerables/cve-2017-7494 docker image to test it
"""
from sys import argv, exit
from argparse ... |
"""一些 MySQL 数据库操作。
create: 2018-12-12
modified:
"""
import pymysql
from .types import *
def insert_data(mysql_config: MysqlConfig, sql: str, item: Dict) -> int:
"""插入数据。"""
mysql_conn = pymysql.connect(
host=mysql_config['host'], port=mysql_config['port'],
user=mysql_config['user'], pas... |
import sys
class UnionFind:
def __init__(self, n):
self.root = [i for i in range(n+1)]
self.rank = [0] * (n+1)
self.size = [1] * (n+1)
def find(self, x):
if self.root[x] == x:
return x
else:
y = self.find(self.root[x])
self.root[x] = ... |
from __future__ import unicode_literals
from django import forms
from django.forms.widgets import SelectDateWidget
import calendar, datetime
from django.utils import timezone
from .models import *
TYPE = (('parent', 'Parent'), ('estate', 'Estate'),)
TERMS = (('first', 'First'), ('second', 'Second'), ('third', 'Third'... |
import pyttsx3
import pandas as pd
import openpyxl # 需有此才能順利開啟xlsx
import tkinter as tk
import PyPDF2
# 也可用pdfplumber
import os
import boto3 # AWS SDK for Python (Boto3)
# ---------------------------------- 常數設定 ---------------------------------- #
KEY_WORDS = "Many online quizzes at URL below\n "
KEY_END_WORDS = "... |
"""
UConnMQTT module
This module implements the MQTT connection and messaging through the Mosquitto broker
"""
import logging
from . import exceptions, config
import paho.mqtt.client as mqtt
import time
class UConnMQTT(object):
"""
MQTT class
"""
def __init__(self):
"""
Initialize M... |
#!/usr/bin/env python3
n, *a = map(int, open(0))
print(-(-n // min(a)) + 4) |
from __future__ import absolute_import
from django.apps import AppConfig
class Config(AppConfig):
name = "sentry.lang.java"
def ready(self):
from .plugin import JavaPlugin
from sentry.plugins import register
register(JavaPlugin)
|
# -*- coding: utf-8 -*-
# @File : SimpleRewMsfModule.py
# @Date : 2019/1/11
# @Desc :
from Lib.ModuleAPI import *
class PostModule(PostMSFCSharpModule):
NAME_ZH = "Windows注册表Run键值持久化(C#)"
DESC_ZH = "模块通过调用SharpHide.exe写入隐藏的注册表键值,实现持久化.\n" \
"SharpHide.exe会将目标exe路径写入到注册表Run键值中.\n"
NAME_E... |
'''
Created on 17.07.2011
@author: kca
'''
import logging, sys
from futile.logging import get_logger
from subprocess import check_output as _check_output, check_call as _check_call, CalledProcessError, STDOUT, Popen
try:
from subprocces import SubprocessError, TimeoutExpired
except ImportError:
class SubprocessErr... |
"""Support testing with Pytest."""
import pytest
import os
import logging
from asgi_tools.tests import manage_lifespan
from . import TestClient
def pytest_addoption(parser):
"""Append pytest options for testing Muffin apps."""
parser.addini('muffin_app', 'Set path to muffin application')
parser.addoptio... |
import re
import functools
from collections import OrderedDict
from functools import partialmethod as pm
from typing import Optional
from lxml import etree
from zeep import Client, Plugin
from zeep.exceptions import Fault
from zeep.helpers import serialize_object
from . import utils
class TRTH:
"""A Pythonic wr... |
# standard libraries
import logging
import unittest
# local libraries
from nion.utils import Converter
class TestConverter(unittest.TestCase):
def setUp(self) -> None:
pass
def tearDown(self) -> None:
pass
def test_float_to_scaled_integer_with_negative_min(self) -> None:
conver... |
import secrets
from ..common import cloudcli_server_request, assert_only_one_server, assert_no_matching_servers, wait_command
def test_server_hdlib_only_one_server(session_server_powered_on, session_server_powered_off):
assert_only_one_server([session_server_powered_on, session_server_powered_off], "/server/hdlib... |
"""from django.shortcuts import render_to_response
class GeogebraAppletForm(forms.ModelForm):
"Форма для загрузки архива""
class Meta:
model = GeogebraApplet
fields = ['archive']
def main_page(request):
# если в POST есть данные, значит это post-запрос и мы пытаемся загрузить архив
... |
"""Top-level package for Regression Enrichment Surface."""
__author__ = """Austin Clyde"""
__email__ = 'aclyde@uchicago.edu'
__version__ = '0.1.0'
|
# Load in our dependencies
from __future__ import absolute_import
import os
import subprocess
import sys
import textwrap
from unittest import TestCase
import restructuredtext_lint
_dir = os.path.dirname(os.path.abspath(__file__))
valid_rst = os.path.join(_dir, 'test_files', 'valid.rst')
warning_rst = os.path.join(_d... |
# Generated by Django 3.1.7 on 2021-07-28 11:38
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('simple', '0004_auto_20210726_1217'),
]
operations = [
migrations.RemoveField(
model_name='post',
name='slug',
),
... |
# encoding: utf-8
"""
Enumerations related to styles
"""
from __future__ import absolute_import, print_function, unicode_literals
from docxx.enum.base import alias, EnumMember, XmlEnumeration, XmlMappedEnumMember
@alias('WD_STYLE')
class WD_BUILTIN_STYLE(XmlEnumeration):
"""
alias: **WD_STYLE**
Specif... |
#!/usr/bin/python3
# RNANet statistics
# Developed by Aglaé Tabot & Louis Becquey, 2021
# This file computes additional geometric measures over the produced dataset,
# and estimates their distribtuions through Gaussian mixture models.
# THIS FILE IS NOT SUPPOSED TO BE RUN DIRECTLY.
import matplotlib.pyplot as plt
i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.